@ansonlai/docx-redline-js 0.7.2 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +15 -10
- package/ARCHITECTURE.md +30 -10
- package/CHANGELOG.md +539 -431
- package/README.md +331 -309
- package/adapters/xml-adapter.js +84 -56
- package/core/sha256.js +120 -0
- package/dist/docx-redline-js.esm.js +8982 -693
- package/dist/docx-redline-js.esm.js.map +4 -4
- package/dist/docx-redline-js.esm.min.js +102 -89
- package/dist/docx-redline-js.esm.min.js.map +4 -4
- package/dist/docx-redline.bundle.cjs +28305 -0
- package/dist/docx-redline.bundle.cjs.map +7 -0
- package/dist/docx-redline.bundle.js +28296 -0
- package/dist/docx-redline.bundle.js.map +7 -0
- package/docs/AGENT_FAST_START.md +2 -1
- package/docs/AGENT_KNOWLEDGE_BASE.md +480 -393
- package/docs/SKILL_AUTHORING.md +5 -2
- package/docs/TESTING.md +2 -1
- package/docs/schemas/document-operations.schema.json +29 -0
- package/document/docx-document.d.ts +39 -0
- package/document/docx-document.js +1010 -0
- package/document/zip-archive.js +258 -0
- package/engine/reconstruction-writer.js +18 -0
- package/index.d.ts +598 -531
- package/index.js +349 -340
- package/node/cli-help.js +5 -5
- package/node/cli.js +760 -754
- package/node/docx-document.js +11 -355
- package/node/index.d.ts +1 -1
- package/node/zip-archive.js +28 -38
- package/package.json +14 -11
- package/scripts/build.mjs +40 -5
- package/scripts/generate-word-comment-edge-case-fixture.ps1 +58 -0
- package/scripts/generate-word-comment-thread-fixture.ps1 +36 -0
- package/scripts/generate-word-header-footer-fixture.ps1 +32 -0
- package/scripts/generate-word-multi-section-fixture.ps1 +27 -0
- package/scripts/generate-word-package-integrity-cases.mjs +141 -0
- package/scripts/generate-word-thread-state-fixtures.ps1 +50 -0
- package/scripts/word-com-package-integrity.ps1 +98 -0
- package/services/batch-operation-orchestrator.js +262 -259
- package/services/comment-replies.js +96 -95
- package/services/comment-thread-parts.js +280 -0
- package/services/document-inspection.js +366 -365
- package/services/document-operation-applier.js +230 -202
- package/services/document-operation-contract.js +17 -2
- package/services/error-recovery.js +6 -0
- package/services/headers-footers.js +206 -0
- package/services/operation-batch-compiler.js +1 -0
- package/services/operation-preflight.js +231 -218
- package/services/package-parts.js +80 -0
- package/services/revision-token.js +11 -7
- package/services/standalone-docx-plumbing.js +631 -569
- package/services/standalone-operation-runner.d.ts +19 -3
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,u),f==-1&&(f=l.length-1);var d=l.substring(u,f+1);(n.hasOwnProperty?n.hasOwnProperty(d):n[d]!==void 0)?c+=String.fromCharCode(n[d]):(m==i&&(d=l.substring(u),f=l.length),c+=String.fromCharCode(m),n[d]=m,r[m++]=d),u=f+1}return c}var i=4e4,a=o(e);i=65535;var s=o(t);return{chars1:a,chars2:s,lineArray:r}};P.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],o=[],i=0;i<n.length;i++)o[i]=t[n.charCodeAt(i)];e[r][1]=o.join("")}};P.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,i=0;r<o;)e.substring(i,o)==t.substring(i,o)?(r=o,i=r):n=o,o=Math.floor((n-r)/2+r);return o};P.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,i=0;r<o;)e.substring(e.length-o,e.length-i)==t.substring(t.length-o,t.length-i)?(r=o,i=r):n=o,o=Math.floor((n-r)/2+r);return o};P.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var o=Math.min(r,n);if(e==t)return o;for(var i=0,a=1;;){var s=e.substring(o-a),l=t.indexOf(s);if(l==-1)return i;a+=l,(l==0||e.substring(o-a)==t.substring(0,a))&&(i=a,a++)}};P.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var o=this;function i(p,h,w){for(var b=p.substring(w,w+Math.floor(p.length/4)),g=-1,x="",v,N,S,y;(g=h.indexOf(b,g+1))!=-1;){var T=o.diff_commonPrefix(p.substring(w),h.substring(g)),A=o.diff_commonSuffix(p.substring(0,w),h.substring(0,g));x.length<A+T&&(x=h.substring(g-A,g)+h.substring(g,g+T),v=p.substring(0,w-A),N=p.substring(w+T),S=h.substring(0,g-A),y=h.substring(g+T))}return x.length*2>=p.length?[v,N,S,y,x]:null}var a=i(r,n,Math.ceil(r.length/4)),s=i(r,n,Math.ceil(r.length/2)),l;if(!a&&!s)return null;s?a?l=a[4].length>s[4].length?a:s:l=s:l=a;var c,u,f,m;e.length>t.length?(c=l[0],u=l[1],f=l[2],m=l[3]):(f=l[0],m=l[1],c=l[2],u=l[3]);var d=l[4];return[c,u,f,m,d]};P.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=0,s=0,l=0,c=0;i<e.length;)e[i][0]==U?(r[n++]=i,a=l,s=c,l=0,c=0,o=e[i][1]):(e[i][0]==Q?l+=e[i][1].length:c+=e[i][1].length,o&&o.length<=Math.max(a,s)&&o.length<=Math.max(l,c)&&(e.splice(r[n-1],0,new P.Diff(J,o)),e[r[n-1]+1][0]=Q,n--,n--,i=n>0?r[n-1]:-1,a=0,s=0,l=0,c=0,o=null,t=!0)),i++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),i=1;i<e.length;){if(e[i-1][0]==J&&e[i][0]==Q){var u=e[i-1][1],f=e[i][1],m=this.diff_commonOverlap_(u,f),d=this.diff_commonOverlap_(f,u);m>=d?(m>=u.length/2||m>=f.length/2)&&(e.splice(i,0,new P.Diff(U,f.substring(0,m))),e[i-1][1]=u.substring(0,u.length-m),e[i+1][1]=f.substring(m),i++):(d>=u.length/2||d>=f.length/2)&&(e.splice(i,0,new P.Diff(U,u.substring(0,d))),e[i-1][0]=Q,e[i-1][1]=f.substring(0,f.length-d),e[i+1][0]=J,e[i+1][1]=u.substring(d),i++),i++}i++}};P.prototype.diff_cleanupSemanticLossless=function(e){function t(d,p){if(!d||!p)return 6;var h=d.charAt(d.length-1),w=p.charAt(0),b=h.match(P.nonAlphaNumericRegex_),g=w.match(P.nonAlphaNumericRegex_),x=b&&h.match(P.whitespaceRegex_),v=g&&w.match(P.whitespaceRegex_),N=x&&h.match(P.linebreakRegex_),S=v&&w.match(P.linebreakRegex_),y=N&&d.match(P.blanklineEndRegex_),T=S&&p.match(P.blanklineStartRegex_);return y||T?5:N||S?4:b&&!x&&v?3:x||v?2:b||g?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==U&&e[r+1][0]==U){var n=e[r-1][1],o=e[r][1],i=e[r+1][1],a=this.diff_commonSuffix(n,o);if(a){var s=o.substring(o.length-a);n=n.substring(0,n.length-a),o=s+o.substring(0,o.length-a),i=s+i}for(var l=n,c=o,u=i,f=t(n,o)+t(o,i);o.charAt(0)===i.charAt(0);){n+=o.charAt(0),o=o.substring(1)+i.charAt(0),i=i.substring(1);var m=t(n,o)+t(o,i);m>=f&&(f=m,l=n,c=o,u=i)}e[r-1][1]!=l&&(l?e[r-1][1]=l:(e.splice(r-1,1),r--),e[r][1]=c,u?e[r+1][1]=u:(e.splice(r+1,1),r--))}r++}};P.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;P.whitespaceRegex_=/\s/;P.linebreakRegex_=/[\r\n]/;P.blanklineEndRegex_=/\n\r?\n$/;P.blanklineStartRegex_=/^\r?\n\r?\n/;P.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=!1,s=!1,l=!1,c=!1;i<e.length;)e[i][0]==U?(e[i][1].length<this.Diff_EditCost&&(l||c)?(r[n++]=i,a=l,s=c,o=e[i][1]):(n=0,o=null),l=c=!1):(e[i][0]==J?c=!0:l=!0,o&&(a&&s&&l&&c||o.length<this.Diff_EditCost/2&&a+s+l+c==3)&&(e.splice(r[n-1],0,new P.Diff(J,o)),e[r[n-1]+1][0]=Q,n--,o=null,a&&s?(l=c=!0,n=0):(n--,i=n>0?r[n-1]:-1,l=c=!1),t=!0)),i++;t&&this.diff_cleanupMerge(e)};P.prototype.diff_cleanupMerge=function(e){e.push(new P.Diff(U,""));for(var t=0,r=0,n=0,o="",i="",a;t<e.length;)switch(e[t][0]){case Q:n++,i+=e[t][1],t++;break;case J:r++,o+=e[t][1],t++;break;case U:r+n>1?(r!==0&&n!==0&&(a=this.diff_commonPrefix(i,o),a!==0&&(t-r-n>0&&e[t-r-n-1][0]==U?e[t-r-n-1][1]+=i.substring(0,a):(e.splice(0,0,new P.Diff(U,i.substring(0,a))),t++),i=i.substring(a),o=o.substring(a)),a=this.diff_commonSuffix(i,o),a!==0&&(e[t][1]=i.substring(i.length-a)+e[t][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a))),t-=r+n,e.splice(t,r+n),o.length&&(e.splice(t,0,new P.Diff(J,o)),t++),i.length&&(e.splice(t,0,new P.Diff(Q,i)),t++),t++):t!==0&&e[t-1][0]==U?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,o="",i="";break}e[e.length-1][1]===""&&e.pop();var s=!1;for(t=1;t<e.length-1;)e[t-1][0]==U&&e[t+1][0]==U&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),s=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),s=!0)),t++;s&&this.diff_cleanupMerge(e)};P.prototype.diff_xIndex=function(e,t){var r=0,n=0,o=0,i=0,a;for(a=0;a<e.length&&(e[a][0]!==Q&&(r+=e[a][1].length),e[a][0]!==J&&(n+=e[a][1].length),!(r>t));a++)o=r,i=n;return e.length!=a&&e[a][0]===J?i:i+(t-o)};P.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,o=/>/g,i=/\n/g,a=0;a<e.length;a++){var s=e[a][0],l=e[a][1],c=l.replace(r,"&").replace(n,"<").replace(o,">").replace(i,"¶<br>");switch(s){case Q:t[a]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case J:t[a]='<del style="background:#ffe6e6;">'+c+"</del>";break;case U:t[a]="<span>"+c+"</span>";break}}return t.join("")};P.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==Q&&(t[r]=e[r][1]);return t.join("")};P.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==J&&(t[r]=e[r][1]);return t.join("")};P.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,o=0;o<e.length;o++){var i=e[o][0],a=e[o][1];switch(i){case Q:r+=a.length;break;case J:n+=a.length;break;case U:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};P.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case Q:t[r]="+"+encodeURI(e[r][1]);break;case J:t[r]="-"+e[r][1].length;break;case U:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};P.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,o=0,i=t.split(/\t/g),a=0;a<i.length;a++){var s=i[a].substring(1);switch(i[a].charAt(0)){case"+":try{r[n++]=new P.Diff(Q,decodeURI(s))}catch{throw new Error("Illegal escape in diff_fromDelta: "+s)}break;case"-":case"=":var l=parseInt(s,10);if(isNaN(l)||l<0)throw new Error("Invalid number in diff_fromDelta: "+s);var c=e.substring(o,o+=l);i[a].charAt(0)=="="?r[n++]=new P.Diff(U,c):r[n++]=new P.Diff(J,c);break;default:if(i[a])throw new Error("Invalid diff operation in diff_fromDelta: "+i[a])}}if(o!=e.length)throw new Error("Delta length ("+o+") does not equal source text length ("+e.length+").");return r};P.prototype.match_main=function(e,t,r){if(e==null||t==null||r==null)throw new Error("Null input. (match_main)");return r=Math.max(0,Math.min(r,e.length)),e==t?0:e.length?e.substring(r,r+t.length)==t?r:this.match_bitap_(e,t,r):-1};P.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),o=this;function i(v,N){var S=v/t.length,y=Math.abs(r-N);return o.Match_Distance?S+y/o.Match_Distance:y?1:S}var a=this.Match_Threshold,s=e.indexOf(t,r);s!=-1&&(a=Math.min(i(0,s),a),s=e.lastIndexOf(t,r+t.length),s!=-1&&(a=Math.min(i(0,s),a)));var l=1<<t.length-1;s=-1;for(var c,u,f=t.length+e.length,m,d=0;d<t.length;d++){for(c=0,u=f;c<u;)i(d,r+u)<=a?c=u:f=u,u=Math.floor((f-c)/2+c);f=u;var p=Math.max(1,r-u+1),h=Math.min(r+u,e.length)+t.length,w=Array(h+2);w[h+1]=(1<<d)-1;for(var b=h;b>=p;b--){var g=n[e.charAt(b-1)];if(d===0?w[b]=(w[b+1]<<1|1)&g:w[b]=(w[b+1]<<1|1)&g|((m[b+1]|m[b])<<1|1)|m[b+1],w[b]&l){var x=i(d,b-1);if(x<=a)if(a=x,s=b-1,s>r)p=Math.max(1,2*r-s);else break}}if(i(d+1,r)>a)break;m=w}return s};P.prototype.match_alphabet_=function(e){for(var t={},r=0;r<e.length;r++)t[e.charAt(r)]=0;for(var r=0;r<e.length;r++)t[e.charAt(r)]|=1<<e.length-r-1;return t};P.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error("patch not initialized");for(var r=t.substring(e.start2,e.start2+e.length1),n=0;t.indexOf(r)!=t.lastIndexOf(r)&&r.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)n+=this.Patch_Margin,r=t.substring(e.start2-n,e.start2+e.length1+n);n+=this.Patch_Margin;var o=t.substring(e.start2-n,e.start2);o&&e.diffs.unshift(new P.Diff(U,o));var i=t.substring(e.start2+e.length1,e.start2+e.length1+n);i&&e.diffs.push(new P.Diff(U,i)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+i.length,e.length2+=o.length+i.length}};P.prototype.patch_make=function(e,t,r){var n,o;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,o=this.diff_main(n,t,!0),o.length>2&&(this.diff_cleanupSemantic(o),this.diff_cleanupEfficiency(o));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")o=e,n=this.diff_text1(o);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,o=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,o=r;else throw new Error("Unknown call format to patch_make.");if(o.length===0)return[];for(var i=[],a=new P.patch_obj,s=0,l=0,c=0,u=n,f=n,m=0;m<o.length;m++){var d=o[m][0],p=o[m][1];switch(!s&&d!==U&&(a.start1=l,a.start2=c),d){case Q:a.diffs[s++]=o[m],a.length2+=p.length,f=f.substring(0,c)+p+f.substring(c);break;case J:a.length1+=p.length,a.diffs[s++]=o[m],f=f.substring(0,c)+f.substring(c+p.length);break;case U:p.length<=2*this.Patch_Margin&&s&&o.length!=m+1?(a.diffs[s++]=o[m],a.length1+=p.length,a.length2+=p.length):p.length>=2*this.Patch_Margin&&s&&(this.patch_addContext_(a,u),i.push(a),a=new P.patch_obj,s=0,u=f,l=c);break}d!==Q&&(l+=p.length),d!==J&&(c+=p.length)}return s&&(this.patch_addContext_(a,u),i.push(a)),i};P.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new P.patch_obj;o.diffs=[];for(var i=0;i<n.diffs.length;i++)o.diffs[i]=new P.Diff(n.diffs[i][0],n.diffs[i][1]);o.start1=n.start1,o.start2=n.start2,o.length1=n.length1,o.length2=n.length2,t[r]=o}return t};P.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,o=[],i=0;i<e.length;i++){var a=e[i].start2+n,s=this.diff_text1(e[i].diffs),l,c=-1;if(s.length>this.Match_MaxBits?(l=this.match_main(t,s.substring(0,this.Match_MaxBits),a),l!=-1&&(c=this.match_main(t,s.substring(s.length-this.Match_MaxBits),a+s.length-this.Match_MaxBits),(c==-1||l>=c)&&(l=-1))):l=this.match_main(t,s,a),l==-1)o[i]=!1,n-=e[i].length2-e[i].length1;else{o[i]=!0,n=l-a;var u;if(c==-1?u=t.substring(l,l+s.length):u=t.substring(l,c+this.Match_MaxBits),s==u)t=t.substring(0,l)+this.diff_text2(e[i].diffs)+t.substring(l+s.length);else{var f=this.diff_main(s,u,!1);if(s.length>this.Match_MaxBits&&this.diff_levenshtein(f)/s.length>this.Patch_DeleteThreshold)o[i]=!1;else{this.diff_cleanupSemanticLossless(f);for(var m=0,d,p=0;p<e[i].diffs.length;p++){var h=e[i].diffs[p];h[0]!==U&&(d=this.diff_xIndex(f,m)),h[0]===Q?t=t.substring(0,l+d)+h[1]+t.substring(l+d):h[0]===J&&(t=t.substring(0,l+d)+t.substring(l+this.diff_xIndex(f,m+h[1].length))),h[0]!==J&&(m+=h[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};P.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var o=e[0],i=o.diffs;if(i.length==0||i[0][0]!=U)i.unshift(new P.Diff(U,r)),o.start1-=t,o.start2-=t,o.length1+=t,o.length2+=t;else if(t>i[0][1].length){var a=t-i[0][1].length;i[0][1]=r.substring(i[0][1].length)+i[0][1],o.start1-=a,o.start2-=a,o.length1+=a,o.length2+=a}if(o=e[e.length-1],i=o.diffs,i.length==0||i[i.length-1][0]!=U)i.push(new P.Diff(U,r)),o.length1+=t,o.length2+=t;else if(t>i[i.length-1][1].length){var a=t-i[i.length-1][1].length;i[i.length-1][1]+=r.substring(0,a),o.length1+=a,o.length2+=a}return r};P.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var o=n.start1,i=n.start2,a="";n.diffs.length!==0;){var s=new P.patch_obj,l=!0;for(s.start1=o-a.length,s.start2=i-a.length,a!==""&&(s.length1=s.length2=a.length,s.diffs.push(new P.Diff(U,a)));n.diffs.length!==0&&s.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],u=n.diffs[0][1];c===Q?(s.length2+=u.length,i+=u.length,s.diffs.push(n.diffs.shift()),l=!1):c===J&&s.diffs.length==1&&s.diffs[0][0]==U&&u.length>2*t?(s.length1+=u.length,o+=u.length,l=!1,s.diffs.push(new P.Diff(c,u)),n.diffs.shift()):(u=u.substring(0,t-s.length1-this.Patch_Margin),s.length1+=u.length,o+=u.length,c===U?(s.length2+=u.length,i+=u.length):l=!1,s.diffs.push(new P.Diff(c,u)),u==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(u.length))}a=this.diff_text2(s.diffs),a=a.substring(a.length-this.Patch_Margin);var f=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);f!==""&&(s.length1+=f.length,s.length2+=f.length,s.diffs.length!==0&&s.diffs[s.diffs.length-1][0]===U?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new P.Diff(U,f))),l||e.splice(++r,0,s)}}};P.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};P.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
|
|
3
|
-
`),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var
|
|
4
|
-
`],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case
|
|
5
|
-
`}return r.join("").replace(/%20/g," ")};
|
|
6
|
-
`)&&
|
|
7
|
-
`)&&
|
|
8
|
-
`:e}function
|
|
9
|
-
`:
|
|
10
|
-
`)},
|
|
11
|
-
`)}}function
|
|
12
|
-
`),c=
|
|
13
|
-
<w:numbering xmlns:w="${
|
|
1
|
+
var uf=Object.create;var Ns=Object.defineProperty;var ff=Object.getOwnPropertyDescriptor;var df=Object.getOwnPropertyNames;var mf=Object.getPrototypeOf,pf=Object.prototype.hasOwnProperty;var gf=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var hf=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of df(t))!pf.call(e,o)&&o!==r&&Ns(e,o,{get:()=>t[o],enumerable:!(n=ff(t,o))||n.enumerable});return e};var Is=(e,t,r)=>(r=e!=null?uf(mf(e)):{},hf(t||!e||!e.__esModule?Ns(r,"default",{value:e,enumerable:!0}):r,e));var Ha=gf((jh,Gr)=>{var F=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},me=-1,he=1,Q=0;F.Diff=function(e,t){return[e,t]};F.prototype.diff_main=function(e,t,r,n){typeof n>"u"&&(this.Diff_Timeout<=0?n=Number.MAX_VALUE:n=new Date().getTime()+this.Diff_Timeout*1e3);var o=n;if(e==null||t==null)throw new Error("Null input. (diff_main)");if(e==t)return e?[new F.Diff(Q,e)]:[];typeof r>"u"&&(r=!0);var a=r,i=this.diff_commonPrefix(e,t),s=e.substring(0,i);e=e.substring(i),t=t.substring(i),i=this.diff_commonSuffix(e,t);var l=e.substring(e.length-i);e=e.substring(0,e.length-i),t=t.substring(0,t.length-i);var c=this.diff_compute_(e,t,a,o);return s&&c.unshift(new F.Diff(Q,s)),l&&c.push(new F.Diff(Q,l)),this.diff_cleanupMerge(c),c};F.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new F.Diff(he,t)];if(!t)return[new F.Diff(me,e)];var a=e.length>t.length?e:t,i=e.length>t.length?t:e,s=a.indexOf(i);if(s!=-1)return o=[new F.Diff(he,a.substring(0,s)),new F.Diff(Q,i),new F.Diff(he,a.substring(s+i.length))],e.length>t.length&&(o[0][0]=o[2][0]=me),o;if(i.length==1)return[new F.Diff(me,e),new F.Diff(he,t)];var l=this.diff_halfMatch_(e,t);if(l){var c=l[0],u=l[1],f=l[2],d=l[3],m=l[4],p=this.diff_main(c,f,r,n),g=this.diff_main(u,d,r,n);return p.concat([new F.Diff(Q,m)],g)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};F.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var o=n.lineArray,a=this.diff_main(e,t,!1,r);this.diff_charsToLines_(a,o),this.diff_cleanupSemantic(a),a.push(new F.Diff(Q,""));for(var i=0,s=0,l=0,c="",u="";i<a.length;){switch(a[i][0]){case he:l++,u+=a[i][1];break;case me:s++,c+=a[i][1];break;case Q:if(s>=1&&l>=1){a.splice(i-s-l,s+l),i=i-s-l;for(var f=this.diff_main(c,u,!1,r),d=f.length-1;d>=0;d--)a.splice(i,0,f[d]);i=i+f.length}l=0,s=0,c="",u="";break}i++}return a.pop(),a};F.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,o=t.length,a=Math.ceil((n+o)/2),i=a,s=2*a,l=new Array(s),c=new Array(s),u=0;u<s;u++)l[u]=-1,c[u]=-1;l[i+1]=0,c[i+1]=0;for(var f=n-o,d=f%2!=0,m=0,p=0,g=0,h=0,y=0;y<a&&!(new Date().getTime()>r);y++){for(var w=-y+m;w<=y-p;w+=2){var v=i+w,b;w==-y||w!=y&&l[v-1]<l[v+1]?b=l[v+1]:b=l[v-1]+1;for(var x=b-w;b<n&&x<o&&e.charAt(b)==t.charAt(x);)b++,x++;if(l[v]=b,b>n)p+=2;else if(x>o)m+=2;else if(d){var I=i+f-w;if(I>=0&&I<s&&c[I]!=-1){var N=n-c[I];if(b>=N)return this.diff_bisectSplit_(e,t,b,x,r)}}}for(var T=-y+g;T<=y-h;T+=2){var I=i+T,N;T==-y||T!=y&&c[I-1]<c[I+1]?N=c[I+1]:N=c[I-1]+1;for(var E=N-T;N<n&&E<o&&e.charAt(n-N-1)==t.charAt(o-E-1);)N++,E++;if(c[I]=N,N>n)h+=2;else if(E>o)g+=2;else if(!d){var v=i+f-T;if(v>=0&&v<s&&l[v]!=-1){var b=l[v],x=i+b-v;if(N=n-N,b>=N)return this.diff_bisectSplit_(e,t,b,x,r)}}}}return[new F.Diff(me,e),new F.Diff(he,t)]};F.prototype.diff_bisectSplit_=function(e,t,r,n,o){var a=e.substring(0,r),i=t.substring(0,n),s=e.substring(r),l=t.substring(n),c=this.diff_main(a,i,!1,o),u=this.diff_main(s,l,!1,o);return c.concat(u)};F.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(l){for(var c="",u=0,f=-1,d=r.length;f<l.length-1;){f=l.indexOf(`
|
|
2
|
+
`,u),f==-1&&(f=l.length-1);var m=l.substring(u,f+1);(n.hasOwnProperty?n.hasOwnProperty(m):n[m]!==void 0)?c+=String.fromCharCode(n[m]):(d==a&&(m=l.substring(u),f=l.length),c+=String.fromCharCode(d),n[m]=d,r[d++]=m),u=f+1}return c}var a=4e4,i=o(e);a=65535;var s=o(t);return{chars1:i,chars2:s,lineArray:r}};F.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],o=[],a=0;a<n.length;a++)o[a]=t[n.charCodeAt(a)];e[r][1]=o.join("")}};F.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(a,o)==t.substring(a,o)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};F.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(e.length-o,e.length-a)==t.substring(t.length-o,t.length-a)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};F.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var o=Math.min(r,n);if(e==t)return o;for(var a=0,i=1;;){var s=e.substring(o-i),l=t.indexOf(s);if(l==-1)return a;i+=l,(l==0||e.substring(o-i)==t.substring(0,i))&&(a=i,i++)}};F.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var o=this;function a(p,g,h){for(var y=p.substring(h,h+Math.floor(p.length/4)),w=-1,v="",b,x,I,N;(w=g.indexOf(y,w+1))!=-1;){var T=o.diff_commonPrefix(p.substring(h),g.substring(w)),E=o.diff_commonSuffix(p.substring(0,h),g.substring(0,w));v.length<E+T&&(v=g.substring(w-E,w)+g.substring(w,w+T),b=p.substring(0,h-E),x=p.substring(h+T),I=g.substring(0,w-E),N=g.substring(w+T))}return v.length*2>=p.length?[b,x,I,N,v]:null}var i=a(r,n,Math.ceil(r.length/4)),s=a(r,n,Math.ceil(r.length/2)),l;if(!i&&!s)return null;s?i?l=i[4].length>s[4].length?i:s:l=s:l=i;var c,u,f,d;e.length>t.length?(c=l[0],u=l[1],f=l[2],d=l[3]):(f=l[0],d=l[1],c=l[2],u=l[3]);var m=l[4];return[c,u,f,d,m]};F.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=0,s=0,l=0,c=0;a<e.length;)e[a][0]==Q?(r[n++]=a,i=l,s=c,l=0,c=0,o=e[a][1]):(e[a][0]==he?l+=e[a][1].length:c+=e[a][1].length,o&&o.length<=Math.max(i,s)&&o.length<=Math.max(l,c)&&(e.splice(r[n-1],0,new F.Diff(me,o)),e[r[n-1]+1][0]=he,n--,n--,a=n>0?r[n-1]:-1,i=0,s=0,l=0,c=0,o=null,t=!0)),a++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),a=1;a<e.length;){if(e[a-1][0]==me&&e[a][0]==he){var u=e[a-1][1],f=e[a][1],d=this.diff_commonOverlap_(u,f),m=this.diff_commonOverlap_(f,u);d>=m?(d>=u.length/2||d>=f.length/2)&&(e.splice(a,0,new F.Diff(Q,f.substring(0,d))),e[a-1][1]=u.substring(0,u.length-d),e[a+1][1]=f.substring(d),a++):(m>=u.length/2||m>=f.length/2)&&(e.splice(a,0,new F.Diff(Q,u.substring(0,m))),e[a-1][0]=he,e[a-1][1]=f.substring(0,f.length-m),e[a+1][0]=me,e[a+1][1]=u.substring(m),a++),a++}a++}};F.prototype.diff_cleanupSemanticLossless=function(e){function t(m,p){if(!m||!p)return 6;var g=m.charAt(m.length-1),h=p.charAt(0),y=g.match(F.nonAlphaNumericRegex_),w=h.match(F.nonAlphaNumericRegex_),v=y&&g.match(F.whitespaceRegex_),b=w&&h.match(F.whitespaceRegex_),x=v&&g.match(F.linebreakRegex_),I=b&&h.match(F.linebreakRegex_),N=x&&m.match(F.blanklineEndRegex_),T=I&&p.match(F.blanklineStartRegex_);return N||T?5:x||I?4:y&&!v&&b?3:v||b?2:y||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==Q&&e[r+1][0]==Q){var n=e[r-1][1],o=e[r][1],a=e[r+1][1],i=this.diff_commonSuffix(n,o);if(i){var s=o.substring(o.length-i);n=n.substring(0,n.length-i),o=s+o.substring(0,o.length-i),a=s+a}for(var l=n,c=o,u=a,f=t(n,o)+t(o,a);o.charAt(0)===a.charAt(0);){n+=o.charAt(0),o=o.substring(1)+a.charAt(0),a=a.substring(1);var d=t(n,o)+t(o,a);d>=f&&(f=d,l=n,c=o,u=a)}e[r-1][1]!=l&&(l?e[r-1][1]=l:(e.splice(r-1,1),r--),e[r][1]=c,u?e[r+1][1]=u:(e.splice(r+1,1),r--))}r++}};F.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;F.whitespaceRegex_=/\s/;F.linebreakRegex_=/[\r\n]/;F.blanklineEndRegex_=/\n\r?\n$/;F.blanklineStartRegex_=/^\r?\n\r?\n/;F.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=!1,s=!1,l=!1,c=!1;a<e.length;)e[a][0]==Q?(e[a][1].length<this.Diff_EditCost&&(l||c)?(r[n++]=a,i=l,s=c,o=e[a][1]):(n=0,o=null),l=c=!1):(e[a][0]==me?c=!0:l=!0,o&&(i&&s&&l&&c||o.length<this.Diff_EditCost/2&&i+s+l+c==3)&&(e.splice(r[n-1],0,new F.Diff(me,o)),e[r[n-1]+1][0]=he,n--,o=null,i&&s?(l=c=!0,n=0):(n--,a=n>0?r[n-1]:-1,l=c=!1),t=!0)),a++;t&&this.diff_cleanupMerge(e)};F.prototype.diff_cleanupMerge=function(e){e.push(new F.Diff(Q,""));for(var t=0,r=0,n=0,o="",a="",i;t<e.length;)switch(e[t][0]){case he:n++,a+=e[t][1],t++;break;case me:r++,o+=e[t][1],t++;break;case Q:r+n>1?(r!==0&&n!==0&&(i=this.diff_commonPrefix(a,o),i!==0&&(t-r-n>0&&e[t-r-n-1][0]==Q?e[t-r-n-1][1]+=a.substring(0,i):(e.splice(0,0,new F.Diff(Q,a.substring(0,i))),t++),a=a.substring(i),o=o.substring(i)),i=this.diff_commonSuffix(a,o),i!==0&&(e[t][1]=a.substring(a.length-i)+e[t][1],a=a.substring(0,a.length-i),o=o.substring(0,o.length-i))),t-=r+n,e.splice(t,r+n),o.length&&(e.splice(t,0,new F.Diff(me,o)),t++),a.length&&(e.splice(t,0,new F.Diff(he,a)),t++),t++):t!==0&&e[t-1][0]==Q?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,o="",a="";break}e[e.length-1][1]===""&&e.pop();var s=!1;for(t=1;t<e.length-1;)e[t-1][0]==Q&&e[t+1][0]==Q&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),s=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),s=!0)),t++;s&&this.diff_cleanupMerge(e)};F.prototype.diff_xIndex=function(e,t){var r=0,n=0,o=0,a=0,i;for(i=0;i<e.length&&(e[i][0]!==he&&(r+=e[i][1].length),e[i][0]!==me&&(n+=e[i][1].length),!(r>t));i++)o=r,a=n;return e.length!=i&&e[i][0]===me?a:a+(t-o)};F.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,o=/>/g,a=/\n/g,i=0;i<e.length;i++){var s=e[i][0],l=e[i][1],c=l.replace(r,"&").replace(n,"<").replace(o,">").replace(a,"¶<br>");switch(s){case he:t[i]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case me:t[i]='<del style="background:#ffe6e6;">'+c+"</del>";break;case Q:t[i]="<span>"+c+"</span>";break}}return t.join("")};F.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==he&&(t[r]=e[r][1]);return t.join("")};F.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==me&&(t[r]=e[r][1]);return t.join("")};F.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,o=0;o<e.length;o++){var a=e[o][0],i=e[o][1];switch(a){case he:r+=i.length;break;case me:n+=i.length;break;case Q:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};F.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case he:t[r]="+"+encodeURI(e[r][1]);break;case me:t[r]="-"+e[r][1].length;break;case Q:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};F.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,o=0,a=t.split(/\t/g),i=0;i<a.length;i++){var s=a[i].substring(1);switch(a[i].charAt(0)){case"+":try{r[n++]=new F.Diff(he,decodeURI(s))}catch{throw new Error("Illegal escape in diff_fromDelta: "+s)}break;case"-":case"=":var l=parseInt(s,10);if(isNaN(l)||l<0)throw new Error("Invalid number in diff_fromDelta: "+s);var c=e.substring(o,o+=l);a[i].charAt(0)=="="?r[n++]=new F.Diff(Q,c):r[n++]=new F.Diff(me,c);break;default:if(a[i])throw new Error("Invalid diff operation in diff_fromDelta: "+a[i])}}if(o!=e.length)throw new Error("Delta length ("+o+") does not equal source text length ("+e.length+").");return r};F.prototype.match_main=function(e,t,r){if(e==null||t==null||r==null)throw new Error("Null input. (match_main)");return r=Math.max(0,Math.min(r,e.length)),e==t?0:e.length?e.substring(r,r+t.length)==t?r:this.match_bitap_(e,t,r):-1};F.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),o=this;function a(b,x){var I=b/t.length,N=Math.abs(r-x);return o.Match_Distance?I+N/o.Match_Distance:N?1:I}var i=this.Match_Threshold,s=e.indexOf(t,r);s!=-1&&(i=Math.min(a(0,s),i),s=e.lastIndexOf(t,r+t.length),s!=-1&&(i=Math.min(a(0,s),i)));var l=1<<t.length-1;s=-1;for(var c,u,f=t.length+e.length,d,m=0;m<t.length;m++){for(c=0,u=f;c<u;)a(m,r+u)<=i?c=u:f=u,u=Math.floor((f-c)/2+c);f=u;var p=Math.max(1,r-u+1),g=Math.min(r+u,e.length)+t.length,h=Array(g+2);h[g+1]=(1<<m)-1;for(var y=g;y>=p;y--){var w=n[e.charAt(y-1)];if(m===0?h[y]=(h[y+1]<<1|1)&w:h[y]=(h[y+1]<<1|1)&w|((d[y+1]|d[y])<<1|1)|d[y+1],h[y]&l){var v=a(m,y-1);if(v<=i)if(i=v,s=y-1,s>r)p=Math.max(1,2*r-s);else break}}if(a(m+1,r)>i)break;d=h}return s};F.prototype.match_alphabet_=function(e){for(var t={},r=0;r<e.length;r++)t[e.charAt(r)]=0;for(var r=0;r<e.length;r++)t[e.charAt(r)]|=1<<e.length-r-1;return t};F.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error("patch not initialized");for(var r=t.substring(e.start2,e.start2+e.length1),n=0;t.indexOf(r)!=t.lastIndexOf(r)&&r.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)n+=this.Patch_Margin,r=t.substring(e.start2-n,e.start2+e.length1+n);n+=this.Patch_Margin;var o=t.substring(e.start2-n,e.start2);o&&e.diffs.unshift(new F.Diff(Q,o));var a=t.substring(e.start2+e.length1,e.start2+e.length1+n);a&&e.diffs.push(new F.Diff(Q,a)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+a.length,e.length2+=o.length+a.length}};F.prototype.patch_make=function(e,t,r){var n,o;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,o=this.diff_main(n,t,!0),o.length>2&&(this.diff_cleanupSemantic(o),this.diff_cleanupEfficiency(o));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")o=e,n=this.diff_text1(o);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,o=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,o=r;else throw new Error("Unknown call format to patch_make.");if(o.length===0)return[];for(var a=[],i=new F.patch_obj,s=0,l=0,c=0,u=n,f=n,d=0;d<o.length;d++){var m=o[d][0],p=o[d][1];switch(!s&&m!==Q&&(i.start1=l,i.start2=c),m){case he:i.diffs[s++]=o[d],i.length2+=p.length,f=f.substring(0,c)+p+f.substring(c);break;case me:i.length1+=p.length,i.diffs[s++]=o[d],f=f.substring(0,c)+f.substring(c+p.length);break;case Q:p.length<=2*this.Patch_Margin&&s&&o.length!=d+1?(i.diffs[s++]=o[d],i.length1+=p.length,i.length2+=p.length):p.length>=2*this.Patch_Margin&&s&&(this.patch_addContext_(i,u),a.push(i),i=new F.patch_obj,s=0,u=f,l=c);break}m!==he&&(l+=p.length),m!==me&&(c+=p.length)}return s&&(this.patch_addContext_(i,u),a.push(i)),a};F.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new F.patch_obj;o.diffs=[];for(var a=0;a<n.diffs.length;a++)o.diffs[a]=new F.Diff(n.diffs[a][0],n.diffs[a][1]);o.start1=n.start1,o.start2=n.start2,o.length1=n.length1,o.length2=n.length2,t[r]=o}return t};F.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,o=[],a=0;a<e.length;a++){var i=e[a].start2+n,s=this.diff_text1(e[a].diffs),l,c=-1;if(s.length>this.Match_MaxBits?(l=this.match_main(t,s.substring(0,this.Match_MaxBits),i),l!=-1&&(c=this.match_main(t,s.substring(s.length-this.Match_MaxBits),i+s.length-this.Match_MaxBits),(c==-1||l>=c)&&(l=-1))):l=this.match_main(t,s,i),l==-1)o[a]=!1,n-=e[a].length2-e[a].length1;else{o[a]=!0,n=l-i;var u;if(c==-1?u=t.substring(l,l+s.length):u=t.substring(l,c+this.Match_MaxBits),s==u)t=t.substring(0,l)+this.diff_text2(e[a].diffs)+t.substring(l+s.length);else{var f=this.diff_main(s,u,!1);if(s.length>this.Match_MaxBits&&this.diff_levenshtein(f)/s.length>this.Patch_DeleteThreshold)o[a]=!1;else{this.diff_cleanupSemanticLossless(f);for(var d=0,m,p=0;p<e[a].diffs.length;p++){var g=e[a].diffs[p];g[0]!==Q&&(m=this.diff_xIndex(f,d)),g[0]===he?t=t.substring(0,l+m)+g[1]+t.substring(l+m):g[0]===me&&(t=t.substring(0,l+m)+t.substring(l+this.diff_xIndex(f,d+g[1].length))),g[0]!==me&&(d+=g[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};F.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var o=e[0],a=o.diffs;if(a.length==0||a[0][0]!=Q)a.unshift(new F.Diff(Q,r)),o.start1-=t,o.start2-=t,o.length1+=t,o.length2+=t;else if(t>a[0][1].length){var i=t-a[0][1].length;a[0][1]=r.substring(a[0][1].length)+a[0][1],o.start1-=i,o.start2-=i,o.length1+=i,o.length2+=i}if(o=e[e.length-1],a=o.diffs,a.length==0||a[a.length-1][0]!=Q)a.push(new F.Diff(Q,r)),o.length1+=t,o.length2+=t;else if(t>a[a.length-1][1].length){var i=t-a[a.length-1][1].length;a[a.length-1][1]+=r.substring(0,i),o.length1+=i,o.length2+=i}return r};F.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var o=n.start1,a=n.start2,i="";n.diffs.length!==0;){var s=new F.patch_obj,l=!0;for(s.start1=o-i.length,s.start2=a-i.length,i!==""&&(s.length1=s.length2=i.length,s.diffs.push(new F.Diff(Q,i)));n.diffs.length!==0&&s.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],u=n.diffs[0][1];c===he?(s.length2+=u.length,a+=u.length,s.diffs.push(n.diffs.shift()),l=!1):c===me&&s.diffs.length==1&&s.diffs[0][0]==Q&&u.length>2*t?(s.length1+=u.length,o+=u.length,l=!1,s.diffs.push(new F.Diff(c,u)),n.diffs.shift()):(u=u.substring(0,t-s.length1-this.Patch_Margin),s.length1+=u.length,o+=u.length,c===Q?(s.length2+=u.length,a+=u.length):l=!1,s.diffs.push(new F.Diff(c,u)),u==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(u.length))}i=this.diff_text2(s.diffs),i=i.substring(i.length-this.Patch_Margin);var f=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);f!==""&&(s.length1+=f.length,s.length2+=f.length,s.diffs.length!==0&&s.diffs[s.diffs.length-1][0]===Q?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new F.Diff(Q,f))),l||e.splice(++r,0,s)}}};F.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};F.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
|
|
3
|
+
`),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var a=r[n].match(o);if(!a)throw new Error("Invalid patch string: "+r[n]);var i=new F.patch_obj;for(t.push(i),i.start1=parseInt(a[1],10),a[2]===""?(i.start1--,i.length1=1):a[2]=="0"?i.length1=0:(i.start1--,i.length1=parseInt(a[2],10)),i.start2=parseInt(a[3],10),a[4]===""?(i.start2--,i.length2=1):a[4]=="0"?i.length2=0:(i.start2--,i.length2=parseInt(a[4],10)),n++;n<r.length;){var s=r[n].charAt(0);try{var l=decodeURI(r[n].substring(1))}catch{throw new Error("Illegal escape in patch_fromText: "+l)}if(s=="-")i.diffs.push(new F.Diff(me,l));else if(s=="+")i.diffs.push(new F.Diff(he,l));else if(s==" ")i.diffs.push(new F.Diff(Q,l));else{if(s=="@")break;if(s!=="")throw new Error('Invalid patch mode "'+s+'" in: '+l)}n++}}return t};F.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};F.patch_obj.prototype.toString=function(){var e,t;this.length1===0?e=this.start1+",0":this.length1==1?e=this.start1+1:e=this.start1+1+","+this.length1,this.length2===0?t=this.start2+",0":this.length2==1?t=this.start2+1:t=this.start2+1+","+this.length2;for(var r=["@@ -"+e+" +"+t+` @@
|
|
4
|
+
`],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case he:n="+";break;case me:n="-";break;case Q:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
|
|
5
|
+
`}return r.join("").replace(/%20/g," ")};Gr.exports=F;Gr.exports.diff_match_patch=F;Gr.exports.DIFF_DELETE=me;Gr.exports.DIFF_INSERT=he;Gr.exports.DIFF_EQUAL=Q});import{DOMParser as xf,XMLSerializer as bf}from"@xmldom/xmldom";var wo=console,Ma=Object.freeze({silent:0,error:1,warn:2,info:3}),wf=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",La=wf;function yf(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(Ma,t)?t:La}function Ba(e){return Ma[La]>=Ma[e]}function vf(e,t={}){wo=e||console,t.level&&(La=yf(t.level))}function K(...e){Ba("info")&&(wo.log||(()=>{}))(...e)}function vt(...e){Ba("warn")&&(wo.warn||(()=>{}))(...e)}function Ne(...e){Ba("error")&&(wo.error||(()=>{}))(...e)}var Ts=null,Ss=null;function Nf(e={}){"DOMParser"in e&&(Ts=e.DOMParser),"XMLSerializer"in e&&(Ss=e.XMLSerializer)}function If(){return Ts||globalThis.DOMParser||xf}function Tf(){return Ss||globalThis.XMLSerializer||bf}function Sf(e={}){let t=If();if(!t)throw new Error("DOMParser is not configured and no fallback XML parser is available.");return new t(e)}function oe(){let e=Tf();if(!e)throw new Error("XMLSerializer is not configured and no fallback XML serializer is available.");return new e}function Es(e,t="text/xml"){let r=W(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function Ef(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function W(e,t="application/xml"){let r=[];if(typeof e!="string"||e.trim()==="")return{doc:null,error:{code:"PARSE_ERROR",message:"Input is not a non-empty XML string."},warnings:r};let n=(o,a)=>{let i=String(a||"XML parser diagnostic.");o==="fatalError"?Ne("[XmlAdapter] XML fatal parse error:",i):(r.push(i),vt(`[XmlAdapter] XML ${o||"warning"}:`,i))};try{let a=Sf({onError:n}).parseFromString(e,t),i=Ef(a);if(!a?.documentElement||i){let s=i?.textContent||"Could not parse XML input.";return Ne("[XmlAdapter] XML parse error:",s),{doc:null,error:{code:"PARSE_ERROR",message:s},warnings:r}}return{doc:a,error:null,warnings:r}}catch(o){let a=o?.message||String(o||"Could not parse XML input.");return Ne("[XmlAdapter] XML parse error:",a),{doc:null,error:{code:"PARSE_ERROR",message:a},warnings:r}}}function Ie(e){return oe().serializeToString(e)}var As=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",Rs=As(),Ps="Unknown";function Af(e){Rs=typeof e=="string"&&e.trim()?e.trim():As()}function re(){return Rs}function Rf(e){Ps=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function Da(){return Ps}var Pf=[{regex:/<b>(.+?)<\/b>/i,format:{bold:!0}},{regex:/<strong>(.+?)<\/strong>/i,format:{bold:!0}},{regex:/<i>(.+?)<\/i>/i,format:{italic:!0}},{regex:/<em>(.+?)<\/em>/i,format:{italic:!0}},{regex:/<u>(.+?)<\/u>/i,format:{underline:!0}},{regex:/<s>(.+?)<\/s>/i,format:{strikethrough:!0}},{regex:/<strike>(.+?)<\/strike>/i,format:{strikethrough:!0}},{regex:/<del>(.+?)<\/del>/i,format:{strikethrough:!0}},{regex:/<b>(.+?)<\/b>/i,format:{bold:!0},isEscaped:!0},{regex:/<strong>(.+?)<\/strong>/i,format:{bold:!0},isEscaped:!0},{regex:/<i>(.+?)<\/i>/i,format:{italic:!0},isEscaped:!0},{regex:/<em>(.+?)<\/em>/i,format:{italic:!0},isEscaped:!0},{regex:/<u>(.+?)<\/u>/i,format:{underline:!0},isEscaped:!0},{regex:/<s>(.+?)<\/s>/i,format:{strikethrough:!0},isEscaped:!0},{regex:/\*\*\*(.+?)\*\*\*/,format:{bold:!0,italic:!0}},{regex:/\*\*\+\+(.+?)\+\+\*\*/,format:{bold:!0,underline:!0}},{regex:/\*\*(.+?)\*\*/,format:{bold:!0}},{regex:/__(.+?)__/,format:{bold:!0}},{regex:/\+\+(.+?)\+\+/,format:{underline:!0}},{regex:/~~(.+?)~~/,format:{strikethrough:!0}},{regex:/~(.+?)~/,format:{strikethrough:!0}},{regex:/\*(?!\*)(.+?)\*(?!\*)/,format:{italic:!0}},{regex:/_(?!_)(.+?)_(?!_)/,format:{italic:!0}}];function Je(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let s of Pf){let l,c=s.regex.source||s.regex.toString().replace(/^\/|\/[gimuy]*$/g,""),u="g"+(s.regex.ignoreCase?"i":""),f=new RegExp(c,u);for(;(l=f.exec(e))!==null;)n.push({start:l.index,end:l.index+l[0].length,fullMatch:l[0],innerText:s.isEscaped?Cf(l[1]):l[1],format:s.format}),l.index===f.lastIndex&&f.lastIndex++}n.sort((s,l)=>s.start-l.start||l.end-s.end);let o=[],a=0;for(let s of n)s.start>=a&&(o.push(s),a=s.end);let i=0;for(let s of o){r+=e.slice(i,s.start);let l=Je(s.innerText),c=r.length;r+=l.cleanText;let u=r.length;t.push({start:c,end:u,format:s.format});for(let f of l.formatHints)t.push({start:c+f.start,end:c+f.end,format:f.format});i=s.end}return r+=e.slice(i),{cleanText:r,formatHints:t}}function Bt(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function Fa(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function Cf(e){return e?e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'"):""}var yo=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,Cs=new RegExp(`^(\\s*)((?:${yo})\\s+)`),Os=new RegExp(`^(\\s*)((?:${yo})\\s*)`),Of=new RegExp(`^(\\s*)((?:${yo})\\s+)`,"m"),_f=new RegExp(`^(\\s*)((?:${yo})\\s*)`,"m");function $a(e){return typeof e!="string"?!1:e.includes(`
|
|
6
|
+
`)&&Of.test(e)}function bn(e){return typeof e!="string"?!1:e.includes(`
|
|
7
|
+
`)&&_f.test(e.trim())}function xt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Os:Cs;return e.match(n)}function Rt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Os:Cs;return e.replace(n,"")}function _s(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function Nn(e){let t=String(e||"").trim();return _s(t)==="bullet"?"bullet":/^\d+(?:\.\d+)*\.?$/.test(t)||/^\(\d+\)$/.test(t)?"decimal":/^[ivxlcdm]+\.$/.test(t)?"lowerRoman":/^[IVXLCDM]{2,}\.$/.test(t)?"upperRoman":/^[a-z]\.$/.test(t)?"lowerAlpha":/^[A-Z]\.$/.test(t)?"upperAlpha":"decimal"}function kf(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function In(e,t={}){let r=xt(String(e||""),t);if(!r)return null;let n=r[2].trim(),o=(r[1]||"").length,a=Math.max(1,Number(t.indentSpaces)||2),i=_s(n);return{line:String(e||""),text:Rt(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/a)),markerType:i,listType:i,numberingStyle:Nn(n),outlineLevel:i==="numbered"?kf(n):null}}var L="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var mt=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),Z=Object.freeze({TEXT:"run",DELETION:"deletion",INSERTION:"insertion",HYPERLINK:"hyperlink",BOOKMARK:"bookmark",FIELD:"field",CONTAINER_START:"container_start",CONTAINER_END:"container_end",PARAGRAPH_START:"paragraph_start"}),Wr=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),Ls=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),de=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),Le=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function ze(e){return e?e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}var Ua=1e3,ks=2147483647,Ms=1e4,Mf=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Bs=new WeakMap;function Lf(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return Mf.has(t)?!e.namespaceURI||e.namespaceURI===L||String(e.nodeName||"").startsWith("w:"):!1}function Bf(e){let t=e?.getAttributeNS?.(L,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var Ae=class{constructor(t=Ua){this.startValue=Number.isInteger(t)&&t>=0?t:Ua,this.nextId=this.startValue,this.occupiedIds=new Set}seed(t){let r=-1,n=t?.nodeType===9?t.documentElement:t,o=n||null;for(;o;){if(Lf(o)){let i=Bf(o);i!=null&&(this.occupiedIds.add(i),r=Math.max(r,i))}if(o.firstChild){o=o.firstChild;continue}for(;o&&o!==n&&!o.nextSibling;)o=o.parentNode;o=o&&o!==n?o.nextSibling:null}let a=ks-Ms;return this.nextId=r>=a?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=ks-Ms;for(this.nextId>=t&&(this.nextId=this.startValue);this.occupiedIds.has(this.nextId);)this.nextId+=1,this.nextId>=t&&(this.nextId=this.startValue)}next(){this.advanceToAvailableId();let t=this.nextId;return this.occupiedIds.add(t),this.nextId+=1,t}},Tn=new Ae;function er(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof Ae&&Bs.set(r,t),t}function Dt(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Bs.get(t)||null}function tr(e,t=Ua){let r=new Ae(t);return r.seed(e),er(e,r),r}function Ds(){return Tn.next()}function vo(e=new Date){return e.toISOString()}function ie(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():re(),o=t instanceof Ae?t:Dt(t)||Tn,a=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(a,r||"structural"),{id:a,author:n,date:vo()}}function Sn(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():re(),n=t instanceof Ae?t:Dt(t)||Tn,o=vo(),a=n.next(),i=n.next();return n._receiptCollector&&(n._receiptCollector.recordRevision(a,"del"),n._receiptCollector.recordRevision(i,"ins")),{deletionId:a,insertionId:i,author:r,date:o}}function Ft(e,t=Tn){let r=t instanceof Ae?t:Tn,n=r.seed(e);return er(e,r),n}function Fs(e,t){return e<t-1}function jr(e,t,r){return Fs(t,r)?e+`
|
|
8
|
+
`:e}function hr(e,t,r){return Fs(t,r)?e+1:e}function En(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function Re(e,t){if(!e||typeof e.getElementsByTagName!="function")return null;let r=e.getElementsByTagName(t);return r.length>0?r[0]:null}function Ce(e,t,r){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(t,r))}function Te(e,t,r){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let n=e.getElementsByTagNameNS(t,r);return n.length>0?n[0]:null}function Xe(e,t,r,n=`w:${r}`){let o=Ce(e,t,r);return o.length>0?o:En(e,n)}function Ve(e,t,r,n=`w:${r}`){let o=Te(e,t,r);return o||Re(e,n)}function Se(e){return Re(e,"parsererror")}function za(e){return Array.from(e?.childNodes||[])}function $s(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Xa(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var Va=0;function Hr(e,t={}){let r=[],n="",o=t.xmlDoc||null;if(!e&&!o)return{runModel:r,acceptedText:n,pPr:null};try{let a=o?{doc:o,error:null}:W(e,"application/xml"),i=a.doc;if(a.error||!i)return Ne("OOXML parse error:",a.error?.message),{runModel:r,acceptedText:n,pPr:null,error:a.error};let s=Se(i);if(s)return Ne("OOXML parse error:",s.textContent),{runModel:r,acceptedText:n,pPr:null};let l=Ce(i,L,"p");return l.length===0?(vt("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):zs(l,{includeParagraphBoundaries:!0})}catch(a){return Ne("Error ingesting OOXML:",a),{runModel:r,acceptedText:n,pPr:null}}}function Wa(e){return e?zs([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function An(e){let t=Te(e,L,"pPr");if(!t)return null;let r=Te(t,L,"numPr");if(!r)return null;let n=Te(r,L,"numId"),o=Te(r,L,"ilvl");if(!n)return null;let a=n.getAttribute("w:val");if(!/^\d+$/.test(a)||Number.parseInt(a,10)===0)return null;let i=a==="1"?"bullet":a==="2"?"numbered":"unknown";return{numId:a,ilvl:parseInt(o?.getAttribute("w:val")||"0",10),type:i}}function zs(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],o="",a=0,i=null;for(let s=0;s<e.length;s++){let l=e[s],c=Te(l,L,"pPr");s===0&&(i=c),n.push({kind:Z.PARAGRAPH_START,pPrElement:c||null,startOffset:a,endOffset:a,text:""});let u=Kr(l,a,n);o+=u.text,a=o.length,r&&(o=jr(o,s,e.length),a=hr(a,s,e.length))}return{runModel:n,acceptedText:o,pPr:i}}function Kr(e,t,r){let n=t,o="",a=Df(r);for(let i of za(e)){if(Xa(i,L,"pPr")||Xa(i,L,"proofErr"))continue;let s=a.get(i.localName);if(!s)continue;let l=s(i,n);n=l.offset,o+=l.text}return{offset:n,text:o}}function Df(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${Va++}`,a=Te(r,L,"sdtPr"),i=Te(r,L,"sdtContent");e.push({kind:Z.CONTAINER_START,containerKind:Wr.SDT,containerId:o,propertiesXml:a?Ie(a):"",startOffset:n,endOffset:n,text:""});let s=i?Kr(i,n,e):{offset:n,text:""};return e.push({kind:Z.CONTAINER_END,containerKind:Wr.SDT,containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("smartTag",(r,n)=>{let o=`smartTag_${Va++}`;e.push({kind:Z.CONTAINER_START,containerKind:Wr.SMART_TAG,containerId:o,propertiesXml:$s(r),startOffset:n,endOffset:n,text:""});let a=Kr(r,n,e);return e.push({kind:Z.CONTAINER_END,containerKind:Wr.SMART_TAG,containerId:o,startOffset:a.offset,endOffset:a.offset,text:""}),a}),t.set("del",(r,n)=>{let o=Us(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=Us(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>Kr(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:Z.BOOKMARK,nodeXml:Ie(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:Z.BOOKMARK,nodeXml:Ie(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:Z.BOOKMARK,nodeXml:Ie(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>Kr(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${Va++}`,a=r.getAttribute("r:id")||"",i=r.getAttribute("w:anchor")||"";e.push({kind:Z.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:a,anchor:i}),startOffset:n,endOffset:n,text:""});let s=Kr(r,n,e);return e.push({kind:Z.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("r",(r,n)=>{let o=Ff(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function Ff(e,t){let r=Ve(e,L,"rPr"),n=r?Ie(r):"",o="";for(let a of za(e)){let i=a.nodeName;i.endsWith(":t")||i==="t"?o+=a.textContent||"":i.endsWith(":br")||i==="br"||i.endsWith(":cr")||i==="cr"?o+=`
|
|
9
|
+
`:i.endsWith(":tab")||i==="tab"?o+=" ":i.endsWith(":noBreakHyphen")||i==="noBreakHyphen"?o+="\u2011":(i.endsWith(":softHyphen")||i==="softHyphen")&&(o+="\xAD")}return o?{kind:Z.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function Us(e,t){let r=e.getAttribute("w:author")||"",n="",o=Ce(e,L,"delText");for(let i of o)n+=i.textContent||"";let a=Ce(e,L,"r");for(let i of a){let s=Ce(i,L,"delText");for(let l of s)n+=l.textContent||""}return n?{kind:Z.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:Ie(e)}:null}function Ka(e){let t=Te(e,L,"tblGrid"),r=t?Ce(t,L,"gridCol"):[],n=Xe(e,L,"tr"),o=n.length,a=n.reduce((u,f)=>{let d=Xe(f,L,"tc");return Math.max(u,d.length)},0),i=r.length||a,s=Array.from({length:o},()=>Array.from({length:i},()=>null)),l=new Map,c=new Map;for(let u=0;u<n.length;u++){let f=n[u],d=Xe(f,L,"tc"),m=0;for(let p=0;p<d.length;p++){let g=d[p],h=Te(g,L,"tcPr");for(;m<i&&s[u][m]!==null;)m++;if(m>=i)break;let y=h?Te(h,L,"gridSpan")||Re(h,"w:gridSpan"):null,w=parseInt(y?.getAttribute("w:val")||"1",10),v=h?Te(h,L,"vMerge")||Re(h,"w:vMerge"):null,b=v?.getAttribute("w:val"),x=v!==null,I;if(x&&b!=="restart"){let N=c.get(m);N?(N.cell.rowSpan++,I={gridRow:u,gridCol:m,rowSpan:0,colSpan:w,tcNode:g,blocks:[],tcPrXml:ja(h),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:N.cell}):I=$f(u,m,w,g,h)}else{let N=Xs(g);if(I={gridRow:u,gridCol:m,rowSpan:1,colSpan:w,tcNode:g,blocks:N,tcPrXml:ja(h),isMergeOrigin:x&&b==="restart",isMergeContinuation:!1,getText:()=>N.map(T=>T.acceptedText).join(`
|
|
10
|
+
`)},x&&b==="restart")for(let T=0;T<w;T++)c.set(m+T,{originRow:u,cell:I});else for(let T=0;T<w;T++)c.delete(m+T)}for(let N=0;N<w;N++){let T=m+N;T<i&&(s[u][T]=I,l.set(`${u},${T}`,I))}m+=w}}return{rowCount:o,colCount:i,grid:s,cellMap:l,tblPrXml:Uf(e),tblGridXml:zf(e),trPrList:Array.from(n).map(u=>Xf(u))}}function $f(e,t,r,n,o){let a=Xs(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:a,tcPrXml:ja(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>a.map(i=>i.acceptedText).join(`
|
|
11
|
+
`)}}function Xs(e){return Xe(e,L,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:a}=Wa(r);return{runModel:n,acceptedText:o,pPr:a}})}function ja(e){return e?Ie(e):"<w:tcPr/>"}function Uf(e){let t=Te(e,L,"tblPr");return t?Ie(t):"<w:tblPr/>"}function zf(e){let t=Te(e,L,"tblGrid");return t?Ie(t):"<w:tblGrid/>"}function Xf(e){let t=Te(e,L,"trPr");return t?Ie(t):"<w:trPr/>"}var js=Is(Ha(),1);var Vf=65536,xo=262144,bo=1,No=55296-bo,Wf=8192,jf=No+Wf,Ga=class extends Error{constructor(t=xo){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function Ks(e){return e?.code==="DIFF_TOKEN_LIMIT"}function qa(e={}){let t=e.diffTimeoutSeconds??0;if(!Number.isFinite(t)||t<0)throw new TypeError("diffTimeoutSeconds must be a finite non-negative number.");let r=new js.diff_match_patch;return r.Diff_Timeout=t,r}function Vs(e){let t=[],r=e.match(/^\s+/);r&&t.push(r[0]);let n=/(\S+)(\s*)/g;n.lastIndex=r?.[0].length||0;let o;for(;(o=n.exec(e))!==null;)o[1]&&t.push(o[1]),o[2]&&t.push(o[2]);return t}function Kf(e,t,r={}){let n=[],o=new Map,a=r.maxTokens??xo;if(!Number.isInteger(a)||a<1||a>xo)throw new RangeError(`maxTokens must be an integer from 1 to ${xo}.`);function i(f){let d="",m=[];for(let p of f){let g=o.get(p);if(g===void 0){if(n.length>=a)throw new Ga(a);g=n.length,n.push(p),o.set(p,g)}m.push(g),d+=String.fromCodePoint(Vf+g)}return{chars:d,tokenIds:m}}let s=Vs(e),l=Vs(t),c=i(s),u=i(l);return{chars1:c.chars,chars2:u.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:u.tokenIds}}function Hf(e){let t=e<No?bo+e:57344+(e-No);return String.fromCharCode(t)}function Gf(e){if(e>=bo&&e<55296)return e-bo;if(e>=57344&&e<=65535)return No+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function Ws(e){let t="";for(let r of e)t+=Hf(r);return t}function qf(e,t){return e.map(([r,n])=>{let o=[];for(let a=0;a<n.length;a++){let i=Gf(n.charCodeAt(a));if(i>=t.length)throw new RangeError(`BMP diff token ${i} has no mapping.`);o.push(t[i])}return[r,o.join("")]})}function Yf(e,t,r){let n=0,o=Math.min(e.length,t.length);for(;n<o&&e[n]===t[n];)n++;let a=0;for(;a<o-n&&e[e.length-1-a]===t[t.length-1-a];)a++;let i=u=>u.map(f=>r[f]).join(""),s=[];n&&s.push([0,i(e.slice(0,n))]);let l=e.slice(n,e.length-a),c=t.slice(n,t.length-a);return l.length&&s.push([-1,i(l)]),c.length&&s.push([1,i(c)]),a&&s.push([0,i(e.slice(e.length-a))]),s}function Rn(e,t,r={}){if(e===t)return[[0,e]];if(!e)return[[1,t]];if(!t)return[[-1,e]];let{cleanupSemantic:n=!0}=r,{wordArray:o,tokenIds1:a,tokenIds2:i}=Kf(e,t,r);if(o.length>jf)return Yf(a,i,o);let s=qa(r),l=s.diff_main(Ws(a),Ws(i));return n&&s.diff_cleanupSemantic(l),qf(l,o)}function Hs(e,t,r={}){return e===t?[[0,e]]:qa(r).diff_main(e,t)}function Gs(e,t){if(e===t)return[[0,e]];if(!e)return[[1,t]];let r=0;for(let o=0;o<t.length&&r<e.length;o++)t[o]===e[r]&&r++;if(r!==e.length)return null;let n=qa().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function Io(e,t,r={}){if(e===t)return[{type:mt.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:mt.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:mt.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=Rn(e,t,r),o=[],a=0;for(let[i,s]of n)i===0?(o.push({type:mt.EQUAL,startOffset:a,endOffset:a+s.length,text:s}),a+=s.length):i===-1?(o.push({type:mt.DELETE,startOffset:a,endOffset:a+s.length,text:s}),a+=s.length):i===1&&o.push({type:mt.INSERT,startOffset:a,endOffset:a,text:s});return o}var Zf=/\s+xmlns:[^=]+="[^"]*"/g;function To(e,t){let r=nd(t),n=[],o=0;for(let a of e){if(a.kind!==Z.TEXT&&a.kind!==Z.HYPERLINK){n.push(a);continue}for(;o<r.length&&r[o]<=a.startOffset;)o++;let i=o,s=a.startOffset,l=!1;for(;i<r.length;){let c=r[i];if(c>=a.endOffset)break;c>s&&(l=!0,n.push({...a,text:a.text.slice(s-a.startOffset,c-a.startOffset),startOffset:s,endOffset:c}),s=c),i++}if(o=i,!l){n.push(a);continue}n.push({...a,text:a.text.slice(s-a.startOffset),startOffset:s,endOffset:a.endOffset})}return n}function So(e,t,r){let{generateRedlines:n,author:o}=r,a=[],i=new Set,s=od(t),l=td(e),c=rd(s.nonInsertOps),u={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let d of e){if(d.kind===Z.CONTAINER_START){u.containerStack.push(d.containerId),a.push({...d});continue}if(d.kind===Z.CONTAINER_END){u.containerStack.pop(),a.push({...d});continue}if(d.kind===Z.PARAGRAPH_START){u.currentParagraphPPrXml=typeof d.pPrXml=="string"?d.pPrXml:"",u.currentParagraphPPrElement=d.pPrElement||null,a.push({...d}),u.lastParagraphStartIndex=a.length-1;continue}if(d.kind===Z.BOOKMARK||d.kind===Z.DELETION){a.push({...d});continue}let m=c(d.startOffset,d.endOffset),p=s.insertOpsByStartOffset.get(d.startOffset)||[];for(let g of p)i.has(g)||(i.add(g),Jf({insertOp:g,splitModel:e,styleLookup:l,patchedModel:a,state:u,options:r,generateRedlines:n,author:o}));if(!m||m.type===mt.EQUAL){a.push({...d,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null});continue}m.type===mt.DELETE&&n&&a.push({...d,kind:Z.DELETION,author:o,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null})}let f=e.length>0?Math.max(...e.map(d=>d.endOffset)):0;for(let d of s.sortedInsertOps){if(d.startOffset<f||i.has(d))continue;let m=e[e.length-1];a.push({kind:n?Z.INSERTION:Z.TEXT,text:d.text,rPrXml:m?.rPrXml||"",startOffset:d.startOffset,endOffset:d.startOffset+d.text.length,author:n?o:void 0})}return a}function Jf(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:a,generateRedlines:i,author:s}=e,l=t.text.split(`
|
|
12
|
+
`),c=ed(r,t.startOffset,t.text);for(let u=0;u<l.length;u++){let f=Qf(l[u],a.numberingService,o),d=f.lineText;if(u>0){let m=qs(o);f.isListLine&&f.numId&&(m=a.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:Z.PARAGRAPH_START,pPrXml:m,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,o.lastParagraphStartIndex=n.length-1}else if(f.isListLine&&f.numId&&o.lastParagraphStartIndex>=0){let m=a.numberingService.buildListPPr(f.numId,f.ilvl);n[o.lastParagraphStartIndex].pPrXml=m,n[o.lastParagraphStartIndex].pPrElement=null,o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,K(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(d.length>0||u>0)&&n.push({kind:i?Z.INSERTION:Z.TEXT,text:d,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+d.length,author:i?s:void 0,containerContext:o.containerStack.length>0?o.containerStack[o.containerStack.length-1]:null})}}function Qf(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=xt(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let o=n[2].trim(),a=t.detectNumberingFormat(o),i=e.match(/^(\s*)/),s=i?i[1].length:0,l=s>=4?4:2,c=Math.floor(s/l),u=qs(r),f=Rt(e,{allowZeroSpaceAfterMarker:!0}),d=u.match(/w:numId w:val="(\d+)"/),m=u.match(/w:ilvl w:val="(\d+)"/),p=d?d[1]:null,g=m?parseInt(m[1],10):0,h=t.getOrCreateNumId({type:a.format},{numId:p,type:"unknown"}),y=a.format==="outline"?Math.min(8,a.depth):Math.min(8,c+g);return{lineText:f,isListLine:!0,numId:h,ilvl:y}}function qs(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=Ie(e.currentParagraphPPrElement).replace(Zf,""),e.currentParagraphPPrXml):""}function ed(e,t,r){let n=e.findRunBefore(t),o=e.findRunAfter(t);return!n&&!o?null:n?o?r&&r.endsWith(" ")?o:(r&&r.startsWith(" "),n):n:o}function td(e){let t=e.filter(o=>o.kind===Z.TEXT),r=t.map(o=>o.startOffset),n=t.map(o=>o.endOffset);return{findRunBefore(o){let a=0,i=n.length-1,s=-1;for(;a<=i;){let l=a+i>>1;n[l]<=o?(s=l,a=l+1):i=l-1}return s>=0?t[s]:null},findRunAfter(o){let a=0,i=r.length-1,s=-1;for(;a<=i;){let l=a+i>>1;r[l]>=o?(s=l,i=l-1):a=l+1}return s>=0?t[s]:null}}}function rd(e){let t=0;return(r,n)=>{for(;t<e.length&&e[t].endOffset<=r;)t++;let o=e[t];return o&&o.startOffset<=r&&o.endOffset>=n?o:null}}function nd(e){let t=new Set;for(let r of e)t.add(r.startOffset),t.add(r.endOffset);return Array.from(t).sort((r,n)=>r-n)}function od(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===mt.INSERT){t.has(o.startOffset)||t.set(o.startOffset,[]),t.get(o.startOffset).push(o),n.push(o);continue}r.push(o)}return r.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),n.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var Qs="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ad="http://schemas.openxmlformats.org/officeDocument/2006/relationships",id="http://schemas.microsoft.com/office/2006/xmlPackage",Ys="http://schemas.openxmlformats.org/package/2006/relationships",sd='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',Zs='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var ld=`
|
|
13
|
+
<w:numbering xmlns:w="${Qs}">
|
|
14
14
|
<w:abstractNum w:abstractNumId="0">
|
|
15
15
|
<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="•"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>
|
|
16
16
|
</w:abstractNum>
|
|
@@ -19,23 +19,23 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
19
19
|
</w:abstractNum>
|
|
20
20
|
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
|
|
21
21
|
<w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>
|
|
22
|
-
</w:numbering>`.trim();function
|
|
22
|
+
</w:numbering>`.trim();function cd(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function el(e,t=!0){let r=t?` xmlns:r="${ad}"`:"";return`<w:document xmlns:w="${Qs}"${r}><w:body>${e}</w:body></w:document>`}function Js(e){return`
|
|
23
23
|
<pkg:part pkg:name="/word/numbering.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml">
|
|
24
24
|
<pkg:xmlData>
|
|
25
|
-
${
|
|
25
|
+
${cd(e)}
|
|
26
26
|
</pkg:xmlData>
|
|
27
|
-
</pkg:part>`}function
|
|
28
|
-
<pkg:package xmlns:pkg="${
|
|
27
|
+
</pkg:part>`}function tl(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
28
|
+
<pkg:package xmlns:pkg="${id}">
|
|
29
29
|
<pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
|
|
30
30
|
<pkg:xmlData>
|
|
31
|
-
<Relationships xmlns="${
|
|
32
|
-
${
|
|
31
|
+
<Relationships xmlns="${Ys}">
|
|
32
|
+
${sd}
|
|
33
33
|
</Relationships>
|
|
34
34
|
</pkg:xmlData>
|
|
35
35
|
</pkg:part>
|
|
36
36
|
<pkg:part pkg:name="/word/_rels/document.xml.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
|
|
37
37
|
<pkg:xmlData>
|
|
38
|
-
<Relationships xmlns="${
|
|
38
|
+
<Relationships xmlns="${Ys}">
|
|
39
39
|
${t}
|
|
40
40
|
</Relationships>
|
|
41
41
|
</pkg:xmlData>
|
|
@@ -45,7 +45,7 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
45
45
|
${e}
|
|
46
46
|
</pkg:xmlData>
|
|
47
47
|
</pkg:part>
|
|
48
|
-
</pkg:package>`}function
|
|
48
|
+
</pkg:package>`}function rl(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:o=!0}=t,a=o?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,i=el(a,!0),s="",l="";return n?(s=Zs,l+=Js(n)):r&&(s=Zs,l+=Js(ld)),tl(i,s,l)}function nl(e){let t=el(e,!0);return tl(t)}var ud=/\s+xmlns:[^=]+="[^"]*"/g;function bt(e,t,r=[],n={}){let o=fd(n),{generateRedlines:a}=o,i=[],s="",l=null,c=[];function u(){if(c.length>0||i.length===0){let f="";s?f=wr(s):l?(s=wr(Ie(l)),f=s):t&&(typeof t=="string"?f=t:f=Ie(t),f=wr(f)),i.push(`<w:p>${f}${c.join("")}</w:p>`),c=[]}}for(let f of e)switch(f.kind){case Z.PARAGRAPH_START:(c.length>0||i.length>0)&&u(),s=f.pPrXml||"",l=f.pPrElement||null;break;case Z.TEXT:c.push(ol(f,r,o));break;case Z.DELETION:a&&c.push(dd(f,o));break;case Z.INSERTION:a?c.push(md(f,r,o)):c.push(ol(f,r,o));break;case Z.BOOKMARK:case Z.HYPERLINK:f.nodeXml&&c.push(wr(f.nodeXml));break;case Z.CONTAINER_START:if(f.containerKind==="sdt")c.push(`<w:sdt>${f.propertiesXml}<w:sdtContent>`);else if(f.containerKind==="smartTag")c.push(`<w:smartTag ${f.propertiesXml}>`);else if(f.containerKind==="hyperlink"){let d=JSON.parse(f.propertiesXml),m=d.rId?` r:id="${d.rId}"`:"",p=d.anchor?` w:anchor="${d.anchor}"`:"";c.push(`<w:hyperlink${m}${p}>`)}break;case Z.CONTAINER_END:f.containerKind==="sdt"?c.push("</w:sdtContent></w:sdt>"):f.containerKind==="smartTag"?c.push("</w:smartTag>"):f.containerKind==="hyperlink"&&c.push("</w:hyperlink>");break;default:vt("Unknown run kind:",f.kind)}return u(),i.join("")}function fd(e){if(typeof e=="string")return{author:re(),generateRedlines:!0,font:e,revisionIdAllocator:null};let t=e&&typeof e=="object"?e:{};return{author:typeof t.author=="string"&&t.author.trim()?t.author.trim():re(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function ol(e,t,r={}){let n=Bt(t,e.startOffset,e.endOffset),o=r?.font??null,a=e.rPrXml?wr(e.rPrXml):"";if(o&&(a=Ya(a,o)),n.length===0)return rr(e.text,a);let i=[],s=0,l=e.text,c=e.startOffset;for(let u of n){let f=Math.max(0,u.start-c),d=Math.min(l.length,u.end-c);f>s&&i.push(rr(l.slice(s,f),a));let m=al(a,u.format);i.push(rr(l.slice(f,d),m)),s=d}return s<l.length&&i.push(rr(l.slice(s),a)),i.join("")}function rr(e,t){return e?`<w:r>${t||""}<w:t xml:space="preserve">${ze(e)}</w:t></w:r>`:""}function dd(e,t={}){let r=ie(t.author??re(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?wr(e.rPrXml):"";return n&&(o=Ya(o,n)),`<w:del w:id="${r.id}" w:author="${ze(r.author)}" w:date="${r.date}"><w:r>${o}<w:delText xml:space="preserve">${ze(e.text)}</w:delText></w:r></w:del>`}function md(e,t,r={}){let n=ie(r.author??re(),r.revisionIdAllocator,"ins"),o=r.font??null,a=Bt(t,e.startOffset,e.endOffset),i="",s=e.rPrXml?wr(e.rPrXml):"";if(o&&(s=Ya(s,o)),a.length===0)i=rr(e.text,s);else{let l=0,c=e.text,u=e.startOffset;for(let f of a){let d=Math.max(0,f.start-u),m=Math.min(c.length,f.end-u);d>l&&(i+=rr(c.slice(l,d),s));let p=al(s,f.format);i+=rr(c.slice(d,m),p),l=m}l<c.length&&(i+=rr(c.slice(l),s))}return`<w:ins w:id="${n.id}" w:author="${ze(n.author)}" w:date="${n.date}">`+i+"</w:ins>"}function Ya(e,t){if(!t)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),r.includes("<w:rFonts")?r=r.replace(/<w:rFonts[^>]*\/>/,`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`):r=`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`+r,`<w:rPr>${r}</w:rPr>`}function al(e,t){if(!t||Object.keys(t).length===0)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),t.bold&&!r.includes("<w:b")&&(r="<w:b/>"+r),t.italic&&!r.includes("<w:i")&&(r="<w:i/>"+r),t.underline&&!r.includes("<w:u")&&(r='<w:u w:val="single"/>'+r),t.strikethrough&&!r.includes("<w:strike")&&(r="<w:strike/>"+r),`<w:rPr>${r}</w:rPr>`}function nr(e,t={}){let r=pd(t);return rl(e,r)}function pd(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function wr(e){return e?e.replace(ud,""):""}function Za(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var $t=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){Za(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||de.BULLET;if(r&&Za(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let a=this.contextMap.get(n);if(Za(a))return a;this.contextMap.delete(n)}if(n===de.OUTLINE)return"3";if(n===de.DECIMAL)return"2";if(n===de.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==de.DECIMAL&&n!==de.BULLET){let a=`custom_${n}`;if(this.contextMap.has(a))return this.contextMap.get(a);let i=String(this.nextNumId++);return this.customConfigs.push({numId:i,levels:[{format:n,suffix:t.suffix||Le.PERIOD}]}),this.contextMap.set(a,i),i}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:de.BULLET,suffix:Le.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:de.BULLET,suffix:Le.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:de.OUTLINE,suffix:Le.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:de.LOWER_ALPHA,suffix:Le.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?de.LOWER_ROMAN:de.UPPER_ROMAN,suffix:Le.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:de.DECIMAL,suffix:Le.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:de.DECIMAL,suffix:Le.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:de.LOWER_ALPHA,suffix:Le.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:de.UPPER_ALPHA,suffix:Le.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?de.LOWER_ROMAN:de.UPPER_ROMAN,suffix:Le.PERIOD,depth:0}:/^\d+/.test(r)?{format:de.DECIMAL,suffix:Le.PERIOD,depth:0}:{format:de.BULLET,suffix:Le.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[de.DECIMAL]:"decimal",[de.LOWER_ALPHA]:"lowerLetter",[de.UPPER_ALPHA]:"upperLetter",[de.LOWER_ROMAN]:"lowerRoman",[de.UPPER_ROMAN]:"upperRoman",[de.BULLET]:"bullet",[de.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===de.BULLET)return"\u2022";let o=`%${n+1}`;if(t===de.OUTLINE)return Array(n+1).fill(0).map((a,i)=>`%${i+1}`).join(".")+".";switch(r){case Le.PERIOD:return`${o}.`;case Le.PAREN_RIGHT:return`${o})`;case Le.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
|
|
49
49
|
<w:pPr>${n.includeListParagraphStyle===!0?`
|
|
50
50
|
<w:pStyle w:val="ListParagraph"/>`:""}
|
|
51
51
|
<w:numPr>
|
|
@@ -72,7 +72,7 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
72
72
|
<w:lvl w:ilvl="2"><w:start w:val="1"/><w:numFmt w:val="lowerRoman"/><w:lvlText w:val="(%3)"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2160" w:hanging="360"/></w:pPr></w:lvl>
|
|
73
73
|
<w:lvl w:ilvl="3"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="(%4)"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2880" w:hanging="360"/></w:pPr></w:lvl>
|
|
74
74
|
<w:lvl w:ilvl="4"><w:start w:val="1"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%5."/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="3600" w:hanging="360"/></w:pPr></w:lvl>
|
|
75
|
-
</w:abstractNum>`,
|
|
75
|
+
</w:abstractNum>`,a=`
|
|
76
76
|
<w:abstractNum w:abstractNumId="2">
|
|
77
77
|
<w:multiLevelType w:val="multilevel"/>
|
|
78
78
|
<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>
|
|
@@ -80,16 +80,16 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
80
80
|
<w:lvl w:ilvl="2"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2160" w:hanging="360"/></w:pPr></w:lvl>
|
|
81
81
|
<w:lvl w:ilvl="3"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3.%4"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2880" w:hanging="360"/></w:pPr></w:lvl>
|
|
82
82
|
<w:lvl w:ilvl="4"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3.%4.%5"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="3600" w:hanging="360"/></w:pPr></w:lvl>
|
|
83
|
-
</w:abstractNum>`,
|
|
83
|
+
</w:abstractNum>`,i="",s="";return r.forEach((l,c)=>{let u=10+c;i+=`
|
|
84
84
|
<w:abstractNum w:abstractNumId="${u}">
|
|
85
85
|
<w:multiLevelType w:val="multilevel"/>
|
|
86
|
-
${l.levels.map((f,
|
|
87
|
-
<w:lvl w:ilvl="${
|
|
86
|
+
${l.levels.map((f,d)=>`
|
|
87
|
+
<w:lvl w:ilvl="${d}">
|
|
88
88
|
<w:start w:val="1"/>
|
|
89
89
|
<w:numFmt w:val="${this.formatToOoxmlNumFmt(f.format)}"/>
|
|
90
|
-
<w:lvlText w:val="${this.suffixToOoxmlLevelText(f.format,f.suffix,
|
|
90
|
+
<w:lvlText w:val="${this.suffixToOoxmlLevelText(f.format,f.suffix,d)}"/>
|
|
91
91
|
<w:lvlJc w:val="left"/>
|
|
92
|
-
<w:pPr><w:ind w:left="${720*(
|
|
92
|
+
<w:pPr><w:ind w:left="${720*(d+1)}" w:hanging="360"/></w:pPr>
|
|
93
93
|
</w:lvl>`).join("")}
|
|
94
94
|
</w:abstractNum>`,s+=`
|
|
95
95
|
<w:num w:numId="${l.numId}">
|
|
@@ -98,8 +98,8 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
98
98
|
<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
|
|
99
99
|
${n}
|
|
100
100
|
${o}
|
|
101
|
-
${i}
|
|
102
101
|
${a}
|
|
102
|
+
${i}
|
|
103
103
|
<w:num w:numId="1">
|
|
104
104
|
<w:abstractNumId w:val="0"/>
|
|
105
105
|
</w:num>
|
|
@@ -110,7 +110,7 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
110
110
|
<w:abstractNumId w:val="2"/>
|
|
111
111
|
</w:num>
|
|
112
112
|
${s}
|
|
113
|
-
</w:numbering>`}};function
|
|
113
|
+
</w:numbering>`}};function yr(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:o=null,trackAsBlock:a=!1}=t,i=r&&a?ie(n,o):null,s=e.headers?.length||e.rows?.[0]?.length||1,l=`
|
|
114
114
|
<w:tblPr>
|
|
115
115
|
<w:tblW w:w="5000" w:type="pct"/>
|
|
116
116
|
<w:tblBorders>
|
|
@@ -123,55 +123,56 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
123
123
|
</w:tblBorders>
|
|
124
124
|
<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
|
|
125
125
|
</w:tblPr>
|
|
126
|
-
`.trim(),u=`<w:tblGrid>${Array(s).fill("<w:gridCol/>").join("")}</w:tblGrid>`,f=e.hasHeader?[e.headers,...e.rows]:e.rows,
|
|
126
|
+
`.trim(),u=`<w:tblGrid>${Array(s).fill("<w:gridCol/>").join("")}</w:tblGrid>`,f=e.hasHeader?[e.headers,...e.rows]:e.rows,d="";for(let p=0;p<f.length;p++){let g=e.hasHeader&&p===0,h=f[p]||[],y="";for(let v=0;v<s;v++){let b=h[v]||"",{cleanText:x,formatHints:I}=Je(b),N=[{kind:r&&!a?Z.INSERTION:Z.TEXT,text:x,rPrXml:g?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:x.length}],T=bt(N,null,I,{author:n,generateRedlines:r,revisionIdAllocator:o});y+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${T}</w:tc>`}d+=`<w:tr>${g?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>"}${y}</w:tr>`}let m=`<w:tbl>${l}${u}${d}</w:tbl>`;return i&&(m=`<w:ins w:id="${i.id}" w:author="${ze(i.author)}" w:date="${i.date}">${m}</w:ins>`),m}function il(e,t){let r=[],{headers:n,rows:o,hasHeader:a}=t,i=a?[n,...o]:o,s=Math.max(e.rowCount,i.length);for(let l=0;l<s;l++){if(l>=e.rowCount&&i[l]){r.push({type:"row_insert",gridRow:l,cells:i[l]});continue}if(l<e.rowCount&&!i[l]){r.push({type:"row_delete",gridRow:l});continue}let c=i[l];for(let u=0;u<e.colCount;u++){let f=e.grid[l]?.[u],d=c?.[u];f&&(f.isMergeContinuation||u>f.gridCol||d!==void 0&&f.getText()!==d&&r.push({type:"cell_modify",gridRow:l,gridCol:u,originalCell:f,newText:d}))}}return r}function sl(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,i=gd(t),s="";for(let c=0;c<e.rowCount;c++){let u=i.rowDeleteByRow.get(c)||null;if(u&&!n)continue;let f="",d=0;for(;d<e.colCount;){let p=e.grid[c][d];if(!p){d++;continue}if(p.isMergeContinuation){d++;continue}let g=i.cellModifyByCoordinate.get(`${c}:${d}`)||null,h;g?h=hd(p,g.newText,r):h=wd(p.blocks),f+=yd(p,h,r),d+=p.colSpan}let m=e.trPrList[c]||"<w:trPr/>";if(u&&n){let p=ie(o,a),g=`<w:del w:id="${p.id}" w:author="${ze(p.author)}" w:date="${p.date}"/>`;m.includes("</w:trPr>")?m=m.replace("</w:trPr>",`${g}</w:trPr>`):m=`<w:trPr>${g}</w:trPr>`}s+=`<w:tr>${m}${f}</w:tr>`}let l=i.rowInsertOperations;for(let c of l){let u="",f=n?ie(o,a):null;for(let m of c.cells){let{cleanText:p,formatHints:g}=Je(m),h=[{kind:n?Z.INSERTION:Z.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],y=bt(h,null,g,{author:o,generateRedlines:n,revisionIdAllocator:a});u+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${y}</w:tc>`}let d="<w:trPr/>";n&&(d=`<w:trPr><w:ins w:id="${f.id}" w:author="${ze(f.author)}" w:date="${f.date}"/></w:trPr>`),s+=`<w:tr>${d}${u}</w:tr>`}return`
|
|
127
127
|
<w:tbl>
|
|
128
128
|
${e.tblPrXml}
|
|
129
129
|
${e.tblGridXml}
|
|
130
130
|
${s}
|
|
131
131
|
</w:tbl>
|
|
132
|
-
`}function
|
|
133
|
-
`).map(
|
|
134
|
-
`).filter(t=>t.trim().length>0).map(t=>{let r=
|
|
135
|
-
`),r=t.map((
|
|
136
|
-
`)}function
|
|
137
|
-
`),endIndex:
|
|
132
|
+
`}function gd(e){let t=new Map,r=new Map,n=[];for(let o of e)o.type==="row_delete"?t.set(o.gridRow,o):o.type==="cell_modify"?r.set(`${o.gridRow}:${o.gridCol}`,o):o.type==="row_insert"&&n.push(o);return n.sort((o,a)=>o.gridRow-a.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function hd(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,{cleanText:i,formatHints:s}=Je(t),l=e.getText(),c=Io(l,i),u=e.blocks[0]||{runModel:[],pPr:null},f=To(u.runModel,c),d=So(f,c,{generateRedlines:n,author:o,formatHints:s});return bt(d,u.pPr,s,{author:o,generateRedlines:n,revisionIdAllocator:a})}function wd(e){return e.map(t=>bt(t.runModel,t.pPr,[],{})).join("")}function yd(e,t,r){let n=e.tcPrXml;return e.colSpan>1&&!n.includes("gridSpan")?n=n.replace("</w:tcPr>",`<w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`):e.colSpan>1&&n==="<w:tcPr/>"&&(n=`<w:tcPr><w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`),e.rowSpan>1&&e.isMergeOrigin&&!n.includes("vMerge")?n=n.replace("</w:tcPr>",'<w:vMerge w:val="restart"/></w:tcPr>'):e.rowSpan>1&&e.isMergeOrigin&&n==="<w:tcPr/>"&&(n='<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>'),`<w:tc>${n}${t}</w:tc>`}function at(e){let t=e.split(`
|
|
133
|
+
`).map(i=>i.trim()).filter(i=>i.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=i=>{let s=i.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(s)},n=t.some(r),a=t.filter(i=>!r(i)).map(i=>i.split("|").slice(1,-1).map(s=>s.trim()));return n?{headers:a[0]||[],rows:a.slice(1),hasHeader:!0}:{headers:[],rows:a,hasHeader:!1}}function D(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===L&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function B(e,t){return typeof e.createElementNS=="function"?e.createElementNS(L,t):e.createElement(t)}function ll(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(L,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>D(n,t))}var cl=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function or(e){return cl.some(t=>ll(e,t).length>0)}function vr(e){if(!e)return[];let t=new Set;for(let r of cl)for(let n of ll(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(L,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function vd(e){let t=String(e||"").trim();return/^<\?xml\b[^>]*>\s*<pkg:package\b/i.test(t)||/^<pkg:package\b/i.test(t)?"package":/^<\?xml\b[^>]*>\s*<(?:w:)?document\b/i.test(t)||/^<(?:w:)?document\b/i.test(t)?"document":"fragment"}function xe(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:vd(e.oxml)}}async function qr(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:a=!0,author:i="AI",font:s=null,revisionIdAllocator:l=null,numberingService:c}=e,u=bd(t),f=xd(u),d=f.map(N=>N.raw),m=[],p=Td(n),g=ul(n,p),h=ul(n,p,["rFonts","kern","position","rtl","cs","lang"]),y=[];if(a){if(n&&n.length>0)y=n.filter(N=>N.kind==="text"||N.kind==="run").map(N=>({...N,kind:"deletion",author:i}));else if(o&&o.trim().length>0){let N=o.trim();y=[{kind:"deletion",text:N,author:i,startOffset:0,endOffset:N.length}]}}if(a&&y.length>0){let N=fl(p,"del",i,l),T=bt(y,N,[],{author:i,generateRedlines:a,revisionIdAllocator:l});m.push(T)}let w=Ja(d);K(`[ListGen] Detected indentation step: ${w} spaces/chars`);let v=f.find(N=>N.marker)?.marker||"",{format:b}=c.detectNumberingFormat(v);K(`[ListGen] Detected primary marker: "${v}", format: ${b}`);for(let N=0;N<f.length;N++){let T=Nd(f,N);if(T){let O=at(T.tableText);if(O.headers.length>0||O.rows.length>0){m.push(yr(O,{generateRedlines:a,author:i,revisionIdAllocator:l,trackAsBlock:!0})),N=T.endIndex;continue}}let E=f[N],S=Id(E,w,r,c,a,i,s,l,g,h);m.push(S.ooxml)}let x=c.generateNumberingXml(),I=m.join("");return K(`[ListGen] \u2705 Generated OOXML for ${m.length} paragraphs, total length: ${I.length}`),K(`[ListGen] First 200 chars: ${I.substring(0,200)}...`),{ooxml:I,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:x}}function Ja(e){let t=e.map(n=>n.match(/^(\s*)/)[0].length).filter(n=>n>0).sort((n,o)=>n-o);if(t.length===0)return 2;let r=t[0];for(let n=1;n<t.length;n++){let o=t[n]-t[n-1];o>0&&o<r&&(r=o)}return r||2}function xd(e){return e.split(`
|
|
134
|
+
`).filter(t=>t.trim().length>0).map(t=>{let r=xt(t),n=t.match(/^\s*(#{1,9})\s+(.*)/);return{raw:t,marker:r?r[2].trim():"",headerMatch:n,indentSize:t.match(/^(\s*)/)?.[1].length||0,isTableLine:/^\s*\|/.test(t),isTableSeparator:/^\s*\|?[\s:-]*-[-\s|:]*\|?\s*$/.test(t)}})}function bd(e){let t=String(e||"").split(`
|
|
135
|
+
`),r=t.map((i,s)=>({line:i,index:s})).filter(i=>i.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:i,index:s}of r){let l=xt(i);if(!l)return e;let c=Rt(i),u=xt(c);if(!u)return e;let f=(l[2]||"").trim(),d=(u[2]||"").trim();if(!f||!d||f===d)return e;let p=`${l[1]||""}${c.trimStart()}`;n.push({index:s,rewritten:p}),o++}if(o<2)return e;let a=t.slice();for(let i of n)a[i.index]=i.rewritten;return K(`[ListGen] Normalized ${o} composite list markers (e.g., "- A." -> "A.").`),a.join(`
|
|
136
|
+
`)}function Nd(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let o=[],a=t;for(;a<e.length&&e[a].isTableLine;)o.push(e[a].raw),a++;return{tableText:o.join(`
|
|
137
|
+
`),endIndex:a-1}}function Id(e,t,r,n,o,a,i,s,l,c){let u="",f="",d=l;if(e.headerMatch){let h=Math.min(e.headerMatch[1].length,9),y=Math.min(h-1,8),w=[32,28,26,24,22,20,20,20,20],v=w[h-1]||w[w.length-1];f=e.headerMatch[2].trim(),u=`<w:pPr><w:pStyle w:val="Heading${h}"/><w:outlineLvl w:val="${y}"/><w:rPr><w:b/><w:sz w:val="${v}"/><w:szCs w:val="${v}"/></w:rPr></w:pPr>`,d=Sd(c,`<w:rPr><w:b/><w:sz w:val="${v}"/><w:szCs w:val="${v}"/></w:rPr>`)}else if(e.marker){let h=n.detectNumberingFormat(e.marker),y=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,v=h.format==="outline"?Math.min(8,h.depth):Math.min(8,y+w);f=Rt(e.raw);let b=n.getOrCreateNumId({type:h.format},r);u=n.buildListPPr(b,v)}else f=e.raw;o&&(u=fl(u||"<w:pPr/>","ins",a,s));let{cleanText:m,formatHints:p}=Je(f),g=[];return g.push({kind:o?"insertion":"run",text:m,rPrXml:d,author:a,startOffset:0,endOffset:m.length}),{ooxml:bt(g,u,p,{author:a,generateRedlines:o,font:i,revisionIdAllocator:s})}}function Td(e){let t=(e||[]).find(r=>r.kind===Z.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function ul(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(a=>(a.kind===Z.TEXT||a.kind==="text")&&a.rPrXml).map(a=>a.rPrXml);t&&n.push(typeof t=="string"?t:Ie(t));let o=[];for(let a of r){let i=null;for(let s of n)if(i=String(s||"").match(new RegExp(`<w:${a}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${a}>)`)),i)break;i&&o.push(i[0])}return o.length>0?`<w:rPr>${o.join("")}</w:rPr>`:""}function Sd(...e){let t=e.map(r=>String(r||"").replace(/^\s*<w:rPr[^>]*>|<\/w:rPr>\s*$/g,"")).filter(Boolean).join("");return t?`<w:rPr>${t}</w:rPr>`:""}function fl(e,t,r,n){let o=ie(r,n),a,i;if(e?.nodeType===1)a=e.cloneNode(!0),i=a.ownerDocument;else{let c=typeof e=="string"&&e.trim()?e:"<w:pPr/>",u=W(`<w:root xmlns:w="${L}">${c}</w:root>`);if(!u.doc)throw new Error(u.error?.message||"Could not parse paragraph properties for list revision");i=u.doc,a=Array.from(i.documentElement.childNodes||[]).find(f=>f.nodeType===1&&f.localName==="pPr")}if(!a||!i)throw new Error("List paragraph properties are unavailable");let s=Array.from(a.childNodes||[]).find(c=>c.nodeType===1&&c.localName==="rPr");s||(s=B(i,"w:rPr"),a.appendChild(s));let l=B(i,t==="del"?"w:del":"w:ins");return l.setAttribute("w:id",String(o.id)),l.setAttribute("w:author",o.author),l.setAttribute("w:date",o.date),s.appendChild(l),Ie(a)}var Ed=new Set(["officeonline","officeweb","web"]);function Ad(e){return e?Ed.has(String(e).toLowerCase()):!1}function Rd(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function Pd(){return new Promise(e=>setTimeout(e,0))}var Pn=class{constructor(t={}){this.generateRedlines=t.generateRedlines??!0,this.author=t.author??"AI",this.validateOutput=t.validateOutput??!0,this.validationMode=t.validationMode??"auto",this.numberingService=t.numberingService||new $t,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??Da(),this.isWebPlatform=t.isWebPlatform??Ad(this.platform),this.enableEventLoopYielding=t.enableEventLoopYielding??this.isWebPlatform,this.yieldRunThreshold=t.yieldRunThreshold??50,this.yieldCharThreshold=t.yieldCharThreshold??5e3,this.disableSemanticCleanupOverChars=t.disableSemanticCleanupOverChars??(this.isWebPlatform?8e3:Number.POSITIVE_INFINITY)}async execute(t,r,n={}){let o=[];try{let a=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:W(t,"application/xml");if(a.error||!a.doc)return{ooxml:t,isValid:!1,status:"error",error:a.error,warnings:a.warnings||[]};o.push(...a.warnings||[]);let i=a.doc,s=Te(i,"*","p"),{runModel:l,acceptedText:c,pPr:u}=Hr(t,{xmlDoc:i}),f=s?An(s):null;K(`[Reconcile] Ingested ${l.length} runs, ${c.length} chars, numbering:`,f),await this.maybeYield(l.length,Math.max(c.length,r?.length||0));let{cleanText:d,formatHints:m}=Je(r);K(`[Reconcile] Preprocessed: ${m.length} format hints`),await this.maybeYield(l.length,Math.max(c.length,d.length));let p=$a(d),g=bn(d),h=p||g;if(!p&&g&&K("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===d&&m.length===0&&!h)return K("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let y=Math.max(c.length,d.length)<this.disableSemanticCleanupOverChars,w=Io(c,d,{cleanupSemantic:y});y||K("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(l.length,Math.max(c.length,d.length));let v=l.filter(E=>E.kind===Z.PARAGRAPH_START).length,b=$a(c)||bn(c),x=h&&b&&v>1&&c!==d;if(K(`[Reconcile] isTargetList: ${h}, paragraphCount: ${v}`),x)K("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(h)return K("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),K(`[Reconcile] cleanText preview: ${d.substring(0,100)}...`),K(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(d,f,l);K(`[Reconcile] Computed ${w.length} diff operations`);let I=To(l,w);K(`[Reconcile] Split into ${I.length} runs`);let N=So(I,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:m,numberingService:this.numberingService});K(`[Reconcile] Patched model has ${N.length} runs`),await this.maybeYield(N.length,Math.max(c.length,d.length));let T=bt(N,u,m,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let E=this.validateBasic(T);E.isValid||o.push(...E.errors)}return{ooxml:T,isValid:o.length===0,warnings:o}}catch(a){return Ne("[Reconcile] Pipeline error:",a),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${a.message}`],error:a?.code?{code:a.code,message:a.message}:void 0}}}validateBasic(t){let r=[];try{let n=`<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${t}</root>`,o=W(n,"application/xml"),a=o.doc;if(o.error||!a)return r.push("Generated OOXML is not well-formed XML: "+(o.error?.message||"parse error")),{isValid:!1,errors:r};let i=Se(a);i&&r.push("Generated OOXML is not well-formed XML: "+i.textContent.substring(0,100)),t.includes("<w:p")||r.push("Generated OOXML missing paragraph element")}catch(n){r.push(`Validation error: ${n.message}`)}return{isValid:r.length===0,errors:r}}shouldRunValidation(){return this.validateOutput?this.validationMode==="always"?!0:this.validationMode==="never"?!1:!(this.isWebPlatform&&Rd()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await Pd())}wrapForInsertion(t,r={}){return nr(t,r)}async executeListGeneration(t,r,n,o=""){return qr({cleanText:t,numberingContext:r,originalRunModel:n,originalText:o,generateRedlines:this.generateRedlines,author:this.author,font:this.font,revisionIdAllocator:this.revisionIdAllocator,numberingService:this.numberingService})}detectIndentationStep(t){return Ja(t)}executeTableGeneration(t){let r=at(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:yr(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var dl=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function ml(e){return!e||e.trim().length===0}function pl(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function Cd(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function Qa(e){return ml(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":pl(e)?"table":xt(e)?"list":"paragraph"}function Eo(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
|
|
138
138
|
`):String(e??"")).split(`
|
|
139
|
-
`),n=[],o=[],
|
|
140
|
-
`)});continue}if(l==="list"){let
|
|
141
|
-
`)});continue}let u=[];for(;
|
|
139
|
+
`),n=[],o=[],a=0;for(;a<r.length;){if(ml(r[a])){a++;continue}let l=Qa(r[a]),c=a+1;if(l==="heading"){let d=r[a].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:d[1].length,text:d[2],markdown:r[a].trim()}),a++;continue}if(l==="table"){let d=[];for(;a<r.length&&pl(r[a]);)d.push(r[a].trim()),a++;let m=d.length>1&&dl.test(d[1]),p=d.filter(g=>!dl.test(g)).map(g=>Cd(g).length);m||o.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:c,message:"Markdown tables require a separator row immediately after the header (for example | --- | --- |)."}),p.length<2?o.push({severity:"error",code:"TABLE_DATA_ROW_REQUIRED",line:c,message:"Markdown tables require a header and at least one data row."}):new Set(p).size>1&&o.push({severity:"error",code:"TABLE_COLUMN_COUNT_MISMATCH",line:c,message:`Markdown table rows have inconsistent column counts: ${p.join(", ")}.`}),n.push({type:"table",columns:p[0]||0,rows:Math.max(0,p.length-1),hasHeader:m,markdown:d.join(`
|
|
140
|
+
`)});continue}if(l==="list"){let d=[];for(;a<r.length&&Qa(r[a])==="list";)d.push(r[a].trimEnd()),a++;n.push({type:"list",items:d.length,markdown:d.join(`
|
|
141
|
+
`)});continue}let u=[];for(;a<r.length&&Qa(r[a])==="paragraph";)u.push(r[a].trim()),a++;let f=u.join(" ").trim();n.push({type:"paragraph",text:f,markdown:f})}let i={heading:0,paragraph:0,list:0,table:0};for(let l of n)i[l.type]=(i[l.type]||0)+1;let s=n.map(l=>l.markdown).join(`
|
|
142
142
|
|
|
143
|
-
`);return{valid:o.every(l=>l.severity!=="error"),normalizedMarkdown:s,blocks:n,issues:o,counts:a,requiresStructuredContent:n.length>1||n.some(l=>l.type==="heading"||l.type==="table"||l.type==="list"&&l.items>1)}}function Bl(e,t,r={}){let n=Wr(t);return{...n,operation:n.valid?{type:"replace",target:e,modified:n.normalizedMarkdown,structuredContent:!0,...r.author?{author:r.author}:{},...typeof r.generateRedlines=="boolean"?{generateRedlines:r.generateRedlines}:{},...r.existingRevisions?{existingRevisions:r.existingRevisions}:{}}:null}}var sr=["w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"];function Lt(e,t){let r=sr.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let i of Array.from(e.childNodes)){if(i.nodeType!==1)continue;let a=sr.indexOf(i.nodeName);if((a===-1?999:a)>n){e.insertBefore(t,i),o=!0;break}}o||e.appendChild(t)}function Fl(e,t,r,n){if(!t||!r)return;let o=!!r.bold,i=!!r.italic,a=!!r.underline,s=!!r.strikethrough,l=new Set;if(o&&(l.add("w:b"),l.add("w:bCs")),i&&(l.add("w:i"),l.add("w:iCs")),a&&l.add("w:u"),s&&l.add("w:strike"),l.size>0){let c=[];for(let u of Array.from(t.childNodes))l.has(u.nodeName)&&c.push(u);for(let u of c)t.removeChild(u)}if(o){let c=O(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c);let u=O(e,"w:bCs");u.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,u)}if(i){let c=O(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c);let u=O(e,"w:iCs");u.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,u)}if(a){let c=O(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),Lt(t,c)}if(s){let c=O(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c)}}function Ri(e,t,r){Fl(e,t,r,"remove")}function qe(e){let t={bold:!1,italic:!1,underline:!1,strikethrough:!1,hasFormatting:!1};if(!e)return t;for(let r of Array.from(e.childNodes))if(r.nodeName==="w:b"&&(t.bold=Ur(r,!1)),r.nodeName==="w:i"&&(t.italic=Ur(r,!1)),r.nodeName==="w:u"&&(t.underline=Ur(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=Ur(r,!1)),r.nodeName==="w:rStyle"){let n=r.getAttribute("w:val");if(n){let o=n.toLowerCase();(o.includes("bold")||o.includes("strong"))&&(t.bold=!0),(o.includes("italic")||o.includes("emphasis"))&&(t.italic=!0),o.includes("underline")&&(t.underline=!0)}}return t.hasFormatting=t.bold||t.italic||t.underline||t.strikethrough,t}function Ur(e,t){let n=(e.getAttribute("w:val")||e.getAttribute("val")||"").toLowerCase();return n?t?n!=="none"&&n!=="0"&&n!=="false"&&n!=="off":n!=="0"&&n!=="false"&&n!=="off":!0}var Ci="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function He(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Ci&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function $l(e){return!e||e.nodeType!==1||e.namespaceURI!==Ci?!1:e.localName==="del"||e.localName==="moveFrom"}function Oi(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||$l(n))continue;if(He(n,"r")){t.push(n);continue}let o=Array.from(n.childNodes||[]);for(let i=o.length-1;i>=0;i-=1)r.push(o[i])}return t}function Pe(e){let t=new Set(["comment","footnote","endnote"]);return ce(e,"*","p").filter(n=>{let o=n.parentNode;for(;o&&o.nodeName;){let i=String(o.localName||"").toLowerCase();if(t.has(i))return!1;o=o.parentNode}return!0})}function ki(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],i=Oi(o);for(let a of i){let s=ae(a,"w:rPr");Array.from(a.childNodes||[]).forEach(l=>{if(He(l,"t")){let c=l.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=c.length)}else(He(l,"br")||He(l,"cr")||He(l,"tab")||He(l,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=1)})}r=pt(r,n,e.length)}return{textSpans:t,charOffset:r}}function Xl(e,t,r,n,o,i=null){let a=null;for(let c of Array.from(e.childNodes))if(He(c,"rPr")){a=c;break}let s=qe(a);i&&(i.bold&&!s.bold&&(s.bold=!0),i.italic&&!s.italic&&(s.italic=!0),i.underline&&!s.underline&&(s.underline=!0),i.strikethrough&&!s.strikethrough&&(s.strikethrough=!0)),s.hasFormatting=s.bold||s.italic||s.underline||s.strikethrough;let l=r;for(let c of Array.from(e.childNodes))if(He(c,"t")){let u=c.textContent||"";if(u.length>0){let f=l,m=l+u.length;n.push({charStart:f,charEnd:m,textElement:c,runElement:e,paragraph:t,rPr:a,format:{...s}}),s.hasFormatting&&o.push({start:f,end:m,format:{...s},run:e,rPr:a}),l=m}}return l}function Mi(e){let t=[],r=[],n=0,o=Pe(e);for(let i=0;i<o.length;i++){let a=o[i],s=null;for(let u of Array.from(a.childNodes))if(He(u,"pPr")){for(let f of Array.from(u.childNodes))if(He(f,"rPr")){s=f;break}break}let l=qe(s);l.hasFormatting&&L(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let c=Oi(a);for(let u of c)n=Xl(u,a,n,r,t,l);n=pt(n,i,o.length)}return L(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var Dl=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function jr(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())Dl.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function at(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof we?t:Ye(r)||nt(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let i of o){if(!I(i,"rPrChange"))continue;let a=String(n.next());typeof i.setAttributeNS=="function"?i.setAttributeNS(E,"w:id",a):i.setAttribute("w:id",a),n._receiptCollector?.recordRevision(Number(a),"rPrChange")}return e}function wt(e,t,r,n,o=null){let i=O(e,t==="ins"?"w:ins":"w:del"),a=o||ie(n,e,t==="ins"?"ins":"del");return i.setAttribute("w:id",String(a.id)),i.setAttribute("w:author",a.author),i.setAttribute("w:date",a.date),r&&i.appendChild(r),i}function _i(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function zl(e,t){let r=_i(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=O(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function Wl(e,t){let r=_i(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=O(e,"w:rPr"),t.appendChild(r)),r}function Li(e,t,r,n,o=null){let i=zl(e,t),a=Wl(e,i);for(let c of Array.from(a.childNodes||[]))c.nodeType===1&&(c.localName==="ins"||c.localName==="del"||c.nodeName==="w:ins"||c.nodeName==="w:del")&&a.removeChild(c);let s=O(e,n==="ins"?"w:ins":"w:del"),l=o||ie(r,e,n==="ins"?"ins":"del");return s.setAttribute("w:id",String(l.id)),s.setAttribute("w:author",l.author),s.setAttribute("w:date",l.date),a.appendChild(s),s}function Bi(e,t,r,n=null){return Li(e,t,r,"ins",n)}function lr(e,t,r,n=null){return Li(e,t,r,"del",n)}function st(e,t,r,n){let o=O(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Fi(e,o,t),o;let i=O(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function Hr(e,t,r,n,o,i,a){if(!t)return[];let s=new Set([0,t.length]);for(let u of n){let f=Math.max(0,u.start-o),m=Math.min(t.length,u.end-o);f>=0&&f<t.length&&s.add(f),m>0&&m<=t.length&&s.add(m)}let l=Array.from(s).sort((u,f)=>u-f),c=[];for(let u=0;u<l.length-1;u++){let f=l[u],m=l[u+1],d=t.slice(f,m);if(!d)continue;let p=o+f,h=o+m,w=n.filter(x=>x.start<=p&&x.end>=h),b={...qe(r)};w.forEach(x=>{x.format&&Object.assign(b,x.format)});let g=w.length>0?Bt(e,r,b,i,a):r?.cloneNode(!0)||null;c.push(Un(e,d,g,!1))}return c}function Un(e,t,r,n){let o=O(e,"w:r");if(r&&o.appendChild(r),!n)return Fi(e,o,t),o;let i=O(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function Fi(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let i of o){if(!i)continue;if(i===" "){t.appendChild(O(e,"w:tab"));continue}if(i===`
|
|
144
|
-
`){t.appendChild(
|
|
145
|
-
`).indexOf(n);if(s!==-1)for(let l of e){let c=l.startOffset,u=l.normalizedText.length;if(s>=c&&s<=c+u){o=l,
|
|
146
|
-
`:
|
|
147
|
-
`).replace(/\u00a0/g," "):""}function
|
|
148
|
-
`:l==="noBreakHyphen"?o+="\u2011":l==="softHyphen"?o+="\xAD":
|
|
149
|
-
`:
|
|
150
|
-
`:
|
|
151
|
-
`&&(I(t,"br")||I(t,"cr"))||r===" "&&I(t,"tab")||r==="\u2011"&&I(t,"noBreakHyphen")||r==="\xAD"&&I(t,"softHyphen"))return t.cloneNode(!0);if(n){let i=O(e,"w:delText");return i.setAttribute("xml:space","preserve"),i.textContent=r,i}let o=O(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function Yi(e,t,r,n,o,i,a){if(o.length===0)return!1;let s=t.rPr,l=qe(s),c={...l};if(o.forEach(S=>Object.assign(c,S.format)),!["bold","italic","underline","strikethrough"].some(S=>!!c[S]!==l[S]))return!1;let m=t.runElement.parentNode;if(!m)return!1;let d=t.textElement.textContent||"",p=t.charStart,h=r-p,w=n-p,b=d.substring(0,h),g=d.substring(h,w),x=d.substring(w);if(b.length>0){let S=st(e,b,s,!1);m.insertBefore(S,t.runElement)}let v=Bt(e,s,c,i,a),N=Un(e,g,v,!1);if(m.insertBefore(N,t.runElement),x.length>0){let S=st(e,x,s,!1);m.insertBefore(S,t.runElement)}return m.removeChild(t.runElement),!0}function eo(e,t,r,n,o,i,a=null){let s=[];if(fr(t,r,n,d=>{s.push(d)}),s.length===0)return!1;let l=new Map;s.forEach(d=>{d.runElement?.parentNode&&(l.has(d.runElement)||l.set(d.runElement,[]),l.get(d.runElement).push(d))});let c=[];l.forEach((d,p)=>{let h=p.parentNode;if(!h)return;let w=$t(p);if(w.length===0)return;let b=1/0,g=-1/0;d.forEach(x=>{let v=w.find(y=>y.node===x.textElement);if(!v)return;let N=Math.max(0,r-x.charStart),S=Math.min(x.charEnd-x.charStart,n-x.charStart);S<=N||(b=Math.min(b,v.start+N),g=Math.max(g,v.start+S))}),!(!Number.isFinite(b)||g<=b)&&c.push({runElement:p,parent:h,rPr:d[0].rPr,beforePieces:Ge(e,w,0,b,!1),deletedPieces:Ge(e,w,b,g,!0),afterPieces:Ge(e,w,g,Ve(w),!1),globalStart:Math.max(r,Math.min(...d.map(x=>x.charStart))),globalEnd:Math.min(n,Math.max(...d.map(x=>x.charEnd))),carrierGlobalStart:I(h,"ins")?Ji(t,h):null})});let u=[];for(let d of c){let p=u[u.length-1],h=p?.[p.length-1];h&&h.parent===d.parent&&cc(h.runElement)===d.runElement?p.push(d):u.push([d])}let f=!1,m=!1;for(let d of u){let p=d[0],h=null;if(i&&d.some(g=>g.deletedPieces.length>0)){let g=a?m?{...a,id:ie(o,e,"del").id}:a:null;m=!0,h=wt(e,"del",null,o,g)}for(let g of d){let{parent:x,runElement:v}=g;Nt(e,x,v,g.beforePieces,g.rPr),h&&g===p&&x.insertBefore(h,v),h&&g.deletedPieces.length>0&&h.appendChild(mr(e,g.deletedPieces,g.rPr));let N=Nt(e,x,v,g.afterPieces,g.rPr);g.globalEnd===n&&!I(x,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:x,referenceNode:N||v.nextSibling,rPr:g.rPr})),x.removeChild(v),f=!0}let w=I(p.parent,"ins")?p.parent:null,b=Math.max(...d.map(g=>g.globalEnd));if(w&&b===n){let g=p.carrierGlobalStart,x=d.filter(N=>N.globalStart<n).reduce((N,S)=>N+S.deletedPieces.reduce((y,T)=>y+(T.textContent||"").length,0),0),v=Math.max(0,n-g-x);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:w,splitOffset:v,rPr:p.rPr})}}return f}function Xt(e,t,r,n,o,i=[],a=0,s=!0,l=null,c=null,u=null,f="merge-same-author"){let m=t.revisionInsertionAnchors?.get(r)||null;if(m&&f==="slice-cross-author"&&Ki(m.carrier)&&Qn(m.carrier,o))return t.revisionInsertionAnchors.delete(r),Zn(e,m.carrier,m.splitOffset,n,m.rPr,o,i,a,s,c);let d=t.replacementInsertionAnchors?.get(r)||null;if(d&&!u&&Ki(d.parent)&&(!d.referenceNode||d.referenceNode.parentNode===d.parent))return t.replacementInsertionAnchors.delete(r),ct(e,d.parent,d.referenceNode,n,d.rPr,o,i,a,s,c),!0;if(!u){let N=Kn(t,r);if(!N&&r>0&&(N=Yn(t,r)),!N&&r>0&&(N=Jn(t,r)),!N&&t.spans.length>0&&(N=t.spans[t.spans.length-1]),!N)return l?(ct(e,l,null,n,null,o,i,a,s,c),!0):!1;let S=N.runElement.parentNode;if(!S)return l?(ct(e,l,null,n,N.rPr,o,i,a,s,c),!0):!1;let y=!(s&&f==="slice-cross-author"&&lc(S,o));if(s&&f==="slice-cross-author"&&Qn(S,o))return Zn(e,S,Gi(t,S,r),n,N.rPr,o,i,a,s,c);let T=$t(N.runElement),A=T.find(F=>F.node===N.textElement),M=A?A.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:Ve(T);if(M>0&&M<Ve(T)){let F=Ge(e,T,0,M,!1),X=Ge(e,T,M,Ve(T),!1);return Nt(e,S,N.runElement,F,N.rPr),ct(e,S,N.runElement,n,N.rPr,o,i,a,y,c),Nt(e,S,N.runElement,X,N.rPr),S.removeChild(N.runElement),!0}let _=r<=N.charStart?N.runElement:N.runElement.nextSibling;return ct(e,S,_,n,N.rPr,o,i,a,y,c),!0}let p=Hi(t,r,l),h=p.leftSpan&&I(p.leftSpan.runElement?.parentNode,"hyperlink"),w=p.rightSpan&&I(p.rightSpan.runElement?.parentNode,"hyperlink"),b=p.containingSpan&&I(p.containingSpan.runElement?.parentNode,"hyperlink");if(u.hyperlink==="outside"){if(p.isInterior&&b)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(u.hyperlink==="inside"&&!h&&!w&&!b)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let g=null;if(u.formatting==="none"?g=null:u.formatting==="right"?g=p.rightSpan?.rPr||null:u.formatting==="left"?g=p.leftSpan?.rPr||null:g=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let N=p.containingSpan,S=N.runElement.parentNode||l;if(!S)return!1;let y=$t(N.runElement),T=y.find(M=>M.node===N.textElement),A=T?T.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:Ve(y);if(A>0&&A<Ve(y)){let M=Ge(e,y,0,A,!1),_=Ge(e,y,A,Ve(y),!1);return Nt(e,S,N.runElement,M,N.rPr),ct(e,S,N.runElement,n,g,o,i,a,s,c),Nt(e,S,N.runElement,_,N.rPr),S.removeChild(N.runElement),!0}}let x=null,v=null;if(u.hyperlink==="outside"){if(w){let N=p.rightSpan.runElement.parentNode;x=N.parentNode||l,v=N}else if(h){let N=p.leftSpan.runElement.parentNode;x=N.parentNode||l,v=N.nextSibling}}else u.hyperlink==="inside"&&(w?(x=p.rightSpan.runElement.parentNode,v=p.rightSpan.runElement):h&&(x=p.leftSpan.runElement.parentNode,v=p.leftSpan.runElement.nextSibling));if(x||(p.rightSpan?(x=p.rightSpan.runElement.parentNode||l,v=p.rightSpan.runElement):p.leftSpan?(x=p.leftSpan.runElement.parentNode||l,v=p.leftSpan.runElement.nextSibling):(x=l,v=null)),u.bookmark&&x&&(u.bookmark==="outside"?(v&&I(v.previousSibling,"bookmarkStart")&&(v=v.previousSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(v=p.leftSpan.runElement.nextSibling.nextSibling)):u.bookmark==="inside"&&(v&&I(v,"bookmarkStart")&&(v=v.nextSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(v=p.leftSpan.runElement.nextSibling))),u.comment&&x)if(u.comment==="outside"){if(v&&I(v.previousSibling,"commentRangeStart")&&(v=v.previousSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let N=p.leftSpan.runElement.nextSibling.nextSibling;N&&(I(N,"commentReference")||I(N,"r"))&&Array.from(N.childNodes||[]).some(y=>I(y,"commentReference"))&&(N=N.nextSibling),v=N}}else u.comment==="inside"&&(v&&I(v,"commentRangeStart")&&(v=v.nextSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(v=p.leftSpan.runElement.nextSibling));if(s&&u.revision==="coalesce_same_author"){let N=null,S=null;if(p.leftSpan&&I(p.leftSpan.runElement.parentNode,"ins")){let y=p.leftSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(E,"author"))===o&&(N=y,S=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&I(p.rightSpan.runElement.parentNode,"ins")){let y=p.rightSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(E,"author"))===o&&(N=y,S=p.rightSpan.runElement)}if(N){let y=st(e,n,g,!1);return N.insertBefore(y,S),!0}}return s&&f==="slice-cross-author"&&Qn(x,o)?Zn(e,x,Gi(t,x,r),n,g,o,i,a,s,c):(ct(e,x,v,n,g,o,i,a,s,c),!0)}function Zn(e,t,r,n,o,i,a,s,l,c){let u=t.parentNode;if(!u)return!1;let{leftCarrier:f,rightCarrier:m}=Vi(e,t,r);return f&&u.insertBefore(f,t),ct(e,u,t,n,sc(o),i,a,s,l,c),m&&u.insertBefore(m,t),u.removeChild(t),!0}function sc(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>I(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Gi(e,t,r){let n=Ji(e,t),o=e.spans.filter(i=>i.runElement?.parentNode===t).reduce((i,a)=>i+(a.charEnd-a.charStart),0);return Math.max(0,Math.min(r-n,o))}function Ji(e,t){let r=e.spans.filter(n=>n.runElement?.parentNode===t);return r.length>0?Math.min(...r.map(n=>n.charStart)):0}function Qn(e,t){return I(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function lc(e,t){return I(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function cc(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Ki(e){return!!e?.parentNode}function ct(e,t,r,n,o,i,a,s,l,c=null){let u=Ke(a,s,s+n.length);if(u.length===0){let m=st(e,n,o,!1);if(l){let d=wt(e,"ins",m,i,c);t.insertBefore(d,r)}else t.insertBefore(m,r);return}let f=Hr(e,n,o,u,s,i,l);if(l){let m=wt(e,"ins",null,i,c);f.forEach(d=>m.appendChild(d)),t.insertBefore(m,r)}else f.forEach(m=>t.insertBefore(m,r))}function qi(e,t,r,n=!1){let o=[];if(fr(e,t,r,d=>o.push(d)),o.length===0)return{safe:!1};let i=o[0].runElement,a=i?.parentNode;if(!a)return{safe:!1};if(!o.every(d=>d.runElement?.parentNode===a))return{safe:!1,structuralBoundary:!0};let l=a.localName||a.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(l)||l==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let d of o){let p=d.runElement;for(let h of Array.from(p.childNodes||[]))if(h.nodeType===1){let w=h.localName||h.nodeName.replace(/^.*:/,"");if(c.has(w)||w==="fldChar")return{safe:!1,structuralBoundary:!0}}}let u=o[o.length-1].runElement,f=i;for(;f&&f!==u;){if(f!==i){let d=f.localName||f.nodeName.replace(/^.*:/,"");if(c.has(d))return{safe:!1,structuralBoundary:!0}}f=f.nextSibling}function m(d){if(!d||d.nodeType!==1)return!1;let p=d.localName||d.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let h of Array.from(d.childNodes||[]))if(h.nodeType===1&&m(h))return!0;return!1}return m(i.previousSibling)||m(u.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function ea(e,t,r,n,o,i,a=!0,s=null,l={},c={}){let u=s?[s]:Pe(e),{fullText:f,textSpans:m}=Yr(u),d=c.existingRevisions==="slice-cross-author"?li(f,r):null,p=d||fc(ir(f,r,l),l),h=Jr(m),w=c.pairReplacements===!0,b=[],g=0,x=0,v=!1,N=d?dc(d):[];if(N.length>1&&i.length===0)for(let T of N.slice().reverse()){let A=Yr(u).textSpans,M=Jr(A),_=T.text.replace(/\n/g," ");if(_.length===0)continue;let F=Xt(e,M,T.originalPos,_,o,i,T.newPos,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(F&&typeof F=="object"&&F.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:F.error});F===!0&&(v=!0)}else if(i.length===0){let T=mc(p);for(let A of T.reverse()){let M=Jr(Yr(u).textSpans);if(A.type==="insert"){let X=Xt(e,M,A.start,A.text.replace(/\n/g," "),o,i,A.newPos,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(X&&typeof X=="object"&&X.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:X.error});X===!0&&(v=!0);continue}let _=null,F=null;if(A.type==="replace"&&w&&a&&A.text.replace(/\n/g," ")){let X=qi(M,A.start,A.end,c?.existingRevisions==="slice-cross-author");if(X.safe){let C=rr(o,e);_={id:C.deletionId,author:C.author,date:C.date},F={id:C.insertionId,author:C.author,date:C.date}}else X.structuralBoundary&&b.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(eo(e,M,A.start,A.end,o,a,_)&&(v=!0),A.type==="replace"){let X=Xt(e,M,A.end,A.text.replace(/\n/g," "),o,i,A.newPos,a,u[0]||null,F,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(X&&typeof X=="object"&&X.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:X.error});X===!0&&(v=!0)}}}else for(let T=0;T<p.length;T++){let[A,M]=p[T];if(A===0){let _=M.length,F=g,X=g+_;fr(h,F,X,C=>{let W=Math.max(C.charStart,F),R=Math.min(C.charEnd,X),B=R-W,$=W-F,K=x+$,V=K+B,Y=Ke(i,K,V);Yi(e,C,W,R,Y,o,a)&&(v=!0)}),g+=_,x+=_}else if(A===-1){let _=T+1<p.length&&p[T+1][0]===1,F=!1,X=null,C=null;if(w&&a&&_&&p[T+1][1].replace(/\n/g," ").length>0){let B=qi(h,g,g+M.length,c?.existingRevisions==="slice-cross-author");if(B.safe){let $=rr(o,e);X={id:$.deletionId,author:$.author,date:$.date},C={id:$.insertionId,author:$.author,date:$.date},F=!0}else B.structuralBoundary&&b.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(eo(e,h,g,g+M.length,o,a,X)&&(v=!0),g+=M.length,F){T++;let[,W]=p[T],R=W.replace(/\n/g," ");if(R.length>0){let B=Xt(e,h,g,R,o,i,x,a,u[0]||null,C,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(B&&typeof B=="object"&&B.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:B.error});B===!0&&(v=!0)}x+=W.length}}else if(A===1){let _=M.replace(/\n/g," ");if(_.length>0){let F=Xt(e,h,g,_,o,i,x,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(F&&typeof F=="object"&&F.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:F.error});F===!0&&(v=!0)}x+=M.length}}let S=u.map(T=>fe(T)).join(`
|
|
152
|
-
`),
|
|
153
|
-
`);if(c.existingRevisions==="slice-cross-author"&&
|
|
154
|
-
`:
|
|
155
|
-
`)+o[u],
|
|
156
|
-
`).replace(/\u00a0/g," ")}function
|
|
157
|
-
`:
|
|
158
|
-
`){let
|
|
159
|
-
`)}function Tc(e){let t=0,r=xe(e,"ins");for(let n of r){if(!n.parentNode||en(n))continue;let o=ma(n);for(;ze(o,"ins")&&qr(Ze(o,"author"))===qr(Ze(n,"author"))&&da(o)===da(n);){let i=ma(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=i}}return t}function Qr(e){let t=e?.parentNode;return ze(t,"trPr")&&ze(t?.parentNode,"tr")}function en(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return ze(t,"rPr")&&ze(r,"pPr")&&ze(n,"p")}function ha(e){return en(e)?e.parentNode.parentNode.parentNode:null}function Ec(e){let t=e?.nextSibling||null;for(;t;){if(ze(t,"p"))return t;t=t.nextSibling}return null}function wa(e){if(!e?.parentNode)return!1;let t=Ec(e);if(!t)return ze(e.parentNode,"tc")&&xe(e.parentNode,"p").length<=1?!1:me(e);let r=Array.from(e.childNodes||[]).filter(o=>!ze(o,"pPr")),n=t.firstChild||null;ze(n,"pPr")&&(n=n.nextSibling||null);for(let o of r)t.insertBefore(o,n);return me(e)}function oo(e,t={}){let r=[],n=ro(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=no(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:i,serializer:a}=o;r.push(...o.warnings||[]);let s=0;for(let u of xe(i,"ins"))if(!(!u.parentNode||!Ce(u,n))){if(en(u)){me(u)&&(s+=1);continue}if(Qr(u)){me(u)&&(s+=1);continue}Zr(u)&&(s+=1)}for(let u of xe(i,"del")){if(!u.parentNode||!Ce(u,n))continue;let f=ha(u);if(f){wa(f)&&(s+=1);continue}if(Qr(u)){let m=u.parentNode?.parentNode;me(m)&&(s+=1);continue}me(u)&&(s+=1)}for(let u of xe(i,"moveFrom"))!u.parentNode||!Ce(u,n)||me(u)&&(s+=1);for(let u of xe(i,"moveTo"))!u.parentNode||!Ce(u,n)||Zr(u)&&(s+=1);s+=ba(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of xe(i,u))!f.parentNode||!Ce(f,n)||me(f)&&(s+=1);return{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(u=>a.serializeToString(u)).join(""):a.serializeToString(i),hasChanges:s>0,acceptedCount:s,warnings:r}}function pa(e,t){for(let r of Array.from(t.getElementsByTagNameNS(E,"delText"))){let n=O(e,"w:t"),o=r.getAttribute("xml:space");for(o&&n.setAttribute("xml:space",o);r.firstChild;)n.appendChild(r.firstChild);r.parentNode?.replaceChild(n,r)}}function Ac(e,t){let r=e?.parentNode;if(!r)return!1;let n=t.endsWith("Change")?t.slice(0,-6):"";if(!n||String(r.localName||"").toLowerCase()!==n.toLowerCase()||r.namespaceURI!==E)return me(e);let o=Array.from(e.childNodes||[]).find(a=>a.nodeType===1&&a.namespaceURI===E&&String(a.localName||"").toLowerCase()===n.toLowerCase());if(!o)return me(e);let i=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let a of i){let s=Ic(r.ownerDocument,a);r.appendChild(s)}return!0}function Ic(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function ga(e,t,r){let n=new Set;for(let o of xe(e,t)){if(!Ce(o,r))continue;let i=Ze(o,"id");i&&n.add(i)}return n}function ba(e,t){let r=0,n=ga(e,"moveFromRangeStart",t),o=ga(e,"moveToRangeStart",t),i=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",o,!0],["moveToRangeEnd",o,!1]];for(let[a,s,l]of i)for(let c of xe(e,a)){if(!c.parentNode)continue;let u=Ze(c,"id");u&&(t.allAuthors||s.has(u)||l&&Ce(c,t))&&me(c)&&(r+=1)}return r}function io(e,t={}){let r=[],n=ro(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=no(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:i,serializer:a}=o;r.push(...o.warnings||[]);let s=0;for(let u of xe(i,"ins")){if(!u.parentNode||!Ce(u,n))continue;let f=ha(u);if(f){wa(f)&&(s+=1);continue}if(Qr(u)){let m=u.parentNode?.parentNode;me(m)&&(s+=1);continue}me(u)&&(s+=1)}for(let u of xe(i,"del"))if(!(!u.parentNode||!Ce(u,n))){if(en(u)){me(u)&&(s+=1);continue}if(Qr(u)){me(u)&&(s+=1);continue}pa(i,u),Zr(u)&&(s+=1)}for(let u of xe(i,"moveFrom"))!u.parentNode||!Ce(u,n)||(pa(i,u),Zr(u)&&(s+=1));for(let u of xe(i,"moveTo"))!u.parentNode||!Ce(u,n)||me(u)&&(s+=1);s+=ba(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of xe(i,u))!f.parentNode||!Ce(f,n)||Ac(f,u)&&(s+=1);return Tc(i),{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(u=>a.serializeToString(u)).join(""):a.serializeToString(i),hasChanges:s>0,rejectedCount:s,warnings:r}}function Pc(e,t){let r=new Set,n=xe(e,"comment");for(let o of n){if(!Ce(o,t))continue;let i=Ze(o,"id");i&&r.add(i)}return{targetIds:r,commentNodes:n}}function Rc(e,t){let r=0;for(let n of e){let o=Ze(n,"id");!o||!t.has(o)||me(n)&&(r+=1)}return r}function Cc(e){return ze(e,"r")?Array.from(e.childNodes||[]).filter(r=>{if(r.nodeType===3)return String(r.nodeValue||"").trim().length>0;if(r.nodeType!==1)return!1;if(r.namespaceURI!==E)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function Oc(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let o of n)for(let i of xe(e,o)){if(!i.parentNode)continue;let a=Ze(i,"id");if(!(!a||!t.has(a))){if(o==="commentReference"&&Cc(i.parentNode)){me(i.parentNode)&&(r+=1);continue}me(i)&&(r+=1)}}return r}function kc(e,t={}){let r=[],n=ro(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=no(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:i,serializer:a}=o;r.push(...o.warnings||[]);let{targetIds:s,commentNodes:l}=Pc(i,n);if(n.allAuthors)for(let f of["commentRangeStart","commentRangeEnd","commentReference"])for(let m of xe(i,f)){let d=Ze(m,"id");d&&s.add(d)}let c=Rc(l,s),u=Oc(i,s);return{oxml:a.serializeToString(i),hasChanges:c>0||u>0,commentsRemoved:c,referencesRemoved:u,warnings:r}}var Mc=Object.freeze({formatOnly:Object.freeze({paragraphs:!0,formatting:!0,tables:"scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved"}),surgical:Object.freeze({paragraphs:!0,tables:"cell-scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved",notes:"preserved"}),reconstruction:Object.freeze({paragraphs:!0,hyperlinks:"sentinel-preserved",fields:"sentinel-preserved",comments:"marker-preserved",notes:"reference-preserved"}),table:Object.freeze({tables:!0,paragraphs:!0,formatting:"cell-dependent",numbering:!1}),listDirect:Object.freeze({lists:!0,numbering:!0,paragraphs:"single-source expansion",tables:"embedded-markdown blocks",formatting:"markdown hints"}),listCompatibilityPipeline:Object.freeze({lists:!0,numbering:!0,paragraphs:"multi-source patching",compatibility:!0})});function Qe(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:Mc[t]||null,...r}))}var _c=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function Me(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function dr(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function ao(e,t){return dr(e).find(r=>Me(r)===t)||null}function so(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function tn(e){return String(e||"").trim().toLowerCase()}function Lc(e){return Me(e)!=="r"?!1:dr(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(Me(t)))}function lo(e){return _c.has(Me(e))||Lc(e)}function co(e){return Me(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(Me(e))?dr(e).filter(r=>!lo(r)&&Me(r)!=="sdtPr").every(co):!1}function xa(e){let t=ao(e,"pPr"),r=ao(t,"rPr");return ao(r,"del")}function Bc(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=Me(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,o=!1;for(;n&&n!==e;){let i=Me(n);if(i==="del"||i==="moveFrom"){o=!0;break}n=n.parentNode}if(!o&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function Na(e,t){let r=xa(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=so(r,"author")||null,o=!n||tn(n)!==tn(t),a=dr(e).filter(s=>!lo(s)).every(co);return{matches:o&&a,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:a,ownerAuthor:n,markDeletion:r}}function va(e){let t=Me(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>Me(n)==="p"),r=[];for(let n of t){let o=xa(n);if(!o)continue;let i=so(o,"author")||null,a=dr(n).filter(c=>!lo(c)),s=a.filter(c=>Me(c)!=="ins"||!Bc(c)?!1:tn(so(c,"author"))!==tn(i)),l=a.every(c=>co(c)||s.includes(c));s.length>0&&l&&r.push({paragraph:n,markDeletion:o,ownerAuthor:i,foreignInsertions:s})}return r}function Fc(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of ve(e,E,r)){let o=n.getAttribute?.("w:id")||n.getAttribute?.("id");o!==""&&t.add(o)}return[...t].sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function vt(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===E&&r.localName===t)||null}function $c(e,t){let r=vt(vt(vt(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(E,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(E,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(E,"date")||""}}function Xc(e,t){let r=e.cloneNode(!1),n=vt(e,"pPr");return n&&r.appendChild(jr(n)),t.serializeToString(r)}function Dc(e,t){if(!t||typeof e!="string"||!e.trim())return e;let r=j(e,"text/xml");if(!r.doc||r.error)return e;let n=r.doc.documentElement?.localName==="p"?r.doc.documentElement:Pe(r.doc)[0];if(!n)return e;let o=vt(n,"pPr");o||(o=O(r.doc,"w:pPr"),n.insertBefore(o,n.firstChild));let i=vt(o,"rPr");if(i||(i=O(r.doc,"w:rPr"),o.appendChild(i)),!vt(i,"ins")){let a=O(r.doc,"w:ins");t.id&&a.setAttribute("w:id",t.id),a.setAttribute("w:author",t.author),t.date&&a.setAttribute("w:date",t.date),i.appendChild(a)}return te(r.doc)}async function uo(e,t,r,n={}){let o=e,i=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let a=n.generateRedlines??!0,s=n.author||pe(),l=de(),c=[],u=[],f=!1,m=null,d=n.existingRevisions||"merge-same-author",p=d==="accept-all-first-keep-normalized",h=z=>{let k={...z};f&&k.hasChanges===!1&&k.status!=="error"&&(d==="merge-same-author"||d==="slice-cross-author"?(k.oxml=i,k.hasChanges=!0,k.warnings=[...Array.isArray(k.warnings)?k.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(k.oxml=i,k.hasChanges=!0,k.warnings=[...Array.isArray(k.warnings)?k.warnings:[],"Existing revisions were accepted before redlining."]):k.oxml=o);let Z=[...c,...u,...Array.isArray(k.warnings)?k.warnings:[]];return Z.length>0&&(k.warnings=[...new Set(Z)]),k.status||(k.status=k.hasChanges?"ok":"no-op"),m&&k.hasChanges&&typeof k.oxml=="string"&&(k.oxml=Dc(k.oxml,m)),se(k)},w=()=>h(f&&p?{oxml:i,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),b=j(o,"text/xml");c=b.warnings;let g=b.doc,x=g?ne(g):null;if(b.error||x){let z=b.error?.message||x?.textContent||"Could not parse OOXML input.";return ee("[OxmlEngine] XML parse error:",z),h({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:z}})}let v=n?._revisionIdAllocator instanceof we?n._revisionIdAllocator:new we;Rt(g,v);let N=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Pe(g);if(N.length===1&&r.length>0){let z=Na(N[0],s);if(z.matches){let k=z.ownerAuthor||"unattributed";return h({oxml:o,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${k}). Use explicit paragraph restoration when supported.`,ownerAuthor:k}})}}if(zr(g))if(d==="merge-same-author"||d==="slice-cross-author"){let z=Dn(g),k=String(s||"").trim().toLowerCase();if(z.length>0&&z.every(le=>le.trim().toLowerCase()===k)){let le=Fc(g);if(le.length>0)return h({oxml:o,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:le}});L("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let Ae=N.length===1?N[0]:null;m=$c(Ae,s);let Yt=io(o,{author:s});if(Yt.status==="error")return h(Yt);i=m&&!String(Yt.oxml||"").trim()?Xc(Ae,l):Yt.oxml,f=!0;let Rr=j(i,"text/xml");c.push(...Rr.warnings),g=Rr.doc;let Bo=g?ne(g):null;if(Rr.error||Bo){let Cr=Rr.error?.message||Bo?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return ee("[OxmlEngine] XML parse error after rejecting same-author revisions:",Cr),h({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Cr}})}if(zr(g))return h({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});Rt(g,v);let Fo=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Pe(g);t=Fo.length>0?Fo.map(Cr=>fe(Cr)).join(`
|
|
160
|
-
`):""}else{if(
|
|
161
|
-
`)||t.includes("\r")?t.split(/\r?\n/).map(
|
|
162
|
-
`),
|
|
163
|
-
`:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function
|
|
164
|
-
`)}function ho(e){if(e==null)return null;if(typeof e=="number"&&Number.isInteger(e)&&e>0)return e;let t=String(e).trim();if(!t)return null;let r=t.match(/^\[?P(\d+)(?:\.\d+)?\]?$/i);if(r)return Number.parseInt(r[1],10);let n=t.match(/^(\d+)$/);return n?Number.parseInt(n[1],10):null}function zc(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function Wc(e){let t=String(e||""),r=t.match(/^\s*\[P(\d+)(?:\.\d+)?\]\s*/i);return r?{text:t.replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim(),targetRef:Number.parseInt(r[1],10)}:{text:t.trim(),targetRef:null}}function Ea(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:Te(e)[t-1]||null}function Dt(e,t,r=Oe){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function on(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,i=o?null:Te(e),a=String(t||"").trim();if(!a)return null;let s=o?o.find(c=>c.text.trim()===a)?.paragraph:i.find(c=>ue(c).trim()===a);if(s)return s;let l=H(a);return n?.byNormalizedText?n.byNormalizedText.get(l)?.[0]?.paragraph||null:i.find(c=>H(ue(c))===l)||null}function mo(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,i=o?.entries||null,a=i?null:Te(e),s=String(t||"").trim();if(!s)return null;let l=on(e,s,{paragraphMetadataIndex:o});if(l)return l;let c=H(s),u=i?i.find(w=>w.normalizedText.length>10&&c.startsWith(w.normalizedText))?.paragraph||null:a.find(w=>{let b=H(ue(w));return b.length>10&&c.startsWith(b)});if(u)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${ue(u).trim().slice(0,60)}..."`),u;let f=i?i.find(w=>w.normalizedText.length>15&&c.includes(w.normalizedText))?.paragraph||null:a.find(w=>{let b=H(ue(w));return b.length>15&&c.includes(b)});if(f)return n(`[Fuzzy] Contains match: "${ue(f).trim().slice(0,60)}..."`),f;let m=0,d=null,p=new Set(c.toLowerCase().split(/\s+/).filter(w=>w.length>2)),h=i?.length??a.length;for(let w=0;w<h;w++){let b=i?.[w]?.paragraph??a[w],g=(i?.[w]?.text??ue(b)).trim();if(!g)continue;let N=H(g).toLowerCase().split(/\s+/).filter(S=>S.length>2).filter(S=>p.has(S)).length/Math.max(p.size,1);N>m&&N>.5&&(m=N,d=b)}return d?(n(`[Fuzzy] Best word-overlap match (${(m*100).toFixed(0)}%): "${ue(d).trim().slice(0,60)}..."`),d):null}function Aa(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},o=t.opType||"operation",i=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,a=i?.revisionView==="rejected"?"rejected":"accepted",s=String(i?.exactText??i?.text??t.targetText??"").trim(),l=ho(i?.index??i?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,u=t.paragraphMetadataIndex||null;if(u&&u.revisionView!==a?u=t.metadataIndices?.[a]||Ta(e,{revisionView:a}):u||(u=Ta(e,{revisionView:a})),i?.paragraphId){let m=jc(e,i.paragraphId,u);if(!m)throw Se("TARGET_NOT_FOUND",`Target paragraphId not found: "${i.paragraphId}".`);let d=u?.byParagraph?.get(m)||null,p=d?.index??Te(e).indexOf(m)+1,h=d?.fingerprint||St(m,{revisionView:a}),w=d?.inTable??gr(m),b=d?.normalizedText||H(fe(m,{revisionView:a}));if(l!=null&&l!==p)throw Se("TARGET_INDEX_MISMATCH",`Target paragraphId "${i.paragraphId}" (index ${p}) does not match requested index ${l}.`,d?[We(d)]:null);if(i.fingerprint&&i.fingerprint!==h){let g=a==="rejected"?"accepted":"rejected",x=St(m,{revisionView:g}),v=i.fingerprint===x?` The supplied fingerprint matches the ${g} view; set target.revisionView to "${g}" or use a fingerprint extracted from the ${a} view.`:"";throw Se("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches its source fingerprint.${v}`,d?[We(d)]:null)}if(typeof i.inTable=="boolean"&&i.inTable!==w)throw Se("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" does not match the requested table context.`,d?[We(d)]:null);if(s&&b!==H(s)){let g=a==="rejected"?"accepted":"rejected",v=H(fe(m,{revisionView:g}))===H(s)?` The supplied text matches the ${g} view; set target.revisionView to "${g}".`:"";throw Se("TARGET_TEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches the supplied text.${v}`,d?[We(d)]:null)}if(i.occurrence!=null){let x=an(e,s||b,u),v=x.findIndex(N=>N.paragraph===m)+1;if(v===0||v!==i.occurrence)throw Se("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${i.paragraphId}" matches occurrence ${v}, not requested occurrence ${i.occurrence}.`,x.map(We))}return{paragraph:m,resolvedBy:"paragraph_id"}}if(i?.fingerprint&&!s&&!l){let m=(u?.entries||[]).filter(d=>d.fingerprint===i.fingerprint);if(typeof i.inTable=="boolean"&&(m=m.filter(d=>d.inTable===i.inTable)),m.length===1)return{paragraph:m[0].paragraph,resolvedBy:"fingerprint"};throw m.length>1?Se("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",m.map(We)):Se("TARGET_NOT_FOUND",`Target fingerprint not found: "${i.fingerprint}".`)}let f=[];if(s){let m=an(e,s,u);if(f=Uc(m,i),i?.fingerprint&&m.length>0&&f.length===0)throw Se("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",m.map(We));if(typeof i?.inTable=="boolean"&&m.length>0&&f.length===0)throw Se("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",m.map(We));if(i?.occurrence){let d=f[i.occurrence-1]||null;if(!d)throw Se("TARGET_NOT_FOUND",`Target occurrence ${i.occurrence} was not found.`,f.map(We));return{paragraph:d.paragraph,resolvedBy:"occurrence"}}if(c){if(l){let d=f.find(p=>p.index===l)||null;if(d)return{paragraph:d.paragraph,resolvedBy:"ref"};if(i?.fingerprint&&f.length>0)throw Se("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`,f.map(We));if(f.length===1)return{paragraph:f[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(f.length>1)throw Se("AMBIGUOUS_TARGET",`Target text matched ${f.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,f.map(We));if(f.length===0)throw pr(`Target paragraph not found: "${s}"`)}if(!l&&f.length===1)return{paragraph:f[0].paragraph,resolvedBy:i?.fingerprint?"fingerprint":"strict_text"}}if(l){let m=Ea(e,l,u);if(m){let d=u?.byParagraph?.get(m)||null;if(i?.fingerprint&&i.fingerprint!==d?.fingerprint)throw Se("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`);if(typeof i?.inTable=="boolean"&&i.inTable!==d?.inTable)throw Se("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${l}] does not match requested table context.`);if(s){let p=on(e,s,{paragraphMetadataIndex:u}),h=(d?.text||fe(m,{revisionView:a})).trim(),w=H(h),b=H(s),g=w!==b;if(g&&p&&p!==m)return r(`[Target] [P${l}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(g){let x=mo(e,s,{onInfo:r,paragraphMetadataIndex:u});if(x&&x!==m)return r(`[Target] [P${l}] drifted for ${o}; using fuzzy text rematch.`),{paragraph:x,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${l}] fallback for ${o}; target text drifted.`)}else p&&p!==m&&r(`[Target] [P${l}] disambiguated duplicate target text for ${o}.`)}else r(`[Target] Using [P${l}] fallback for ${o}.`);return{paragraph:m,resolvedBy:"ref"}}n(`[WARN] Target reference [P${l}] not found; falling back to text matching for ${o}.`)}if(s&&!c){let m=on(e,s,{paragraphMetadataIndex:u});if(m){let p=f.length;if(p>1){let h=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(h),{paragraph:m,resolvedBy:"strict_text",warnings:[h]}}return{paragraph:m,resolvedBy:"strict_text"}}let d=mo(e,s,{onInfo:r,paragraphMetadataIndex:u});if(d)return{paragraph:d,resolvedBy:"fuzzy_text"}}throw pr(s?`Target paragraph not found: "${s}"`:l?`Target paragraph reference not found: [P${l}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function gr(e){return!!Dt(e,"tbl")}function an(e,t,r=null){let n=H(t);if(!n)return[];let o=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,i=r?.revisionView||o?.revisionView||"accepted";if(o?.byNormalizedText&&o.revisionView===i)return Array.from(o.byNormalizedText.get(n)||[]);let a=Te(e),s=[];for(let l=0;l<a.length;l++){let c=a[l],u=fe(c,{revisionView:i}).trim();u&&H(u)===n&&s.push({paragraph:c,index:l+1,inTable:gr(c),paragraphId:Tt(c),fingerprint:St(c,{text:u,index:l+1,revisionView:i}),text:u,revisionView:i})}return s}function We(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function Uc(e,t){let r=e.slice();return t?.paragraphId&&(r=r.filter(n=>n.paragraphId===t.paragraphId)),typeof t?.inTable=="boolean"&&(r=r.filter(n=>n.inTable===t.inTable)),t?.fingerprint&&(r=r.filter(n=>n.fingerprint===t.fingerprint)),r}function jc(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:Te(e).find(n=>Tt(n)===t)||null:null}function Hc(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let o=n.filter(i=>i.inTable===r);o.length>0&&(n=o)}return Number.isInteger(t)&&t>0&&n.sort((o,i)=>Math.abs(o.index-t)-Math.abs(i.index-t)),n[0]||null}function Vc(e,t=null){let r=t?.entries||null,n=r?null:Te(e),o=new Map,i=r?.length??n.length;for(let a=0;a<i;a++){let s=r?.[a]?.paragraph??n[a],l=(r?.[a]?.text??ue(s)).trim();o.set(a+1,{text:l,normalizedText:r?.[a]?.normalizedText??H(l),inTable:r?.[a]?.inTable??gr(s)})}return o}function po(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=Aa(e,t),o=ho(t.targetRef);if(!o||n?.resolvedBy!=="ref")return n;let i=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(o)||null;if(!i)return n;let a=String(t.targetText||"").trim(),s=a||i.text||"",l=H(s);if(!l||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||H(ue(n.paragraph)))===l)return n;let u=[];if(a&&u.push(a),i.text){let m=H(i.text);m&&!u.some(d=>H(d)===m)&&u.push(i.text)}let f=null;for(let m of u){let d=an(e,m,t.paragraphMetadataIndex||null),p=Hc(d,o,i.inTable);if(p&&(f||(f=p),p.paragraph!==n.paragraph)){f=p;break}}if(f&&f.paragraph!==n.paragraph){let m=t.opType||"operation";return r(`[Target] [P${o}] appears stale after prior edits; using strict text rematch for ${m}.`),{paragraph:f.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw pr(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function Gc(e,t,r,n={}){if(!e||!t||!r)return null;let o=n?.opType||"redline",i=n?.targetRefSnapshot||null,a=typeof n?.onInfo=="function"?n.onInfo:()=>{},s=typeof n?.onWarn=="function"?n.onWarn:()=>{},l=po(e,{targetRef:t,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!l)return null;let c=po(e,{targetRef:r,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!c)return null;let u=Array.from(e.getElementsByTagNameNS("*","p")),f=u.indexOf(l),m=u.indexOf(c);if(f<0||m<f)return null;let d=u.slice(f,m+1);if(d.length===0)return null;let p=d[0]?.parentNode||null;return!p||!d.every(h=>h&&h.parentNode===p)?null:d}function sn(e,t){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let r=e.getElementsByTagNameNS(Oe,t);if(r.length>0)return r[0];let n=e.getElementsByTagNameNS("*",t);return n.length>0?n[0]:null}function Ia(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(Oe,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function Ra(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=je(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function Ca(e){let t=String(e||"").split(/\r?\n/g),r=[],n=!1;for(let o of t){let i=o.trimEnd();if(!i.trim())continue;let a=er(i,{indentSpaces:2});if(a){n=!0,r.push({kind:"list",markerType:a.markerType,level:a.level,marker:a.marker,outlineLevel:a.outlineLevel,text:Ra(a.text)});continue}r.push({kind:"text",text:i.trim()})}return{items:r,hasListMarkers:n}}function Pa(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function hr(e,t){return H(e)===H(t)}function ln(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function Kc(e,t,r){if(!Array.isArray(e)||e.length<2||!Number.isInteger(r)||r<0)return!1;let n=e[0],o=e.slice(1).filter(i=>i.kind==="list");if(o.length===0||o.some(i=>i.markerType!=="bullet")||o.some(i=>Number.isInteger(i.outlineLevel)))return!1;if(n?.kind==="text")return hr(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let i=n.level||0;return o.some(s=>(s.level||0)>i)?!1:hr(n.text,t)}return!1}function Yc(e,t){return e.map(r=>{let n=Math.max(0,(r.ilvl||0)-t);return{...r,ilvl:Math.min(8,t+1+n)}})}function Jc(e,t,r,n){let o=e[0],i=e.slice(1).filter(a=>a.kind==="list");if(o?.kind==="text"&&hr(o.text,t)&&i.length>0){let a=i[0].level;return i.map(s=>({ilvl:ln(s,r,a),markerType:s.markerType||n,text:s.text}))}if(e.every(a=>a.kind==="list")){let a=e[0];if(!a||!hr(a.text,t))return null;let s=a.level;return e.slice(1).map(l=>({ilvl:ln(l,r,s),markerType:l.markerType||n,text:l.text})).filter(l=>l.text)}return null}function tt(e){if(!e)return null;let t=sn(e,"pPr");if(!t)return null;let r=sn(t,"numPr");if(!r)return null;let n=sn(r,"numId");if(!n)return null;let o=Ia(n);if(!o||o==="0")return null;let i=sn(r,"ilvl"),a=Ia(i),s=Number.parseInt(a||"0",10);return{numId:String(o),ilvl:Number.isFinite(s)?s:0}}function Oa(e){let t=tt(e);if(!t)return null;let r=e.parentNode;if(!r)return null;let n=Array.from(r.childNodes||[]).filter(s=>s&&s.nodeType===1&&s.namespaceURI===Oe&&s.localName==="p"),o=n.indexOf(e);if(o<0)return null;let i=o;for(;i>0;){let s=tt(n[i-1]);if(!s||s.numId!==t.numId)break;i--}let a=o;for(;a<n.length-1;){let s=tt(n[a+1]);if(!s||s.numId!==t.numId)break;a++}return n.slice(i,a+1)}function qc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
|
|
165
|
-
`)
|
|
166
|
-
`),
|
|
167
|
-
`)
|
|
168
|
-
`)
|
|
169
|
-
`)
|
|
170
|
-
`)
|
|
171
|
-
`))return null;let r=wr(t);if(!r||!wo(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let o=String(n.marker||"").trim(),i=n.type==="numbered"?Qt(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:i,startAt:nu(o,i),contentText:String(n.text||"").trim(),normalizedContent:H(String(n.text||""))}}function ru(e){let t=cn(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function nu(e,t){if(t!=="decimal")return null;let r=String(e||"").trim().match(/^(\d+)\.?$/);if(!r)return null;let n=Number.parseInt(r[1],10);return Number.isFinite(n)&&n>0?n:null}function ou(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let o=t?.explicitByNumberingKey;if(!(o instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let i=o.get(r)||null;return i&&i.numId!=null&&Number.isInteger(i.nextStartAt)&&i.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(i.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function iu(e,t,r,n){!e||!(e.explicitByNumberingKey instanceof Map)||!t||r==null||!Number.isInteger(n)||n<1||e.explicitByNumberingKey.set(String(t),{numId:String(r),nextStartAt:n+1})}function au(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function zt(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI==="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&&r.localName===t)||null}function su(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,o=t?.clearParagraphPropertyChanges!==!1,i=t?.removeListPropertyNode!==!1,a=(Array.isArray(e)?e:[]).filter(l=>l&&l.nodeType===1&&l.localName==="p"),s=0;for(let l of a){let c=l.ownerDocument;if(!c)continue;let u=zt(l,"pPr");if(u||(u=O(c,"w:pPr"),l.insertBefore(u,l.firstChild)),o){let p=zt(u,"pPrChange");p&&u.removeChild(p)}if(i){let p=zt(u,"listPr");p&&u.removeChild(p)}let f=zt(u,"numPr");f||(f=O(c,"w:numPr"),u.appendChild(f));let m=zt(f,"ilvl");m||(m=O(c,"w:ilvl"),f.appendChild(m)),m.setAttribute("w:val",String(n));let d=zt(f,"numId");d||(d=O(c,"w:numId"),f.appendChild(d)),d.setAttribute("w:val",String(r)),s++}return s}function lu(e){let t=j(e,"application/xml").doc;return!t||ne(t)?null:Te(t)[0]||null}function cu(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function uu(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function Wt(e,t){let r=uu(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function _a(e,t){e.setAttribute("w:val",String(t))}function fu(e){let t=j(e,"application/xml").doc;if(!t||ne(t))return null;let o=Te(t)[0]||null;if(!o)return null;let i=Array.from(o.getElementsByTagNameNS("*","numId"));for(let a of i){let s=Wt(a,["w:val","val"]);if(s!=null)return String(s)}return null}function mu(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,i=de(),a=j(e,"application/xml").doc;if(!a||ne(a))return e;let c=Array.from(a.getElementsByTagNameNS("*","num")).find(p=>{let h=Wt(p,["w:numId","numId"]);return h!=null&&String(h)===String(t)});if(!c)return e;let u=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=Wt(u,["w:val","val"]),m=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>Wt(p,["w:ilvl","ilvl"])===0)||null;m||(m=O(a,"w:lvlOverride"),m.setAttribute("w:ilvl","0"),c.appendChild(m));let d=Array.from(m.getElementsByTagNameNS("*","startOverride"))[0]||null;if(d||(d=O(a,"w:startOverride"),m.appendChild(d)),_a(d,r),o&&f!=null){let h=Array.from(a.getElementsByTagNameNS("*","abstractNum")).find(w=>{let b=Wt(w,["w:abstractNumId","abstractNumId"]);return b!=null&&b===f})||null;if(h){let w=Array.from(h.getElementsByTagNameNS("*","lvl")).find(g=>Wt(g,["w:ilvl","ilvl"])===0)||null;w||(w=O(a,"w:lvl"),w.setAttribute("w:ilvl","0"),h.appendChild(w));let b=Array.from(w.getElementsByTagNameNS("*","start"))[0]||null;b||(b=O(a,"w:start"),w.insertBefore(b,w.firstChild)),_a(b,r)}}return i.serializeToString(a)}function bo(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),o=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let i=lu(t);if(!i)return null;let a=tt(i);if(a&&!o)return null;let s=Ie(n).cleanText||n,l=cn(n)||cn(s);if(!l)return null;let c=cn(r),u=H(r)===H(s),f=!!c&&c.type===l.type&&c.normalizedContent===l.normalizedContent;return!u&&!f?null:{listInput:`${l.marker} ${l.contentText}`.trim(),numberingKey:`${l.type}:${l.numberingStyle}:single`,originalText:r,wasListParagraph:!!a,startAt:l.startAt}}async function un(e,t={}){if(!e||!e.listInput)return{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:null,warnings:["Single-line list fallback plan missing"]};let r=t.author||"AI",n=t.generateRedlines??!0,o=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await _t({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new Je}),i=o?.oxml||o?.ooxml||"",a=cu(i),s=fu(a),l=mu(o?.numberingXml||null,s,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=o?.isValid!==!1;return!a||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:a,numberingXml:l,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}var du=new Set(["ins","del","rPrChange","pPrChange"]),pu=/^\d{4}-\d{2}-\d{2}T/;function ut(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Et(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>ut(r)===t)}function At(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function gu(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function hu(e){return ut(e.parentNode)==="rPr"}function wu(e){let t=r=>{let n=Do(r),o=n.getElementsByTagName("parsererror")[0];if(o)throw new Error(o.textContent||"XML parse error");return n};try{return{doc:t(e)}}catch{try{return{doc:t(`<w:root xmlns:w="${E}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function bu(e){let t=[],r=(f,m,d)=>t.push({code:f,severity:m,message:d}),n=e&&typeof e=="object"&&(e.nodeType===9||e.nodeType===1);if(!n&&(typeof e!="string"||e.trim()===""))return r("PARSE_ERROR","error","Input is not non-empty OOXML or a parsed XML DOM."),{valid:!1,issues:t};let{doc:o,error:i}=n?{doc:e.nodeType===9?e:e.ownerDocument}:wu(e);if(!o)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${i}`),{valid:!1,issues:t};let a=Et(o,"ins"),s=Et(o,"del"),l=a.concat(s);for(let f of Et(o,"p")){let m=Array.from(f.getElementsByTagName("*")).find(d=>d!==f&&ut(d)==="p");m&&r("NESTED_PARAGRAPH","error",`<${f.nodeName}> contains nested <${m.nodeName}>.`)}for(let f of Et(o,"body")){let m=Array.from(f.childNodes||[]).filter(p=>p.nodeType===1),d=m.map((p,h)=>ut(p)==="sectPr"?h:-1).filter(p=>p>=0);d.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):d.length===1&&d[0]!==m.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let f of l){let d=Array.from(f.getElementsByTagName("*")).filter(p=>p!==f&&["ins","del"].includes(ut(p))).find(p=>ut(f)!=="ins"||ut(p)!=="del"?!0:p.parentNode!==f);d&&r("NESTED_REVISION","error",`<${f.nodeName}> (w:id="${At(f,"id")}") contains invalid nested <${d.nodeName}>.`)}for(let f of s)Et(f,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${At(f,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let f of l){let m=[];At(f,"id")||m.push("w:id"),At(f,"author")||m.push("w:author"),pu.test(At(f,"date"))||m.push("w:date"),m.length>0&&r("MISSING_REVISION_METADATA","error",`<${f.nodeName}> is missing or has malformed ${m.join(", ")}.`)}let c=new Set;for(let f of Array.from(o.getElementsByTagName("*"))){if(!du.has(ut(f)))continue;let m=At(f,"id");m&&(c.has(m)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${m} appears more than once.`),c.add(m))}let u=Et(o,"t").concat(Et(o,"delText"));for(let f of u){let m=f.textContent||"";/^\s|\s$/.test(m)&&gu(f)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${f.nodeName}> has boundary whitespace without xml:space="preserve".`),m===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${f.nodeName}> is empty.`)}for(let f of l){if(hu(f))continue;Array.from(f.childNodes||[]).some(d=>d.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${f.nodeName}> (w:id="${At(f,"id")}") wraps no content.`)}for(let f of va(o)){let m=f.ownerAuthor||"unattributed";r("FOREIGN_PARAGRAPH_MARK_DELETION","warning",`Paragraph deleted by ${m} also contains non-empty insertion content from another author; Accept/Reject lifecycle may not preserve the apparent restoration.`)}return{valid:!t.some(f=>f.severity==="error"),issues:t}}function fn(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Oe&&r.localName===t):[]}function xu(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function Nu(e){let t=fn(e,"tr"),r=t.map(o=>fn(o,"tc").map(a=>{let s=fn(a,"p");return s.length===0?H(ue(a)):s.map(c=>H(ue(c))).filter(Boolean).join(`
|
|
172
|
-
`)})),n=r.reduce((o,i)=>Math.max(o,i.length),0);return r.forEach(o=>{for(;o.length<n;)o.push("")}),{matrix:r,rowElements:t,columnCount:n}}function vu(e,t){if(!Array.isArray(e)||e.length===0||t<=0)return null;let r=e.map(s=>{let l=Array.isArray(s)?s.slice(0,t):[];for(;l.length<t;)l.push("");return l}),n=r[0],o=new Array(t).fill("---"),i=r.slice(1),a=s=>`| ${s.map(l=>xu(l)).join(" | ")} |`;return[a(n),a(o),...i.map(a)].join(`
|
|
173
|
-
`)}
|
|
174
|
-
`)
|
|
143
|
+
`);return{valid:o.every(l=>l.severity!=="error"),normalizedMarkdown:s,blocks:n,issues:o,counts:i,requiresStructuredContent:n.length>1||n.some(l=>l.type==="heading"||l.type==="table"||l.type==="list"&&l.items>1)}}function Od(e,t,r={}){let n=Eo(t);return{...n,operation:n.valid?{type:"replace",target:e,modified:n.normalizedMarkdown,structuredContent:!0,...r.author?{author:r.author}:{},...typeof r.generateRedlines=="boolean"?{generateRedlines:r.generateRedlines}:{},...r.existingRevisions?{existingRevisions:r.existingRevisions}:{}}:null}}var Cn=["w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"];function Be(e,t){let r=Cn.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=Cn.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function _d(e,t,r,n){if(!t||!r)return;let o=!!r.bold,a=!!r.italic,i=!!r.underline,s=!!r.strikethrough,l=new Set;if(o&&(l.add("w:b"),l.add("w:bCs")),a&&(l.add("w:i"),l.add("w:iCs")),i&&l.add("w:u"),s&&l.add("w:strike"),l.size>0){let c=[];for(let u of Array.from(t.childNodes))l.has(u.nodeName)&&c.push(u);for(let u of c)t.removeChild(u)}if(o){let c=B(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),Be(t,c);let u=B(e,"w:bCs");u.setAttribute("w:val",n==="add"?"1":"0"),Be(t,u)}if(a){let c=B(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),Be(t,c);let u=B(e,"w:iCs");u.setAttribute("w:val",n==="add"?"1":"0"),Be(t,u)}if(i){let c=B(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),Be(t,c)}if(s){let c=B(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),Be(t,c)}}function hl(e,t,r){_d(e,t,r,"remove")}function Pt(e){let t={bold:!1,italic:!1,underline:!1,strikethrough:!1,hasFormatting:!1};if(!e)return t;for(let r of Array.from(e.childNodes))if(r.nodeName==="w:b"&&(t.bold=xr(r,!1)),r.nodeName==="w:i"&&(t.italic=xr(r,!1)),r.nodeName==="w:u"&&(t.underline=xr(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=xr(r,!1)),r.nodeName==="w:rStyle"){let n=r.getAttribute("w:val");if(n){let o=n.toLowerCase();(o.includes("bold")||o.includes("strong"))&&(t.bold=!0),(o.includes("italic")||o.includes("emphasis"))&&(t.italic=!0),o.includes("underline")&&(t.underline=!0)}}return t.hasFormatting=t.bold||t.italic||t.underline||t.strikethrough,t}function xr(e,t){let n=(e.getAttribute("w:val")||e.getAttribute("val")||"").toLowerCase();return n?t?n!=="none"&&n!=="0"&&n!=="false"&&n!=="off":n!=="0"&&n!=="false"&&n!=="off":!0}var gl=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"];function ar(e,t){let r=gl.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=gl.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function wl(e,t){if(!t)return!1;let r=Pt(e);if(t.bold!==void 0&&r.bold!==!!t.bold||t.italic!==void 0&&r.italic!==!!t.italic||t.underline!==void 0&&r.underline!==!!t.underline)return!0;let n=t.strike!==void 0?t.strike:t.strikethrough;if(n!==void 0&&r.strikethrough!==!!n)return!0;if(t.highlight!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:highlight"||s.localName==="highlight")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.highlight&&t.highlight!=="none"?String(t.highlight).toLowerCase():null;if((a||null)!==i)return!0}if(t.color!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:color"||s.localName==="color")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.color&&t.color!=="auto"?String(t.color).replace(/^#/,"").toUpperCase():null;if((a?.toUpperCase()||null)!==i)return!0}if(t.fontSize!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:sz"||s.localName==="sz")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.fontSize!==null&&t.fontSize!==""?String(t.fontSize):null;if(a!==i)return!0}if(t.fontFamily!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:rFonts"||s.localName==="rFonts")),a=o?o.getAttribute("w:ascii")||o.getAttribute("ascii"):null,i=t.fontFamily||null;if(a!==i)return!0}return!1}function yl(e,t,r){if(!t||!r)return;let n=a=>{let i=[];for(let s of Array.from(t.childNodes))s.nodeType===1&&a.includes(s.nodeName)&&i.push(s);for(let s of i)t.removeChild(s)};if(r.bold!==void 0){n(["w:b","w:bCs"]);let a=B(e,"w:b");a.setAttribute("w:val",r.bold?"1":"0"),Be(t,a);let i=B(e,"w:bCs");i.setAttribute("w:val",r.bold?"1":"0"),Be(t,i)}if(r.italic!==void 0){n(["w:i","w:iCs"]);let a=B(e,"w:i");a.setAttribute("w:val",r.italic?"1":"0"),Be(t,a);let i=B(e,"w:iCs");i.setAttribute("w:val",r.italic?"1":"0"),Be(t,i)}if(r.underline!==void 0){n(["w:u"]);let a=B(e,"w:u");a.setAttribute("w:val",r.underline?"single":"none"),Be(t,a)}let o=r.strike!==void 0?r.strike:r.strikethrough;if(o!==void 0){n(["w:strike","w:dstrike"]);let a=B(e,"w:strike");a.setAttribute("w:val",o?"1":"0"),Be(t,a)}if(r.highlight!==void 0&&(n(["w:highlight"]),r.highlight&&r.highlight!=="none")){let a=B(e,"w:highlight");a.setAttribute("w:val",String(r.highlight).toLowerCase()),Be(t,a)}if(r.color!==void 0&&(n(["w:color"]),r.color&&r.color!=="auto")){let a=B(e,"w:color");a.setAttribute("w:val",String(r.color).replace(/^#/,"")),Be(t,a)}if(r.fontSize!==void 0&&(n(["w:sz","w:szCs"]),r.fontSize!==null&&r.fontSize!=="")){let a=String(r.fontSize),i=B(e,"w:sz");i.setAttribute("w:val",a),Be(t,i);let s=B(e,"w:szCs");s.setAttribute("w:val",a),Be(t,s)}if(r.fontFamily!==void 0&&(n(["w:rFonts"]),r.fontFamily)){let a=B(e,"w:rFonts");a.setAttribute("w:ascii",r.fontFamily),a.setAttribute("w:hAnsi",r.fontFamily),a.setAttribute("w:cs",r.fontFamily),Be(t,a)}}function vl(e,t){if(!t)return!1;if(t.alignment!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:jc"||o.localName==="jc"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.alignment)return!0}if(t.keepNext!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepNext"||o.localName==="keepNext"));if((r?xr(r,!1):!1)!==!!t.keepNext)return!0}if(t.keepLines!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepLines"||o.localName==="keepLines"));if((r?xr(r,!1):!1)!==!!t.keepLines)return!0}if(t.pageBreakBefore!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pageBreakBefore"||o.localName==="pageBreakBefore"));if((r?xr(r,!1):!1)!==!!t.pageBreakBefore)return!0}if(t.style!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pStyle"||o.localName==="pStyle"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.style)return!0}return!1}function xl(e,t,r){if(!t||!r)return;let n=o=>{let a=[];for(let i of Array.from(t.childNodes))i.nodeType===1&&o.includes(i.nodeName)&&a.push(i);for(let i of a)t.removeChild(i)};if(r.alignment!==void 0&&(n(["w:jc"]),r.alignment)){let o=B(e,"w:jc");o.setAttribute("w:val",r.alignment),ar(t,o)}if(r.keepNext!==void 0){n(["w:keepNext"]);let o=B(e,"w:keepNext");r.keepNext||o.setAttribute("w:val","0"),ar(t,o)}if(r.keepLines!==void 0){n(["w:keepLines"]);let o=B(e,"w:keepLines");r.keepLines||o.setAttribute("w:val","0"),ar(t,o)}if(r.pageBreakBefore!==void 0){n(["w:pageBreakBefore"]);let o=B(e,"w:pageBreakBefore");r.pageBreakBefore||o.setAttribute("w:val","0"),ar(t,o)}if(r.style!==void 0&&(n(["w:pStyle"]),r.style)){let o=B(e,"w:pStyle");o.setAttribute("w:val",r.style),ar(t,o)}}var bl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Ct(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===bl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function kd(e){return!e||e.nodeType!==1||e.namespaceURI!==bl?!1:e.localName==="del"||e.localName==="moveFrom"}function Nl(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||kd(n))continue;if(Ct(n,"r")){t.push(n);continue}let o=Array.from(n.childNodes||[]);for(let a=o.length-1;a>=0;a-=1)r.push(o[a])}return t}function Qe(e){let t=new Set(["comment","footnote","endnote"]);return Ce(e,"*","p").filter(n=>{let o=n.parentNode;for(;o&&o.nodeName;){let a=String(o.localName||"").toLowerCase();if(t.has(a))return!1;o=o.parentNode}return!0})}function Il(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],a=Nl(o);for(let i of a){let s=Re(i,"w:rPr");Array.from(i.childNodes||[]).forEach(l=>{if(Ct(l,"t")){let c=l.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:l,runElement:i,paragraph:o,container:i.parentNode,rPr:s}),r+=c.length)}else(Ct(l,"br")||Ct(l,"cr")||Ct(l,"tab")||Ct(l,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:l,runElement:i,paragraph:o,container:i.parentNode,rPr:s}),r+=1)})}r=hr(r,n,e.length)}return{textSpans:t,charOffset:r}}function Md(e,t,r,n,o,a=null){let i=null;for(let c of Array.from(e.childNodes))if(Ct(c,"rPr")){i=c;break}let s=Pt(i);a&&(a.bold&&!s.bold&&(s.bold=!0),a.italic&&!s.italic&&(s.italic=!0),a.underline&&!s.underline&&(s.underline=!0),a.strikethrough&&!s.strikethrough&&(s.strikethrough=!0)),s.hasFormatting=s.bold||s.italic||s.underline||s.strikethrough;let l=r;for(let c of Array.from(e.childNodes))if(Ct(c,"t")){let u=c.textContent||"";if(u.length>0){let f=l,d=l+u.length;n.push({charStart:f,charEnd:d,textElement:c,runElement:e,paragraph:t,rPr:i,format:{...s}}),s.hasFormatting&&o.push({start:f,end:d,format:{...s},run:e,rPr:i}),l=d}}return l}function Tl(e){let t=[],r=[],n=0,o=Qe(e);for(let a=0;a<o.length;a++){let i=o[a],s=null;for(let u of Array.from(i.childNodes))if(Ct(u,"pPr")){for(let f of Array.from(u.childNodes))if(Ct(f,"rPr")){s=f;break}break}let l=Pt(s);l.hasFormatting&&K(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let c=Nl(i);for(let u of c)n=Md(u,i,n,r,t,l);n=hr(n,a,o.length)}return K(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var Ld=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function pt(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())Ld.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function Ot(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof Ae?t:Dt(r)||tr(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let a of o){if(!D(a,"rPrChange"))continue;let i=String(n.next());typeof a.setAttributeNS=="function"?a.setAttributeNS(L,"w:id",i):a.setAttribute("w:id",i),n._receiptCollector?.recordRevision(Number(i),"rPrChange")}return e}function br(e,t,r,n,o=null){let a=B(e,t==="ins"?"w:ins":"w:del"),i=o||ie(n,e,t==="ins"?"ins":"del");return a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",i.date),r&&a.appendChild(r),a}function Sl(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function Bd(e,t){let r=Sl(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=B(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function Dd(e,t){let r=Sl(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=B(e,"w:rPr"),t.appendChild(r)),r}function El(e,t,r,n,o=null){let a=Bd(e,t),i=Dd(e,a);for(let c of Array.from(i.childNodes||[]))c.nodeType===1&&(c.localName==="ins"||c.localName==="del"||c.nodeName==="w:ins"||c.nodeName==="w:del")&&i.removeChild(c);let s=B(e,n==="ins"?"w:ins":"w:del"),l=o||ie(r,e,n==="ins"?"ins":"del");return s.setAttribute("w:id",String(l.id)),s.setAttribute("w:author",l.author),s.setAttribute("w:date",l.date),i.appendChild(s),s}function Yr(e,t,r,n=null){return El(e,t,r,"ins",n)}function Nr(e,t,r,n=null){return El(e,t,r,"del",n)}function ir(e,t,r,n){let o=B(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Al(e,o,t),o;let a=B(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Ao(e,t,r,n,o,a,i){if(!t)return[];let s=new Set([0,t.length]);for(let u of n){let f=Math.max(0,u.start-o),d=Math.min(t.length,u.end-o);f>=0&&f<t.length&&s.add(f),d>0&&d<=t.length&&s.add(d)}let l=Array.from(s).sort((u,f)=>u-f),c=[];for(let u=0;u<l.length-1;u++){let f=l[u],d=l[u+1],m=t.slice(f,d);if(!m)continue;let p=o+f,g=o+d,h=n.filter(v=>v.start<=p&&v.end>=g),y={...Pt(r)};h.forEach(v=>{v.format&&Object.assign(y,v.format)});let w=h.length>0?Zr(e,r,y,a,i):r?.cloneNode(!0)||null;c.push(ei(e,m,w,!1))}return c}function ei(e,t,r,n){let o=B(e,"w:r");if(r&&o.appendChild(r),!n)return Al(e,o,t),o;let a=B(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Al(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let a of o){if(!a)continue;if(a===" "){t.appendChild(B(e,"w:tab"));continue}if(a===`
|
|
144
|
+
`){t.appendChild(B(e,"w:br"));continue}if(a==="\u2011"){t.appendChild(B(e,"w:noBreakHyphen"));continue}let i=B(e,"w:t");/^\s|\s$/.test(a)&&i.setAttribute("xml:space","preserve"),i.textContent=a,t.appendChild(i)}}function Zr(e,t,r,n,o){let a=B(e,"w:rPr");t&&Array.from(t.childNodes).forEach(l=>{["w:b","w:bCs","w:i","w:iCs","w:u","w:strike","w:rPrChange"].includes(l.nodeName)||a.appendChild(l.cloneNode(!0))});let i=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&o&&Fd(e,a,n,t);let s=(l,c,u=null,f="0")=>{let d=B(e,l);c?u&&d.setAttribute("w:val",u):f&&d.setAttribute("w:val",f);let m=Cn.indexOf(l),p=m===-1?999:m,g=!1;for(let h of Array.from(a.childNodes)){if(h.nodeType!==1)continue;let y=Cn.indexOf(h.nodeName);if((y===-1?999:y)>p){a.insertBefore(d,h),g=!0;break}}g||a.appendChild(d)};return s("w:b",!!i.bold,"1","0"),s("w:bCs",!!i.bold,"1","0"),s("w:i",!!i.italic,"1","0"),s("w:iCs",!!i.italic,"1","0"),s("w:u",!!i.underline,"single","none"),s("w:strike",!!i.strikethrough,"1","0"),a}function On(e,t,r,n,o){let a=B(e,"w:rPrChange"),i=ie(r,e,"rPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let l=pt(o||t)||B(e,"w:rPr");a.appendChild(l);let c=Re(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(a),a}function Fd(e,t,r,n){On(e,t,r,null,n||t)}function Rl(e,t,r,n,o){let a=B(e,"w:pPrChange"),i=ie(r,e,"pPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let l=pt(o||t)||B(e,"w:pPr");a.appendChild(l);let c=Array.from(t.childNodes).find(u=>u.nodeType===1&&(u.nodeName==="w:pPrChange"||u.localName==="pPrChange"));return c&&t.removeChild(c),t.appendChild(a),a}var $d="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Jr(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===$d&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Ro(e,t,r){let n=new Map;for(let i of r)!i||!i.paragraph||(n.has(i.paragraph)||n.set(i.paragraph,[]),n.get(i.paragraph).push(i));let o=[],a=0;return t.forEach((i,s)=>{let l=(n.get(i)||[]).slice().sort((d,m)=>d.charStart-m.charStart),c=Ud(l),u=ti(c),f=u.trim();o.push({paragraph:i,spans:l,text:c,normalizedText:u,normalizedTrim:f,startOffset:a}),a+=u.length,a=hr(a,s,t.length)}),o}function Pl(e,t){if(!t)return null;let r=ti(t),n=r.trim();if(!n)return null;for(let o of e)if(o.normalizedText===r)return o;for(let o of e)if(o.normalizedTrim===n)return o;return null}function Cl(e,t){let r=ti(t),n=r.trim(),o=null,a=0;for(let i of e)if(i.normalizedText===r)return o=i,{targetInfo:o,matchOffset:a};if(n.length>0){for(let i of e)if(i.normalizedTrim===n)return o=i,{targetInfo:o,matchOffset:a}}if(n.length>0){let s=e.map(l=>l.normalizedText).join(`
|
|
145
|
+
`).indexOf(n);if(s!==-1)for(let l of e){let c=l.startOffset,u=l.normalizedText.length;if(s>=c&&s<=c+u){o=l,a=s-c;break}}}if(!o&&e.length===1&&r.length>0){let i=e[0],s=i.normalizedTrim||"";if(s.length>0){let l=r.indexOf(s);l>=0&&(o=i,a=-l)}}return{targetInfo:o,matchOffset:a}}function Ol(e){let t=e;for(;t;){if(Jr(t,"p"))return t;t=t.parentNode}return null}function Ud(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;Jr(n,"t")?t+=r.textElement.textContent||"":Jr(n,"tab")?t+=" ":Jr(n,"br")||Jr(n,"cr")?t+=`
|
|
146
|
+
`:Jr(n,"noBreakHyphen")&&(t+="\u2011")}return t}function ti(e){return e?e.replace(/\r/g,`
|
|
147
|
+
`).replace(/\u00a0/g," "):""}function _l(e,t,r){let n=Array.from(new Set(r)).sort((s,l)=>s-l);if(n.length===0||t.length===0)return[...t];let o=[...t].sort((s,l)=>s.charStart-l.charStart||s.charEnd-l.charEnd),a=[],i=0;for(let s of o){for(;i<n.length&&n[i]<=s.charStart;)i++;let l=s;for(;i<n.length&&n[i]<l.charEnd;){let c=n[i],u=zd(e,l,c);if(!u){i++;continue}a.push(u[0]),l=u[1],i++}a.push(l)}return a}function zd(e,t,r){let n=t.runElement,o=n.parentNode;if(!o)return null;let a=t.textElement.textContent||"",i=r-t.charStart,s=a.substring(0,i),l=a.substring(i);if(s.length===0||l.length===0)return null;let c=ir(e,s,t.rPr,!1),u=ir(e,l,t.rPr,!1);o.insertBefore(c,n),o.insertBefore(u,n),o.removeChild(n);let f=c.getElementsByTagName("w:t")[0],d=u.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:c},{...t,charStart:r,textElement:d,runElement:u}]}var Xd="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Vd(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Xd&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Wd(e){return Array.isArray(e)?{textSpans:e,paragraphs:null,paragraphInfos:null}:!e||typeof e!="object"?{textSpans:null,paragraphs:null,paragraphInfos:null}:{textSpans:Array.isArray(e.textSpans)?e.textSpans:null,paragraphs:Array.isArray(e.paragraphs)?e.paragraphs:null,paragraphInfos:Array.isArray(e.paragraphInfos)?e.paragraphInfos:null}}function kl(e,t,r,n,o,a=!0){let i=!1,s=new Set;K(`[OxmlEngine] Surgical format removal: ${r.length} hints to process (using w:rPrChange)`);for(let l of r){let c=l.run;if(s.has(c)||(s.add(c),!c.parentNode))continue;K("[OxmlEngine] Processing run for surgical format removal, format:",l.format);let u=Re(c,"w:rPr");u||(u=B(e,"w:rPr"),c.insertBefore(u,c.firstChild)),a&&On(e,u,o||re()),hl(e,u,l.format),i=!0}return i?(K("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(K("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function jd(e,t,r,n,o,a=!0){let i=!1,s=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let l=[];for(let d of r)l.push(d.start,d.end);let u=_l(e,t,l).slice().sort((d,m)=>d.charStart-m.charStart||d.charEnd-m.charEnd),f=Kd(r);for(let d of u){if(!d||!d.textElement||!Vd(d.textElement,"t"))continue;let m=f(d.charStart,d.charEnd);if(m.length===0)continue;let p=Fa(...m.map(S=>S.format)),g={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},h=d.format||Pt(d.rPr),y={bold:!!h.bold,italic:!!h.italic,underline:!!h.underline,strikethrough:!!h.strikethrough};if(!["bold","italic","underline","strikethrough"].some(S=>g[S]!==y[S])||s.has(d.runElement)||(s.add(d.runElement),!(d.textElement.textContent||""))||!d.runElement.parentNode)continue;let I=d.runElement,N=Re(I,"w:rPr"),T=Zr(e,N,g,o||re(),a),E=N;if(!E)I.insertBefore(T,I.firstChild);else{for(;E.firstChild;)E.removeChild(E.firstChild);Array.from(T.childNodes).forEach(S=>E.appendChild(S))}i=!0}return{oxml:n.serializeToString(e),hasChanges:i}}function Ml(e,t,r,n,o,a=!0,i=null){let s=Wd(i),l=s.paragraphs||Qe(e),c=s.textSpans||[];if(s.textSpans||({textSpans:c}=Il(l)),!c||c.length===0)return vt("[OxmlEngine] No spans available for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};if(!r||r.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let u=s.paragraphInfos||Ro(e,l,c),{targetInfo:f,matchOffset:d}=Cl(u,t);if(!f||!f.spans||f.spans.length===0)return vt("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let m=f.spans[0].charStart,p=f.spans.map(h=>({...h,charStart:h.charStart-m,charEnd:h.charEnd-m})),g=r.map(h=>({...h,start:h.start+d,end:h.end+d}));return jd(e,p,g,n,o,a)}function Kd(e){let t=(e||[]).slice().sort((o,a)=>o.start-a.start||o.end-a.end),r=[],n=0;return(o,a)=>{for(;n<t.length&&t[n].start<a;)r.push(t[n]),n++;for(let i=r.length-1;i>=0;i--)r[i].end<=o&&r.splice(i,1);return r.filter(i=>i.start<a&&i.end>o)}}function Po(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Ir(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let a=Po(o);if(n==="accepted"&&(a==="del"||a==="moveFrom")||n==="rejected"&&(a==="ins"||a==="moveTo"))return!1;o=o.parentNode}return!0}function Tr(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!Ir(e,n,r))return"";let o="",a=i=>{for(let s of Array.from(i?.childNodes||[])){if(s?.nodeType!==1||s.namespaceURI&&s.namespaceURI!==L||!Ir(s,n,r))continue;let l=Po(s);l==="t"||l==="delText"&&r==="rejected"?o+=s.textContent||"":l==="tab"?o+=" ":l==="br"||l==="cr"?o+=`
|
|
148
|
+
`:l==="noBreakHyphen"?o+="\u2011":l==="softHyphen"?o+="\xAD":a(s)}};return a(e),o}var sr=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Co(e,t={}){if(!e)return[];let r=[];function n(f,d,m){for(let p of Array.from(f?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==L)continue;let g=Po(p);if(g==="pPr"||g==="rPr")continue;let h=d;g==="ins"?h={kind:"insertion",author:sr(p,"author")||void 0,revisionId:sr(p,"id")||void 0}:g==="del"?h={kind:"deletion",author:sr(p,"author")||void 0,revisionId:sr(p,"id")||void 0}:g==="moveFrom"?h={kind:"move_from",author:sr(p,"author")||void 0,revisionId:sr(p,"id")||void 0}:g==="moveTo"&&(h={kind:"move_to",author:sr(p,"author")||void 0,revisionId:sr(p,"id")||void 0});let y=m;g==="r"&&(y=p);let w=null,v=h?h.kind:"baseline",b=h?.author,x=h?.revisionId;g==="t"?w=p.textContent||"":g==="delText"?(w=p.textContent||"",h||(v="deletion")):g==="tab"?w=" ":g==="br"||g==="cr"?w=`
|
|
149
|
+
`:g==="noBreakHyphen"?w="\u2011":g==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:v,author:b,revisionId:x,carrier:y||p,carrierContainer:(y||p)?.parentNode||null}):n(p,h,y)}}let o=Po(e)==="r"?e:null;if(n(e,null,o),r.length===0)return[];let a=t.mergeRuns!==!1,i=[],s=null;for(let f of r){if(!s){s={...f};continue}let d=s.kind===f.kind,m=s.author===f.author,p=s.revisionId===f.revisionId,g=s.carrier===f.carrier,h=a&&s.carrierContainer===f.carrierContainer;d&&m&&p&&(g||h)?s.text+=f.text:(i.push(s),s={...f})}s&&i.push(s);let l=0,c=0,u=[];for(let f of i){let d=f.kind!=="deletion"&&f.kind!=="move_from",m=f.kind!=="insertion"&&f.kind!=="move_to",p=d?l:null,g=m?c:null;d&&(l+=f.text.length),m&&(c+=f.text.length);let h={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:g};f.author!==void 0&&(h.author=f.author),f.revisionId!==void 0&&(h.revisionId=f.revisionId),u.push(h)}return u}function te(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Co(e,t);return r==="rejected"?n.filter(o=>o.rejectedStart!==null).map(o=>o.text).join(""):n.filter(o=>o.acceptedStart!==null).map(o=>o.text).join("")}var Hd="http://schemas.microsoft.com/office/word/2010/wordml";function Ll(e,t,r={}){let{targetParagraphId:n=null}=r,o=Xe(e,L,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let i=Qe(e).filter(l=>{let c=l.parentNode;for(;c;){if(D(c,"tc"))return!0;c=c.parentNode}return!1});K(`[OxmlEngine] Table wrapper detected: ${o.length} tables, ${i.length} paragraphs in cells`);let s=null;if(n){let l=String(n).toUpperCase();s=i.find(c=>{let u=qd(c);return u&&u.toUpperCase()===l})||null,s?K(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):K(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let l=t.trim();if(!s){for(let c of i)if(te(c).trim()===l){s=c,K(`[OxmlEngine] Found target paragraph by text match: "${l.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:i.length>0,targetParagraph:s,paragraphs:i,paragraph:s||i[0]||null,tableElement:o[0]}}function _n(e,t,r){let n=Array.isArray(t)?t:[t],o="";for(let a of n){if(!a)continue;let i=r.serializeToString(a);i=i.replace(/\s+xmlns:w="[^"]*"/g,""),i=i.replace(/\s+xmlns:r="[^"]*"/g,""),i=i.replace(/\s+xmlns:wp="[^"]*"/g,""),o+=i}return K(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),K(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),Gd(o)}function Gd(e){return nl(e)}function qd(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(Hd,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function ri(e){return D(e,"t")||D(e,"delText")?e.textContent||"":D(e,"br")||D(e,"cr")?`
|
|
150
|
+
`:D(e,"tab")?" ":D(e,"noBreakHyphen")?"\u2011":D(e,"softHyphen")?"\xAD":""}function ni(e){return D(e,"t")||D(e,"delText")||D(e,"br")||D(e,"cr")||D(e,"tab")||D(e,"noBreakHyphen")||D(e,"softHyphen")}function Oo(e){let t="",r=[];return e.forEach((n,o)=>{let a=n.parentNode;for(let i=n.firstChild;i;i=i.nextSibling)if(D(i,"r"))t+=kn(i,n,a,t.length,r).text;else if(D(i,"hyperlink"))for(let s=i.firstChild;s;s=s.nextSibling)D(s,"r")&&(t+=kn(s,n,a,t.length,r).text);else if(D(i,"ins"))for(let s=i.firstChild;s;s=s.nextSibling)D(s,"r")&&(t+=kn(s,n,a,t.length,r).text);else if(D(i,"sdt")){let s=Array.from(i.childNodes||[]).find(l=>D(l,"sdtContent"));if(s)for(let l=s.firstChild;l;l=l.nextSibling)D(l,"r")&&(t+=kn(l,n,a,t.length,r).text)}else if(D(i,"smartTag"))for(let s=i.firstChild;s;s=s.nextSibling)D(s,"r")&&(t+=kn(s,n,a,t.length,r).text);t=jr(t,o,e.length)}),{fullText:t,textSpans:r}}function kn(e,t,r,n,o){let a=Re(e,"w:rPr"),i=n,s=[];for(let l=e.firstChild;l;l=l.nextSibling)if(D(l,"t")){let c=l.textContent||"";if(c.length===0)continue;o.push({charStart:i,charEnd:i+c.length,textElement:l,runElement:e,paragraph:t,container:r,rPr:a}),i+=c.length,s.push(c)}else if(ni(l)){let c=ri(l);o.push({charStart:i,charEnd:i+1,textElement:l,runElement:e,paragraph:t,container:r,rPr:a}),i+=1,s.push(c)}return{text:s.join("")}}function _o(e){let t=e.slice().sort((o,a)=>o.charStart-a.charStart||o.charEnd-a.charEnd),r=t.map(o=>o.charStart),n=t.map(o=>o.charEnd);return{spans:t,starts:r,ends:n}}function Mn(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=si(e.ends,t);for(;o<e.spans.length;){let a=e.spans[o];if(a.charStart>=r)break;n(a),o++}}function oi(e,t){if(e.spans.length===0)return null;let r=si(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function ai(e,t){let r=Yd(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function ii(e,t){let r=si(e.ends,t)-1;return r>=0?e.spans[r]:null}function si(e,t){let r=0,n=e.length;for(;r<n;){let o=r+n>>1;e[o]<=t?r=o+1:n=o}return r}function Yd(e,t){let r=0,n=e.length;for(;r<n;){let o=r+n>>1;e[o]<t?r=o+1:n=o}return r}function Bl(e,t,r=null){if(!e||!e.spans||e.spans.length===0)return{leftSpan:null,rightSpan:null,containingSpan:null,isInterior:!1,fallbackParagraph:r};let n=oi(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,a=ai(e,t)||(t>0?ii(e,t):null),i=e.spans.find(s=>s.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:a,rightSpan:i,containingSpan:n,isInterior:o,fallbackParagraph:r}}var Zd=new Set(["ins","del"]);function Ut(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(D(n,"rPr")||!ni(n))continue;let o=ri(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function gt(e){return e.length===0?0:e[e.length-1].end}function _t(e,t,r,n,o){let a=[];return n<=r||t.forEach(i=>{let s=Math.max(r,i.start),l=Math.min(n,i.end);if(l<=s)return;let c=s-i.start,u=l-i.start,f=i.text.slice(c,u);a.push(tm(e,i.node,f,o))}),a}function Ln(e,t,r){let n=B(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function Sr(e,t,r,n,o){if(n.length===0)return null;let a=Ln(e,n,o);return t.insertBefore(a,r),a}function ko(e,t,r,n=null){let o=em(t);if(!Zd.has(o))throw new TypeError("splitTrackChangeCarrier requires a w:ins or w:del carrier.");if(!Number.isInteger(r)||r<0)throw new RangeError("splitOffset must be a non-negative integer.");let a=Array.from(t.childNodes||[]),i=a.reduce((d,m)=>d+(D(m,"r")?gt(Ut(m)):0),0);if(r>i)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${i}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===i)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let s=t.cloneNode(!1),l=t.cloneNode(!1),c=0;for(let d of a){if(!D(d,"r")){(c<=r?s:l).appendChild(d.cloneNode(!0));continue}let m=Ut(d),p=gt(m),g=c+p;if(g<=r)s.appendChild(d.cloneNode(!0));else if(c>=r)l.appendChild(d.cloneNode(!0));else{let h=r-c,y=Array.from(d.childNodes||[]).find(I=>D(I,"rPr"))||null,w=o==="del",v=_t(e,m,0,h,w),b=_t(e,m,h,p,w);s.appendChild(Ln(e,v,y));let x=Ln(e,b,y);l.appendChild(x)}c=g}let u=Jd(e,n);Ot(l,u);let f=u.next();return Qd(l,"id",String(f)),u._receiptCollector?.recordRevision(f,o),{leftCarrier:s,rightCarrier:l}}function Jd(e,t){return t instanceof Ae?t:Dt(e)||tr(e)}function Qd(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(L,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function em(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function tm(e,t,r,n){if(n&&(D(t,"delText")||D(t,"t"))){let a=B(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}if(D(t,"t")){let a=t.cloneNode(!1);return a.textContent=r,/^\s|\s$/.test(r)&&a.setAttribute("xml:space","preserve"),a}if(r===`
|
|
151
|
+
`&&(D(t,"br")||D(t,"cr"))||r===" "&&D(t,"tab")||r==="\u2011"&&D(t,"noBreakHyphen")||r==="\xAD"&&D(t,"softHyphen"))return t.cloneNode(!0);if(n){let a=B(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}let o=B(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function $l(e,t,r,n,o,a,i){if(o.length===0)return!1;let s=t.rPr,l=Pt(s),c={...l};if(o.forEach(I=>Object.assign(c,I.format)),!["bold","italic","underline","strikethrough"].some(I=>!!c[I]!==l[I]))return!1;let d=t.runElement.parentNode;if(!d)return!1;let m=t.textElement.textContent||"",p=t.charStart,g=r-p,h=n-p,y=m.substring(0,g),w=m.substring(g,h),v=m.substring(h);if(y.length>0){let I=ir(e,y,s,!1);d.insertBefore(I,t.runElement)}let b=Zr(e,s,c,a,i),x=ei(e,w,b,!1);if(d.insertBefore(x,t.runElement),v.length>0){let I=ir(e,v,s,!1);d.insertBefore(I,t.runElement)}return d.removeChild(t.runElement),!0}function ui(e,t,r,n,o,a,i=null){let s=[];if(Mn(t,r,n,m=>{s.push(m)}),s.length===0)return!1;let l=new Map;s.forEach(m=>{m.runElement?.parentNode&&(l.has(m.runElement)||l.set(m.runElement,[]),l.get(m.runElement).push(m))});let c=[];l.forEach((m,p)=>{let g=p.parentNode;if(!g)return;let h=Ut(p);if(h.length===0)return;let y=1/0,w=-1/0;m.forEach(v=>{let b=h.find(N=>N.node===v.textElement);if(!b)return;let x=Math.max(0,r-v.charStart),I=Math.min(v.charEnd-v.charStart,n-v.charStart);I<=x||(y=Math.min(y,b.start+x),w=Math.max(w,b.start+I))}),!(!Number.isFinite(y)||w<=y)&&c.push({runElement:p,parent:g,rPr:m[0].rPr,beforePieces:_t(e,h,0,y,!1),deletedPieces:_t(e,h,y,w,!0),afterPieces:_t(e,h,w,gt(h),!1),globalStart:Math.max(r,Math.min(...m.map(v=>v.charStart))),globalEnd:Math.min(n,Math.max(...m.map(v=>v.charEnd))),carrierGlobalStart:D(g,"ins")?Ul(t,g):null})});let u=[];for(let m of c){let p=u[u.length-1],g=p?.[p.length-1];g&&g.parent===m.parent&&om(g.runElement)===m.runElement?p.push(m):u.push([m])}let f=!1,d=!1;for(let m of u){let p=m[0],g=null;if(a&&m.some(w=>w.deletedPieces.length>0)){let w=i?d?{...i,id:ie(o,e,"del").id}:i:null;d=!0,g=br(e,"del",null,o,w)}for(let w of m){let{parent:v,runElement:b}=w;Sr(e,v,b,w.beforePieces,w.rPr),g&&w===p&&v.insertBefore(g,b),g&&w.deletedPieces.length>0&&g.appendChild(Ln(e,w.deletedPieces,w.rPr));let x=Sr(e,v,b,w.afterPieces,w.rPr);w.globalEnd===n&&!D(v,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:v,referenceNode:x||b.nextSibling,rPr:w.rPr})),v.removeChild(b),f=!0}let h=D(p.parent,"ins")?p.parent:null,y=Math.max(...m.map(w=>w.globalEnd));if(h&&y===n){let w=p.carrierGlobalStart,v=m.filter(x=>x.globalStart<n).reduce((x,I)=>x+I.deletedPieces.reduce((N,T)=>N+(T.textContent||"").length,0),0),b=Math.max(0,n-w-v);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:b,rPr:p.rPr})}}return f}function Qr(e,t,r,n,o,a=[],i=0,s=!0,l=null,c=null,u=null,f="merge-same-author"){let d=t.revisionInsertionAnchors?.get(r)||null;if(d&&f==="slice-cross-author"&&Fl(d.carrier)&&ci(d.carrier,o))return t.revisionInsertionAnchors.delete(r),li(e,d.carrier,d.splitOffset,n,d.rPr,o,a,i,s,c);let m=t.replacementInsertionAnchors?.get(r)||null;if(m&&!u&&Fl(m.parent)&&(!m.referenceNode||m.referenceNode.parentNode===m.parent))return t.replacementInsertionAnchors.delete(r),lr(e,m.parent,m.referenceNode,n,m.rPr,o,a,i,s,c),!0;if(!u){let x=oi(t,r);if(!x&&r>0&&(x=ai(t,r)),!x&&r>0&&(x=ii(t,r)),!x&&t.spans.length>0&&(x=t.spans[t.spans.length-1]),!x)return l?(lr(e,l,null,n,null,o,a,i,s,c),!0):!1;let I=x.runElement.parentNode;if(!I)return l?(lr(e,l,null,n,x.rPr,o,a,i,s,c),!0):!1;let N=!(s&&f==="slice-cross-author"&&nm(I,o));if(s&&f==="slice-cross-author"&&ci(I,o))return li(e,I,Dl(t,I,r),n,x.rPr,o,a,i,s,c);let T=Ut(x.runElement),E=T.find(A=>A.node===x.textElement),S=E?E.start+Math.max(0,Math.min(r-x.charStart,x.charEnd-x.charStart)):r<=x.charStart?0:gt(T);if(S>0&&S<gt(T)){let A=_t(e,T,0,S,!1),P=_t(e,T,S,gt(T),!1);return Sr(e,I,x.runElement,A,x.rPr),lr(e,I,x.runElement,n,x.rPr,o,a,i,N,c),Sr(e,I,x.runElement,P,x.rPr),I.removeChild(x.runElement),!0}let O=r<=x.charStart?x.runElement:x.runElement.nextSibling;return lr(e,I,O,n,x.rPr,o,a,i,N,c),!0}let p=Bl(t,r,l),g=p.leftSpan&&D(p.leftSpan.runElement?.parentNode,"hyperlink"),h=p.rightSpan&&D(p.rightSpan.runElement?.parentNode,"hyperlink"),y=p.containingSpan&&D(p.containingSpan.runElement?.parentNode,"hyperlink");if(u.hyperlink==="outside"){if(p.isInterior&&y)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(u.hyperlink==="inside"&&!g&&!h&&!y)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let w=null;if(u.formatting==="none"?w=null:u.formatting==="right"?w=p.rightSpan?.rPr||null:u.formatting==="left"?w=p.leftSpan?.rPr||null:w=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let x=p.containingSpan,I=x.runElement.parentNode||l;if(!I)return!1;let N=Ut(x.runElement),T=N.find(S=>S.node===x.textElement),E=T?T.start+Math.max(0,Math.min(r-x.charStart,x.charEnd-x.charStart)):r<=x.charStart?0:gt(N);if(E>0&&E<gt(N)){let S=_t(e,N,0,E,!1),O=_t(e,N,E,gt(N),!1);return Sr(e,I,x.runElement,S,x.rPr),lr(e,I,x.runElement,n,w,o,a,i,s,c),Sr(e,I,x.runElement,O,x.rPr),I.removeChild(x.runElement),!0}}let v=null,b=null;if(u.hyperlink==="outside"){if(h){let x=p.rightSpan.runElement.parentNode;v=x.parentNode||l,b=x}else if(g){let x=p.leftSpan.runElement.parentNode;v=x.parentNode||l,b=x.nextSibling}}else u.hyperlink==="inside"&&(h?(v=p.rightSpan.runElement.parentNode,b=p.rightSpan.runElement):g&&(v=p.leftSpan.runElement.parentNode,b=p.leftSpan.runElement.nextSibling));if(v||(p.rightSpan?(v=p.rightSpan.runElement.parentNode||l,b=p.rightSpan.runElement):p.leftSpan?(v=p.leftSpan.runElement.parentNode||l,b=p.leftSpan.runElement.nextSibling):(v=l,b=null)),u.bookmark&&v&&(u.bookmark==="outside"?(b&&D(b.previousSibling,"bookmarkStart")&&(b=b.previousSibling),p.leftSpan&&D(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling.nextSibling)):u.bookmark==="inside"&&(b&&D(b,"bookmarkStart")&&(b=b.nextSibling),p.leftSpan&&D(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling))),u.comment&&v)if(u.comment==="outside"){if(b&&D(b.previousSibling,"commentRangeStart")&&(b=b.previousSibling),p.leftSpan&&D(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let x=p.leftSpan.runElement.nextSibling.nextSibling;x&&(D(x,"commentReference")||D(x,"r"))&&Array.from(x.childNodes||[]).some(N=>D(N,"commentReference"))&&(x=x.nextSibling),b=x}}else u.comment==="inside"&&(b&&D(b,"commentRangeStart")&&(b=b.nextSibling),p.leftSpan&&D(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(b=p.leftSpan.runElement.nextSibling));if(s&&u.revision==="coalesce_same_author"){let x=null,I=null;if(p.leftSpan&&D(p.leftSpan.runElement.parentNode,"ins")){let N=p.leftSpan.runElement.parentNode;(N.getAttribute("w:author")||N.getAttributeNS(L,"author"))===o&&(x=N,I=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&D(p.rightSpan.runElement.parentNode,"ins")){let N=p.rightSpan.runElement.parentNode;(N.getAttribute("w:author")||N.getAttributeNS(L,"author"))===o&&(x=N,I=p.rightSpan.runElement)}if(x){let N=ir(e,n,w,!1);return x.insertBefore(N,I),!0}}return s&&f==="slice-cross-author"&&ci(v,o)?li(e,v,Dl(t,v,r),n,w,o,a,i,s,c):(lr(e,v,b,n,w,o,a,i,s,c),!0)}function li(e,t,r,n,o,a,i,s,l,c){let u=t.parentNode;if(!u)return!1;let{leftCarrier:f,rightCarrier:d}=ko(e,t,r);return f&&u.insertBefore(f,t),lr(e,u,t,n,rm(o),a,i,s,l,c),d&&u.insertBefore(d,t),u.removeChild(t),!0}function rm(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>D(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Dl(e,t,r){let n=Ul(e,t),o=e.spans.filter(a=>a.runElement?.parentNode===t).reduce((a,i)=>a+(i.charEnd-i.charStart),0);return Math.max(0,Math.min(r-n,o))}function Ul(e,t){let r=e.spans.filter(n=>n.runElement?.parentNode===t);return r.length>0?Math.min(...r.map(n=>n.charStart)):0}function ci(e,t){return D(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(L,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function nm(e,t){return D(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(L,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function om(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Fl(e){return!!e?.parentNode}function lr(e,t,r,n,o,a,i,s,l,c=null){let u=Bt(i,s,s+n.length);if(u.length===0){let d=ir(e,n,o,!1);if(l){let m=br(e,"ins",d,a,c);t.insertBefore(m,r)}else t.insertBefore(d,r);return}let f=Ao(e,n,o,u,s,a,l);if(l){let d=br(e,"ins",null,a,c);f.forEach(m=>d.appendChild(m)),t.insertBefore(d,r)}else f.forEach(d=>t.insertBefore(d,r))}function zl(e,t,r,n=!1){let o=[];if(Mn(e,t,r,m=>o.push(m)),o.length===0)return{safe:!1};let a=o[0].runElement,i=a?.parentNode;if(!i)return{safe:!1};if(!o.every(m=>m.runElement?.parentNode===i))return{safe:!1,structuralBoundary:!0};let l=i.localName||i.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(l)||l==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let m of o){let p=m.runElement;for(let g of Array.from(p.childNodes||[]))if(g.nodeType===1){let h=g.localName||g.nodeName.replace(/^.*:/,"");if(c.has(h)||h==="fldChar")return{safe:!1,structuralBoundary:!0}}}let u=o[o.length-1].runElement,f=a;for(;f&&f!==u;){if(f!==a){let m=f.localName||f.nodeName.replace(/^.*:/,"");if(c.has(m))return{safe:!1,structuralBoundary:!0}}f=f.nextSibling}function d(m){if(!m||m.nodeType!==1)return!1;let p=m.localName||m.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let g of Array.from(m.childNodes||[]))if(g.nodeType===1&&d(g))return!0;return!1}return d(a.previousSibling)||d(u.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function Wl(e,t,r,n,o,a,i=!0,s=null,l={},c={}){let u=s?[s]:Qe(e),{fullText:f,textSpans:d}=Oo(u),m=c.existingRevisions==="slice-cross-author"?Gs(f,r):null,p=m||im(Rn(f,r,l),l),g=_o(d),h=c.pairReplacements===!0,y=[],w=0,v=0,b=!1,x=m?lm(m):[];if(x.length>1&&a.length===0)for(let T of x.slice().reverse()){let E=Oo(u).textSpans,S=_o(E),O=T.text.replace(/\n/g," ");if(O.length===0)continue;let A=Qr(e,S,T.originalPos,O,o,a,T.newPos,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(A&&typeof A=="object"&&A.error)return xe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:A.error});A===!0&&(b=!0)}else if(a.length===0){let T=sm(p);for(let E of T.reverse()){let S=_o(Oo(u).textSpans);if(E.type==="insert"){let P=Qr(e,S,E.start,E.text.replace(/\n/g," "),o,a,E.newPos,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(P&&typeof P=="object"&&P.error)return xe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:P.error});P===!0&&(b=!0);continue}let O=null,A=null;if(E.type==="replace"&&h&&i&&E.text.replace(/\n/g," ")){let P=zl(S,E.start,E.end,c?.existingRevisions==="slice-cross-author");if(P.safe){let _=Sn(o,e);O={id:_.deletionId,author:_.author,date:_.date},A={id:_.insertionId,author:_.author,date:_.date}}else P.structuralBoundary&&y.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(ui(e,S,E.start,E.end,o,i,O)&&(b=!0),E.type==="replace"){let P=Qr(e,S,E.end,E.text.replace(/\n/g," "),o,a,E.newPos,i,u[0]||null,A,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(P&&typeof P=="object"&&P.error)return xe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:P.error});P===!0&&(b=!0)}}}else for(let T=0;T<p.length;T++){let[E,S]=p[T];if(E===0){let O=S.length,A=w,P=w+O;Mn(g,A,P,_=>{let R=Math.max(_.charStart,A),k=Math.min(_.charEnd,P),C=k-R,M=R-A,$=v+M,X=$+C,V=Bt(a,$,X);$l(e,_,R,k,V,o,i)&&(b=!0)}),w+=O,v+=O}else if(E===-1){let O=T+1<p.length&&p[T+1][0]===1,A=!1,P=null,_=null;if(h&&i&&O&&p[T+1][1].replace(/\n/g," ").length>0){let C=zl(g,w,w+S.length,c?.existingRevisions==="slice-cross-author");if(C.safe){let M=Sn(o,e);P={id:M.deletionId,author:M.author,date:M.date},_={id:M.insertionId,author:M.author,date:M.date},A=!0}else C.structuralBoundary&&y.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(ui(e,g,w,w+S.length,o,i,P)&&(b=!0),w+=S.length,A){T++;let[,R]=p[T],k=R.replace(/\n/g," ");if(k.length>0){let C=Qr(e,g,w,k,o,a,v,i,u[0]||null,_,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(C&&typeof C=="object"&&C.error)return xe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:C.error});C===!0&&(b=!0)}v+=R.length}}else if(E===1){let O=S.replace(/\n/g," ");if(O.length>0){let A=Qr(e,g,w,O,o,a,v,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(A&&typeof A=="object"&&A.error)return xe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:A.error});A===!0&&(b=!0)}v+=S.length}}let I=u.map(T=>te(T)).join(`
|
|
152
|
+
`),N=String(r).replace(/\r\n/g,`
|
|
153
|
+
`);if(c.existingRevisions==="slice-cross-author"&&I!==N){let T=am(N,I);return xe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Generated OOXML accepted-view text does not match the requested modified text; the mutation was rejected.",mismatchOffset:T,expectedExcerpt:Xl(N,T),actualExcerpt:Xl(I,T),expectedCodePoint:Vl(N,T),actualCodePoint:Vl(I,T)},...y.length>0?{warnings:[...new Set(y)]}:{}})}return xe({oxml:n.serializeToString(e),hasChanges:b,...y.length>0?{warnings:[...new Set(y)]}:{}})}function am(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)if(e[n]!==t[n])return n;return r}function Xl(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}function Vl(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function im(e,t){let r=[];for(let n=0;n<e.length;n++){let[o,a]=e[n],i=e[n+1];if(o===-1&&i?.[0]===1&&a!==i[1]&&a.length===i[1].length&&a.replace(/\u00a0/g," ")===i[1].replace(/\u00a0/g," ")){r.push(...Hs(a,i[1],t)),n++;continue}r.push([o,a])}return r}function sm(e){let t=[],r=0,n=0;for(let o=0;o<e.length;o++){let[a,i]=e[o];if(a===0){r+=i.length,n+=i.length;continue}if(a===-1){let s=e[o+1];s?.[0]===1?(t.push({type:"replace",start:r,end:r+i.length,newPos:n,text:s[1]}),r+=i.length,n+=s[1].length,o++):(t.push({type:"delete",start:r,end:r+i.length,newPos:n,text:""}),r+=i.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:i}),n+=i.length}return t}function lm(e){let t=[],r=0,n=0;for(let[o,a]of e)o===0?(r+=a.length,n+=a.length):o===-1?r+=a.length:o===1&&(t.push({originalPos:r,newPos:n,text:a}),n+=a.length);return t}var Kl=Is(Ha(),1);var Hl=new Kl.diff_match_patch;function Gl(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function cm(e,t){return e?.getAttributeNS?.(L,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function jl(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let o=0,a=t-1;for(;o<=a;){let i=Math.floor((o+a)/2);e[i].end<=r?o=i+1:a=i-1}t=o}for(;t<e.length&&e[t].end<=r;)t++;let n=e[t];return n&&n.start<=r&&r<n.end?n:null}}}function um(e){let t=new Map;return e.forEach(r=>{t.has(r.start)||t.set(r.start,[]),t.get(r.start).push(r)}),t}function ql(e,t,r=null){let n=e.documentElement,o=D(n,"body")||Gl(n)==="package",a=r||Qe(e),i=Ve(e,L,"body");!i&&o&&(i=n);let s="",l=[],c=[],u=[],f=new Map,d=new Map,m=new Set,p={nextCharCode:57344},g=new Set;a.forEach((O,A)=>{let P=s.length;Array.from(O.childNodes).forEach(C=>{s=gm(C,s,l,u,f,d,p,m)}),s=jr(s,A,a.length);let _=s.length,R=Ve(O,L,"pPr"),k=O.parentNode;k&&g.add(k),c.push({start:P,end:_,pPr:R,container:k||i})});let h="";for(let O=0;O<s.length;O++){let A=s[O];h+=m.has(A)?`
|
|
154
|
+
`:A}let y=mm(h,t,u);y=dm(h,s,y,m),d.forEach((O,A)=>{let P=A.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");y=y.replace(new RegExp(P,"g"),O)}),y=pm(s,y,f);let w=new Map;g.forEach(O=>{w.set(O,e.createDocumentFragment())}),i&&!w.has(i)&&w.set(i,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let v=new Map,b=new Set(c.map(O=>O.start)),x=jl(c),I=jl(l),N=um(u);return{paragraphs:a,body:i||e,paragraphMap:c,paragraphStarts:b,propertyMap:l,sentinelMap:u,sentinelMapByStart:N,referenceMap:f,tokenToCharMap:d,containerFragments:w,replacementContainers:v,originalFullText:s,processedModifiedText:y,getParagraphInfo:O=>{let A=x.at(O);return A||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:i||e})},getRunProperties:O=>{let A=I.at(O);return A?{rPr:A.rPr,wrapper:A.wrapper}:{rPr:null}},getPropertySpanLength:(O,A)=>{let P=I.at(O);return P?Math.min(P.end-O,A):1},isParagraphStart:O=>b.has(O)}}function Mo(e,t){let r=Qe(e);if(r.length===0)return[];let n=Yl(t),o=r.map(fm);if(!n){let i=o.findIndex(s=>s==="");return i>=0?[r[i]]:null}if(r.length===1&&o[0]==="")return r;let a=[i=>i,i=>i.trim(),i=>i.replace(/\s+/g," ").trim()];for(let i of a){let s=i(n);for(let l=0;l<r.length;l++){let c="";for(let u=l;u<r.length;u++)if(c+=(u===l?"":`
|
|
155
|
+
`)+o[u],i(c)===s)return r.slice(l,u+1)}}return null}function Yl(e){return String(e??"").replace(/\r\n?/g,`
|
|
156
|
+
`).replace(/\u00a0/g," ")}function fm(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&(D(o,"pPr")||D(o,"del")||D(o,"moveFrom")||(D(o,"t")?t+=o.textContent||"":D(o,"tab")?t+=" ":D(o,"br")||D(o,"cr")?t+=`
|
|
157
|
+
`:D(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),Yl(t)}function dm(e,t,r,n){if(n.size===0)return r;let o=Hl.diff_main(e,r),a=0,i="";for(let[s,l]of o)if(s===0){for(let c=0;c<l.length;c++){let u=t[a+c];i+=n.has(u)?u:l[c]}a+=l.length}else s===-1?a+=l.length:i+=l;return i}function mm(e,t,r){let n=new Map;if(r.forEach(f=>{f.zeroWidth&&n.set(f.start,f)}),n.size===0)return t;let o="",a=0,i=new Map;for(let f=0;f<e.length;f++){let d=n.get(f);if(d){i.has(a)||i.set(a,[]),i.get(a).push({char:e[f],affinity:d.affinity||"right",emitted:!1});continue}o+=e[f],a++}let s=Hl.diff_main(o,t),l=0,c="",u=(f,d)=>{let m=i.get(f)||[];for(let p of m)p.emitted||d&&p.affinity!==d||(c+=p.char,p.emitted=!0)};for(let[f,d]of s){if(f===1){u(l,"left"),c+=d;continue}for(let m=0;m<d.length;m++)u(l),f===0&&(c+=d[m]),l++}return u(l),c}function pm(e,t,r){let n=t;for(let o of r.keys()){if(n.includes(o))continue;let a=e.indexOf(o);if(a<0)continue;let i=e.slice(0,a),s=e.slice(a+o.length);if(i&&n.startsWith(i)){n=`${n.slice(0,i.length)}${o}${n.slice(i.length)}`;continue}if(s&&n.endsWith(s)){let l=n.length-s.length;n=`${n.slice(0,l)}${o}${n.slice(l)}`}}return n}function gm(e,t,r,n,o,a,i,s){return D(e,"r")?hm(e,t,r,n,o,a,i,s):D(e,"hyperlink")?wm(e,t,r):D(e,"sdt")||D(e,"oMath")||Gl(e)==="oMath"||D(e,"bookmarkStart")||D(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((D(e,"commentRangeStart")||D(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function hm(e,t,r,n,o,a,i,s){let l=t,c=Ve(e,L,"rPr");return Array.from(e.childNodes).forEach(u=>{if(D(u,"t")){let f=u.textContent||"";f.length>0&&(r.push({start:l.length,end:l.length+f.length,rPr:c}),l+=f)}else if(D(u,"br")||D(u,"cr")){let f=String.fromCharCode(i.nextCharCode++);o.set(f,u),s.add(f),l+=f,r.push({start:l.length-1,end:l.length,rPr:c})}else if(D(u,"tab"))l+=" ",r.push({start:l.length-1,end:l.length,rPr:c});else if(D(u,"noBreakHyphen"))l+="\u2011",r.push({start:l.length-1,end:l.length,rPr:c});else if(["drawing","pict","object","fldChar","instrText","sym"].some(f=>D(u,f))){let f=Ve(u,L,"txbxContent"),d=D(u,"pict")&&!!f,m=D(u,"fldChar")||D(u,"instrText"),p=D(u,"fldChar")?u.getAttributeNS?.(L,"fldCharType")||u.getAttribute("w:fldCharType")||u.getAttribute("fldCharType"):null;n.push({start:l.length,node:u,wrapInRun:!0,rPr:c,zeroWidth:m,affinity:p==="end"?"left":"right",isTextBox:d,originalContainer:d?f:void 0}),l+="\uFFFC",r.push({start:l.length-1,end:l.length,rPr:c})}else if(D(u,"footnoteReference")||D(u,"endnoteReference")){let f=cm(u,"id");if(f){let m=`{{__${D(u,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(i.nextCharCode++);o.set(p,u),a.set(m,p),l+=p,r.push({start:l.length-1,end:l.length,rPr:c})}}else D(u,"commentReference")&&n.push({start:l.length,node:u,isCommentMarker:!0})}),l}function wm(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!D(o,"r"))return;let a=Ve(o,L,"rPr");Xe(o,L,"t").forEach(s=>{let l=s.textContent||"";l.length!==0&&(r.push({start:n.length,end:n.length+l.length,rPr:a,wrapper:e}),n+=l)})}),n}function Jl(e,t,r,n,o,a,i=!0,s={}){let{paragraphs:l,containerFragments:c,sentinelMapByStart:u,referenceMap:f,replacementContainers:d,getParagraphInfo:m,getRunProperties:p,getPropertySpanLength:g,isParagraphStart:h}=r,y=k=>{let C=B(e,"w:p");if(k){let M=k.cloneNode(!0),$=Ve(M,L,"sectPr");$&&M.removeChild($),C.appendChild(M)}return C},w=m(0),v=y(w.pPr),b=c.get(w.container);b&&b.appendChild(v);let x=0,I=0,N=s?.pairReplacements===!0,T=null,E=null,S=new WeakSet;for(let k=0;k<t.length;k++){let[C,M]=t[k];if(C===0||C===-1){let $=C===0?"equal":"delete";if(C===0)T=null,E=null;else if(T===null){T=x;let V=!1;for(let Y=k+1;Y<t.length;Y++){if(t[Y][0]===1){V=!0;break}if(t[Y][0]===0)break}N&&i&&V&&(E=Sn(o,e))}let X=0;for(;X<M.length;){let V=x+X,Y=p(V),ye=g(V,M.length-X),fe=M.substring(X,X+ye);v=Zl(e,fe,$,Y.rPr,Y.wrapper,V,v,c,u,f,d,m,y,o,a,I,i,S,E).currentParagraph,C===0&&(I+=ye),X+=ye}x+=M.length;continue}if(C===1){let $=T!==null?T:x>0&&!h(x)?x-1:x,X=p($);v=Zl(e,M,"insert",X.rPr,X.wrapper,x,v,c,u,f,d,m,y,o,a,I,i,S,E,T!==null).currentParagraph,I+=M.length,T=null,E=null}}for(let k of Array.from(u.keys()).sort((C,M)=>C-M))for(let C of u.get(k))if(!(!C.isCommentMarker||S.has(C.node)))if(S.add(C.node),D(C.node,"commentReference")){let M=B(e,"w:r");M.appendChild(C.node.cloneNode(!0)),v.appendChild(M)}else v.appendChild(C.node.cloneNode(!0));i&&c.forEach(k=>{Array.from(k.childNodes).forEach(C=>{if(D(C,"p")){let M=Array.from(C.getElementsByTagNameNS(L,"t")).length>0,$=Array.from(C.getElementsByTagNameNS(L,"delText")).length>0;l.length===1&&!M&&($||r.originalFullText.trim()!=="")&&Nr(e,C,o)}})}),c.forEach(k=>{let C=Array.from(k.childNodes).filter(M=>D(M,"p"));if(C.length>1){let M=C[0],$=C[C.length-1],X=Ve(M,L,"pPr"),V=X?Ve(X,L,"sectPr"):null;if(V){X.removeChild(V);let Y=Ve($,L,"pPr");Y||(Y=B(e,"w:pPr"),$.insertBefore(Y,$.firstChild||null)),Y.appendChild(V)}}});let O=new Set(l),A=new Map;l.forEach(k=>{let C=k.parentNode;if(!C||A.has(C))return;let M=k.nextSibling;for(;M&&O.has(M);)M=M.nextSibling;A.set(C,M)}),l.forEach(k=>{k.parentNode&&k.parentNode.removeChild(k)});let P=!1,_="";return c.forEach((k,C)=>{let M=d.get(C),$=M||C;if($.nodeType===9){P=!0,k.childNodes.length===1?$.appendChild(k.firstChild):_=Array.from(k.childNodes).map(V=>n.serializeToString(V)).join("");return}let X=M?null:A.get(C);X&&X.parentNode===$?$.insertBefore(k,X):$.appendChild(k)}),{oxml:P&&_?_:n.serializeToString(e),hasChanges:!0}}function Zl(e,t,r,n,o,a,i,s,l,c,u,f,d,m,p=[],g=0,h=!0,y=new WeakSet,w=null,v=!1){let b=a,x=g,I=i,N=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(E=>{let S=l.get(b)||[],O=S.filter(_=>_.isCommentMarker&&!y.has(_.node)),A=v?new Set(O.filter(_=>D(_.node,"commentRangeEnd")).map(_=>_.node.getAttributeNS?.(L,"id")||_.node.getAttribute?.("w:id")||_.node.getAttribute?.("id"))):new Set;if(O.forEach(_=>{y.add(_.node);let R=_.node.getAttributeNS?.(L,"id")||_.node.getAttribute?.("w:id")||_.node.getAttribute?.("id");if(v&&A.has(R)&&(D(_.node,"commentRangeEnd")||D(_.node,"commentReference"))){N.push(_.node);return}if(D(_.node,"commentReference")){let k=B(e,"w:r");k.appendChild(_.node.cloneNode(!0)),I.appendChild(k)}else I.appendChild(_.node.cloneNode(!0))}),E===`
|
|
158
|
+
`){let _=f(b+1),R=d(_.pPr);h&&r==="insert"?Yr(e,I,m):h&&r==="delete"&&Nr(e,I,m);let k=s.get(_.container);k&&(k.appendChild(R),I=R),b++,r!=="delete"&&x++;return}if(E==="\uFFFC"){let _=S.find(R=>!R.isCommentMarker)||S[0];if(_){let R=_.node.cloneNode(!0);if(_.isTextBox&&_.originalContainer){let k=Ve(R,L,"txbxContent");if(k){for(;k.firstChild;)k.removeChild(k.firstChild);u.set(_.originalContainer,k)}}if(_.wrapInRun){let k=B(e,"w:r");_.rPr&&k.appendChild(_.rPr.cloneNode(!0)),k.appendChild(R),I.appendChild(k)}else I.appendChild(R)}b++,r!=="delete"&&x++;return}if(c.has(E)){if(r!=="delete"){let _=c.get(E);if(_){let R=_.cloneNode(!0),k=B(e,"w:r");n&&k.appendChild(n.cloneNode(!0)),k.appendChild(R),I.appendChild(k)}}b++,r!=="delete"&&x++;return}if(E.length===0)return;let P=I;if(o){let _=o.cloneNode(!1);P=_,I.appendChild(_)}if(r==="delete"){let _=B(e,"w:r");n&&_.appendChild(n.cloneNode(!0));let R=B(e,"w:delText");if(R.setAttribute("xml:space","preserve"),R.textContent=E,_.appendChild(R),h){let k=null;if(w){let M=w.usedDeletionId?ie(m,e,"del").id:w.deletionId;w.usedDeletionId=!0,k={id:M,author:w.author,date:w.date}}let C=br(e,"del",_,m,k);P.appendChild(C)}}else{let _=Bt(p,x,x+E.length),R=Ao(e,E,n,_,x,m,h);if(r==="insert"&&h){let k=null;if(w){let M=w.usedInsertionId?ie(m,e,"ins").id:w.insertionId;w.usedInsertionId=!0,k={id:M,author:w.author,date:w.date}}let C=br(e,"ins",null,m,k);R.forEach(M=>C.appendChild(M)),P.appendChild(C)}else R.forEach(k=>P.appendChild(k))}r!=="delete"&&(x+=E.length),b+=E.length}),N.forEach(E=>{if(D(E,"commentReference")){let S=B(e,"w:r");S.appendChild(E.cloneNode(!0)),I.appendChild(S)}else I.appendChild(E.cloneNode(!0))}),{currentParagraph:I}}function fi(e,t,r,n,o,a,i=!0,s={},l={}){let c=Mo(e,t);if(c===null)return xe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PARTIAL_TARGET",message:"Original text did not identify a complete contiguous paragraph range for reconstruction."}});let u=ql(e,r,c);if(u.paragraphs.length===0)return xe({oxml:n.serializeToString(e),hasChanges:!1});let f=Rn(u.originalFullText,u.processedModifiedText,s);return xe(Jl(e,f,u,n,o,a,i,l))}function Nt(e,t){return xe({oxml:e.serializeToString(t),hasChanges:!1})}function Ql(e,t,r,n,o,a=!0){let i=Xe(e,L,"tbl"),s=at(t),l=s.rows.length>0||s.headers.length>0;if(i.length===0||!l)return Nt(r,e);let c=i[0],u=Ka(c),f=il(u,s);if(f.length===0)return Nt(r,e);let d={generateRedlines:a,author:o,revisionIdAllocator:Dt(e)},m=sl(u,f,d),p=`<root xmlns:w="${L}">${m}</root>`,g=W(p,"application/xml").doc;if(!g)return Nt(r,e);let h=Se(g);if(h)return Ne("[OxmlEngine] Failed to parse reconciled table OOXML:",h.textContent),Nt(r,e);let y=Ve(g,L,"tbl");if(!y)return Ne("[OxmlEngine] No table found in reconciled OOXML"),Nt(r,e);let w=e.importNode(y,!0);return c.parentNode.replaceChild(w,c),xe({oxml:r.serializeToString(e),hasChanges:!0})}function ec(e,t,r,n,o,a){let i=Dt(e),s=at(t);if(!s||s.rows.length===0&&s.headers.length===0)return K("[OxmlEngine] Failed to parse table data from Markdown"),Nt(r,e);let l=yr(s,{generateRedlines:a,author:o,revisionIdAllocator:i}),c=W(`<root xmlns:w="${L}">${l}</root>`,"application/xml").doc;if(!c)return Nt(r,e);let u=Se(c);if(u)return Ne("[OxmlEngine] Failed to parse generated table OOXML:",u.textContent),Nt(r,e);let f=Te(c,L,"tbl");if(f||(f=Te(c,L,"ins")),!f)return Ne("[OxmlEngine] No table element found in generated OOXML"),Nt(r,e);let d=e,m=Ce(d,L,"p");if(m.length===0)return K("[OxmlEngine] No paragraphs found to replace"),Nt(r,d);let p=m[0],g=p.parentNode;if(g&&g.nodeType===9){let y=W(`<w:document xmlns:w="${L}"><w:body/></w:document>`,"application/xml").doc;if(!y)return Nt(r,d);let w=Te(y,L,"body");m.forEach(v=>w.appendChild(y.importNode(v,!0))),d=y,er(d,i),m=Ce(d,L,"p"),p=m[0],g=p.parentNode}let h=d.importNode(f,!0);return a?m.forEach(y=>{Nr(d,y,o),Ce(y,L,"r").forEach(v=>{Ce(v,L,"t").forEach(N=>{let T=N.textContent||"";if(T.trim()){let E=B(d,"w:delText");E.textContent=T,N.parentNode.replaceChild(E,N)}});let x=B(d,"w:del"),I=ie(o,d,"del");x.setAttribute("w:id",String(I.id)),x.setAttribute("w:author",I.author),x.setAttribute("w:date",I.date),v.parentNode.insertBefore(x,v),x.appendChild(v)})}):m.slice(1).forEach(y=>y.parentNode.removeChild(y)),g.insertBefore(h,p),a||g.removeChild(p),K("[OxmlEngine] Text-to-table transformation complete"),xe({oxml:r.serializeToString(d),hasChanges:!0})}function zt(e,t){if(!e||!e.attributes)return"";for(let r of Array.from(e.attributes))if((r.localName||"").toLowerCase()===t.toLowerCase())return String(r.value||"");return String(e.getAttribute?.(`w:${t}`)||e.getAttribute?.(t)||"")}function Lo(e){return typeof e=="string"?e.trim().toLowerCase():""}function ym(e){return!!e&&e.nodeType===1}function It(e,t){return ym(e)&&e.namespaceURI===L&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function De(e,t){return Array.from(e.getElementsByTagNameNS(L,t))}function di(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=Lo(e?.author);return t?{valid:!0,allAuthors:!1,normalizedAuthor:t}:{valid:!1,allAuthors:!1,normalizedAuthor:"",warning:"No author provided. Pass { author } or set { allAuthors: true }."}}function it(e,t){if(t.allAuthors)return!0;let r=Lo(zt(e,"author"));return!!r&&r===t.normalizedAuthor}function mi(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=W(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let i=`<w:body xmlns:w="${L}">${r}</w:body>`,s=W(i,"application/xml");s.error||(o=s,n=!0)}let a=o.doc?Se(o.doc):null;if(o.error||a){let i=o.error?.message||a?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${i}`,warnings:o.warnings,error:{code:"PARSE_ERROR",message:i}}}return{xmlDoc:o.doc,serializer:oe(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function ke(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Bo(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function tc(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function rc(e){return Array.from(e?.attributes||[]).filter(t=>String(t.localName||t.name||"").toLowerCase()!=="id").map(t=>`${t.namespaceURI||""}|${t.localName||t.name}=${t.value}`).sort().join(`
|
|
159
|
+
`)}function vm(e){let t=0,r=De(e,"ins");for(let n of r){if(!n.parentNode||Fo(n))continue;let o=tc(n);for(;It(o,"ins")&&Lo(zt(o,"author"))===Lo(zt(n,"author"))&&rc(o)===rc(n);){let a=tc(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=a}}return t}function Do(e){let t=e?.parentNode;return It(t,"trPr")&&It(t?.parentNode,"tr")}function Fo(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return It(t,"rPr")&&It(r,"pPr")&&It(n,"p")}function ac(e){return Fo(e)?e.parentNode.parentNode.parentNode:null}function xm(e){let t=e?.nextSibling||null;for(;t;){if(It(t,"p"))return t;t=t.nextSibling}return null}function ic(e){if(!e?.parentNode)return!1;let t=xm(e);if(!t)return It(e.parentNode,"tc")&&De(e.parentNode,"p").length<=1?!1:ke(e);let r=Array.from(e.childNodes||[]).filter(o=>!It(o,"pPr")),n=t.firstChild||null;It(n,"pPr")&&(n=n.nextSibling||null);for(let o of r)t.insertBefore(o,n);return ke(e)}function Er(e,t={}){let r=[],n=di(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=mi(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let s=0;for(let u of De(a,"ins"))if(!(!u.parentNode||!it(u,n))){if(Fo(u)){ke(u)&&(s+=1);continue}if(Do(u)){ke(u)&&(s+=1);continue}Bo(u)&&(s+=1)}for(let u of De(a,"del")){if(!u.parentNode||!it(u,n))continue;let f=ac(u);if(f){ic(f)&&(s+=1);continue}if(Do(u)){let d=u.parentNode?.parentNode;ke(d)&&(s+=1);continue}ke(u)&&(s+=1)}for(let u of De(a,"moveFrom"))!u.parentNode||!it(u,n)||ke(u)&&(s+=1);for(let u of De(a,"moveTo"))!u.parentNode||!it(u,n)||Bo(u)&&(s+=1);s+=sc(a,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of De(a,u))!f.parentNode||!it(f,n)||ke(f)&&(s+=1);return{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(a),hasChanges:s>0,acceptedCount:s,warnings:r}}function nc(e,t){for(let r of Array.from(t.getElementsByTagNameNS(L,"delText"))){let n=B(e,"w:t"),o=r.getAttribute("xml:space");for(o&&n.setAttribute("xml:space",o);r.firstChild;)n.appendChild(r.firstChild);r.parentNode?.replaceChild(n,r)}}function bm(e,t){let r=e?.parentNode;if(!r)return!1;let n=t.endsWith("Change")?t.slice(0,-6):"";if(!n||String(r.localName||"").toLowerCase()!==n.toLowerCase()||r.namespaceURI!==L)return ke(e);let o=Array.from(e.childNodes||[]).find(i=>i.nodeType===1&&i.namespaceURI===L&&String(i.localName||"").toLowerCase()===n.toLowerCase());if(!o)return ke(e);let a=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let i of a){let s=Nm(r.ownerDocument,i);r.appendChild(s)}return!0}function Nm(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function oc(e,t,r){let n=new Set;for(let o of De(e,t)){if(!it(o,r))continue;let a=zt(o,"id");a&&n.add(a)}return n}function sc(e,t){let r=0,n=oc(e,"moveFromRangeStart",t),o=oc(e,"moveToRangeStart",t),a=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",o,!0],["moveToRangeEnd",o,!1]];for(let[i,s,l]of a)for(let c of De(e,i)){if(!c.parentNode)continue;let u=zt(c,"id");u&&(t.allAuthors||s.has(u)||l&&it(c,t))&&ke(c)&&(r+=1)}return r}function cr(e,t={}){let r=[],n=di(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=mi(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let s=0;for(let u of De(a,"ins")){if(!u.parentNode||!it(u,n))continue;let f=ac(u);if(f){ic(f)&&(s+=1);continue}if(Do(u)){let d=u.parentNode?.parentNode;ke(d)&&(s+=1);continue}ke(u)&&(s+=1)}for(let u of De(a,"del"))if(!(!u.parentNode||!it(u,n))){if(Fo(u)){ke(u)&&(s+=1);continue}if(Do(u)){ke(u)&&(s+=1);continue}nc(a,u),Bo(u)&&(s+=1)}for(let u of De(a,"moveFrom"))!u.parentNode||!it(u,n)||(nc(a,u),Bo(u)&&(s+=1));for(let u of De(a,"moveTo"))!u.parentNode||!it(u,n)||ke(u)&&(s+=1);s+=sc(a,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of De(a,u))!f.parentNode||!it(f,n)||bm(f,u)&&(s+=1);return vm(a),{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(a),hasChanges:s>0,rejectedCount:s,warnings:r}}function Im(e,t){let r=new Set,n=De(e,"comment");for(let o of n){if(!it(o,t))continue;let a=zt(o,"id");a&&r.add(a)}return{targetIds:r,commentNodes:n}}function Tm(e,t){let r=0;for(let n of e){let o=zt(n,"id");!o||!t.has(o)||ke(n)&&(r+=1)}return r}function Sm(e){return It(e,"r")?Array.from(e.childNodes||[]).filter(r=>{if(r.nodeType===3)return String(r.nodeValue||"").trim().length>0;if(r.nodeType!==1)return!1;if(r.namespaceURI!==L)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function Em(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let o of n)for(let a of De(e,o)){if(!a.parentNode)continue;let i=zt(a,"id");if(!(!i||!t.has(i))){if(o==="commentReference"&&Sm(a.parentNode)){ke(a.parentNode)&&(r+=1);continue}ke(a)&&(r+=1)}}return r}function pi(e,t={}){let r=[],n=di(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=mi(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let{targetIds:s,commentNodes:l}=Im(a,n);if(n.allAuthors)for(let f of["commentRangeStart","commentRangeEnd","commentReference"])for(let d of De(a,f)){let m=zt(d,"id");m&&s.add(m)}let c=Tm(l,s),u=Em(a,s);return{oxml:i.serializeToString(a),hasChanges:c>0||u>0,commentsRemoved:c,referencesRemoved:u,warnings:r}}var Am=Object.freeze({formatOnly:Object.freeze({paragraphs:!0,formatting:!0,tables:"scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved"}),surgical:Object.freeze({paragraphs:!0,tables:"cell-scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved",notes:"preserved"}),reconstruction:Object.freeze({paragraphs:!0,hyperlinks:"sentinel-preserved",fields:"sentinel-preserved",comments:"marker-preserved",notes:"reference-preserved"}),table:Object.freeze({tables:!0,paragraphs:!0,formatting:"cell-dependent",numbering:!1}),listDirect:Object.freeze({lists:!0,numbering:!0,paragraphs:"single-source expansion",tables:"embedded-markdown blocks",formatting:"markdown hints"}),listCompatibilityPipeline:Object.freeze({lists:!0,numbering:!0,paragraphs:"multi-source patching",compatibility:!0})});function Xt(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:Am[t]||null,...r}))}var Rm=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function Fe(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Bn(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function Ar(e,t){return Bn(e).find(r=>Fe(r)===t)||null}function $o(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Uo(e){return String(e||"").trim().toLowerCase()}function Pm(e){return Fe(e)!=="r"?!1:Bn(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(Fe(t)))}function gi(e){return Rm.has(Fe(e))||Pm(e)}function hi(e){return Fe(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(Fe(e))?Bn(e).filter(r=>!gi(r)&&Fe(r)!=="sdtPr").every(hi):!1}function Cm(e){let t=e?.ownerDocument?.documentElement||null;if(!t)return!1;let r=new Set;for(let n of[t,...Array.from(t.getElementsByTagName?.("*")||[])]){if(n===e&&r.size>0)return!0;let o=Fe(n),a=$o(n,"id");o==="moveFromRangeStart"&&a!==""&&r.add(a),o==="moveFromRangeEnd"&&a!==""&&r.delete(a)}return!1}function lc(e){let t=Ar(e,"pPr"),r=Ar(t,"rPr");return Ar(r,"del")}function Om(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=Fe(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,o=!1;for(;n&&n!==e;){let a=Fe(n);if(a==="del"||a==="moveFrom"){o=!0;break}n=n.parentNode}if(!o&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function ur(e,t){let r=lc(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=$o(r,"author")||null,o=!n||Uo(n)!==Uo(t),i=Bn(e).filter(s=>!gi(s)).every(hi);return{matches:o&&i,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:i,ownerAuthor:n,markDeletion:r}}function Rr(e,t={}){let r=Ar(e,"pPr");if(Ar(r,"sectPr"))return{code:"SECTION_BREAK_PARAGRAPH",message:"Refusing to restore a deleted paragraph whose paragraph properties contain a section break."};let n=e?.parentNode||null;for(;n;){if(Fe(n)==="moveFrom")return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};n=n.parentNode}if(Cm(e)||e?.getElementsByTagName?.("*")&&Array.from(e.getElementsByTagName("*")).some(i=>["moveFrom","moveFromRangeStart","moveFromRangeEnd"].includes(Fe(i))))return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};let o=e?.parentNode||null;for(;o&&Fe(o)!=="tr";)o=o.parentNode;let a=Ar(o,"trPr");if(a&&Ar(a,"del"))return{code:"UNSAFE_DELETED_TABLE_ROW",message:"Refusing to restore a paragraph inside a table row with a pending row deletion."};if(t.requireFollowingParagraph!==!1){let i=e?.nextSibling||null;for(;i&&(i.nodeType!==1||Fe(i)!=="p");)i=i.nextSibling;if(!i)return{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Refusing to restore a deleted paragraph without a following paragraph in the same structural container."}}return null}function cc(e){let t=Fe(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>Fe(n)==="p"),r=[];for(let n of t){let o=lc(n);if(!o)continue;let a=$o(o,"author")||null,i=Bn(n).filter(c=>!gi(c)),s=i.filter(c=>Fe(c)!=="ins"||!Om(c)?!1:Uo($o(c,"author"))!==Uo(a)),l=i.every(c=>hi(c)||s.includes(c));s.length>0&&l&&r.push({paragraph:n,markDeletion:o,ownerAuthor:a,foreignInsertions:s})}return r}function _m(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Xe(e,L,r)){let o=n.getAttribute?.("w:id")||n.getAttribute?.("id");o!==""&&t.add(o)}return[...t].sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Pr(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===L&&r.localName===t)||null}function km(e,t){let r=Pr(Pr(Pr(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(L,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(L,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(L,"date")||""}}function Mm(e,t){let r=e.cloneNode(!1),n=Pr(e,"pPr");return n&&r.appendChild(pt(n)),t.serializeToString(r)}function Lm(e,t){if(!t||typeof e!="string"||!e.trim())return e;let r=W(e,"text/xml");if(!r.doc||r.error)return e;let n=r.doc.documentElement?.localName==="p"?r.doc.documentElement:Qe(r.doc)[0];if(!n)return e;let o=Pr(n,"pPr");o||(o=B(r.doc,"w:pPr"),n.insertBefore(o,n.firstChild));let a=Pr(o,"rPr");if(a||(a=B(r.doc,"w:rPr"),o.appendChild(a)),!Pr(a,"ins")){let i=B(r.doc,"w:ins");t.id&&i.setAttribute("w:id",t.id),i.setAttribute("w:author",t.author),t.date&&i.setAttribute("w:date",t.date),a.appendChild(i)}return Ie(r.doc)}async function Dn(e,t,r,n={}){let o=e,a=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let i=n.generateRedlines??!0,s=n.author||re(),l=oe(),c=[],u=[],f=!1,d=null,m=n.existingRevisions||"merge-same-author",p=m==="accept-all-first-keep-normalized",g=j=>{let z={...j};f&&z.hasChanges===!1&&z.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(z.oxml=a,z.hasChanges=!0,z.warnings=[...Array.isArray(z.warnings)?z.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(z.oxml=a,z.hasChanges=!0,z.warnings=[...Array.isArray(z.warnings)?z.warnings:[],"Existing revisions were accepted before redlining."]):z.oxml=o);let U=[...c,...u,...Array.isArray(z.warnings)?z.warnings:[]];return U.length>0&&(z.warnings=[...new Set(U)]),z.status||(z.status=z.hasChanges?"ok":"no-op"),d&&z.hasChanges&&typeof z.oxml=="string"&&(z.oxml=Lm(z.oxml,d)),xe(z)},h=()=>g(f&&p?{oxml:a,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),y=W(o,"text/xml");c=y.warnings;let w=y.doc,v=w?Se(w):null;if(y.error||v){let j=y.error?.message||v?.textContent||"Could not parse OOXML input.";return Ne("[OxmlEngine] XML parse error:",j),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:j}})}let b=n?._revisionIdAllocator instanceof Ae?n._revisionIdAllocator:new Ae;Ft(w,b);let x=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:Qe(w);if(x.length===1&&r.length>0){let j=ur(x[0],s);if(j.matches){let z=j.ownerAuthor||"unattributed";return g({oxml:o,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${z}). Use explicit paragraph restoration when supported.`,ownerAuthor:z}})}}if(or(w))if(m==="merge-same-author"||m==="slice-cross-author"){let j=vr(w),z=String(s||"").trim().toLowerCase();if(j.length>0&&j.every(G=>G.trim().toLowerCase()===z)){let G=_m(w);if(G.length>0)return g({oxml:o,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:G}});K("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let ee=x.length===1?x[0]:null;d=km(ee,s);let Ge=cr(o,{author:s});if(Ge.status==="error")return g(Ge);a=d&&!String(Ge.oxml||"").trim()?Mm(ee,l):Ge.oxml,f=!0;let ot=W(a,"text/xml");c.push(...ot.warnings),w=ot.doc;let go=w?Se(w):null;if(ot.error||go){let ho=ot.error?.message||go?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return Ne("[OxmlEngine] XML parse error after rejecting same-author revisions:",ho),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:ho}})}if(or(w))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});Ft(w,b);let bs=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:Qe(w);t=bs.length>0?bs.map(ho=>te(ho)).join(`
|
|
160
|
+
`):""}else{if(m==="merge-same-author")return K("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${j.length?j.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:j,currentPolicy:m}});if(["moveFrom","moveTo"].some(ee=>Xe(w,L,ee).length>0))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});K("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(m==="accept-all-first"||m==="accept-all-first-keep-normalized"){K("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let j=Er(o,{allAuthors:!0});if(j.status==="error")return g(j);a=j.oxml,f=!0;let z=W(a,"text/xml");c.push(...z.warnings),w=z.doc;let U=w?Se(w):null;if(z.error||U){let G=z.error?.message||U?.textContent||"Could not parse OOXML after accepting existing revisions.";return Ne("[OxmlEngine] XML parse error after accepting existing revisions:",G),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:G}})}Ft(w,b)}else return K("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let I=Ll(w,t,n);if(I.hasTableWrapper&&I.targetParagraph&&!n._isolatedTableCell){K("[OxmlEngine] Isolating table-cell paragraph before diff");let j=_n(w,I.targetParagraph,l),z=await Dn(j,t,r,{...n,_isolatedTableCell:!0});return!z.hasChanges&&z.status==="no-op"?h():z}let N=n.sanitizeInput===!0?wi(r):r;N!==r&&u.push("Input was sanitized; pass sanitizeInput: false to disable.");let T=null;if(n.structuredContent!==!1)if(T=Eo(N),T.valid)T.requiresStructuredContent&&(N=T.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let j=T.issues.map(z=>`${z.code}: ${z.message}`).join(" ");return g({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:j},warnings:T.issues.map(z=>z.message)})}T=null}let{cleanText:E,formatHints:S}=Je(N),O=m==="slice-cross-author"?E!==t:E.trim()!==t.trim(),A=S.length>0,{existingFormatHints:P,textSpans:_,paragraphs:R}=Tl(w),k=P.length>0,C=_.map(j=>uc(j)).join(""),M=t.includes(`
|
|
161
|
+
`)||t.includes("\r")?t.split(/\r?\n/).map(zo).filter(Boolean).every(j=>R.some(z=>{let U=_.filter(G=>G.paragraph===z).map(uc).join("");return zo(U).includes(j)})):C.includes(t.trim())||C.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||zo(C).includes(zo(t));if(O&&typeof t=="string"&&t.trim()&&!M)return K("[OxmlEngine] Target text not found in OOXML"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let $=null,X=()=>($||($=Ro(w,R,_)),$),V=(j=null)=>{let z=Ml(w,t,S,l,s,i,j);return z.useNativeApi?(K("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),fi(w,t,E,l,s,S,i)):z};K(`[OxmlEngine] Text changes: ${O}, New format hints: ${S.length}, Existing format hints: ${P.length}`);let Y=n.removeFormatting===!0&&!O&&!A&&k;if(!O&&!A&&!k)return Xt(n,"noChange"),K("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),h();if(!O&&!A&&k&&!Y)return K("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),h();if(Y){Xt(n,"formatOnly",{removeFormatting:!0}),K("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let j=I,z=j.targetParagraph||null;if(!z){let ee=Pl(X(),t);ee&&(z=ee.paragraph)}let U=P;z&&(U=P.filter(ee=>Ol(ee.run)===z));let G=kl(w,_,U,l,s,i);return j.hasTableWrapper&&z?g({oxml:_n(w,z,l),hasChanges:G.hasChanges}):g(G)}if(!O&&A){Xt(n,"formatOnly",{removeFormatting:!1}),K(`[OxmlEngine] Format-only change detected: ${S.length} format hints`);let j=I,z={textSpans:_,paragraphs:R,paragraphInfos:X()};if(j.hasTableWrapper&&j.targetParagraph){K("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let U=V(z);return K("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),g({oxml:_n(w,j.targetParagraph,l),hasChanges:U.hasChanges})}return g(V(z))}let fe=Xe(w,L,"tbl").length>0,H=/^\|.+\|/.test(E.trim())&&E.includes(`
|
|
162
|
+
`),q=bn(E),ge=n.structuredContent!==!1&&T?.requiresStructuredContent===!0,ce=I,ve=fe||m==="slice-cross-author";K(`[OxmlEngine] Mode: ${ve?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${S.length}, isMarkdownTable: ${H}, isTargetList: ${q}, isTableCellParagraph: ${ce.isTableCellParagraph}`);try{if(H&&!fe)return Xt(n,"table",{transformation:"text-to-table"}),K("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),g(ec(w,E,l,null,s,i));if(fe&&H)return Xt(n,"table",{transformation:"table-reconciliation"}),g(Ql(w,E,l,null,s,i));if(ve){Xt(n,"surgical",{tableScoped:fe});let j=ce.hasTableWrapper&&ce.targetParagraph?ce.targetParagraph:null;j&&K("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let z=Wl(w,t,E,l,s,S,i,j,{},n);return z.status==="error"&&z.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?g({...z,oxml:o,hasChanges:!1}):ce.hasTableWrapper&&z.hasChanges&&ce.targetParagraph?(K("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),g({oxml:_n(w,ce.targetParagraph,l),hasChanges:!0})):g(z)}if(q||ge){let j=Xe(w,L,"p"),z=j.length===1;Xt(n,z?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:j.length}),K(`[OxmlEngine] \u{1F3AF} Using ${z?"direct list generation":"compatibility pipeline"} for list reconciliation`);let U;if(z){let G=Hr(a,{xmlDoc:w}),ee=An(j[0]);U=await qr({cleanText:E,numberingContext:ee,originalRunModel:G.runModel,originalText:G.acceptedText,generateRedlines:i,author:s,font:n.font||null,revisionIdAllocator:b,numberingService:new $t})}else U=await new Pn({author:s,generateRedlines:i,revisionIdAllocator:b}).execute(a,N,{xmlDoc:w});if(U.error?.code==="DIFF_TOKEN_LIMIT")return g({oxml:o,hasChanges:!1,status:"error",error:U.error});if(U.isValid&&U.ooxml&&U.ooxml!==a){let G=U.includeNumbering===!0;K(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${G}`);let ee=nr(U.ooxml,{includeNumbering:G,numberingXml:U.numberingXml});return K(`[OxmlEngine] \u2705 Wrapped OOXML length: ${ee.length}`),g({oxml:ee,hasChanges:!0,...Array.isArray(U.warnings)?{warnings:U.warnings}:{}})}return h()}return Xt(n,"reconstruction"),g(fi(w,t,E,l,s,S,i,{},n))}catch(j){if(Ks(j))return g({oxml:o,hasChanges:!1,status:"error",error:{code:j.code,message:j.message}});throw j}}function zo(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function uc(e){let t=e?.textElement,r=String(t?.localName||t?.nodeName||"").replace(/^.*:/,"");return r==="tab"?" ":r==="br"||r==="cr"?`
|
|
163
|
+
`:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function wi(e){return String(e??"").replace(/^(?:Here is the redline:|Here is the text:|Sure, I can help:|Here's the updated text:)[ \t]*\r?\n/i,"")}function Vt(e){return W(e,"application/xml").doc}function Cr(e){return Ie(e)}function Xo(e){return Array.from(e||[])}function Fn(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function qe(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var Pe="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function fc(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=Xo(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=Xo(e.getElementsByTagName(`w:${t}`));return r.length>0?r:Xo(e.getElementsByTagName(t))}function be(e){return e?te(e):""}function se(e){if(!e)return[];let t=fc(e,"body"),r=t.length>0?t[0]:e;return fc(r,"p")}function $e(e){return e&&Xo(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function st(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:te(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:se(e.ownerDocument||e).indexOf(e)+1,a=t.paragraphId===void 0?$e(e):t.paragraphId,i=typeof t.inTable=="boolean"?t.inTable:Un(e),l=`${a||""}${o}${i?"table":"body"}${r==="rejected"?"rejected":""}${n}`,c=2166136261;for(let u=0;u<l.length;u++)c^=l.charCodeAt(u),c=Math.imul(c,16777619)>>>0;return`fnv1a32:${c.toString(16).padStart(8,"0")}`}function kt(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=se(e),o=[],a=new Map,i=new Map,s=new Map;for(let l=0;l<n.length;l++){let c=n[l],u=te(c,{revisionView:r}),f=$e(c),d=Un(c),m=J(u),p=Object.freeze({paragraph:c,index:l+1,paragraphId:f,text:u,normalizedText:m,revisionView:r,fingerprint:st(c,{text:u,index:l+1,paragraphId:f,inTable:d,revisionView:r}),inTable:d});o.push(p),a.set(c,p),f&&!i.has(f)&&i.set(f,p),m&&(s.has(m)||s.set(m,[]),s.get(m).push(p))}for(let[l,c]of s)s.set(l,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:a,byId:i,byNormalizedText:s})}function J(e){return String(e||"").replace(/\s+/g," ").trim()}function Or(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
|
|
164
|
+
`)}function vi(e){if(e==null)return null;if(typeof e=="number"&&Number.isInteger(e)&&e>0)return e;let t=String(e).trim();if(!t)return null;let r=t.match(/^\[?P(\d+)(?:\.\d+)?\]?$/i);if(r)return Number.parseInt(r[1],10);let n=t.match(/^(\d+)$/);return n?Number.parseInt(n[1],10):null}function Bm(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function Dm(e){let t=String(e||""),r=t.match(/^\s*\[P(\d+)(?:\.\d+)?\]\s*/i);return r?{text:t.replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim(),targetRef:Number.parseInt(r[1],10)}:{text:t.trim(),targetRef:null}}function dc(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:se(e)[t-1]||null}function We(e,t,r=Pe){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function Vo(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,a=o?null:se(e),i=String(t||"").trim();if(!i)return null;let s=o?o.find(c=>c.text.trim()===i)?.paragraph:a.find(c=>be(c).trim()===i);if(s)return s;let l=J(i);return n?.byNormalizedText?n.byNormalizedText.get(l)?.[0]?.paragraph||null:a.find(c=>J(be(c))===l)||null}function yi(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,a=o?.entries||null,i=a?null:se(e),s=String(t||"").trim();if(!s)return null;let l=Vo(e,s,{paragraphMetadataIndex:o});if(l)return l;let c=J(s),u=a?a.find(h=>h.normalizedText.length>10&&c.startsWith(h.normalizedText))?.paragraph||null:i.find(h=>{let y=J(be(h));return y.length>10&&c.startsWith(y)});if(u)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${be(u).trim().slice(0,60)}..."`),u;let f=a?a.find(h=>h.normalizedText.length>15&&c.includes(h.normalizedText))?.paragraph||null:i.find(h=>{let y=J(be(h));return y.length>15&&c.includes(y)});if(f)return n(`[Fuzzy] Contains match: "${be(f).trim().slice(0,60)}..."`),f;let d=0,m=null,p=new Set(c.toLowerCase().split(/\s+/).filter(h=>h.length>2)),g=a?.length??i.length;for(let h=0;h<g;h++){let y=a?.[h]?.paragraph??i[h],w=(a?.[h]?.text??be(y)).trim();if(!w)continue;let x=J(w).toLowerCase().split(/\s+/).filter(I=>I.length>2).filter(I=>p.has(I)).length/Math.max(p.size,1);x>d&&x>.5&&(d=x,m=y)}return m?(n(`[Fuzzy] Best word-overlap match (${(d*100).toFixed(0)}%): "${be(m).trim().slice(0,60)}..."`),m):null}function _r(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},o=t.opType||"operation",a=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,i=a?.revisionView==="rejected"?"rejected":"accepted",s=String(a?.exactText??a?.text??t.targetText??"").trim(),l=vi(a?.index??a?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,u=t.paragraphMetadataIndex||null;if(u&&u.revisionView!==i?u=t.metadataIndices?.[i]||kt(e,{revisionView:i}):u||(u=kt(e,{revisionView:i})),a?.paragraphId){let d=$m(e,a.paragraphId,u);if(!d)throw qe("TARGET_NOT_FOUND",`Target paragraphId not found: "${a.paragraphId}".`);let m=u?.byParagraph?.get(d)||null,p=m?.index??se(e).indexOf(d)+1,g=m?.fingerprint||st(d,{revisionView:i}),h=m?.inTable??Un(d),y=m?.normalizedText||J(te(d,{revisionView:i}));if(l!=null&&l!==p)throw qe("TARGET_INDEX_MISMATCH",`Target paragraphId "${a.paragraphId}" (index ${p}) does not match requested index ${l}.`,m?[Tt(m)]:null);if(a.fingerprint&&a.fingerprint!==g){let w=i==="rejected"?"accepted":"rejected",v=st(d,{revisionView:w}),b=a.fingerprint===v?` The supplied fingerprint matches the ${w} view; set target.revisionView to "${w}" or use a fingerprint extracted from the ${i} view.`:"";throw qe("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches its source fingerprint.${b}`,m?[Tt(m)]:null)}if(typeof a.inTable=="boolean"&&a.inTable!==h)throw qe("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" does not match the requested table context.`,m?[Tt(m)]:null);if(s&&y!==J(s)){let w=i==="rejected"?"accepted":"rejected",b=J(te(d,{revisionView:w}))===J(s)?` The supplied text matches the ${w} view; set target.revisionView to "${w}".`:"";throw qe("TARGET_TEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches the supplied text.${b}`,m?[Tt(m)]:null)}if(a.occurrence!=null){let v=Wo(e,s||y,u),b=v.findIndex(x=>x.paragraph===d)+1;if(b===0||b!==a.occurrence)throw qe("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${a.paragraphId}" matches occurrence ${b}, not requested occurrence ${a.occurrence}.`,v.map(Tt))}return{paragraph:d,resolvedBy:"paragraph_id"}}if(a?.fingerprint&&!s&&!l){let d=(u?.entries||[]).filter(m=>m.fingerprint===a.fingerprint);if(typeof a.inTable=="boolean"&&(d=d.filter(m=>m.inTable===a.inTable)),d.length===1)return{paragraph:d[0].paragraph,resolvedBy:"fingerprint"};throw d.length>1?qe("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",d.map(Tt)):qe("TARGET_NOT_FOUND",`Target fingerprint not found: "${a.fingerprint}".`)}let f=[];if(s){let d=Wo(e,s,u);if(f=Fm(d,a),a?.fingerprint&&d.length>0&&f.length===0)throw qe("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",d.map(Tt));if(typeof a?.inTable=="boolean"&&d.length>0&&f.length===0)throw qe("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",d.map(Tt));if(a?.occurrence){let m=f[a.occurrence-1]||null;if(!m)throw qe("TARGET_NOT_FOUND",`Target occurrence ${a.occurrence} was not found.`,f.map(Tt));return{paragraph:m.paragraph,resolvedBy:"occurrence"}}if(c){if(l){let m=f.find(p=>p.index===l)||null;if(m)return{paragraph:m.paragraph,resolvedBy:"ref"};if(a?.fingerprint&&f.length>0)throw qe("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`,f.map(Tt));if(f.length===1)return{paragraph:f[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(f.length>1)throw qe("AMBIGUOUS_TARGET",`Target text matched ${f.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,f.map(Tt));if(f.length===0)throw Fn(`Target paragraph not found: "${s}"`)}if(!l&&f.length===1)return{paragraph:f[0].paragraph,resolvedBy:a?.fingerprint?"fingerprint":"strict_text"}}if(l){let d=dc(e,l,u);if(d){let m=u?.byParagraph?.get(d)||null;if(a?.fingerprint&&a.fingerprint!==m?.fingerprint)throw qe("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`);if(typeof a?.inTable=="boolean"&&a.inTable!==m?.inTable)throw qe("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${l}] does not match requested table context.`);if(s){let p=Vo(e,s,{paragraphMetadataIndex:u}),g=(m?.text||te(d,{revisionView:i})).trim(),h=J(g),y=J(s),w=h!==y;if(w&&p&&p!==d)return r(`[Target] [P${l}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let v=yi(e,s,{onInfo:r,paragraphMetadataIndex:u});if(v&&v!==d)return r(`[Target] [P${l}] drifted for ${o}; using fuzzy text rematch.`),{paragraph:v,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${l}] fallback for ${o}; target text drifted.`)}else p&&p!==d&&r(`[Target] [P${l}] disambiguated duplicate target text for ${o}.`)}else r(`[Target] Using [P${l}] fallback for ${o}.`);return{paragraph:d,resolvedBy:"ref"}}n(`[WARN] Target reference [P${l}] not found; falling back to text matching for ${o}.`)}if(s&&!c){let d=Vo(e,s,{paragraphMetadataIndex:u});if(d){let p=f.length;if(p>1){let g=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(g),{paragraph:d,resolvedBy:"strict_text",warnings:[g]}}return{paragraph:d,resolvedBy:"strict_text"}}let m=yi(e,s,{onInfo:r,paragraphMetadataIndex:u});if(m)return{paragraph:m,resolvedBy:"fuzzy_text"}}throw Fn(s?`Target paragraph not found: "${s}"`:l?`Target paragraph reference not found: [P${l}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function Un(e){return!!We(e,"tbl")}function Wo(e,t,r=null){let n=J(t);if(!n)return[];let o=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,a=r?.revisionView||o?.revisionView||"accepted";if(o?.byNormalizedText&&o.revisionView===a)return Array.from(o.byNormalizedText.get(n)||[]);let i=se(e),s=[];for(let l=0;l<i.length;l++){let c=i[l],u=te(c,{revisionView:a}).trim();u&&J(u)===n&&s.push({paragraph:c,index:l+1,inTable:Un(c),paragraphId:$e(c),fingerprint:st(c,{text:u,index:l+1,revisionView:a}),text:u,revisionView:a})}return s}function Tt(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function Fm(e,t){let r=e.slice();return t?.paragraphId&&(r=r.filter(n=>n.paragraphId===t.paragraphId)),typeof t?.inTable=="boolean"&&(r=r.filter(n=>n.inTable===t.inTable)),t?.fingerprint&&(r=r.filter(n=>n.fingerprint===t.fingerprint)),r}function $m(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:se(e).find(n=>$e(n)===t)||null:null}function Um(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let o=n.filter(a=>a.inTable===r);o.length>0&&(n=o)}return Number.isInteger(t)&&t>0&&n.sort((o,a)=>Math.abs(o.index-t)-Math.abs(a.index-t)),n[0]||null}function xi(e,t=null){let r=t?.entries||null,n=r?null:se(e),o=new Map,a=r?.length??n.length;for(let i=0;i<a;i++){let s=r?.[i]?.paragraph??n[i],l=(r?.[i]?.text??be(s)).trim();o.set(i+1,{text:l,normalizedText:r?.[i]?.normalizedText??J(l),inTable:r?.[i]?.inTable??Un(s)})}return o}function $n(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=_r(e,t),o=vi(t.targetRef);if(!o||n?.resolvedBy!=="ref")return n;let a=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(o)||null;if(!a)return n;let i=String(t.targetText||"").trim(),s=i||a.text||"",l=J(s);if(!l||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||J(be(n.paragraph)))===l)return n;let u=[];if(i&&u.push(i),a.text){let d=J(a.text);d&&!u.some(m=>J(m)===d)&&u.push(a.text)}let f=null;for(let d of u){let m=Wo(e,d,t.paragraphMetadataIndex||null),p=Um(m,o,a.inTable);if(p&&(f||(f=p),p.paragraph!==n.paragraph)){f=p;break}}if(f&&f.paragraph!==n.paragraph){let d=t.opType||"operation";return r(`[Target] [P${o}] appears stale after prior edits; using strict text rematch for ${d}.`),{paragraph:f.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw Fn(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function en(e,t,r,n={}){if(!e||!t||!r)return null;let o=n?.opType||"redline",a=n?.targetRefSnapshot||null,i=typeof n?.onInfo=="function"?n.onInfo:()=>{},s=typeof n?.onWarn=="function"?n.onWarn:()=>{},l=$n(e,{targetRef:t,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:s})?.paragraph;if(!l)return null;let c=$n(e,{targetRef:r,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:s})?.paragraph;if(!c)return null;let u=Array.from(e.getElementsByTagNameNS("*","p")),f=u.indexOf(l),d=u.indexOf(c);if(f<0||d<f)return null;let m=u.slice(f,d+1);if(m.length===0)return null;let p=m[0]?.parentNode||null;return!p||!m.every(g=>g&&g.parentNode===p)?null:m}function jo(e,t,r={}){if(!e||!e.parentNode)return{valid:!0};let n=t===""||r.operationKind==="delete",o=typeof t=="string"&&t.includes(`
|
|
165
|
+
`),a=r.targetEndParagraph||null,i=We(e,"tc");if(i){if(n&&Array.from(i.childNodes).filter(c=>D(c,"p")).length<=1)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete the sole terminal paragraph of a table cell."};if(a&&We(a,"tc")!==i)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across different table cells."}}else if(a&&We(a,"tc"))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across table boundaries."};if(e.getElementsByTagNameNS(Pe,"sectPr").length>0&&n)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete paragraph containing section properties (w:sectPr)."};if(a){let l=e;for(;l&&l!==a;){if(D(l,"p")&&l.getElementsByTagNameNS(Pe,"sectPr").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across section break."};l=l.nextSibling}}if(o){if(e.getElementsByTagNameNS(Pe,"fldSimple").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph containing a simple field instruction (w:fldSimple)."};let c=Array.from(e.getElementsByTagNameNS(Pe,"fldChar"));if(c.length>0){let p=0;for(let g of c){let h=g.getAttributeNS(Pe,"fldCharType")||g.getAttribute("w:fldCharType");h==="begin"?p++:h==="end"&&(p=Math.max(0,p-1))}if(p>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph across an unclosed field instruction."}}let u=Array.from(e.getElementsByTagNameNS(Pe,"bookmarkStart")),f=Array.from(e.getElementsByTagNameNS(Pe,"bookmarkEnd")),d=new Set(u.map(p=>p.getAttributeNS(Pe,"id")||p.getAttribute("w:id"))),m=new Set(f.map(p=>p.getAttributeNS(Pe,"id")||p.getAttribute("w:id")));for(let p of d)if(p&&!m.has(p))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:`Refusing to split paragraph across open bookmark range (ID: ${p}).`}}return{valid:!0}}function Ko(e,t){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let r=e.getElementsByTagNameNS(Pe,t);if(r.length>0)return r[0];let n=e.getElementsByTagNameNS("*",t);return n.length>0?n[0]:null}function mc(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(Pe,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function kr(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=Rt(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function gc(e){let t=String(e||"").split(/\r?\n/g),r=[],n=!1;for(let o of t){let a=o.trimEnd();if(!a.trim())continue;let i=In(a,{indentSpaces:2});if(i){n=!0,r.push({kind:"list",markerType:i.markerType,level:i.level,marker:i.marker,outlineLevel:i.outlineLevel,text:kr(i.text)});continue}r.push({kind:"text",text:a.trim()})}return{items:r,hasListMarkers:n}}function pc(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function zn(e,t){return J(e)===J(t)}function Ho(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function zm(e,t,r){if(!Array.isArray(e)||e.length<2||!Number.isInteger(r)||r<0)return!1;let n=e[0],o=e.slice(1).filter(a=>a.kind==="list");if(o.length===0||o.some(a=>a.markerType!=="bullet")||o.some(a=>Number.isInteger(a.outlineLevel)))return!1;if(n?.kind==="text")return zn(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let a=n.level||0;return o.some(s=>(s.level||0)>a)?!1:zn(n.text,t)}return!1}function Xm(e,t){return e.map(r=>{let n=Math.max(0,(r.ilvl||0)-t);return{...r,ilvl:Math.min(8,t+1+n)}})}function Vm(e,t,r,n){let o=e[0],a=e.slice(1).filter(i=>i.kind==="list");if(o?.kind==="text"&&zn(o.text,t)&&a.length>0){let i=a[0].level;return a.map(s=>({ilvl:Ho(s,r,i),markerType:s.markerType||n,text:s.text}))}if(e.every(i=>i.kind==="list")){let i=e[0];if(!i||!zn(i.text,t))return null;let s=i.level;return e.slice(1).map(l=>({ilvl:Ho(l,r,s),markerType:l.markerType||n,text:l.text})).filter(l=>l.text)}return null}function lt(e){if(!e)return null;let t=Ko(e,"pPr");if(!t)return null;let r=Ko(t,"numPr");if(!r)return null;let n=Ko(r,"numId");if(!n)return null;let o=mc(n);if(!o||o==="0")return null;let a=Ko(r,"ilvl"),i=mc(a),s=Number.parseInt(i||"0",10);return{numId:String(o),ilvl:Number.isFinite(s)?s:0}}function hc(e){let t=lt(e);if(!t)return null;let r=e.parentNode;if(!r)return null;let n=Array.from(r.childNodes||[]).filter(s=>s&&s.nodeType===1&&s.namespaceURI===Pe&&s.localName==="p"),o=n.indexOf(e);if(o<0)return null;let a=o;for(;a>0;){let s=lt(n[a-1]);if(!s||s.numId!==t.numId)break;a--}let i=o;for(;i<n.length-1;){let s=lt(n[i+1]);if(!s||s.numId!==t.numId)break;i++}return n.slice(a,i+1)}function bi(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
|
|
166
|
+
`)||!lt(e))return null;let s=hc(e);if(!s||s.length===0)return null;let l=gc(a);if(!l.hasListMarkers||l.items.length<2)return null;let c=J(r.currentParagraphText||be(e)),f=l.items.filter(N=>N.kind==="list")[0]?.markerType||"bullet",d=s.map(N=>({paragraph:N,list:lt(N),text:String(be(N)||"").trim()})),m=s.indexOf(e);if(m<0)return null;let p=Math.min(...d.map(N=>N.list?.ilvl??0)),g=d.map(N=>pc((N.list?.ilvl??0)-p,f,N.text)),h=null,y=l.items[0],w=l.items.slice(1).filter(N=>N.kind==="list");if(y?.kind==="text"&&zn(y.text,c)&&w.length>0){let N=Math.max(0,(d[m].list?.ilvl??0)-p),T=w[0].level;h=[{level:N,markerType:f,text:d[m].text},...w.map(E=>({level:Ho(E,N,T),markerType:E.markerType||f,text:E.text}))]}else if(l.items.every(N=>N.kind==="list")){let N=Math.max(0,(d[m].list?.ilvl??0)-p),T=l.items[0].level;h=l.items.map(E=>({level:Ho(E,N,T),markerType:E.markerType||f,text:E.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let v=h.map(N=>pc(N.level,N.markerType,N.text)),b=g.slice(0,m).concat(v).concat(g.slice(m+1)),x=g.join(`
|
|
167
|
+
`),I=b.join(`
|
|
168
|
+
`);return I===x?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:s,originalText:x,modifiedText:I})}function Ni(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
|
|
169
|
+
`))return null;let i=lt(e);if(!i)return null;let s=gc(a);if(!s.hasListMarkers||s.items.length<2)return null;let l=J(r.currentParagraphText||be(e)),u=s.items.filter(m=>m.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,i.ilvl),d=Vm(s.items,l,f,u);return!d||d.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(zm(s.items,l,f)&&(d=Xm(d,f),n("[List] Promoted bullet insertion to child depth for nested numbered-list intent.")),n("[List] Planned insertion-only list redline entries (no block rewrite)."),{targetParagraph:e,numId:i.numId,entries:d})}function Xn(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
|
|
170
|
+
`),n=[];for(let i of r){if(!i.trim())continue;let s=In(i,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});if(s){n.push({type:s.markerType,level:s.level,text:s.text.trim(),marker:s.marker});continue}n.push({type:"text",level:0,text:i.trim()})}if(n.length===0)return null;let o=n.some(i=>i.type==="numbered"),a=n.some(i=>i.type==="bullet");return{type:o?"numbered":a?"bullet":"text",items:n}}function Ii(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function Wm(e,t,r){let n=new Map,o=[];for(let a of e){let i=Math.max(0,Number(a?.level)||0);for(let u of Array.from(n.keys()))u>i&&n.delete(u);let s=(n.get(i)||0)+1;n.set(i,s);let l=Km(s,t,r),c=" ".repeat(i*4);o.push(`${c}${l} ${a.text||""}`.trimEnd())}return o.join(`
|
|
171
|
+
`)}function jm(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let o=String(n??""),a=o.match(/^(\s*)/),i=a?a[1].length:0,s=Math.floor(i/r),l=o.trim(),c=null,u=xt(l,{allowZeroSpaceAfterMarker:!0});return u&&(c=u[2].trim()||null,l=Rt(l,{allowZeroSpaceAfterMarker:!0})),{text:l.trim(),level:s,removedMarker:c}})}function Km(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${wc(e,!1)}.`;case"upperAlpha":return`${wc(e,!0)}.`;case"lowerRoman":return`${yc(e,!1)}.`;case"upperRoman":return`${yc(e,!0)}.`;default:return`${e}.`}}function wc(e,t=!1){let r=Math.max(1,Number(e)||1),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function yc(e,t=!1){let r=Math.max(1,Number(e)||1),n=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],o="";for(let[a,i]of n)for(;r>=a;)o+=i,r-=a;return t?o:o.toLowerCase()}function Go(e){let t=String(e||"");if(!t.trim()||t.includes(`
|
|
172
|
+
`))return null;let r=Xn(t);if(!r||!Ii(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let o=String(n.marker||"").trim(),a=n.type==="numbered"?Nn(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:a,startAt:Hm(o,a),contentText:String(n.text||"").trim(),normalizedContent:J(String(n.text||""))}}function Ti(e){let t=Go(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function Hm(e,t){if(t!=="decimal")return null;let r=String(e||"").trim().match(/^(\d+)\.?$/);if(!r)return null;let n=Number.parseInt(r[1],10);return Number.isFinite(n)&&n>0?n:null}function qo(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let o=t?.explicitByNumberingKey;if(!(o instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let a=o.get(r)||null;return a&&a.numId!=null&&Number.isInteger(a.nextStartAt)&&a.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(a.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function Yo(e,t,r,n){!e||!(e.explicitByNumberingKey instanceof Map)||!t||r==null||!Number.isInteger(n)||n<1||e.explicitByNumberingKey.set(String(t),{numId:String(r),nextStartAt:n+1})}function Vn(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function tn(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI==="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&&r.localName===t)||null}function Zo(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,o=t?.clearParagraphPropertyChanges!==!1,a=t?.removeListPropertyNode!==!1,i=(Array.isArray(e)?e:[]).filter(l=>l&&l.nodeType===1&&l.localName==="p"),s=0;for(let l of i){let c=l.ownerDocument;if(!c)continue;let u=tn(l,"pPr");if(u||(u=B(c,"w:pPr"),l.insertBefore(u,l.firstChild)),o){let p=tn(u,"pPrChange");p&&u.removeChild(p)}if(a){let p=tn(u,"listPr");p&&u.removeChild(p)}let f=tn(u,"numPr");f||(f=B(c,"w:numPr"),u.appendChild(f));let d=tn(f,"ilvl");d||(d=B(c,"w:ilvl"),f.appendChild(d)),d.setAttribute("w:val",String(n));let m=tn(f,"numId");m||(m=B(c,"w:numId"),f.appendChild(m)),m.setAttribute("w:val",String(r)),s++}return s}function Gm(e){let t=W(e,"application/xml").doc;return!t||Se(t)?null:se(t)[0]||null}function qm(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function Ym(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function rn(e,t){let r=Ym(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function vc(e,t){e.setAttribute("w:val",String(t))}function Zm(e){let t=W(e,"application/xml").doc;if(!t||Se(t))return null;let o=se(t)[0]||null;if(!o)return null;let a=Array.from(o.getElementsByTagNameNS("*","numId"));for(let i of a){let s=rn(i,["w:val","val"]);if(s!=null)return String(s)}return null}function Jm(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,a=oe(),i=W(e,"application/xml").doc;if(!i||Se(i))return e;let c=Array.from(i.getElementsByTagNameNS("*","num")).find(p=>{let g=rn(p,["w:numId","numId"]);return g!=null&&String(g)===String(t)});if(!c)return e;let u=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=rn(u,["w:val","val"]),d=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>rn(p,["w:ilvl","ilvl"])===0)||null;d||(d=B(i,"w:lvlOverride"),d.setAttribute("w:ilvl","0"),c.appendChild(d));let m=Array.from(d.getElementsByTagNameNS("*","startOverride"))[0]||null;if(m||(m=B(i,"w:startOverride"),d.appendChild(m)),vc(m,r),o&&f!=null){let g=Array.from(i.getElementsByTagNameNS("*","abstractNum")).find(h=>{let y=rn(h,["w:abstractNumId","abstractNumId"]);return y!=null&&y===f})||null;if(g){let h=Array.from(g.getElementsByTagNameNS("*","lvl")).find(w=>rn(w,["w:ilvl","ilvl"])===0)||null;h||(h=B(i,"w:lvl"),h.setAttribute("w:ilvl","0"),g.appendChild(h));let y=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;y||(y=B(i,"w:start"),h.insertBefore(y,h.firstChild)),vc(y,r)}}return a.serializeToString(i)}function nn(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),o=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let a=Gm(t);if(!a)return null;let i=lt(a);if(i&&!o)return null;let s=Je(n).cleanText||n,l=Go(n)||Go(s);if(!l)return null;let c=Go(r),u=J(r)===J(s),f=!!c&&c.type===l.type&&c.normalizedContent===l.normalizedContent;return!u&&!f?null:{listInput:`${l.marker} ${l.contentText}`.trim(),numberingKey:`${l.type}:${l.numberingStyle}:single`,originalText:r,wasListParagraph:!!i,startAt:l.startAt}}async function on(e,t={}){if(!e||!e.listInput)return{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:null,warnings:["Single-line list fallback plan missing"]};let r=t.author||"AI",n=t.generateRedlines??!0,o=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await qr({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new $t}),a=o?.oxml||o?.ooxml||"",i=qm(a),s=Zm(i),l=Jm(o?.numberingXml||null,s,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=o?.isValid!==!1;return!i||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:i,numberingXml:l,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}var Qm=new Set(["ins","del","rPrChange","pPrChange"]),ep=/^\d{4}-\d{2}-\d{2}T/;function fr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Mr(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>fr(r)===t)}function Lr(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function tp(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function rp(e){return fr(e.parentNode)==="rPr"}function np(e){let t=r=>{let n=Es(r),o=n.getElementsByTagName("parsererror")[0];if(o)throw new Error(o.textContent||"XML parse error");return n};try{return{doc:t(e)}}catch{try{return{doc:t(`<w:root xmlns:w="${L}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function ct(e){let t=[],r=(f,d,m)=>t.push({code:f,severity:d,message:m}),n=e&&typeof e=="object"&&(e.nodeType===9||e.nodeType===1);if(!n&&(typeof e!="string"||e.trim()===""))return r("PARSE_ERROR","error","Input is not non-empty OOXML or a parsed XML DOM."),{valid:!1,issues:t};let{doc:o,error:a}=n?{doc:e.nodeType===9?e:e.ownerDocument}:np(e);if(!o)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${a}`),{valid:!1,issues:t};let i=Mr(o,"ins"),s=Mr(o,"del"),l=i.concat(s);for(let f of Mr(o,"p")){let d=Array.from(f.getElementsByTagName("*")).find(m=>m!==f&&fr(m)==="p");d&&r("NESTED_PARAGRAPH","error",`<${f.nodeName}> contains nested <${d.nodeName}>.`)}for(let f of Mr(o,"body")){let d=Array.from(f.childNodes||[]).filter(p=>p.nodeType===1),m=d.map((p,g)=>fr(p)==="sectPr"?g:-1).filter(p=>p>=0);m.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):m.length===1&&m[0]!==d.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let f of l){let m=Array.from(f.getElementsByTagName("*")).filter(p=>p!==f&&["ins","del"].includes(fr(p))).find(p=>fr(f)!=="ins"||fr(p)!=="del"?!0:p.parentNode!==f);m&&r("NESTED_REVISION","error",`<${f.nodeName}> (w:id="${Lr(f,"id")}") contains invalid nested <${m.nodeName}>.`)}for(let f of s)Mr(f,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${Lr(f,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let f of l){let d=[];Lr(f,"id")||d.push("w:id"),Lr(f,"author")||d.push("w:author"),ep.test(Lr(f,"date"))||d.push("w:date"),d.length>0&&r("MISSING_REVISION_METADATA","error",`<${f.nodeName}> is missing or has malformed ${d.join(", ")}.`)}let c=new Set;for(let f of Array.from(o.getElementsByTagName("*"))){if(!Qm.has(fr(f)))continue;let d=Lr(f,"id");d&&(c.has(d)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${d} appears more than once.`),c.add(d))}let u=Mr(o,"t").concat(Mr(o,"delText"));for(let f of u){let d=f.textContent||"";/^\s|\s$/.test(d)&&tp(f)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${f.nodeName}> has boundary whitespace without xml:space="preserve".`),d===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${f.nodeName}> is empty.`)}for(let f of l){if(rp(f))continue;Array.from(f.childNodes||[]).some(m=>m.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${f.nodeName}> (w:id="${Lr(f,"id")}") wraps no content.`)}for(let f of cc(o)){let d=f.ownerAuthor||"unattributed";r("FOREIGN_PARAGRAPH_MARK_DELETION","warning",`Paragraph deleted by ${d} also contains non-empty insertion content from another author; Accept/Reject lifecycle may not preserve the apparent restoration.`)}return{valid:!t.some(f=>f.severity==="error"),issues:t}}function Jo(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Pe&&r.localName===t):[]}function op(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function ap(e){let t=Jo(e,"tr"),r=t.map(o=>Jo(o,"tc").map(i=>{let s=Jo(i,"p");return s.length===0?J(be(i)):s.map(c=>J(be(c))).filter(Boolean).join(`
|
|
173
|
+
`)})),n=r.reduce((o,a)=>Math.max(o,a.length),0);return r.forEach(o=>{for(;o.length<n;)o.push("")}),{matrix:r,rowElements:t,columnCount:n}}function ip(e,t){if(!Array.isArray(e)||e.length===0||t<=0)return null;let r=e.map(s=>{let l=Array.isArray(s)?s.slice(0,t):[];for(;l.length<t;)l.push("");return l}),n=r[0],o=new Array(t).fill("---"),a=r.slice(1),i=s=>`| ${s.map(l=>op(l)).join(" | ")} |`;return[i(n),i(o),...a.map(i)].join(`
|
|
174
|
+
`)}function sp(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>J(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function xc(e){let t=String(e||"").trim();return t?!!(/^and$/i.test(t)||/^\[.*\]$/.test(t)||/^\(.*\)$/.test(t)||/:\s*$/.test(t)||t.length<=90&&!/[.!?]$/.test(t)&&/[:\[\]()]/.test(t)||/^[\[(]/.test(t)):!1}function Si(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:be;if(!e||!e.parentNode)return null;let o=[e],a=e.nextSibling,i=0;for(;a&&i<r;){i+=1;let s=a.nextSibling;if(a.nodeType!==1||a.namespaceURI!==Pe||a.localName!=="p"){a=s;continue}let l=String(n(a)||"").trim();if(!l){if(o.length>1)break;a=s;continue}if(!xc(l))break;o.push(a),a=s}return o.length>1?o:null}function Ei(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
|
|
175
|
+
`)||Or(a))return null;let i=a.split(/\r?\n/g).map(b=>b.trim()).filter(Boolean);if(i.length<2)return null;let s=r.tableElement||We(e,"tbl"),l=We(e,"tr"),c=We(e,"tc");if(!s||!l||!c)return null;let u=J(r.currentParagraphText||be(e)),f=J(i[0]);if(u&&f&&f!==u)return o("[Table] Multiline cell text did not anchor to original cell text; skipping table-row synthesis heuristic."),null;let{matrix:d,rowElements:m,columnCount:p}=ap(s);if(d.length===0||p===0)return null;let g=m.indexOf(l),y=Jo(l,"tc").indexOf(c);if(g<0||y<0||y>=p)return null;d[g][y]=i[0];let w=sp(d[g]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let b=1;b<i.length;b++){let x=g+b,I=i[b];if(x<d.length&&!J(d[x][y]))if(w)for(let N=0;N<p;N++)J(d[x][N])||(d[x][N]=I);else d[x][y]=I;else{let N=new Array(p).fill("");if(w)for(let T=0;T<p;T++)N[T]=I;else N[y]=I;d.splice(Math.min(x,d.length),0,N)}}let v=ip(d,p);return v?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),v):null}function an(e,t){if(!e||!Array.isArray(t))return null;for(let r of t){let n=e.getAttribute(r);if(n==null||n==="")continue;let o=Number.parseInt(String(n),10);if(Number.isFinite(o))return o}return null}function sn(e,t,r=null){let n=Number.isInteger(e)&&e>0?e:1,o=t instanceof Set?t:new Set;for(;o.has(n);)n+=1;if(Number.isInteger(r)&&r>0&&n>r){for(let a=1;a<=r;a+=1)if(!o.has(a))return a}return n}function ea(e,t={}){let r=Number.isInteger(t?.minId)&&t.minId>0?t.minId:1,n=Number.isInteger(t?.maxPreferred)&&t.maxPreferred>=r?t.maxPreferred:32767,o=new Set,a=new Set;if(String(e||"").trim())try{let u=Vt(e),f=Array.from(u.getElementsByTagNameNS("*","abstractNum")),d=Array.from(u.getElementsByTagNameNS("*","num"));for(let m of f){let p=an(m,["w:abstractNumId","abstractNumId"]);p!=null&&a.add(p)}for(let m of d){let p=an(m,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let i=o.size>0?Math.max(...o):0,s=a.size>0?Math.max(...a):0,l=Math.max(r,i+1),c=Math.max(r,s+1);return{nextNumId:sn(l,o,n),nextAbstractNumId:sn(c,a,n),usedNumIds:o,usedAbstractNumIds:a,minId:r,maxPreferred:n}}function lp(e){return!e||typeof e!="object"?null:(e.usedNumIds instanceof Set||(e.usedNumIds=new Set),e.usedAbstractNumIds instanceof Set||(e.usedAbstractNumIds=new Set),(!Number.isInteger(e.minId)||e.minId<1)&&(e.minId=1),(!Number.isInteger(e.maxPreferred)||e.maxPreferred<e.minId)&&(e.maxPreferred=32767),(!Number.isInteger(e.nextNumId)||e.nextNumId<e.minId)&&(e.nextNumId=e.minId),(!Number.isInteger(e.nextAbstractNumId)||e.nextAbstractNumId<e.minId)&&(e.nextAbstractNumId=e.minId),e.nextNumId=sn(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=sn(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function jn(e,t="num"){let r=lp(e);if(!r)return null;let n=t==="abstract",o=n?r.nextAbstractNumId:r.nextNumId;return!Number.isInteger(o)||o<1?null:(n?(r.usedAbstractNumIds.add(o),r.nextAbstractNumId=sn(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=sn(o+1,r.usedNumIds,r.maxPreferred)),o)}function ta(e){let t=jn(e,"num"),r=jn(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function Ai(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function Qo(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Pe&&e.localName===t)}function bc(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(a=>a&&a.nodeType===1&&a.namespaceURI===Pe),o=null;r==="abstract"?o=n.find(a=>a.localName==="num"||a.localName==="numIdMacAtCleanup")||null:o=n.find(a=>a.localName==="numIdMacAtCleanup")||null,o?e.insertBefore(t,o):e.appendChild(t)}function cp(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function Wn(e,t){let r=cp(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Nc(e,t,r){e?.setAttribute?.(t,String(r))}function Ri(e,t){e?.setAttribute?.("w:val",String(t))}function ra(e,t){if(!(!Array.isArray(e)||t==null))for(let r of e){let n=Array.from(r?.getElementsByTagNameNS?.("*","numId")||[]);for(let o of n)Ri(o,t)}}function na(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let o=Wn(n,["w:val","val"]);if(o!=null)return String(o)}}return null}function oa(e,t,r){let n=String(e),o=String(t),a=Number.isInteger(r)&&r>0?r:1,i=Array.from({length:9},(s,l)=>{let c=Array.from({length:l+1},(f,d)=>`%${d+1}`).join(".")+".",u=720*(l+1);return`
|
|
175
176
|
<w:lvl w:ilvl="${l}">
|
|
176
177
|
<w:start w:val="1"/>
|
|
177
178
|
<w:numFmt w:val="decimal"/>
|
|
@@ -179,36 +180,48 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
|
|
|
179
180
|
<w:lvlJc w:val="left"/>
|
|
180
181
|
<w:pPr><w:ind w:left="${u}" w:hanging="360"/></w:pPr>
|
|
181
182
|
</w:lvl>`}).join("");return`
|
|
182
|
-
<w:numbering xmlns:w="${
|
|
183
|
+
<w:numbering xmlns:w="${Pe}">
|
|
183
184
|
<w:abstractNum w:abstractNumId="${o}">
|
|
184
185
|
<w:multiLevelType w:val="multilevel"/>
|
|
185
|
-
${
|
|
186
|
+
${i}
|
|
186
187
|
</w:abstractNum>
|
|
187
188
|
<w:num w:numId="${n}">
|
|
188
189
|
<w:abstractNumId w:val="${o}"/>
|
|
189
190
|
<w:lvlOverride w:ilvl="0">
|
|
190
|
-
<w:startOverride w:val="${
|
|
191
|
+
<w:startOverride w:val="${a}"/>
|
|
191
192
|
</w:lvlOverride>
|
|
192
193
|
</w:num>
|
|
193
|
-
</w:numbering>`.trim()}function
|
|
194
|
+
</w:numbering>`.trim()}function aa(e,t,r){let n=Vt(e);if(Ai(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let o=new Map,a=new Map,i=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of i){let u=Wn(c,["w:abstractNumId","abstractNumId"]);if(u==null)continue;let f=jn(r,"abstract");f!=null&&(o.set(u,f),Nc(c,"w:abstractNumId",f))}let s=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of s){let u=Wn(c,["w:numId","numId"]);if(u==null)continue;let f=jn(r,"num");if(f==null)continue;a.set(u,f),Nc(c,"w:numId",f);let d=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(d){let m=Wn(d,["w:val","val"]);m!=null&&o.has(m)&&Ri(d,o.get(m))}}let l=Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[];for(let c of l){let u=Array.from(c?.getElementsByTagNameNS?.("*","numId")||[]);for(let f of u){let d=Wn(f,["w:val","val"]);d!=null&&a.has(d)&&Ri(f,a.get(d))}}return{numberingXml:Cr(n),replacementNodes:l}}function ia(e,t){let r=String(e||""),n=String(t||"");if(!n.trim())return r;if(!r.trim())return n;try{let o=Vt(r),a=Vt(n);if(Ai(o)||Ai(a))return r;let i=o.documentElement,s=a.documentElement;if(!i||!s)return r;let l=new Set(Array.from(i.childNodes||[]).filter(u=>Qo(u,"abstractNum")).map(u=>an(u,["w:abstractNumId","abstractNumId"])).filter(u=>u!=null)),c=new Set(Array.from(i.childNodes||[]).filter(u=>Qo(u,"num")).map(u=>an(u,["w:numId","numId"])).filter(u=>u!=null));for(let u of Array.from(s.childNodes||[])){if(!Qo(u,"abstractNum"))continue;let f=an(u,["w:abstractNumId","abstractNumId"]);f==null||l.has(f)||(bc(i,o.importNode(u,!0),"abstract"),l.add(f))}for(let u of Array.from(s.childNodes||[])){if(!Qo(u,"num"))continue;let f=an(u,["w:numId","numId"]);f==null||c.has(f)||(bc(i,o.importNode(u,!0),"num"),c.add(f))}return Cr(o)}catch{return r}}function up(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!Se(e)}function Ic(e){let t=W(e,"application/xml");return t.error||up(t.doc)?{...t,doc:null}:t}function Tc(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(L,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function Pi(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===L&&n.localName===t)return n;return null}function dr(e,t){return Array.from(e?.getElementsByTagNameNS?.(L,t)||[])}function Kn(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function fp(e){let t=Pi(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=dr(t,"rStyle")[0]||null,n=Kn(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),a=n.includes("italic")||n.includes("emphasis");return{bold:dr(t,"b").length>0||o,italic:dr(t,"i").length>0||a}}function Sc(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(L,"r")||[]);for(let n of r){if(!Ir(n,e,"accepted"))continue;let o=Tr(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...fp(n)})}return t}function Ci(e){return String(e||"").replace(/\r/g,"").split(`
|
|
194
195
|
`).map(r=>r.replace(/[ \t]+/g," ").trim()).join(`
|
|
195
|
-
`).trim()}function
|
|
196
|
+
`).trim()}function dp(e,t){let r=String(e||"");if(!r)return"";if(!t?.bold&&!t?.italic)return r;let n=r.match(/^(\s*)([\s\S]*?)(\s*)$/);if(!n)return r;let o=n[1]||"",a=n[2]||"",i=n[3]||"";if(!a.trim())return r;let s=a;return t.bold&&t.italic?s=`***${a}***`:t.bold?s=`**${a}**`:t.italic&&(s=`*${a}*`),`${o}${s}${i}`}function mp(e){let t=Pi(e,"pPr");if(!t)return null;let r=dr(t,"pStyle")[0]||null,n=Kn(r,["w:val","val"]);if(n){let s=n.match(/^heading\s*([1-9])$/i);if(s){let l=Number.parseInt(s[1],10);if(Number.isInteger(l))return Math.min(Math.max(l,1),6)}}let o=dr(t,"outlineLvl")[0]||null,a=Kn(o,["w:val","val"]),i=Number.parseInt(a,10);return Number.isInteger(i)&&i>=0?Math.min(i+1,6):null}function pp(e){let t=Pi(e,"pPr");if(!t)return null;let r=dr(t,"numPr")[0]||null;if(!r)return null;let n=dr(r,"ilvl")[0]||null,o=dr(r,"numId")[0]||null,a=Number.parseInt(Kn(n,["w:val","val"]),10),i=Kn(o,["w:val","val"]);return{level:Number.isInteger(a)&&a>=0?a:0,marker:i==="1"?"-":"1."}}function gp(e){let t=Sc(e).map(r=>r.text).join("");return Ci(t)}function hp(e){let r=Sc(e).map(i=>dp(i.text,i)).join(""),n=Ci(r);if(!n)return"";let o=mp(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let a=pp(e);return a?`${" ".repeat(a.level)}${a.marker} ${n}`:n}function wp(e){return Ec(e).text}function Ec(e){let t=Ic(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Tc(r);return n.length===0?{text:Ci(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(gp).join(`
|
|
196
197
|
|
|
197
|
-
`).trim(),status:"ok",warnings:t.warnings}}function
|
|
198
|
+
`).trim(),status:"ok",warnings:t.warnings}}function yp(e){return Ac(e).text}function Ac(e){let t=Ic(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Tc(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(hp).join(`
|
|
198
199
|
|
|
199
|
-
`).trim(),status:"ok",warnings:t.warnings}}var
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
<w:p w14:paraId="${Ne(o)}" xmlns:w14="${gn}">
|
|
203
|
-
<w:r><w:t>${a}</w:t></w:r>
|
|
200
|
+
`).trim(),status:"ok",warnings:t.warnings}}var ln="http://schemas.microsoft.com/office/word/2010/wordml",je="http://schemas.microsoft.com/office/word/2012/wordml";function Oi(e){let t=Number.parseInt(String(e),10);return(Number.isFinite(t)?1879048192+(t>>>0)>>>0:1879048192).toString(16).toUpperCase().padStart(8,"0").slice(-8)}function Hn(e,t,r,n,o=Oi(e)){let a=t.split(" ").map(l=>l[0]).join("").toUpperCase()||"AI",i=ze(r),s=ze(t);return`<w:comment w:id="${e}" w:author="${s}" w:date="${n}" w:initials="${a}">
|
|
201
|
+
<w:p w14:paraId="${ze(o)}" xmlns:w14="${ln}">
|
|
202
|
+
<w:r><w:t>${i}</w:t></w:r>
|
|
204
203
|
</w:p>
|
|
205
|
-
</w:comment>`}function
|
|
206
|
-
`);return`<w:comments xmlns:w="${
|
|
204
|
+
</w:comment>`}function _i(e){if(!e||e.length===0)return`<w:comments xmlns:w="${L}"></w:comments>`;let t=e.map(r=>Hn(r.id,r.author,r.content,r.date,r.paraId)).join(`
|
|
205
|
+
`);return`<w:comments xmlns:w="${L}">
|
|
207
206
|
${t}
|
|
208
|
-
</w:comments>`}function Ya(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${Ne(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${Ne(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${rt}">${t}</w15:commentsEx>`}function hn(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=nr(e,"w:r"),o=[],i="";for(let a of n){if(!bt(a,e,r))continue;let s=i.length,l=xt(a,{revisionView:r,boundary:e});i+=l,o.push({run:a,start:s,end:i.length})}return{fullText:i,runOffsets:o}}function Ja(e,t){if(!t)return[];let r=[],n=e.indexOf(t);for(;n!==-1;)r.push({start:n,end:n+t.length}),n=e.indexOf(t,n+1);return r}function qa(e){return String(e).replace(/[ \u00a0]/g," ")}function Sr(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Za(e,t,r){let n=null,o=null,i=0,a=0;for(let{run:s,start:l,end:c}of e.runOffsets)t.start>=l&&t.start<c&&(n=s,i=t.start-l),t.end>l&&t.end<=c&&(o=s,a=t.end-l);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:i,endRun:o,endOffset:a}}function Qa(e,t,r=null){let n=e?.parentNode;for(;n&&n.nodeType===1&&n!==r&&(n.localName||n.nodeName.replace(/^.*:/,""))!=="p";){let o=n.localName||n.nodeName.replace(/^.*:/,"");if(t.includes(o))return{node:n,tag:o};n=n.parentNode}return null}function es(e,t){if(!t||!t.found)return t;let r=e.runOffsets.filter(n=>n.end>t.start&&n.start<t.end).map(n=>n.run);for(let n of r){if(Qa(n,["del"]))return{found:!1,error:Sr("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(Qa(n,["moveFrom","moveTo"]))return{found:!1,error:Sr("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function Io(e,t){let r=String(t??""),n=Ja(e.fullText,r);if(n.length>1)return{found:!1,error:Sr("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=Za(e,n[0],"exact_anchor");if(s)return es(e,s)}let o=qa(r),i=qa(e.fullText),a=Ja(i,o);if(a.length>1)return{found:!1,error:Sr("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${a.length} locations in the target paragraph.`,a)};if(a.length===1){let s=Za(e,a[0],"space_equivalent_anchor");if(s)return es(e,s)}return{found:!1,error:Sr("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function yr(e,t,r,n,o=!1){let i=O(e,"w:r");if(t){let s=t.cloneNode(!0);o||at(s,n),i.appendChild(s)}let a=O(e,"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=r,i.appendChild(a),i}function ts(e,t,r,n,o=null,i=null,a=null){let s=o||hn(t),l=a||Io(s,r);if(!l.found||!l.startRun)return!1;let c=O(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let u=O(e,"w:commentRangeEnd");u.setAttribute("w:id",String(n));let f=O(e,"w:r"),m=O(e,"w:commentReference");if(m.setAttribute("w:id",String(n)),f.appendChild(m),l.startRun===l.endRun){let w=l.startRun,b=ae(w,"w:t");if(!b)return w.parentNode.insertBefore(c,w),w.nextSibling?(w.parentNode.insertBefore(u,w.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(w.parentNode.appendChild(u),w.parentNode.appendChild(f)),!0;let g=b.textContent||"",x=g.substring(0,l.startOffset),v=g.substring(l.startOffset,l.endOffset),N=g.substring(l.endOffset),S=ae(w,"w:rPr"),y=w.parentNode;return x&&(y.insertBefore(yr(e,S,x,i,!0),w),at(S,i)),y.insertBefore(c,w),b.textContent=v,w.nextSibling?y.insertBefore(u,w.nextSibling):y.appendChild(u),y.insertBefore(f,u.nextSibling||null),N&&y.insertBefore(yr(e,S,N,i),f.nextSibling||null),!0}let d=ae(l.startRun,"w:t");if(d&&l.startOffset>0){let w=d.textContent||"",b=w.substring(0,l.startOffset),g=w.substring(l.startOffset);if(b){let x=ae(l.startRun,"w:rPr");l.startRun.parentNode.insertBefore(yr(e,x,b,i,!0),l.startRun),at(x,i)}d.textContent=g}l.startRun.parentNode.insertBefore(c,l.startRun);let p=l.endRun||l.startRun,h=ae(p,"w:t");if(h&&l.endOffset<(h.textContent||"").length){let w=h.textContent||"",b=w.substring(0,l.endOffset),g=w.substring(l.endOffset);if(h.textContent=b,g){let x=ae(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(yr(e,x,g,i),p.nextSibling):p.parentNode.appendChild(yr(e,x,g,i))}}return p.nextSibling?(p.parentNode.insertBefore(u,p.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(p.parentNode.appendChild(u),p.parentNode.appendChild(f)),!0}var Vt="http://schemas.microsoft.com/office/2006/xmlPackage",Tr="http://schemas.openxmlformats.org/package/2006/relationships";function rs(e,t){let r=de(),n=j(e,"text/xml"),o=n.doc,i=o?ne(o):null;if(n.error||i)return ee("[CommentEngine] Failed to parse package:",n.error?.message||i?.textContent),e;let a=o.documentElement,s=o.createElementNS(Vt,"pkg:part");s.setAttribute("pkg:name","/word/comments.xml"),s.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let l=o.createElementNS(Vt,"pkg:xmlData"),c=j(t,"text/xml").doc;if(!c)return e;l.appendChild(o.importNode(c.documentElement,!0)),s.appendChild(l),a.appendChild(s);let f=ce(a,Vt,"part").find(m=>m.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let m=ce(f,Vt,"xmlData");if(m.length>0){let d=ce(m[0],Tr,"Relationships");if(d.length>0){let p=d[0],h=ce(p,Tr,"Relationship");if(!h.some(b=>b.getAttribute("Type")?.includes("comments"))){let b=0;h.forEach(x=>{let v=x.getAttribute("Id"),N=parseInt(v?.replace("rId","")||"0",10);N>b&&(b=N)});let g=o.createElementNS(Tr,"Relationship");g.setAttribute("Id",`rId${b+1}`),g.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),g.setAttribute("Target","comments.xml"),p.appendChild(g)}}}}else{let m=o.createElementNS(Vt,"pkg:part");m.setAttribute("pkg:name","/word/_rels/document.xml.rels"),m.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let d=o.createElementNS(Vt,"pkg:xmlData"),p=o.createElementNS(Tr,"Relationships"),h=o.createElementNS(Tr,"Relationship");h.setAttribute("Id","rId1"),h.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),h.setAttribute("Target","comments.xml"),p.appendChild(h),d.appendChild(p),m.appendChild(d),a.appendChild(m)}return r.serializeToString(o)}function nf(e,t){let r=j(e,"text/xml"),n=r.doc?ne(r.doc):null;if(r.error||n){let o=r.error?.message||n?.textContent||"parse error";return{xmlDoc:null,warning:t(o),warnings:r.warnings,error:{code:"PARSE_ERROR",message:o}}}return{xmlDoc:r.doc,warning:null,warnings:r.warnings,error:null}}function of(e,t,r={}){let n=r?.author||pe(),o=_r(),i=[],a=[],s=[],l=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=de(),u=nf(e,w=>`Failed to parse OXML: ${w}`);if(i.push(...u.warnings||[]),!u.xmlDoc)return ee("[CommentEngine] Parse failure:",u.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:u.error,warnings:[...i,u.warning]};let f=u.xmlDoc,m=nt(f),d=nr(f,"w:p");L(`[CommentEngine] Found ${d.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let w of t){let b=w.paragraphIndex-1;if(b<0||b>=d.length){let g=`Paragraph ${w.paragraphIndex} out of range (1-${d.length})`;i.push(g),l.push({code:"TARGET_NOT_FOUND",message:g,paragraphIndex:w.paragraphIndex});continue}p.set(b,(p.get(b)||0)+1)}let h=new Map;for(let[w,b]of t.entries()){let g=b.paragraphIndex-1;if(g<0||g>=d.length)continue;let x=d[g],v=h.get(g);v||(v=hn(x),h.set(g,v));let N=String(b.textToFind??""),S=Io(v,N),y=(p.get(g)||1)-1;if(p.set(g,y),!S.found){let M={...S.error,requestIndex:w+1,paragraphIndex:b.paragraphIndex};l.push(M),i.push(M.message),y===0&&h.delete(g);continue}let T=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():qo();if(!ts(f,x,N,T,v,m,S)){let M={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${b.paragraphIndex}.`,requestIndex:w+1,paragraphIndex:b.paragraphIndex};l.push(M),i.push(M.message),y===0&&h.delete(g);continue}a.push({id:T,content:b.commentContent,author:n,date:o}),s.push({requestIndex:w+1,paragraphIndex:b.paragraphIndex,text:N,resolvedBy:S.resolvedBy,start:S.start,end:S.end}),y>0?h.set(g,hn(x)):h.delete(g)}return a.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:i,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}:{oxml:c.serializeToString(f),hasChanges:!0,commentsXml:Ao(a),commentsApplied:a.length,placedComments:a,warnings:i,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}}function af(e,t){return rs(e,t)}var ns="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Er(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function wn(e,t){let r=j(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}}function sf(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=Er(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=Er(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function os(e,t){let r=Eo(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}function lf({commentsXml:e,commentsExtendedXml:t=null,parentCommentId:r,commentId:n,commentContent:o,author:i,date:a=new Date().toISOString()}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing word/comments.xml part."}};let s=wn(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let l=s.doc,c=Array.from(l.getElementsByTagNameNS("*","comment")).find(v=>Er(v,"w:id","id")===String(r));if(!c)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${r}' was not found.`}};let u=null;if(t){let v=wn(t,"word/commentsExtended.xml");if(v.error)return{status:"error",error:v.error};u=v.doc}let f=sf(l,u),m=Array.from(c.getElementsByTagNameNS(ns,"p"))[0]||Array.from(c.getElementsByTagNameNS("*","p"))[0];if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${r}' has no paragraph.`}};let d=Er(m,"w14:paraId","paraId");d?d=d.toUpperCase():(d=os(r,f),m.setAttributeNS(gn,"w14:paraId",d));let p=os(n,f),h=wn(`<w:comments xmlns:w="${ns}" xmlns:w14="${gn}">${vr(n,i,o,a,p)}</w:comments>`,"reply comment");l.documentElement.appendChild(l.importNode(h.doc.documentElement.firstChild,!0)),u||(u=wn(Ya([]),"word/commentsExtended.xml").doc);let w=u.documentElement;if(!Array.from(w.getElementsByTagNameNS("*","commentEx")).some(v=>Er(v,"w15:paraId","paraId").toUpperCase()===d)){let v=u.createElementNS(rt,"w15:commentEx");v.setAttributeNS(rt,"w15:paraId",d),v.setAttributeNS(rt,"w15:done","0"),w.appendChild(v)}let g=u.createElementNS(rt,"w15:commentEx");g.setAttributeNS(rt,"w15:paraId",p),g.setAttributeNS(rt,"w15:paraIdParent",d),g.setAttributeNS(rt,"w15:done","0"),w.appendChild(g);let x=de();return{status:"ok",hasChanges:!0,commentsXml:x.serializeToString(l),commentsExtendedXml:x.serializeToString(u),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:n,parentCommentId:String(r),paraId:p,parentParaId:d}}function Gt(e){e?.parentNode&&e.parentNode.removeChild(e)}function is(e,t=["all"]){if(!e)return null;let r=e.cloneNode(!0);if(t.includes("all"))["w:b","w:i","w:u","w:strike","w:dstrike","w:color","w:sz","w:szCs","w:rFonts","w:highlight","w:vertAlign","w:spacing","w:w","w:kern","w:position"].forEach(o=>{r.querySelectorAll(`${o}, ${o.replace("w:","")}`).forEach(Gt)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(o=>{let i=n[o];i&&r.querySelectorAll(`${i}, ${i.replace("w:","")}`).forEach(Gt)})}return r.children.length>0?r:null}function cf(e,t,r){if(!t||!e)return e;let n=et(e);if(!n)return e;let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=n.getElementsByTagNameNS(o,"r"),a=n.getElementsByTagNameNS(o,"ins"),s=[...Array.from(i)];for(let l of a){let c=l.getElementsByTagNameNS(o,"r");s.push(...Array.from(c))}for(let l of s){let c=l.getElementsByTagNameNS(o,"t"),u=Array.from(c).map(f=>f.textContent).join("");if(u.includes(t)||u===t){let f=l.getElementsByTagNameNS(o,"rPr");if(f.length>0){let m=f[0],d=is(m,r);d?m.parentNode&&m.parentNode.replaceChild(d,m):Gt(m)}}}return yt(n)}var uf={yellow:"yellow",green:"green",cyan:"cyan",magenta:"magenta",blue:"blue",red:"red",darkblue:"darkBlue",darkcyan:"darkCyan",darkgreen:"darkGreen",darkmagenta:"darkMagenta",darkred:"darkRed",darkyellow:"darkYellow",gray25:"lightGray",gray50:"darkGray",black:"black",white:"white"};function ff(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=uf[r.toLowerCase()]||"yellow",a=n?.generateRedlines??!1,s=n?.author||pe(),l=t;l?l=t.cloneNode(!0):l=O(e,"w:rPr");let c=null;a&&(c=O(e,"w:rPr"),Array.from(l.childNodes).forEach(m=>{m.nodeName!=="w:rPrChange"&&c.appendChild(m.cloneNode(!0))}));let u=l.getElementsByTagNameNS(o,"highlight");Array.from(u).forEach(Gt);let f=O(e,"w:highlight");if(f.setAttributeNS(o,"w:val",i),l.appendChild(f),a&&c){let m=O(e,"w:rPrChange"),d=ie(s,e);m.setAttribute("w:id",String(d.id)),m.setAttribute("w:author",d.author),m.setAttribute("w:date",d.date),m.appendChild(c);let p=l.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(Gt),l.appendChild(m)}return l}function mf(e,t,r="yellow",n={}){if(!t||!e)return e;let o=et(e);if(!o)return e;let i;n?._revisionIdAllocator instanceof we?(i=n._revisionIdAllocator,Rt(o,i)):i=nt(o);let a="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=f=>{let m=f.getElementsByTagNameNS(a,"t");return Array.from(m).map(d=>d.textContent).join("")},l=Array.from(o.getElementsByTagNameNS(a,"r")),c=new WeakSet,u=(f,m,d)=>{let p=f.cloneNode(!0);c.has(f)?at(p,i):c.add(f);let h=p.getElementsByTagNameNS(a,"t");Array.from(h).forEach(Gt);let w=O(o,"w:t");if(w.setAttribute("xml:space","preserve"),w.textContent=m,p.appendChild(w),d){let b=p.getElementsByTagNameNS(a,"rPr"),g=b.length>0?b[0]:null,x=ff(o,g,r,n);g?p.replaceChild(x,g):p.insertBefore(x,p.firstChild)}return p};for(let f of l){let m=s(f);if(!m)continue;let d=[],p=0;for(;p<=m.length-t.length;){let g=m.indexOf(t,p);if(g===-1)break;d.push(g),p=g+t.length}if(d.length===0)continue;let h=f.parentNode;if(!h){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let w=o.createDocumentFragment(),b=0;for(let g of d)g>b&&w.appendChild(u(f,m.slice(b,g),!1)),w.appendChild(u(f,m.slice(g,g+t.length),!0)),b=g+t.length;b<m.length&&w.appendChild(u(f,m.slice(b),!1)),h.replaceChild(w,f)}return yt(o)}var Ee="http://schemas.openxmlformats.org/wordprocessingml/2006/main",df="http://schemas.openxmlformats.org/package/2006/content-types",pf="http://schemas.openxmlformats.org/package/2006/relationships",ss="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",ls="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",cs="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",us="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",fs="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",ms="application/vnd.ms-word.commentsExtended+xml",as="word/document.xml",bn="word/numbering.xml",Ar="word/comments.xml",Po="word/commentsExtended.xml",_e="[Content_Types].xml",Le="word/_rels/document.xml.rels";function he(e,t="xml"){let r=j(e,"application/xml");if(r.error||!r.doc){let n=new Error(`[XML parse error] ${t}: ${r.error?.message||"Unknown"}`);throw n.code="PARSE_ERROR",n}return r.doc}function xn(e){return!!e&&e.nodeType===1&&e.namespaceURI===Ee&&e.localName==="sectPr"}function Co(e){return e.getElementsByTagNameNS("*","body")[0]||null}function ds(e){for(let t of Array.from(e.childNodes||[]))if(xn(t))return t;return null}function gf(e,t){let r=ds(e);r?e.insertBefore(t,r):e.appendChild(t)}function ps(e){let t=Co(e);if(!t)return;let r=ds(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function hf(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(Ee,"tc"),o=0;for(let i of Array.from(n)){let a=Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===Ee&&s.localName==="p");for(let s of a){let l=Array.from(s.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===Ee&&c.localName==="p");for(let c of l)i.insertBefore(c,s),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function Ro(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function wf(e){let t=de(),r=he(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(f=>Ro(f)==="/word/document.xml");if(!o)throw new Error("Package output missing /word/document.xml part");let i=o.getElementsByTagNameNS("*","xmlData")[0];if(!i)throw new Error("Package document part missing pkg:xmlData");let a=Array.from(i.childNodes||[]).find(f=>f.nodeType===1);if(!a)throw new Error("Package document part missing XML payload");let s=a.getElementsByTagNameNS("*","body")[0],l=s?Array.from(s.childNodes||[]).filter(f=>f.nodeType===1&&!xn(f)):[a],c=n.find(f=>Ro(f)==="/word/numbering.xml"),u=null;if(c){let f=c.getElementsByTagNameNS("*","xmlData")[0],m=f?Array.from(f.childNodes||[]).find(d=>d.nodeType===1):null;m&&(u=t.serializeToString(m))}return{replacementNodes:l,numberingXml:u,sourceType:"package"}}function bf(e){if(typeof e!="string"||!e.trim())return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:"Reconciliation engine returned no OOXML payload for this operation"}};try{if(e.includes("<pkg:package"))return wf(e);if(e.includes("<w:document")){let o=he(e,"document OOXML"),i=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:i?Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&!xn(s)):Array.from(o.childNodes||[]).filter(s=>s.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${Ee}">${e}</root>`,r=he(t,"OOXML fragment");return{replacementNodes:Array.from(r.documentElement.childNodes||[]).filter(o=>o.nodeType===1),numberingXml:null,sourceType:"fragment"}}catch(t){return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:t?.message||"Could not parse OOXML payload."}}}}function Oo(e,t,r){let o=Array.from(e.getElementsByTagNameNS("*","Override")).find(a=>(a.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(o)return(o.getAttribute("ContentType")||"")===r?!1:(o.setAttribute("ContentType",r),!0);let i=e.createElementNS(df,"Override");return i.setAttribute("PartName",t),i.setAttribute("ContentType",r),e.documentElement.appendChild(i),!0}function ko(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,i=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(i.some(u=>(u.getAttribute("Type")||"")===t))return!1;let s=0;for(let u of i){let f=u.getAttribute("Id")||"",m=Number.parseInt(f.replace(/^rId/i,""),10);Number.isFinite(m)&&(s=Math.max(s,m))}let l=`rId${s+1}`,c=e.createElementNS(pf,"Relationship");return c.setAttribute("Id",l),c.setAttribute("Type",t),c.setAttribute("Target",r),o.appendChild(c),n?._receiptCollector?n._receiptCollector.recordRelationship(l):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(l),!0}async function Re(e,t){let r=e.file(t);return r?r.async("string"):null}async function xf(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},o=typeof r?.mergeNumberingXml=="function"?r.mergeNumberingXml:null,i=typeof r?.onWarn=="function"?r.onWarn:Be,a=(Array.isArray(t)?t:[t]).filter(Boolean);if(a.length===0)return;let s=await Re(e,bn);s&&!o&&i("[Deprecation] Replacing an existing numbering.xml without mergeNumberingXml is deprecated and will throw in the next major version.");let l=s||null;for(let m of a){if(!l){l=m;continue}l=o?o(l,m):m}n(s?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(bn,l);let c=de(),u=await Re(e,_e);if(u){let m=he(u,_e);Oo(m,"/word/numbering.xml",ls)&&e.file(_e,c.serializeToString(m))}let f=await Re(e,Le);if(f){let m=he(f,Le);ko(m,ss,"numbering.xml",r)&&e.file(Le,c.serializeToString(m))}}async function Nf(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=de(),i=await Re(e,Ar);if(!i||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(Ar,t);else{let l=he(i,"word/comments.xml (existing)"),c=he(t,"word/comments.xml (incoming)"),u=l.documentElement,f=new Set(Array.from(u.getElementsByTagNameNS(Ee,"comment")).map(m=>m.getAttribute("w:id")||m.getAttribute("id")).filter(Boolean));for(let m of Array.from(c.documentElement.getElementsByTagNameNS(Ee,"comment"))){let d=m.getAttribute("w:id")||m.getAttribute("id");if(d&&f.has(d))throw new Error(`Duplicate comment id: ${d}`);u.appendChild(l.importNode(m,!0))}e.file(Ar,o.serializeToString(l))}let a=await Re(e,_e);if(a){let l=he(a,_e);Oo(l,"/word/comments.xml",us)&&e.file(_e,o.serializeToString(l))}let s=await Re(e,Le);if(s){let l=he(s,Le);ko(l,cs,"comments.xml",r)&&e.file(Le,o.serializeToString(l))}}async function vf(e,t,r={}){if(!t)return;he(t,"word/commentsExtended.xml"),e.file(Po,t);let n=de(),o=await Re(e,_e);if(o){let a=he(o,_e);Oo(a,"/word/commentsExtended.xml",ms)&&e.file(_e,n.serializeToString(a))}let i=await Re(e,Le);if(i){let a=he(i,Le);ko(a,fs,"commentsExtended.xml",r)&&e.file(Le,n.serializeToString(a))}}async function yf(e){let t=await Re(e,as);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=he(t,as);ps(r);let n=Co(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(w=>w.nodeType===1),i=o.map((w,b)=>({node:w,index:b})).filter(w=>xn(w.node)).map(w=>w.index);if(i.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(i.length===1&&i[0]!==o.length-1)throw new Error("Validation failed: w:sectPr not last");let a=r.getElementsByTagNameNS(Ee,"tc");for(let w of Array.from(a))for(let b of Array.from(w.childNodes||[]).filter(g=>g.nodeType===1))if(b.namespaceURI===Ee&&b.localName==="p"&&Array.from(b.childNodes||[]).some(x=>x.nodeType===1&&x.namespaceURI===Ee&&x.localName==="p"))throw new Error("Validation failed: nested w:p");let s=r.getElementsByTagNameNS(Ee,"numPr").length>0,l=r.getElementsByTagNameNS(Ee,"commentRangeStart").length>0||r.getElementsByTagNameNS(Ee,"commentRangeEnd").length>0||r.getElementsByTagNameNS(Ee,"commentReference").length>0,c=await Re(e,bn),u=await Re(e,Ar),f=await Re(e,Po);if(f&&!u)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)he(c,bn);else if(s)throw new Error("Validation failed: numbering used but part missing");if(u){let w=he(u,Ar),b=(R,B)=>Array.from(R.getElementsByTagNameNS(Ee,B)).map($=>$.getAttribute("w:id")||$.getAttribute("id")).filter($=>$!==""),g=new Set(b(r,"commentRangeStart")),x=new Set(b(r,"commentRangeEnd")),v=new Set(b(r,"commentReference")),N=b(w,"comment"),S=new Set(N),y=R=>Array.from(R).sort((B,$)=>Number(B)-Number($)||B.localeCompare($)),T=(R,B)=>y(new Set(Array.from(R).filter($=>!B.has($)))),A=y(new Set(N.filter((R,B)=>N.indexOf(R)!==B)));if(A.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${A.join(", ")}`);let M=T(g,x),_=T(x,g);if(M.length>0||_.length>0){let R=[];throw M.length>0&&R.push(`start without end: ${M.join(", ")}`),_.length>0&&R.push(`end without start: ${_.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${R.join("; ")})`)}let F=T(new Set([...g,...x]),v);if(F.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${F.join(", ")}`);let X=T(new Set([...g,...x,...v]),S);if(X.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${X.join(", ")}`);let C=new Set;if(f){let R=he(f,Po),B=new Map;for(let V of Array.from(w.getElementsByTagNameNS("*","comment"))){let Y=V.getAttribute("w:id")||V.getAttribute("id"),oe=Array.from(V.getElementsByTagNameNS("*","p"))[0],mt=oe?.getAttribute("w14:paraId")||oe?.getAttribute("paraId");mt&&B.set(mt.toUpperCase(),Y)}let $=new Set(B.keys()),K=new Set;for(let V of Array.from(R.getElementsByTagNameNS("*","commentEx"))){let Y=V.getAttribute("w15:paraId")||V.getAttribute("paraId"),oe=V.getAttribute("w15:paraIdParent")||V.getAttribute("paraIdParent");if(!Y||!$.has(Y.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${Y||"(missing)"}`);if(K.has(Y.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${Y}`);if(K.add(Y.toUpperCase()),oe){if(!$.has(oe.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${oe}`);C.add(B.get(Y.toUpperCase()))}}}let W=T(new Set([...S].filter(R=>!C.has(R))),v);if(W.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${W.join(", ")}`)}else if(l)throw new Error("Validation failed: comments used but part missing");let m=await Re(e,_e);if(!m)throw new Error(`Validation failed: missing ${_e}`);let d=he(m,_e),p=await Re(e,Le);if(!p)throw new Error(`Validation failed: missing ${Le}`);let h=he(p,Le);if(c){let w=Array.from(d.getElementsByTagNameNS("*","Override")).some(g=>(g.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(g.getAttribute("ContentType")||"")===ls),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===ss);if(!w)throw new Error("Validation failed: numbering CT override missing");if(!b)throw new Error("Validation failed: numbering rel missing")}if(u){let w=Array.from(d.getElementsByTagNameNS("*","Override")).some(g=>(g.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(g.getAttribute("ContentType")||"")===us),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===cs);if(!w)throw new Error("Validation failed: comments CT override missing");if(!b)throw new Error("Validation failed: comments rel missing")}if(f){let w=Array.from(d.getElementsByTagNameNS("*","Override")).some(g=>(g.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml"&&(g.getAttribute("ContentType")||"")===ms),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===fs);if(!w)throw new Error("Validation failed: commentsExtended CT override missing");if(!b)throw new Error("Validation failed: commentsExtended rel missing")}}var Kt=Object.freeze({STRUCTURED_LIST_DIRECT:"structured_list_direct",EMPTY_FORMATTED_TEXT:"empty_formatted_text",EMPTY_HTML:"empty_html",BLOCK_HTML:"block_html",OOXML_ENGINE:"ooxml_engine"});function hs(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
|
|
209
|
-
`).
|
|
210
|
-
`)&&n.type!=="text"?{kind:Kt.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:gs(t),hasInlineFormatting:Nn(r),hasBlockElements:vn(r),hasMarkdownTable:Ir(r)}}:gs(t)?Nn(r)?{kind:Kt.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:vn(r),hasMarkdownTable:Ir(r)}}:{kind:Kt.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:vn(r),hasMarkdownTable:Ir(r)}}:vn(r)?{kind:Kt.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:Nn(r),hasBlockElements:!0,hasMarkdownTable:Ir(r)}}:{kind:Kt.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:Nn(r),hasBlockElements:!1,hasMarkdownTable:Ir(r)}}}function gs(e){return!e||e.trim().length===0}function Ir(e){if(!e||!e.includes("|"))return!1;let t=Xe(e);return t.rows.length>0||t.headers.length>0}function Nn(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function vn(e){if(!e)return!1;let t=/^[\s]*[-*+]\s+/m.test(e),r=/^[\s]*\d+\.\s+/m.test(e),n=/^[\s]*\d+\.\d+(?:\.\d+)*\.?\s+/m.test(e),o=/^[\s]*[A-Za-z]\.\s+/m.test(e),i=/^[\s]*[ivxlcIVXLC]+\.\s+/m.test(e),a=/^[\s]*\([a-z]\)\s+/m.test(e),s=/\|.*\|.*\n/.test(e),l=/^#{1,9}\s/m.test(e),c=e.includes(`
|
|
207
|
+
</w:comments>`}function Rc(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${ze(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${ze(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${je}">${t}</w15:commentsEx>`}var et=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function la(e){let t=Array.from(e?.getElementsByTagNameNS?.("*","p")||[]);return t.length?t[t.length-1]:null}function tt(e){return et(la(e),"w14:paraId","paraId").toUpperCase()}function Bi(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=et(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=et(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function ca(e,t){let r=Oi(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}var ki=(e,t)=>{let r=W(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}};function ua({commentsXml:e,commentsExtendedXml:t=null,commentId:r,resolved:n=!0}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"Resolving a comment requires an existing word/comments.xml part."}};let o=ki(e,"word/comments.xml");if(o.error)return{status:"error",error:o.error};let a=o.doc,i=S=>et(S,"w:id","id"),s=Array.from(a.getElementsByTagNameNS("*","comment")),l=s.find(S=>i(S)===String(r));if(!l)return{status:"error",error:{code:"COMMENT_NOT_FOUND",message:`Comment '${r}' was not found.`}};let c;if(t){let S=ki(t,"word/commentsExtended.xml");if(S.error)return{status:"error",error:S.error};c=S.doc}else c=ki(`<w15:commentsEx xmlns:w15="${je}"/>`,"word/commentsExtended.xml").doc;let u=c.documentElement,f=S=>Array.from(u.getElementsByTagNameNS("*","commentEx")).find(O=>et(O,"w15:paraId","paraId").toUpperCase()===S)||null,d=Bi(a,c),m=!1,g=(S=>{let O=tt(S);return O||(O=ca(i(S),d),la(S)?.setAttributeNS(ln,"w14:paraId",O),m=!0),O})(l),h=f(g),y=h&&et(h,"w15:paraIdParent","paraIdParent").toUpperCase()||g,w=new Set([y,g]);for(let S of Array.from(u.getElementsByTagNameNS("*","commentEx")))et(S,"w15:paraIdParent","paraIdParent").toUpperCase()===y&&w.add(et(S,"w15:paraId","paraId").toUpperCase());let v=n?"1":"0",b=!t;for(let S of w){let O=f(S);O?et(O,"w15:done","done")!==v&&(O.setAttributeNS(je,"w15:done",v),b=!0):(O=c.createElementNS(je,"w15:commentEx"),O.setAttributeNS(je,"w15:paraId",S),S!==y&&O.setAttributeNS(je,"w15:paraIdParent",y),O.setAttributeNS(je,"w15:done",v),u.appendChild(O),b=!0)}let x=new Map(s.map(S=>[tt(S),S])),I=[...w].map(S=>x.get(S)).filter(Boolean).map(i),N=x.get(y),T=oe(),E=b||m;return{status:"ok",hasChanges:E,resolved:n,threadRootId:N?i(N):String(r),commentIds:I,...E?{commentsExtendedXml:T.serializeToString(c)}:{},...m?{commentsXml:T.serializeToString(a)}:{}}}var sa="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Pc(e,t,r){let n=new Set(t.map(String)),o=g=>et(g,"w:id","id"),a=g=>Array.from(e.getElementsByTagNameNS("*",g)).filter(h=>n.has(o(h))),i=a("commentRangeStart"),s=a("commentReference");if(!i.length||!s.length)return!1;let l=i[i.length-1],c=s[s.length-1],u=c.parentNode?.localName==="r"?c.parentNode:c,f=(g,h)=>{let y=e.createElementNS(sa,`w:${g}`);return y.setAttributeNS(sa,"w:id",String(r)),h&&h.appendChild(y),y},d=(g,h)=>g.parentNode.insertBefore(h,g.nextSibling);d(l,f("commentRangeStart"));let m=f("commentRangeEnd"),p=e.createElementNS(sa,"w:r");return p.appendChild(e.createElementNS(sa,"w:rPr")),f("commentReference",p),d(u,m),d(m,p),!0}var Mi="http://schemas.microsoft.com/office/word/2016/wordml/cid",Li="http://schemas.microsoft.com/office/word/2018/wordml/cex",vp=(e,t)=>{let r=(Number.parseInt(e,16)^625341585)&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");for(;t.has(n);)r=r+2&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");return t.add(n),n};function Cc({commentsXml:e,commentsIdsXml:t=null,commentsExtensibleXml:r=null}){let n={};if(!e||!t&&!r)return n;let o=W(e,"application/xml");if(!o.doc||o.error)return n;let a=oe(),i=new Map;for(let m of Array.from(o.doc.getElementsByTagNameNS("*","comment"))){let p=tt(m);p&&i.set(p,m)}let s=null,l=new Map,c=new Set,u=!1;if(t){let m=W(t,"application/xml");if(!m.doc||m.error)return n;s=m.doc;let p=s.documentElement;for(let g of Array.from(p.getElementsByTagNameNS("*","commentId"))){let h=et(g,"w16cid:paraId","paraId").toUpperCase(),y=et(g,"w16cid:durableId","durableId").toUpperCase();if(y&&c.add(y),!i.has(h)){p.removeChild(g),u=!0;continue}l.set(h,y)}for(let g of i.keys()){if(l.has(g))continue;let h=vp(g,c),y=s.createElementNS(Mi,"w16cid:commentId");y.setAttributeNS(Mi,"w16cid:paraId",g),y.setAttributeNS(Mi,"w16cid:durableId",h),p.appendChild(y),l.set(g,h),u=!0}}let f=null,d=!1;if(r&&s){let m=W(r,"application/xml");if(m.doc&&!m.error){f=m.doc;let p=f.documentElement,g=new Set(l.values()),h=new Set;for(let y of Array.from(p.getElementsByTagNameNS("*","commentExtensible"))){let w=et(y,"w16cex:durableId","durableId").toUpperCase();g.has(w)?h.add(w):(p.removeChild(y),d=!0)}for(let[y,w]of l){if(h.has(w))continue;let v=et(i.get(y),"w:date","date"),b=f.createElementNS(Li,"w16cex:commentExtensible");b.setAttributeNS(Li,"w16cex:durableId",w),v&&b.setAttributeNS(Li,"w16cex:dateUtc",v),p.appendChild(b),d=!0}}}return u&&(n.commentsIdsXml=a.serializeToString(s)),d&&(n.commentsExtensibleXml=a.serializeToString(f)),n}var xp=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bp=new TextEncoder;function Gn(e){let t;if(typeof e=="string")t=bp.encode(e);else if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else throw new TypeError("sha256 input must be a string, Uint8Array, Buffer, or ArrayBuffer.");let r=t.length,n=r*8,o=Math.ceil((r+9)/64)*64,a=new Uint8Array(o);a.set(t,0),a[r]=128;let i=new DataView(a.buffer,a.byteOffset,a.byteLength),s=Math.floor(n/4294967296),l=n>>>0;i.setUint32(o-8,s,!1),i.setUint32(o-4,l,!1);let c=1779033703,u=3144134277,f=1013904242,d=2773480762,m=1359893119,p=2600822924,g=528734635,h=1541459225,y=new Uint32Array(64);for(let v=0;v<o;v+=64){for(let A=0;A<16;A++)y[A]=i.getUint32(v+A*4,!1);for(let A=16;A<64;A++){let P=y[A-15],_=(P>>>7|P<<25)^(P>>>18|P<<14)^P>>>3,R=y[A-2],k=(R>>>17|R<<15)^(R>>>19|R<<13)^R>>>10;y[A]=y[A-16]+_+y[A-7]+k|0}let b=c,x=u,I=f,N=d,T=m,E=p,S=g,O=h;for(let A=0;A<64;A++){let P=(T>>>6|T<<26)^(T>>>11|T<<21)^(T>>>25|T<<7),_=T&E^~T&S,R=O+P+_+xp[A]+y[A]|0,k=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),C=b&x^b&I^x&I,M=k+C|0;O=S,S=E,E=T,T=N+R|0,N=I,I=x,x=b,b=R+M|0}c=c+b|0,u=u+x|0,f=f+I|0,d=d+N|0,m=m+T|0,p=p+E|0,g=g+S|0,h=h+O|0}let w=v=>(v>>>0).toString(16).padStart(8,"0");return w(c)+w(u)+w(f)+w(d)+w(m)+w(p)+w(g)+w(h)}var cn=new TextEncoder;function Oc(e){if(typeof e!="string")throw new TypeError(`Entry name must be a string, got ${typeof e}`);let t=e.replace(/\\/g,"/");for(t=t.replace(/^\/+/,"");t.startsWith("./");)t=t.slice(2);if(t=t.replace(/\/+/g,"/"),!t)throw new Error(`Invalid empty entry name: "${e}"`);return t}function Di({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=cn.encode("docx-redline-revision-token\0"),n=1,o=cn.encode(e),a=[],i=new Set,s=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let d of s){if(!d)continue;let m=Array.isArray(d)?d[0]:d.name,p=Array.isArray(d)?d[1]:d.payload??d.bytes;if(m==null)continue;let g=Oc(String(m));if(i.has(g))throw new Error(`Duplicate normalized entry path detected: "${g}"`);i.add(g);let h;typeof p=="string"?h=cn.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),a.push({name:g,nameBytes:cn.encode(g),payloadBytes:h})}a.sort((d,m)=>d.name<m.name?-1:d.name>m.name?1:0);let l=r.length+4+4+o.length+4;for(let d of a)l+=4+d.nameBytes.length+4+d.payloadBytes.length;let c=new Uint8Array(l),u=new DataView(c.buffer,c.byteOffset,c.byteLength),f=0;c.set(r,f),f+=r.length,u.setUint32(f,n,!1),f+=4,u.setUint32(f,o.length,!1),f+=4,c.set(o,f),f+=o.length,u.setUint32(f,a.length,!1),f+=4;for(let d of a)u.setUint32(f,d.nameBytes.length,!1),f+=4,c.set(d.nameBytes,f),f+=d.nameBytes.length,u.setUint32(f,d.payloadBytes.length,!1),f+=4,c.set(d.payloadBytes,f),f+=d.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:a.map(d=>d.name)}}async function _c({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:a}=Di({scope:e,entries:t}),i="";if(typeof r=="function")i=await r(n);else if(typeof globalThis.crypto?.subtle?.digest=="function"){let s=await globalThis.crypto.subtle.digest("SHA-256",n),l=new Uint8Array(s);i=Array.from(l).map(c=>c.toString(16).padStart(2,"0")).join("")}else i=Gn(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function qn({scope:e,entries:t=[],digestFn:r=null}){if(r!=null&&typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn when specified.");let{framing:n,coveredParts:o,version:a}=Di({scope:e,entries:t}),i=typeof r=="function"?r(n):Gn(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function fa(e){let t=[];if(e?.documentXml&&t.push({name:"word/document.xml",payload:e.documentXml}),e?.commentsXml&&t.push({name:"word/comments.xml",payload:e.commentsXml}),e?.commentsExtendedXml&&t.push({name:"word/commentsExtended.xml",payload:e.commentsExtendedXml}),e?.numberingXml&&t.push({name:"word/numbering.xml",payload:e.numberingXml}),e?.stylesXml&&t.push({name:"word/styles.xml",payload:e.stylesXml}),e?.parts instanceof Map)for(let[r,n]of e.parts.entries())t.push({name:r,payload:n});else if(e?.additionalParts&&typeof e.additionalParts=="object")for(let[r,n]of Object.entries(e.additionalParts))t.push({name:r,payload:n});return t}async function Yn(e,t={}){let r=fa(e);return _c({scope:"document-parts",entries:r,digestFn:t.digestFn})}function Br(e){return!e||typeof e!="object"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token must be an object."}}:e.algorithm!=="sha256"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token algorithm: "${e.algorithm}". Expected "sha256".`}}:e.version!==1?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token version: "${e.version}". Expected 1.`}}:e.scope!=="document-parts"&&e.scope!=="package"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token scope: "${e.scope}". Expected "document-parts" or "package".`}}:typeof e.value!="string"||!/^[0-9a-f]{64}$/i.test(e.value.trim())?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token value must be a 64-character hex string."}}:{valid:!0}}function Dr(e,t){if(typeof e!="string"||typeof t!="string")return!1;let r=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(r.length!==n.length)return!1;let o=cn.encode(r),a=cn.encode(n),i=0;for(let s=0;s<o.length;s++)i|=o[s]^a[s];return i===0}var pe=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",St=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(L,t)||[]),Me=(e,t)=>St(e,t)[0]||null;function kc(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===L))return!0;r=r.parentNode}return!1}function da(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=W(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function Np(e){let t=Me(Me(e,"pPr"),"numPr");if(!t)return null;let r=pe(Me(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(pe(Me(t,"ilvl"),"val")||"0",10)||0}}function Ip(e){let t=new Map;for(let n of St(e,"abstractNum")){let o=new Map;for(let a of St(n,"lvl")){let i=Number.parseInt(pe(a,"ilvl")||"0",10)||0;o.set(i,{start:Number.parseInt(pe(Me(a,"start"),"val")||"1",10)||1,format:pe(Me(a,"numFmt"),"val")||"decimal",text:pe(Me(a,"lvlText"),"val")||`%${i+1}.`})}t.set(pe(n,"abstractNumId"),o)}let r=new Map;for(let n of St(e,"num")){let o=pe(Me(n,"abstractNumId"),"val"),a=new Map(t.get(o)||[]);for(let i of St(n,"lvlOverride")){let s=Number.parseInt(pe(i,"ilvl")||"0",10)||0,l=Me(i,"lvl"),c={...a.get(s)||{start:1,format:"decimal",text:`%${s+1}.`}};l&&(c.start=Number.parseInt(pe(Me(l,"start"),"val")||String(c.start),10)||c.start,c.format=pe(Me(l,"numFmt"),"val")||c.format,c.text=pe(Me(l,"lvlText"),"val")||c.text);let u=Me(i,"startOverride");u&&(c.start=Number.parseInt(pe(u,"val")||String(c.start),10)||c.start),a.set(s,c)}r.set(pe(n,"numId"),a)}return r}function Mc(e,t){let r=Math.max(1,e),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function Lc(e){let t=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],r=e,n="";for(let[o,a]of t)for(;r>=o;)n+=a,r-=o;return n}function Tp(e,t){return t==="lowerLetter"?Mc(e,!1):t==="upperLetter"?Mc(e,!0):t==="lowerRoman"?Lc(e).toLowerCase():t==="upperRoman"?Lc(e):String(e)}function Sp(e){let t=e?Ip(e):new Map,r=new Map;return n=>{if(!n?.numId)return null;let o=t.get(String(n.numId));if(!o)return{...n,label:null,format:null};let a=r.get(n.numId)||[],i=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};a[n.level]=a[n.level]==null?i.start:a[n.level]+1,a.length=n.level+1,r.set(n.numId,a);let s=i.text.replace(/%([1-9])/g,(l,c)=>{let u=Number(c)-1,f=o.get(u)||i;return Tp(a[u]??f.start,f.format)});return{...n,label:s,format:i.format}}}function Ep(e){let t=Me(e,"pPr"),n=pe(Me(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(pe(Me(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function Ap(e,t){let r=[];for(let[s,l]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of St(e,s))r.push({type:l,id:pe(c,"id")||null});let n=e.parentNode;for(;n&&n.localName!=="tc";)n=n.parentNode;let o=n?.parentNode;for(;o&&o.localName!=="tr";)o=o.parentNode;let a=o?.parentNode;for(;a&&a.localName!=="tbl";)a=a.parentNode;let i=e.ownerDocument;return{references:r,table:a?{tableIndex:Array.from(i.getElementsByTagNameNS(L,"tbl")).indexOf(a)+1,rowIndex:Array.from(a.getElementsByTagNameNS(L,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(L,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Bc(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of St(e,r))pe(n,"author")&&t.add(pe(n,"author"));return[...t].sort()}function Rp(e){let t=new Map;for(let r of St(e,"comment")){let n=St(r,"p");t.set(pe(r,"id"),{id:pe(r,"id"),author:pe(r,"author")||null,date:pe(r,"date")||null,text:n.map(o=>te(o)).join(`
|
|
208
|
+
`),paraId:tt(r)||null})}return t}function Pp(e,t){if(!t)return;let r=new Map([...e.values()].filter(n=>n.paraId).map(n=>[n.paraId.toUpperCase(),n]));for(let n of Array.from(t.getElementsByTagNameNS("*","commentEx"))){let o=n.getAttribute("w15:paraId")||n.getAttribute("paraId")||"",a=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",i=r.get(o.toUpperCase());i&&(i.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",a&&(i.parentParaId=a,i.parentCommentId=r.get(a.toUpperCase())?.id||null))}}function Cp(e,t){let r=new Map,n=new Map,o=null,a=s=>{for(let l of r.values())l.text+=s},i=s=>{for(let l of Array.from(s?.childNodes||[])){if(l?.nodeType!==1)continue;let c=l.localName;if(!(t==="accepted"&&(c==="del"||c==="moveFrom")||t==="rejected"&&(c==="ins"||c==="moveTo")))if(c==="commentRangeStart")r.set(pe(l,"id"),{text:""});else if(c==="commentRangeEnd"){let u=pe(l,"id");r.has(u)&&(n.set(u,r.get(u).text),r.delete(u))}else c==="r"?a(Tr(l,{revisionView:t,boundary:o})):i(l)}};return e.forEach((s,l)=>{o=s,i(s),l<e.length-1&&r.size&&a(`
|
|
209
|
+
`)}),n}function Op(e,t){let r=e;if(t.revisedOnly&&(r=r.filter(p=>p.hasRevisions)),t.inTable!=null&&(r=r.filter(p=>p.inTable===!!t.inTable)),t.skipEmpty&&(r=r.filter(p=>p.text.length>0)),t.search){let p=String(t.search).toLowerCase();r=r.filter(g=>g.text.toLowerCase().includes(p))}if(Array.isArray(t.indexes)){let p=new Set(t.indexes);r=r.filter(g=>p.has(g.index))}let n=1,o=e.length;t.range&&(n=Number(t.range.start??t.range[0]),o=Number(t.range.end??t.range[1]),r=r.filter(p=>p.index>=n&&p.index<=o));let a=r.length,i=Number.isInteger(t.after)&&t.after>0?t.after:null,s=i==null?r:r.filter(p=>p.index>i),l=Number.isInteger(t.limit)&&t.limit>0?t.limit:null,c=l==null?s:s.slice(0,l),u=c.length<s.length,f=Number.isInteger(t.around)&&t.around>0?t.around:0,d=!!t.search||f>0||l!=null||i!=null,m=c;if(f>0&&t.search){let p=new Set(c.map(y=>y.index)),g=new Map;for(let y of c){let w=Math.max(n,y.index-f),v=Math.min(o,y.index+f);for(let b=w;b<=v;b++){if(p.has(b))continue;let x=g.get(b)||[];x.push(y.index),g.set(b,x)}}let h=new Set([...p,...g.keys()]);m=e.filter(y=>h.has(y.index)).map(y=>p.has(y.index)?{...y,selectionRole:"match"}:{...y,selectionRole:"context",contextFor:g.get(y.index)||[]})}else d&&(m=c.map(p=>({...p,selectionRole:"match"})));return{paragraphs:m,...d?{selection:{...t.search?{search:String(t.search),caseSensitive:!1}:{},totalMatches:a,returnedMatches:c.length,returnedParagraphs:m.length,truncated:u,nextAfter:u&&c.length>0?c[c.length-1].index:null,...l!=null?{limit:l}:{},...i!=null?{after:i}:{},...f>0?{around:f}:{}}}:{}}}function ma(e,t={}){let r=da(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=da(e?.commentsXml,"word/comments.xml"),o=da(e?.commentsExtendedXml,"word/commentsExtended.xml"),a=da(e?.numberingXml,"word/numbering.xml"),i=[...r.warnings||[]];n.error&&i.push(n.error.message),o.error&&i.push(o.error.message),a.error&&i.push(a.error.message);let s=Rp(n.doc);Pp(s,o.doc);let l=Sp(a.doc),c=null,u=se(r.doc),f=t.revisionView==="rejected"?"rejected":"accepted",d=Cp(u,f),m=u.map((v,b)=>{let x=te(v,{revisionView:f}),I=Ep(v);I&&(c={level:I,text:x});let N=[...new Set([...St(v,"commentRangeStart"),...St(v,"commentReference")].map(M=>pe(M,"id")).filter(Boolean))],T=Bc(v),E=l(Np(v)),S=pe(Me(Me(v,"pPr"),"pStyle"),"val")||null,O=Ap(v,x),A=b+1,P=E?.label&&E.format!=="bullet"?E.label:null,_=c?.text||null,R=x.slice(0,t.excerptLength||120),k=I?x:P?[P,_].filter(Boolean).join(" \u2014 "):_?[_,R].filter(Boolean).join(" \u2014 "):R,C=Co(v);return{index:A,ref:`P${A}`,paragraphId:$e(v),fingerprint:st(v,{text:x,index:A,revisionView:f}),revisionView:f,text:x,exactText:x,excerpt:R,humanReference:k,provision:P,inTable:kc(v,"tc"),table:O.table,styleId:S,headingLevel:I,nearestHeading:c,list:E,structuralReferences:O.references,hasRevisions:T.length>0,revisionAuthors:T,commentIds:N,segments:C}});for(let v of m)for(let b of v.commentIds){let x=s.get(b)||{id:b,author:null,date:null,text:""};x.paragraphIndex??(x.paragraphIndex=v.index),x.targetRef??(x.targetRef=v.ref),x.anchoredText??(x.anchoredText=d.get(b)||v.text),s.set(b,x)}let p=Op(m,t);if(t.search&&p.selection&&p.selection.totalMatches===0){let v=String(t.search).toLowerCase(),b=f==="accepted"?"rejected":"accepted",x=1,I=u.length;t.range&&(x=Number(t.range.start??t.range[0]),I=Number(t.range.end??t.range[1]));let N=0;for(let T=0;T<u.length;T++){let E=T+1;if(t.range&&(E<x||E>I)||Array.isArray(t.indexes)&&!t.indexes.includes(E))continue;let S=u[T];if(t.inTable!=null&&kc(S,"tc")!==!!t.inTable||t.revisedOnly&&Bc(S).length===0)continue;let O=te(S,{revisionView:b});t.skipEmpty&&O.length===0||O.toLowerCase().includes(v)&&N++}N>0&&(p.selection.hint=f==="accepted"?`0 matches in accepted view, but ${N} match${N===1?"":"es"} found in --view rejected. If searching for deleted text to restore, re-run with --view rejected.`:`0 matches in rejected view, but ${N} match${N===1?"":"es"} found in --view accepted. Re-run with --view accepted.`)}m=p.paragraphs;let g=[...new Set(m.flatMap(v=>v.revisionAuthors))].sort(),h=fa(e),y=h.map(v=>v.name).sort(),w=null;return typeof t.digestFn=="function"&&(w=qn({scope:"document-parts",entries:h,digestFn:t.digestFn})),{status:"ok",revisionToken:w,coveredParts:y,paragraphs:m,...p.selection?{selection:p.selection}:{},comments:[...s.values()],revisionAuthors:g,commentAuthors:[...new Set([...s.values()].map(v=>v.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:s.size,revisedParagraphs:m.filter(v=>v.hasRevisions).length},warnings:i}}function un(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=En(e,"w:r"),o=[],a="";for(let i of n){if(!Ir(i,e,r))continue;let s=a.length,l=Tr(i,{revisionView:r,boundary:e});a+=l,o.push({run:i,start:s,end:a.length})}return{fullText:a,runOffsets:o}}function Dc(e,t){if(!t)return[];let r=[],n=e.indexOf(t);for(;n!==-1;)r.push({start:n,end:n+t.length}),n=e.indexOf(t,n+1);return r}function Fc(e){return String(e).replace(/[ \u00a0]/g," ")}function Jn(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function $c(e,t,r){let n=null,o=null,a=0,i=0;for(let{run:s,start:l,end:c}of e.runOffsets)t.start>=l&&t.start<c&&(n=s,a=t.start-l),t.end>l&&t.end<=c&&(o=s,i=t.end-l);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:a,endRun:o,endOffset:i}}function Uc(e,t,r=null){let n=e?.parentNode;for(;n&&n.nodeType===1&&n!==r&&(n.localName||n.nodeName.replace(/^.*:/,""))!=="p";){let o=n.localName||n.nodeName.replace(/^.*:/,"");if(t.includes(o))return{node:n,tag:o};n=n.parentNode}return null}function zc(e,t){if(!t||!t.found)return t;let r=e.runOffsets.filter(n=>n.end>t.start&&n.start<t.end).map(n=>n.run);for(let n of r){if(Uc(n,["del"]))return{found:!1,error:Jn("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(Uc(n,["moveFrom","moveTo"]))return{found:!1,error:Jn("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function Qn(e,t){let r=String(t??""),n=Dc(e.fullText,r);if(n.length>1)return{found:!1,error:Jn("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=$c(e,n[0],"exact_anchor");if(s)return zc(e,s)}let o=Fc(r),a=Fc(e.fullText),i=Dc(a,o);if(i.length>1)return{found:!1,error:Jn("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${i.length} locations in the target paragraph.`,i)};if(i.length===1){let s=$c(e,i[0],"space_equivalent_anchor");if(s)return zc(e,s)}return{found:!1,error:Jn("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function Zn(e,t,r,n,o=!1){let a=B(e,"w:r");if(t){let s=t.cloneNode(!0);o||Ot(s,n),a.appendChild(s)}let i=B(e,"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=r,a.appendChild(i),a}function Xc(e,t,r,n,o=null,a=null,i=null){let s=o||un(t),l=i||Qn(s,r);if(!l.found||!l.startRun)return!1;let c=B(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let u=B(e,"w:commentRangeEnd");u.setAttribute("w:id",String(n));let f=B(e,"w:r"),d=B(e,"w:commentReference");if(d.setAttribute("w:id",String(n)),f.appendChild(d),l.startRun===l.endRun){let h=l.startRun,y=Re(h,"w:t");if(!y)return h.parentNode.insertBefore(c,h),h.nextSibling?(h.parentNode.insertBefore(u,h.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(h.parentNode.appendChild(u),h.parentNode.appendChild(f)),!0;let w=y.textContent||"",v=w.substring(0,l.startOffset),b=w.substring(l.startOffset,l.endOffset),x=w.substring(l.endOffset),I=Re(h,"w:rPr"),N=h.parentNode;return v&&(N.insertBefore(Zn(e,I,v,a,!0),h),Ot(I,a)),N.insertBefore(c,h),y.textContent=b,h.nextSibling?N.insertBefore(u,h.nextSibling):N.appendChild(u),N.insertBefore(f,u.nextSibling||null),x&&N.insertBefore(Zn(e,I,x,a),f.nextSibling||null),!0}let m=Re(l.startRun,"w:t");if(m&&l.startOffset>0){let h=m.textContent||"",y=h.substring(0,l.startOffset),w=h.substring(l.startOffset);if(y){let v=Re(l.startRun,"w:rPr");l.startRun.parentNode.insertBefore(Zn(e,v,y,a,!0),l.startRun),Ot(v,a)}m.textContent=w}l.startRun.parentNode.insertBefore(c,l.startRun);let p=l.endRun||l.startRun,g=Re(p,"w:t");if(g&&l.endOffset<(g.textContent||"").length){let h=g.textContent||"",y=h.substring(0,l.endOffset),w=h.substring(l.endOffset);if(g.textContent=y,w){let v=Re(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(Zn(e,v,w,a),p.nextSibling):p.parentNode.appendChild(Zn(e,v,w,a))}}return p.nextSibling?(p.parentNode.insertBefore(u,p.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(p.parentNode.appendChild(u),p.parentNode.appendChild(f)),!0}var fn="http://schemas.microsoft.com/office/2006/xmlPackage",eo="http://schemas.openxmlformats.org/package/2006/relationships";function Vc(e,t){let r=oe(),n=W(e,"text/xml"),o=n.doc,a=o?Se(o):null;if(n.error||a)return Ne("[CommentEngine] Failed to parse package:",n.error?.message||a?.textContent),e;let i=o.documentElement,s=o.createElementNS(fn,"pkg:part");s.setAttribute("pkg:name","/word/comments.xml"),s.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let l=o.createElementNS(fn,"pkg:xmlData"),c=W(t,"text/xml").doc;if(!c)return e;l.appendChild(o.importNode(c.documentElement,!0)),s.appendChild(l),i.appendChild(s);let f=Ce(i,fn,"part").find(d=>d.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let d=Ce(f,fn,"xmlData");if(d.length>0){let m=Ce(d[0],eo,"Relationships");if(m.length>0){let p=m[0],g=Ce(p,eo,"Relationship");if(!g.some(y=>y.getAttribute("Type")?.includes("comments"))){let y=0;g.forEach(v=>{let b=v.getAttribute("Id"),x=parseInt(b?.replace("rId","")||"0",10);x>y&&(y=x)});let w=o.createElementNS(eo,"Relationship");w.setAttribute("Id",`rId${y+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let d=o.createElementNS(fn,"pkg:part");d.setAttribute("pkg:name","/word/_rels/document.xml.rels"),d.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let m=o.createElementNS(fn,"pkg:xmlData"),p=o.createElementNS(eo,"Relationships"),g=o.createElementNS(eo,"Relationship");g.setAttribute("Id","rId1"),g.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),g.setAttribute("Target","comments.xml"),p.appendChild(g),m.appendChild(p),d.appendChild(m),i.appendChild(d)}return r.serializeToString(o)}function _p(e,t){let r=W(e,"text/xml"),n=r.doc?Se(r.doc):null;if(r.error||n){let o=r.error?.message||n?.textContent||"parse error";return{xmlDoc:null,warning:t(o),warnings:r.warnings,error:{code:"PARSE_ERROR",message:o}}}return{xmlDoc:r.doc,warning:null,warnings:r.warnings,error:null}}function Fi(e,t,r={}){let n=r?.author||re(),o=vo(),a=[],i=[],s=[],l=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=oe(),u=_p(e,h=>`Failed to parse OXML: ${h}`);if(a.push(...u.warnings||[]),!u.xmlDoc)return Ne("[CommentEngine] Parse failure:",u.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:u.error,warnings:[...a,u.warning]};let f=u.xmlDoc,d=tr(f),m=En(f,"w:p");K(`[CommentEngine] Found ${m.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let y=h.paragraphIndex-1;if(y<0||y>=m.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${m.length})`;a.push(w),l.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(y,(p.get(y)||0)+1)}let g=new Map;for(let[h,y]of t.entries()){let w=y.paragraphIndex-1;if(w<0||w>=m.length)continue;let v=m[w],b=g.get(w);b||(b=un(v),g.set(w,b));let x=String(y.textToFind??""),I=Qn(b,x),N=(p.get(w)||1)-1;if(p.set(w,N),!I.found){let S={...I.error,requestIndex:h+1,paragraphIndex:y.paragraphIndex};l.push(S),a.push(S.message),N===0&&g.delete(w);continue}let T=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():Ds();if(!Xc(f,v,x,T,b,d,I)){let S={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${y.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:y.paragraphIndex};l.push(S),a.push(S.message),N===0&&g.delete(w);continue}i.push({id:T,content:y.commentContent,author:n,date:o}),s.push({requestIndex:h+1,paragraphIndex:y.paragraphIndex,text:x,resolvedBy:I.resolvedBy,start:I.start,end:I.end}),N>0?g.set(w,un(v)):g.delete(w)}return i.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:a,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}:{oxml:c.serializeToString(f),hasChanges:!0,commentsXml:_i(i),commentsApplied:i.length,placedComments:i,warnings:a,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}}function kp(e,t){return Vc(e,t)}var Mp="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Wt(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function pa(e,t){let r=W(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}}function $i({commentsXml:e,commentsExtendedXml:t=null,documentXml:r=null,parentCommentId:n,commentId:o,commentContent:a,author:i,date:s=new Date().toISOString()}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing word/comments.xml part."}};let l=pa(e,"word/comments.xml");if(l.error)return{status:"error",error:l.error};let c=l.doc,u=Array.from(c.getElementsByTagNameNS("*","comment")).find(O=>Wt(O,"w:id","id")===String(n));if(!u)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${n}' was not found.`}};let f=null;if(t){let O=pa(t,"word/commentsExtended.xml");if(O.error)return{status:"error",error:O.error};f=O.doc}let d=Bi(c,f);if(r)for(let O of String(r).matchAll(/w14:paraId="([0-9A-Fa-f]{8})"/g))d.add(O[1].toUpperCase());let m=la(u);if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${n}' has no paragraph.`}};let p=tt(u);p?p=p.toUpperCase():(p=ca(n,d),m.setAttributeNS(ln,"w14:paraId",p));for(let O of Array.from(f?.getElementsByTagNameNS("*","commentEx")||[]))if(Wt(O,"w15:paraId","paraId").toUpperCase()===p){let A=Wt(O,"w15:paraIdParent","paraIdParent").toUpperCase();A&&(p=A);break}let g=[],h=Array.from(c.getElementsByTagNameNS("*","comment")),y=new Map(Array.from(f?.getElementsByTagNameNS("*","commentEx")||[]).map(O=>[Wt(O,"w15:paraId","paraId").toUpperCase(),Wt(O,"w15:paraIdParent","paraIdParent").toUpperCase()]));for(let O of h){let A=tt(O);(A===p||y.get(A)===p)&&g.push(Wt(O,"w:id","id"))}let w=Wt(h.find(O=>tt(O)===p),"w:id","id")||String(n),v=ca(o,d),b=pa(`<w:comments xmlns:w="${Mp}" xmlns:w14="${ln}">${Hn(o,i,a,s,v)}</w:comments>`,"reply comment");c.documentElement.appendChild(c.importNode(b.doc.documentElement.firstChild,!0)),f||(f=pa(Rc([]),"word/commentsExtended.xml").doc);let x=f.documentElement,N=Array.from(x.getElementsByTagNameNS("*","commentEx")).find(O=>Wt(O,"w15:paraId","paraId").toUpperCase()===p);if(!N){let O=f.createElementNS(je,"w15:commentEx");O.setAttributeNS(je,"w15:paraId",p),O.setAttributeNS(je,"w15:done","0"),x.appendChild(O)}let T=Wt(N,"w15:done","done")==="1"?"1":"0",E=f.createElementNS(je,"w15:commentEx");E.setAttributeNS(je,"w15:paraId",v),E.setAttributeNS(je,"w15:paraIdParent",p),E.setAttributeNS(je,"w15:done",T),x.appendChild(E);let S=oe();return{status:"ok",hasChanges:!0,commentsXml:S.serializeToString(c),commentsExtendedXml:S.serializeToString(f),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:o,parentCommentId:String(n),paraId:v,parentParaId:p,threadRootCommentId:w,threadCommentIds:g.length?g:[w]}}function dn(e){e?.parentNode&&e.parentNode.removeChild(e)}function Wc(e,t=["all"]){if(!e)return null;let r=e.cloneNode(!0);if(t.includes("all"))["w:b","w:i","w:u","w:strike","w:dstrike","w:color","w:sz","w:szCs","w:rFonts","w:highlight","w:vertAlign","w:spacing","w:w","w:kern","w:position"].forEach(o=>{r.querySelectorAll(`${o}, ${o.replace("w:","")}`).forEach(dn)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(o=>{let a=n[o];a&&r.querySelectorAll(`${a}, ${a.replace("w:","")}`).forEach(dn)})}return r.children.length>0?r:null}function Lp(e,t,r){if(!t||!e)return e;let n=Vt(e);if(!n)return e;let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=n.getElementsByTagNameNS(o,"r"),i=n.getElementsByTagNameNS(o,"ins"),s=[...Array.from(a)];for(let l of i){let c=l.getElementsByTagNameNS(o,"r");s.push(...Array.from(c))}for(let l of s){let c=l.getElementsByTagNameNS(o,"t"),u=Array.from(c).map(f=>f.textContent).join("");if(u.includes(t)||u===t){let f=l.getElementsByTagNameNS(o,"rPr");if(f.length>0){let d=f[0],m=Wc(d,r);m?d.parentNode&&d.parentNode.replaceChild(m,d):dn(d)}}}return Cr(n)}var Bp={yellow:"yellow",green:"green",cyan:"cyan",magenta:"magenta",blue:"blue",red:"red",darkblue:"darkBlue",darkcyan:"darkCyan",darkgreen:"darkGreen",darkmagenta:"darkMagenta",darkred:"darkRed",darkyellow:"darkYellow",gray25:"lightGray",gray50:"darkGray",black:"black",white:"white"};function Dp(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=Bp[r.toLowerCase()]||"yellow",i=n?.generateRedlines??!1,s=n?.author||re(),l=t;l?l=t.cloneNode(!0):l=B(e,"w:rPr");let c=null;i&&(c=B(e,"w:rPr"),Array.from(l.childNodes).forEach(d=>{d.nodeName!=="w:rPrChange"&&c.appendChild(d.cloneNode(!0))}));let u=l.getElementsByTagNameNS(o,"highlight");Array.from(u).forEach(dn);let f=B(e,"w:highlight");if(f.setAttributeNS(o,"w:val",a),l.appendChild(f),i&&c){let d=B(e,"w:rPrChange"),m=ie(s,e);d.setAttribute("w:id",String(m.id)),d.setAttribute("w:author",m.author),d.setAttribute("w:date",m.date),d.appendChild(c);let p=l.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(dn),l.appendChild(d)}return l}function Ui(e,t,r="yellow",n={}){if(!t||!e)return e;let o=Vt(e);if(!o)return e;let a;n?._revisionIdAllocator instanceof Ae?(a=n._revisionIdAllocator,Ft(o,a)):a=tr(o);let i="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=f=>{let d=f.getElementsByTagNameNS(i,"t");return Array.from(d).map(m=>m.textContent).join("")},l=Array.from(o.getElementsByTagNameNS(i,"r")),c=new WeakSet,u=(f,d,m)=>{let p=f.cloneNode(!0);c.has(f)?Ot(p,a):c.add(f);let g=p.getElementsByTagNameNS(i,"t");Array.from(g).forEach(dn);let h=B(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=d,p.appendChild(h),m){let y=p.getElementsByTagNameNS(i,"rPr"),w=y.length>0?y[0]:null,v=Dp(o,w,r,n);w?p.replaceChild(v,w):p.insertBefore(v,p.firstChild)}return p};for(let f of l){let d=s(f);if(!d)continue;let m=[],p=0;for(;p<=d.length-t.length;){let w=d.indexOf(t,p);if(w===-1)break;m.push(w),p=w+t.length}if(m.length===0)continue;let g=f.parentNode;if(!g){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),y=0;for(let w of m)w>y&&h.appendChild(u(f,d.slice(y,w),!1)),h.appendChild(u(f,d.slice(w,w+t.length),!0)),y=w+t.length;y<d.length&&h.appendChild(u(f,d.slice(y),!1)),g.replaceChild(h,f)}return Cr(o)}var jt="application/vnd.openxmlformats-officedocument.wordprocessingml",to="http://schemas.openxmlformats.org/officeDocument/2006/relationships",jc=Object.freeze([{id:"document",path:"word/document.xml",pathPattern:null,contentType:`${jt}.document.main+xml`,legacyContentTypes:[],relType:`${to}/officeDocument`,relTarget:null,verified:!0},{id:"numbering",path:"word/numbering.xml",pathPattern:null,contentType:`${jt}.numbering+xml`,legacyContentTypes:[],relType:`${to}/numbering`,relTarget:"numbering.xml",verified:!1},{id:"comments",path:"word/comments.xml",pathPattern:null,contentType:`${jt}.comments+xml`,legacyContentTypes:[],relType:`${to}/comments`,relTarget:"comments.xml",verified:!0},{id:"commentsExtended",path:"word/commentsExtended.xml",pathPattern:null,contentType:`${jt}.commentsExtended+xml`,legacyContentTypes:["application/vnd.ms-word.commentsExtended+xml"],relType:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",relTarget:"commentsExtended.xml",verified:!0},{id:"commentsIds",path:"word/commentsIds.xml",pathPattern:null,contentType:`${jt}.commentsIds+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",relTarget:"commentsIds.xml",verified:!0},{id:"commentsExtensible",path:"word/commentsExtensible.xml",pathPattern:null,contentType:`${jt}.commentsExtensible+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible",relTarget:"commentsExtensible.xml",verified:!0},{id:"people",path:"word/people.xml",pathPattern:null,contentType:`${jt}.people+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2011/relationships/people",relTarget:"people.xml",verified:!1},{id:"header",path:null,pathPattern:/^word\/header\d+\.xml$/i,contentType:`${jt}.header+xml`,legacyContentTypes:[],relType:`${to}/header`,relTarget:null,verified:!0},{id:"footer",path:null,pathPattern:/^word\/footer\d+\.xml$/i,contentType:`${jt}.footer+xml`,legacyContentTypes:[],relType:`${to}/footer`,relTarget:null,verified:!0}].map(e=>Object.freeze(e))),Fp=new Map(jc.map(e=>[e.id,e]));function Fr(e){let t=Fp.get(e);if(!t)throw new Error(`Unknown package part: ${e}`);return t}function $p(e){return String(e||"").replace(/^\/+/,"")}function zi(e){let t=$p(e),r=t.toLowerCase();return jc.find(n=>n.path?n.path.toLowerCase()===r:n.pathPattern?.test(t))||null}function Kc(e,t){let r=zi(e);return!r||!r.legacyContentTypes.includes(t)?null:r.contentType}var Ue="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Up="http://schemas.openxmlformats.org/package/2006/content-types",zp="http://schemas.openxmlformats.org/package/2006/relationships",ji=Fr("numbering"),Ki=Fr("comments"),Hi=Fr("commentsExtended"),Gc=ji.relType,qc=ji.contentType,Yc=Ki.relType,Zc=Ki.contentType,Jc=Hi.relType,Xi=Hi.contentType,Hc=Fr("document").path,ga=ji.path,ro=Ki.path,Vi=Hi.path,Ye="[Content_Types].xml",ht="word/_rels/document.xml.rels";function Oe(e,t="xml"){let r=W(e,"application/xml");if(r.error||!r.doc){let n=new Error(`[XML parse error] ${t}: ${r.error?.message||"Unknown"}`);throw n.code="PARSE_ERROR",n}return r.doc}function ha(e){return!!e&&e.nodeType===1&&e.namespaceURI===Ue&&e.localName==="sectPr"}function Gi(e){return e.getElementsByTagNameNS("*","body")[0]||null}function Qc(e){for(let t of Array.from(e.childNodes||[]))if(ha(t))return t;return null}function Xp(e,t){let r=Qc(e);r?e.insertBefore(t,r):e.appendChild(t)}function wa(e){let t=Gi(e);if(!t)return;let r=Qc(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function Vp(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(Ue,"tc"),o=0;for(let a of Array.from(n)){let i=Array.from(a.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===Ue&&s.localName==="p");for(let s of i){let l=Array.from(s.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===Ue&&c.localName==="p");for(let c of l)a.insertBefore(c,s),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function Wi(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function Wp(e){let t=oe(),r=Oe(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(f=>Wi(f)==="/word/document.xml");if(!o)throw new Error("Package output missing /word/document.xml part");let a=o.getElementsByTagNameNS("*","xmlData")[0];if(!a)throw new Error("Package document part missing pkg:xmlData");let i=Array.from(a.childNodes||[]).find(f=>f.nodeType===1);if(!i)throw new Error("Package document part missing XML payload");let s=i.getElementsByTagNameNS("*","body")[0],l=s?Array.from(s.childNodes||[]).filter(f=>f.nodeType===1&&!ha(f)):[i],c=n.find(f=>Wi(f)==="/word/numbering.xml"),u=null;if(c){let f=c.getElementsByTagNameNS("*","xmlData")[0],d=f?Array.from(f.childNodes||[]).find(m=>m.nodeType===1):null;d&&(u=t.serializeToString(d))}return{replacementNodes:l,numberingXml:u,sourceType:"package"}}function qi(e){if(typeof e!="string"||!e.trim())return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:"Reconciliation engine returned no OOXML payload for this operation"}};try{if(e.includes("<pkg:package"))return Wp(e);if(e.includes("<w:document")){let o=Oe(e,"document OOXML"),a=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:a?Array.from(a.childNodes||[]).filter(s=>s.nodeType===1&&!ha(s)):Array.from(o.childNodes||[]).filter(s=>s.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${Ue}">${e}</root>`,r=Oe(t,"OOXML fragment");return{replacementNodes:Array.from(r.documentElement.childNodes||[]).filter(o=>o.nodeType===1),numberingXml:null,sourceType:"fragment"}}catch(t){return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:t?.message||"Could not parse OOXML payload."}}}}function Yi(e,t,r){let o=Array.from(e.getElementsByTagNameNS("*","Override")).find(i=>(i.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(o)return(o.getAttribute("ContentType")||"")===r?!1:(o.setAttribute("ContentType",r),!0);let a=e.createElementNS(Up,"Override");return a.setAttribute("PartName",t),a.setAttribute("ContentType",r),e.documentElement.appendChild(a),!0}function Zi(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,a=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(a.some(u=>(u.getAttribute("Type")||"")===t))return!1;let s=0;for(let u of a){let f=u.getAttribute("Id")||"",d=Number.parseInt(f.replace(/^rId/i,""),10);Number.isFinite(d)&&(s=Math.max(s,d))}let l=`rId${s+1}`,c=e.createElementNS(zp,"Relationship");return c.setAttribute("Id",l),c.setAttribute("Type",t),c.setAttribute("Target",r),o.appendChild(c),n?._receiptCollector?n._receiptCollector.recordRelationship(l):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(l),!0}async function Ke(e,t){let r=e.file(t);return r?r.async("string"):null}async function ya(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},o=typeof r?.mergeNumberingXml=="function"?r.mergeNumberingXml:null,a=typeof r?.onWarn=="function"?r.onWarn:vt,i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0)return;let s=await Ke(e,ga);s&&!o&&a("[Deprecation] Replacing an existing numbering.xml without mergeNumberingXml is deprecated and will throw in the next major version.");let l=s||null;for(let d of i){if(!l){l=d;continue}l=o?o(l,d):d}n(s?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(ga,l);let c=oe(),u=await Ke(e,Ye);if(u){let d=Oe(u,Ye);Yi(d,"/word/numbering.xml",qc)&&e.file(Ye,c.serializeToString(d))}let f=await Ke(e,ht);if(f){let d=Oe(f,ht);Zi(d,Gc,"numbering.xml",r)&&e.file(ht,c.serializeToString(d))}}async function Ji(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=oe(),a=await Ke(e,ro);if(!a||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(ro,t);else{let l=Oe(a,"word/comments.xml (existing)"),c=Oe(t,"word/comments.xml (incoming)"),u=l.documentElement,f=new Set(Array.from(u.getElementsByTagNameNS(Ue,"comment")).map(d=>d.getAttribute("w:id")||d.getAttribute("id")).filter(Boolean));for(let d of Array.from(c.documentElement.getElementsByTagNameNS(Ue,"comment"))){let m=d.getAttribute("w:id")||d.getAttribute("id");if(m&&f.has(m))throw new Error(`Duplicate comment id: ${m}`);u.appendChild(l.importNode(d,!0))}e.file(ro,o.serializeToString(l))}let i=await Ke(e,Ye);if(i){let l=Oe(i,Ye);Yi(l,"/word/comments.xml",Zc)&&e.file(Ye,o.serializeToString(l))}let s=await Ke(e,ht);if(s){let l=Oe(s,ht);Zi(l,Yc,"comments.xml",r)&&e.file(ht,o.serializeToString(l))}}async function va(e,t,r={}){if(!t)return;Oe(t,"word/commentsExtended.xml"),e.file(Vi,t);let n=oe(),o=await Ke(e,Ye);if(o){let i=Oe(o,Ye);Yi(i,"/word/commentsExtended.xml",Xi)&&e.file(Ye,n.serializeToString(i))}let a=await Ke(e,ht);if(a){let i=Oe(a,ht);Zi(i,Jc,"commentsExtended.xml",r)&&e.file(ht,n.serializeToString(i))}}async function mn(e){let t=await Ke(e,Ye);if(!t)return[];let r=Oe(t,Ye),n=[];for(let o of Array.from(r.getElementsByTagNameNS("*","Override"))){let a=o.getAttribute("PartName")||"",i=o.getAttribute("ContentType")||"",s=Kc(a,i);s&&(o.setAttribute("ContentType",s),n.push({partName:a,from:i,to:s}))}return n.length>0&&e.file(Ye,oe().serializeToString(r)),n}async function mr(e){let t=await Ke(e,Hc);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=Oe(t,Hc);wa(r);let n=Gi(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(h=>h.nodeType===1),a=o.map((h,y)=>({node:h,index:y})).filter(h=>ha(h.node)).map(h=>h.index);if(a.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(a.length===1&&a[0]!==o.length-1)throw new Error("Validation failed: w:sectPr not last");let i=r.getElementsByTagNameNS(Ue,"tc");for(let h of Array.from(i))for(let y of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(y.namespaceURI===Ue&&y.localName==="p"&&Array.from(y.childNodes||[]).some(v=>v.nodeType===1&&v.namespaceURI===Ue&&v.localName==="p"))throw new Error("Validation failed: nested w:p");let s=r.getElementsByTagNameNS(Ue,"numPr").length>0,l=r.getElementsByTagNameNS(Ue,"commentRangeStart").length>0||r.getElementsByTagNameNS(Ue,"commentRangeEnd").length>0||r.getElementsByTagNameNS(Ue,"commentReference").length>0,c=await Ke(e,ga),u=await Ke(e,ro),f=await Ke(e,Vi);if(f&&!u)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)Oe(c,ga);else if(s)throw new Error("Validation failed: numbering used but part missing");if(u){let h=Oe(u,ro),y=(k,C)=>Array.from(k.getElementsByTagNameNS(Ue,C)).map(M=>M.getAttribute("w:id")||M.getAttribute("id")).filter(M=>M!==""),w=new Set(y(r,"commentRangeStart")),v=new Set(y(r,"commentRangeEnd")),b=new Set(y(r,"commentReference")),x=y(h,"comment"),I=new Set(x),N=k=>Array.from(k).sort((C,M)=>Number(C)-Number(M)||C.localeCompare(M)),T=(k,C)=>N(new Set(Array.from(k).filter(M=>!C.has(M)))),E=N(new Set(x.filter((k,C)=>x.indexOf(k)!==C)));if(E.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${E.join(", ")}`);let S=T(w,v),O=T(v,w);if(S.length>0||O.length>0){let k=[];throw S.length>0&&k.push(`start without end: ${S.join(", ")}`),O.length>0&&k.push(`end without start: ${O.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${k.join("; ")})`)}let A=T(new Set([...w,...v]),b);if(A.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${A.join(", ")}`);let P=T(new Set([...w,...v,...b]),I);if(P.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${P.join(", ")}`);let _=new Set;if(f){let k=Oe(f,Vi),C=new Map;for(let X of Array.from(h.getElementsByTagNameNS("*","comment"))){let V=X.getAttribute("w:id")||X.getAttribute("id"),Y=tt(X);Y&&C.set(Y,V)}let M=new Set(C.keys()),$=new Set;for(let X of Array.from(k.getElementsByTagNameNS("*","commentEx"))){let V=X.getAttribute("w15:paraId")||X.getAttribute("paraId"),Y=X.getAttribute("w15:paraIdParent")||X.getAttribute("paraIdParent");if(!V||!M.has(V.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${V||"(missing)"}`);if($.has(V.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${V}`);if($.add(V.toUpperCase()),Y){if(!M.has(Y.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${Y}`);_.add(C.get(V.toUpperCase()))}}}let R=T(new Set([...I].filter(k=>!_.has(k))),b);if(R.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${R.join(", ")}`)}else if(l)throw new Error("Validation failed: comments used but part missing");let d=await Ke(e,Ye);if(!d)throw new Error(`Validation failed: missing ${Ye}`);let m=Oe(d,Ye),p=await Ke(e,ht);if(!p)throw new Error(`Validation failed: missing ${ht}`);let g=Oe(p,ht);if(c){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===qc),y=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Gc);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!y)throw new Error("Validation failed: numbering rel missing")}if(u){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===Zc),y=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Yc);if(!h)throw new Error("Validation failed: comments CT override missing");if(!y)throw new Error("Validation failed: comments rel missing")}{let h=new Map;for(let b of Array.from(g.getElementsByTagNameNS("*","Relationship")))h.set(b.getAttribute("Id")||"",{type:b.getAttribute("Type")||"",target:b.getAttribute("Target")||""});let y=Fr("header"),w=Fr("footer"),v=new Map(Array.from(m.getElementsByTagNameNS("*","Override")).map(b=>[(b.getAttribute("PartName")||"").toLowerCase(),b.getAttribute("ContentType")||""]));for(let b of[...Array.from(r.getElementsByTagNameNS(Ue,"headerReference")),...Array.from(r.getElementsByTagNameNS(Ue,"footerReference"))]){let x=b.getAttributeNS?.("http://schemas.openxmlformats.org/officeDocument/2006/relationships","id")||b.getAttribute("r:id")||"",I=b.localName==="headerReference"?y:w,N=h.get(x);if(!N)throw new Error(`Validation failed: ${b.localName} ${x||"(no r:id)"} has no document relationship`);if(N.type!==I.relType)throw new Error(`Validation failed: ${b.localName} ${x} points at a relationship of the wrong type (${N.type})`);let T=N.target.startsWith("/")?N.target:`/word/${N.target}`,E=await Ke(e,T.slice(1));if(!E)throw new Error(`Validation failed: ${b.localName} ${x} targets a missing part: ${T}`);Oe(E,T.slice(1));let S=v.get(T.toLowerCase());if(S!==I.contentType)throw new Error(`Validation failed: ${T} content type is ${S?`'${S}'`:"missing"}; Word expects '${I.contentType}'`)}}if(f){let h=Array.from(m.getElementsByTagNameNS("*","Override")).find(v=>(v.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml");if(h&&h.getAttribute("ContentType")!==Xi)throw new Error(`Validation failed: commentsExtended CT override has wrong content type '${h.getAttribute("ContentType")}' (Word expects '${Xi}')`);let y=!!h,w=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(v=>(v.getAttribute("Type")||"")===Jc);if(!y)throw new Error("Validation failed: commentsExtended CT override missing");if(!w)throw new Error("Validation failed: commentsExtended rel missing")}}var pn=Object.freeze({STRUCTURED_LIST_DIRECT:"structured_list_direct",EMPTY_FORMATTED_TEXT:"empty_formatted_text",EMPTY_HTML:"empty_html",BLOCK_HTML:"block_html",OOXML_ENGINE:"ooxml_engine"});function tu(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
|
|
210
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function jp(e={}){let t=e.originalText||"",r=tu(e.newContent||""),n=Xn(r)||{type:"text",items:[]};return r.includes(`
|
|
211
|
+
`)&&n.type!=="text"?{kind:pn.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:eu(t),hasInlineFormatting:xa(r),hasBlockElements:ba(r),hasMarkdownTable:no(r)}}:eu(t)?xa(r)?{kind:pn.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:ba(r),hasMarkdownTable:no(r)}}:{kind:pn.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:ba(r),hasMarkdownTable:no(r)}}:ba(r)?{kind:pn.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:xa(r),hasBlockElements:!0,hasMarkdownTable:no(r)}}:{kind:pn.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:xa(r),hasBlockElements:!1,hasMarkdownTable:no(r)}}}function eu(e){return!e||e.trim().length===0}function no(e){if(!e||!e.includes("|"))return!1;let t=at(e);return t.rows.length>0||t.headers.length>0}function xa(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function ba(e){if(!e)return!1;let t=/^[\s]*[-*+]\s+/m.test(e),r=/^[\s]*\d+\.\s+/m.test(e),n=/^[\s]*\d+\.\d+(?:\.\d+)*\.?\s+/m.test(e),o=/^[\s]*[A-Za-z]\.\s+/m.test(e),a=/^[\s]*[ivxlcIVXLC]+\.\s+/m.test(e),i=/^[\s]*\([a-z]\)\s+/m.test(e),s=/\|.*\|.*\n/.test(e),l=/^#{1,9}\s/m.test(e),c=e.includes(`
|
|
211
212
|
|
|
212
|
-
`);return t||r||n||o||i||
|
|
213
|
-
`);if(a){let l=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=l.exec(a))!==null;)i.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=l.exec(e.documentXml))!==null;)i.add(c[1])}let s=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let l=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=l.exec(e.relationshipsXml))!==null;)s.add(c[1])}for(let l of r){if(Array.isArray(l.revisionItems)){for(let c of l.revisionItems)if(c.partName==="word/document.xml"&&!n.has(String(c.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${c.id}' (kind: ${c.kind}) was not found in word/document.xml.`}}}if(Array.isArray(l.commentIds)){for(let c of l.commentIds)if(!o.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${c}' was not found in word/comments.xml.`}}}if(Array.isArray(l.numberingIds)){for(let c of l.numberingIds)if(!i.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(l.relationshipIds)){for(let c of l.relationshipIds)if(!s.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}async function ws(e,t,r,n={}){let o=await uo(e,t,r,n);if(o?.useNativeApi&&typeof o?.oxml!="string"){let i=Array.isArray(o?.warnings)?o.warnings:[];return se({...o,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return o}async function ww(e,t,r,n={}){let o=typeof e=="string"?e:"",i=typeof r=="string"?r:String(r||""),a;try{a=Xe(i)}catch{a={headers:[],rows:[]}}return(a?.headers?.length||0)>0||(a?.rows?.length||0)>0?{...await ws(o,t||"",i,n),isMarkdownTable:!0,tableData:a}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function bw(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,i=n.sanitizeInput===!0?fo(r):r,a=i!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],s=bo({oxml:e,originalText:t,modifiedText:i,allowExistingList:o}),l=n.preferListStructuralFallback!==!1,c=[];if(s&&l){let h=await un(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(h?.hasChanges&&h?.oxml){let w=it(h.oxml,{includeNumbering:h.includeNumbering??!0,numberingXml:h.numberingXml}),b=Array.isArray(h?.warnings)?h.warnings:[];return se({oxml:w,hasChanges:!0,warnings:[...a,...b],listStructuralFallbackApplied:!0,listStructuralFallbackKey:h.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:h.numberingXml||null})}c=Array.isArray(h?.warnings)?h.warnings:[]}let u=await ws(e,t,r,n);if(!s)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(l)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(u?.hasChanges)return{...u,listStructuralFallbackApplied:!1};let f=await un(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let h=Array.isArray(u?.warnings)?u.warnings:[],w=Array.isArray(f?.warnings)?f.warnings:[];return{...u,warnings:[...h,...w],listStructuralFallbackApplied:!1}}let m=it(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),d=Array.isArray(u?.warnings)?u.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return se({...u,oxml:m,hasChanges:!0,warnings:[...d,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{Pt as ContainerKind,Yo as ContentType,ke as DiffOp,E as NS_W,Je as NumberingService,Mo as ReceiptCollector,ar as ReconciliationPipeline,Kt as RoutePlanKind,D as RunKind,Oe as WORD_MAIN_NS,oo as acceptTrackedChangesInOoxml,Wr as analyzeStructuredContent,lf as applyCommentReplyToParts,cf as applyFormattingRemovalToOoxml,mf as applyHighlightToOoxml,ws as applyRedlineToOxml,bw as applyRedlineToOxmlWithListFallback,Hu as areRevisionTokensEqual,vr as buildCommentElement,Ao as buildCommentsPartXml,Ou as buildExplicitDecimalMultilevelNumberingXml,Qc as buildListMarkdown,Sf as buildReconciliationPlan,So as buildRevisionTokenFraming,bo as buildSingleLineListStructuralFallbackPlan,Vc as buildTargetReferenceSnapshot,au as clearSingleLineListFallbackExplicitSequence,Oa as collectContiguousListParagraphBlock,Uu as computeDocumentPartsRevisionToken,ja as computeRevisionToken,To as computeRevisionTokenSync,Ps as configureLogger,Rs as configureXmlProvider,zr as containsTrackedChanges,Eu as createDynamicNumberingIdState,Ef as createEmptyReceipt,St as createParagraphFingerprint,kc as deleteCommentsByAuthorInOoxml,su as enforceListBindingOnParagraphNodes,Nf as ensureCommentsArtifactsInZip,vf as ensureCommentsExtendedArtifactsInZip,xf as ensureNumberingArtifactsInZip,Ne as escapeXml,un as executeSingleLineListStructuralFallback,fe as extractCanonicalParagraphText,dn as extractDocumentPartsEntries,Cu as extractFirstParagraphNumId,Tf as extractParagraphIdFromOoxml,Kr as extractParagraphRevisionSegments,bf as extractReplacementNodesFromOoxml,Dt as findContainingWordElement,mo as findParagraphByBestTextMatch,Ea as findParagraphByReference,on as findParagraphByStrictText,an as findStrictTargetCandidates,ht as generateTableOoxml,Co as getBodyElementFromDocument,pe as getDefaultAuthor,Te as getDocumentParagraphNodes,Ro as getPackagePartName,Tt as getParagraphId,tt as getParagraphListInfo,ue as getParagraphText,En as getPlatform,Dn as getTrackedChangeAuthors,wo as hasListItems,Qt as inferNumberingStyleFromMarker,Su as inferTableReplacementParagraphBlock,kt as ingestOoxml,Wu as ingestWordOoxmlToMarkdown,Wa as ingestWordOoxmlToMarkdownResult,zu as ingestWordOoxmlToPlainText,za as ingestWordOoxmlToPlainTextResult,of as injectCommentsIntoOoxml,af as injectCommentsIntoPackage,gf as insertBodyElementBeforeSectPr,rf as inspectDocumentParts,La as isLikelyStructuredTableSourceParagraph,go as isMarkdownTableText,bt as isNodeVisibleInRevisionView,Mu as mergeNumberingXmlBySchemaOrder,ps as normalizeBodySectionOrderStandalone,hs as normalizeContentEscapesForRouting,eu as normalizeListItemsWithLevels,Ua as normalizeOpcEntryName,H as normalizeWhitespaceForTargeting,Ru as overwriteParagraphNumIds,wr as parseMarkdownListContent,et as parseOoxml,j as parseOoxmlSafe,ho as parseParagraphReference,Zc as planListInsertionOnlyEdit,Bl as planStructuredReplacement,Ie as preprocessMarkdown,xt as readCanonicalRunText,ww as reconcileMarkdownTableOoxml,Af as reconcileReceiptsAgainstOutput,iu as recordSingleLineListFallbackExplicitSequence,io as rejectTrackedChangesInOoxml,ku as remapNumberingPayloadForDocument,is as removeFormattingFromRPr,xr as reserveNextNumberingId,Iu as reserveNextNumberingIdPair,Gc as resolveParagraphRangeByRefs,ou as resolveSingleLineListFallbackNumberingAction,Aa as resolveTargetParagraph,po as resolveTargetParagraphWithSnapshot,fo as sanitizeAiResponse,hf as sanitizeNestedParagraphsInTables,yt as serializeOoxml,$e as serializeToOoxml,ks as setDefaultAuthor,Ms as setPlatform,Wc as splitLeadingParagraphMarker,zc as stripLeadingParagraphMarker,Ra as stripRedundantLeadingListMarkers,ru as stripSingleLineListMarkerPrefix,qc as synthesizeExpandedListScopeEdit,Tu as synthesizeTableMarkdownFromMultilineCellEdit,yf as validateDocxPackage,bu as validateRedlineOoxml,ju as validateRevisionToken,it as wrapInDocumentFragment};
|
|
213
|
+
`);return t||r||n||o||a||i||s||l||c}function Kp(e){if(!e||typeof e!="string")return null;let t=e.match(/\b(?:w14:paraId|w:paraId|paraId)="([^"]+)"/i);return t?t[1]:null}var oo=class{constructor(){this.receipts=[],this.activeReceipt=null}beginOperation(t,r=null,n=null){this.activeReceipt={operationIndex:typeof t=="number"?t:1,...r?{operationId:String(r)}:{},attemptedDisposition:"applied",finalDisposition:"applied",committed:!0,...n?{authorUsed:String(n)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}recordRevision(t,r="structural",n="word/document.xml"){if(!this.activeReceipt||t==null)return;let o=String(t);this.activeReceipt.revisionItems.some(a=>a.id===o&&a.kind===r&&a.partName===n)||this.activeReceipt.revisionItems.push({id:o,kind:r,partName:n})}recordComment(t,r="word/comments.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.commentIds.includes(n)||this.activeReceipt.commentIds.push(n)}recordNumbering(t,r="word/numbering.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.numberingIds.includes(n)||this.activeReceipt.numberingIds.push(n)}recordRelationship(t,r="word/_rels/document.xml.rels"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.relationshipIds.includes(n)||this.activeReceipt.relationshipIds.push(n)}recordAffectedTarget(t){!this.activeReceipt||!t||this.activeReceipt.affectedTargets.push(JSON.parse(JSON.stringify(t)))}recordWarning(t){!this.activeReceipt||!t||this.activeReceipt.warnings.push(String(t))}commitOperation(t="applied"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=t==="applied";let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.receipts.push(r),this.activeReceipt=null,r}abortOperation(t="refused"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=!1;let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.activeReceipt=null,r}createSavepoint(){return{receipts:JSON.parse(JSON.stringify(this.receipts)),activeReceipt:this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}}restoreSavepoint(t){t&&(this.receipts=Array.isArray(t.receipts)?JSON.parse(JSON.stringify(t.receipts)):[],this.activeReceipt=t.activeReceipt?JSON.parse(JSON.stringify(t.activeReceipt)):null)}clear(){this.receipts=[],this.activeReceipt=null}markRolledBack(){for(let t of this.receipts)t.attemptedDisposition==="applied"&&(t.finalDisposition="rolled_back",t.committed=!1);this.activeReceipt=null}getReceipts(){return JSON.parse(JSON.stringify(this.receipts))}getCurrentReceipt(){return this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}};function _e(e,t=null,r=null,n="not_attempted"){return{operationIndex:typeof e=="number"?e:1,...t?{operationId:String(t)}:{},attemptedDisposition:n,finalDisposition:n,committed:!1,...r?{authorUsed:String(r)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}function ao(e,t){if(!Array.isArray(t)||t.length===0)return{valid:!0};let r=t.filter(l=>l&&l.committed===!0&&l.finalDisposition==="applied");if(r.length===0)return{valid:!0};let n=new Set;if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?(?:ins|del|rPrChange|pPrChange|moveFrom|moveTo)\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=l.exec(e.documentXml))!==null;)n.add(c[1])}let o=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let l=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=l.exec(e.commentsXml))!==null;)o.add(c[1])}let a=new Set,i=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
|
|
214
|
+
`);if(i){let l=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=l.exec(i))!==null;)a.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=l.exec(e.documentXml))!==null;)a.add(c[1])}let s=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let l=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=l.exec(e.relationshipsXml))!==null;)s.add(c[1])}for(let l of r){if(Array.isArray(l.revisionItems)){for(let c of l.revisionItems)if(c.partName==="word/document.xml"&&!n.has(String(c.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${c.id}' (kind: ${c.kind}) was not found in word/document.xml.`}}}if(Array.isArray(l.commentIds)){for(let c of l.commentIds)if(!o.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${c}' was not found in word/comments.xml.`}}}if(Array.isArray(l.numberingIds)){for(let c of l.numberingIds)if(!a.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(l.relationshipIds)){for(let c of l.relationshipIds)if(!s.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}var ru="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Hp="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Gp=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tcPrChange","trPrChange","numberingChange"]),qp=new Set(["ins","del","moveFrom","moveTo"]),Na=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function Yp(e){let t=String(e||"");if(t.startsWith("/"))return t.replace(/^\/+/,"");let r=["word"];for(let n of t.split("/"))n===".."?r.pop():n&&n!=="."&&r.push(n);return r.join("/")}function Qi({documentXml:e,relsXml:t=null,settingsXml:r=null}){if(!e||!t)return[];let n=W(e,"application/xml"),o=W(t,"application/xml");if(!n.doc||n.error||!o.doc||o.error)return[];let a=new Map;for(let u of Array.from(o.doc.getElementsByTagNameNS("*","Relationship")))a.set(u.getAttribute("Id")||"",u.getAttribute("Target")||"");let i=!!r&&/<w:evenAndOddHeaders\b(?![^>]*w:val="(?:0|false|off)")/.test(r),s=new Map,l=new Map;return Array.from(n.doc.getElementsByTagNameNS(ru,"sectPr")).forEach((u,f)=>{let d=Array.from(u.childNodes||[]).some(m=>m.localName==="titlePg"&&!/^(0|false|off)$/i.test(Na(m,"w:val","val")));for(let m of Array.from(u.childNodes||[])){if(m.nodeType!==1||m.localName!=="headerReference"&&m.localName!=="footerReference")continue;let p=m.getAttributeNS?.(Hp,"id")||m.getAttribute("r:id")||"",g=a.get(p);if(!g)continue;let h=Yp(g),y=m.localName==="headerReference"?"header":"footer",w=Na(m,"w:type","type")||"default",v=s.get(h)||{path:h,kind:y,type:w,sections:[],applies:[],titlePgSections:0};v.sections.includes(f)||v.sections.push(f),d&&(v.titlePgSections+=1),s.set(h,v),l.set(`${y}:${w}`,h)}for(let m of l.values()){let p=s.get(m);p&&!p.applies.includes(f)&&p.applies.push(f)}}),Array.from(s.values()).map(u=>({path:u.path,kind:u.kind,type:u.type,sections:u.sections,appliesToSections:u.applies,sharedBySections:u.applies.length>1,active:u.type==="first"?u.titlePgSections>0:u.type==="even"?i:!0}))}function es(e,t){let r=a=>({path:a.path,kind:a.kind,type:a.type,sections:a.sections,appliesToSections:a.appliesToSections});if(typeof t=="string"){let a=t.replace(/^\/+/,"").toLowerCase(),i=e.find(s=>s.path.toLowerCase()===a||s.path.toLowerCase()===`word/${a}`);return i?{part:i}:{error:{code:"PART_NOT_FOUND",message:`No header/footer part '${t}' is referenced by the document.`,candidates:e.map(r)}}}if(!t||typeof t!="object"||t.kind!=="header"&&t.kind!=="footer")return{error:{code:"INVALID_OPERATION",message:'part must be a part path or { kind: "header"|"footer", type?: "default"|"first"|"even", section?: number }.'}};let n=t.type||"default";if(!["default","first","even"].includes(n))return{error:{code:"INVALID_OPERATION",message:`part.type must be default, first or even (got '${n}').`}};let o=e.filter(a=>a.kind===t.kind&&a.type===n);return Number.isInteger(t.section)&&(o=o.filter(a=>a.appliesToSections.includes(t.section))),o.length===1?{part:o[0]}:o.length===0?{error:{code:"PART_NOT_FOUND",message:`The document has no ${n} ${t.kind}${Number.isInteger(t.section)?` for section ${t.section}`:""}.`,candidates:e.map(r)}}:{error:{code:"PART_AMBIGUOUS",message:`Several ${n} ${t.kind} parts exist; add "section" or use the part path.`,candidates:o.map(r)}}}function nu(e){let t=zi(e);return t?.id==="header"||t?.id==="footer"}function ts(e){let t=W(e,"application/xml");if(!t.doc||t.error)return 0;let r=0,n=0,o=a=>{for(let i of Array.from(a.childNodes||[])){if(i.nodeType!==1)continue;let s=i.localName;if(s==="fldChar"){let l=Na(i,"w:fldCharType","fldCharType");l==="begin"?r+=1:l==="end"&&(r=Math.max(0,r-1));continue}if(qp.has(s)&&r>0&&(n+=1),s==="fldSimple"){r+=1,o(i),r-=1;continue}o(i)}};return o(t.doc.documentElement),n}function ou(e){let t=new Set;for(let r of String(e||"").matchAll(/<w:(?:ins|del|moveFrom|moveTo|rPrChange|pPrChange|sectPrChange|tblPrChange|tblGridChange|tcPrChange|trPrChange|numberingChange)\b[^>]*?\bw:id="(\d+)"/g))t.add(r[1]);return t}function au(e,t){let r=W(e,"application/xml");if(!r.doc||r.error)return{xml:e,renumbered:0,idMap:new Map};let n=new Map,o=1+Math.max(0,...Array.from(t,l=>Number(l)).filter(Number.isFinite)),a=new Set(t),i=0,s=l=>{for(let c of Array.from(l.childNodes||[]))if(c.nodeType===1){if(Gp.has(c.localName)){let u=Na(c,"w:id","id");if(u&&a.has(u)){for(;a.has(String(o));)o+=1;c.setAttributeNS(ru,"w:id",String(o)),n.set(u,String(o)),a.add(String(o)),i+=1}else u&&a.add(u)}s(c)}};return s(r.doc.documentElement),i>0?{xml:oe().serializeToString(r.doc),renumbered:i,idMap:n}:{xml:e,renumbered:0,idMap:n}}var Zp=Object.freeze({INVALID_OPERATION:["request","request_fixable","change_request"],INVALID_AGENT_REQUEST:["request","request_fixable","change_request"],INVALID_FILTER:["request","request_fixable","change_request"],INVALID_OPERATIONS_FILE:["request","request_fixable","change_request"],OPERATIONS_REQUIRED:["request","request_fixable","change_request"],UNKNOWN_OPTION:["request","request_fixable","change_request"],UNEXPECTED_ARGUMENT:["request","request_fixable","change_request"],INVALID_ACTION:["request","request_fixable","change_request"],INVALID_PROFILE:["request","request_fixable","change_request"],INVALID_REVISION_TOKEN:["revision-check","request_fixable","change_request"],BATCH_OPERATION_FAILED:["batch-execution","request_fixable","inspect_failed_operations"],REVISION_TOKEN_SCOPE_MISMATCH:["revision-check","request_fixable","change_request"],REVISION_MISMATCH:["revision-check","target_refresh_required","reinspect"],TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],SOURCE_TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],TARGET_TEXT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_FINGERPRINT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_INDEX_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_OCCURRENCE_MISMATCH:["target-resolution","candidate_selection_required","choose_candidate"],STALE_TARGET_HANDLE:["target-resolution","target_refresh_required","reinspect"],TARGET_HANDLE_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],AMBIGUOUS_TARGET:["target-resolution","candidate_selection_required","choose_candidate"],TARGET_RANGE_INVALID:["target-resolution","request_fixable","change_target_range"],ANCHOR_NOT_FOUND:["anchor-resolution","request_fixable","change_anchor"],AMBIGUOUS_ANCHOR:["anchor-resolution","candidate_selection_required","choose_candidate"],PATCH_SOURCE_NOT_FOUND:["patch-compilation","request_fixable","change_patch"],AMBIGUOUS_PATCH_SOURCE:["patch-compilation","candidate_selection_required","choose_occurrence"],OVERLAPPING_PATCHES:["patch-compilation","source_conflict","combine_patches"],CONFLICTING_PATCHES:["patch-compilation","source_conflict","combine_patches"],PATCH_ROUNDTRIP_MISMATCH:["patch-validation","request_fixable","reinspect_and_narrow"],DIFF_TOKEN_LIMIT:["patch-compilation","request_fixable","narrow_operation"],STRUCTURED_CONTENT_INVALID:["request","request_fixable","change_request"],UNSUPPORTED_INSERTION_AFFINITY:["request","request_fixable","change_request"],EXISTING_REVISIONS:["target-safety","policy_choice_required","set_option"],PART_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PART_AMBIGUOUS:["target-resolution","candidate_selection_required","choose_candidate"],COMMENT_IN_HEADER_FOOTER:["request","request_fixable","change_request"],FIELD_EDIT_REFUSED:["target-safety","request_fixable","change_request"],COMMENT_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PARENT_ANCHOR_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],COMMENTED_CONTENT_MERGE:["target-safety","user_authorization_required","resolve_comments"],COMMENTED_CONTENT_DELETE:["target-safety","user_authorization_required","resolve_comments"],OVERLAPPING_SOURCE_TARGETS:["batch-compilation","source_conflict","consolidate_operations"],OVERLAPPING_TEXT_EDITS:["batch-compilation","source_conflict","consolidate_operations"],REVISION_ORDER_CONFLICT:["batch-compilation","source_conflict","split_or_consolidate_operations"],TARGET_CONSUMED_BY_OPERATION:["batch-execution","source_conflict","use_created_content_dependency"],CAPTURE_FANOUT_CONFLICT:["batch-compilation","source_conflict","split_or_chain_capture_consumers"],DUPLICATE_CAPTURE_KEY:["batch-compilation","request_fixable","rename_capture"],CAPTURE_NOT_FOUND:["batch-compilation","request_fixable","add_or_correct_capture"],CAPTURE_DEPENDENCY_CYCLE:["batch-compilation","source_conflict","replan_batch"],AMBIGUOUS_CAPTURE_SELECTION:["batch-compilation","candidate_selection_required","choose_candidate"],CAPTURE_STALE:["batch-execution","source_conflict","replan_batch"],GENERATED_OOXML_INVALID:["validation","library_or_builder_failure","report_library_failure"],DOCUMENT_SERIALIZATION_FAILED:["serialization","library_or_builder_failure","report_library_failure"],PACKAGE_OPERATION_FAILED:["package","library_or_builder_failure","report_library_failure"],PACKAGE_VALIDATION:["package-validation","library_or_builder_failure","report_library_failure"],MUTATION_RECEIPT_MISMATCH:["receipt-validation","library_or_builder_failure","report_library_failure"],FOREIGN_PARAGRAPH_MARK_DELETION:["target-safety","policy_choice_required","use_restore_or_leave_deleted"],RESTORATION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],RESTORATION_COUNT_MISMATCH:["request","request_fixable","change_request"],REJECTED_INSERTION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],UNSAFE_REVISION_NESTING:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_REVISION_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_DELETED_TABLE_ROW:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_MOVE_REVISION:["target-safety","manual_document_resolution","manual_resolution"],SECTION_BREAK_PARAGRAPH:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_PLACEMENT:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_REVISION_VIEW_MUTATION:["target-safety","manual_document_resolution","manual_resolution"]});function Jp(e){let t=Array.isArray(e?.generatedIssues)?e.generatedIssues:Array.isArray(e?.issues)?e.issues:null;if(!t)return null;let r=new Map;for(let n of t){let o=n?.code||"UNKNOWN";r.set(o,(r.get(o)||0)+1)}return{total:t.length,byCode:Array.from(r,([n,o])=>({code:n,count:o}))}}function Qp(e){return Zp[e]||["operation","manual_document_resolution","inspect_error"]}function Ze(e,t={}){let r=e&&typeof e=="object"?e:{},n=typeof r.code=="string"&&r.code?r.code:"OPERATION_ERROR",[o,a,i]=Qp(n),s={};for(let[m,p]of Object.entries(r))m==="name"||m==="stack"||m==="message"||m==="code"||(s[m]=p);let u={action:i,sameArgumentsSafe:!1,requiresReinspection:a==="target_refresh_required"||n==="PATCH_ROUNDTRIP_MISMATCH",requiresUserAuthorization:a==="user_authorization_required",...n==="EXISTING_REVISIONS"?{field:"existingRevisions",recommendedValue:"slice-cross-author"}:{},...r.recovery&&typeof r.recovery=="object"?r.recovery:{}},f=Jp(r),d={...t,...Array.isArray(r.revisionAuthors)?{revisionAuthors:r.revisionAuthors}:{},...r.currentPolicy?{currentPolicy:r.currentPolicy}:{}};return["TARGET_TEXT_MISMATCH","TARGET_FINGERPRINT_MISMATCH"].includes(n)&&Array.isArray(r.candidates)&&r.candidates.length===1&&(d.currentTarget=r.candidates[0],d.requiresRecomposeModified=!0),{recoveryVersion:1,code:n,message:r.message||String(e),stage:r.stage||o,category:r.category||a,...s,...Object.keys(d).length>0||r.context?{context:{...r.context||{},...d}}:{},...f?{issueSummary:f}:{},recovery:u}}function Kt({atomic:e=!1,rolledBack:t=!1,results:r=[],receipts:n=[],operationCount:o=null}={}){let a=Number.isInteger(o)?o:Math.max(r.length,n.length),i=new Set(r.map(f=>f?.index).filter(Number.isInteger)),s=r.filter(f=>f?.status==="error").map(f=>f.index).filter(Number.isInteger),l=n.filter(f=>f?.committed===!0).map(f=>f.operationIndex).filter(Number.isInteger),c=[];for(let f=1;f<=a;f+=1)i.has(f)||c.push(f);let u=t||e||l.length===0?"original":"output";return{base:u,committedIndexes:l,failedIndexes:s,unattemptedIndexes:c,replayWholeBatch:u==="original",sameArgumentsSafe:!1}}function $r(e,t,r){return Ze({code:r,message:e,...t?{field:t}:{},recovery:{action:"change_request",sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function Ia(e,t,r,n,o={}){return Ze({code:e,message:t,field:r,...o,recovery:{action:n,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function eg(e,t){let r=[],n=0;for(;n<=e.length-t.length;){let o=e.indexOf(t,n);if(o<0)break;r.push(o),n=o+1}return r}function io(e,t){return(e===" "||e==="\xA0")&&(t===" "||t==="\xA0")}function tg(e,t){let r=[];for(let n=0;n<=e.length-t.length;n+=1){let o=!0;for(let a=0;a<t.length;a+=1){let i=e[n+a],s=t[a];if(i!==s&&!io(i,s)){o=!1;break}}o&&r.push(n)}return r}function rg(e,t){let r=eg(e,t);return r.length>0?{offsets:r,matchMode:"exact"}:{offsets:tg(e,t),matchMode:"space_equivalent"}}function ng(e,t,r){let n=r.split(""),o=0;for(;o<t.length&&o<r.length&&(t[o]===r[o]||io(t[o],r[o]));)io(e[o],r[o])&&(n[o]=e[o]),o+=1;let a=t.length-1,i=r.length-1;for(;a>=o&&i>=o&&(t[a]===r[i]||io(t[a],r[i]));)io(e[a],r[i])&&(n[i]=e[a]),a-=1,i-=1;return n.join("")}function og(e,t,r){let n=Math.max(0,t-40),o=Math.min(e.length,t+r+40);return{start:t,end:t+r,excerpt:e.slice(n,o)}}function iu(e,t,r,n=120){let o=String(e??""),a=Math.max(0,Math.min(o.length,t)),i=Math.max(a,Math.min(o.length,r)),s=Math.floor((a+i)/2),l=Math.max(0,s-Math.floor(n/2)),c=Math.min(o.length,l+n);l=Math.max(0,c-n);let u=l>0?"\u2026":"",f=c<o.length?"\u2026":"",d=Math.max(0,n-u.length-f.length);return`${u}${o.slice(l,l+d)}${f}`}function Ta(e,t="replacements",{invalidCode:r="INVALID_OPERATION"}={}){if(!Array.isArray(e)||e.length===0)return{ok:!1,error:$r("replacements must be a non-empty array.",t,r)};let n=[];for(let o=0;o<e.length;o+=1){let a=e[o],i=`${t}[${o}]`;if(!a||typeof a!="object"||Array.isArray(a))return{ok:!1,error:$r(`${i} must be an object.`,i,r)};if(typeof a.find!="string"||a.find.length===0)return{ok:!1,error:$r(`${i}.find must be a non-empty string.`,`${i}.find`,r)};if(typeof a.replace!="string")return{ok:!1,error:$r(`${i}.replace must be a string.`,`${i}.replace`,r)};if(a.find===a.replace)return{ok:!1,error:$r(`${i} must change the matched text.`,i,r)};let s=a.occurrence==null?null:Number(a.occurrence);if(s!=null&&(!Number.isInteger(s)||s<1))return{ok:!1,error:$r(`${i}.occurrence must be a positive integer.`,`${i}.occurrence`,r)};n.push({find:a.find,replace:a.replace,...s==null?{}:{occurrence:s}})}return{ok:!0,replacements:n}}function su(e,t,r="replacements",n={}){let o=n.invalidCode||"INVALID_OPERATION";if(typeof e!="string")return{ok:!1,error:$r("Localized replacements require string source text.",r,o)};let a=Ta(t,r,{invalidCode:o});if(!a.ok)return a;let i=[];for(let u=0;u<a.replacements.length;u+=1){let f=a.replacements[u],d=`${r}[${u}]`,m=f.occurrence??null,{offsets:p,matchMode:g}=rg(e,f.find);if(p.length===0||m!=null&&m>p.length)return{ok:!1,error:Ia("PATCH_SOURCE_NOT_FOUND",m==null?`Patch source was not found: "${f.find}".`:`Occurrence ${m} of patch source was not found: "${f.find}".`,d,"change_patch",{matchCount:p.length})};if(m==null&&p.length>1)return{ok:!1,error:Ia("AMBIGUOUS_PATCH_SOURCE",`Patch source matched ${p.length} locations; provide occurrence.`,d,"choose_occurrence",{candidates:p.map(w=>og(e,w,f.find.length))})};let h=p[(m||1)-1],y=e.slice(h,h+f.find.length);i.push({requestIndex:u,start:h,end:h+f.find.length,find:f.find,replace:f.replace,effectiveReplace:g==="space_equivalent"?ng(y,f.find,f.replace):f.replace,matchMode:g,occurrence:m||1})}i.sort((u,f)=>u.start-f.start||u.end-f.end||u.requestIndex-f.requestIndex);let s=[];for(let u of i){let f=s.at(-1);if(f&&u.start===f.start&&u.end===f.end){if(u.effectiveReplace!==f.effectiveReplace)return{ok:!1,error:Ia("CONFLICTING_PATCHES",`Localized replacements ${f.requestIndex+1} and ${u.requestIndex+1} assign different text to the same source range.`,r,"combine_patches",{replacementIndexes:[f.requestIndex+1,u.requestIndex+1]})};continue}if(f&&u.start<f.end)return{ok:!1,error:Ia("OVERLAPPING_PATCHES",`Localized replacements ${f.requestIndex+1} and ${u.requestIndex+1} overlap.`,r,"combine_patches",{replacementIndexes:[f.requestIndex+1,u.requestIndex+1]})};s.push(u)}let l=0,c="";for(let u of s)c+=e.slice(l,u.start),c+=u.effectiveReplace,l=u.end;return c+=e.slice(l),{ok:!0,desiredText:c,replacements:s.map(u=>({requestIndex:u.requestIndex+1,start:u.start,end:u.end,find:u.find,replace:u.replace,matchMode:u.matchMode,occurrence:u.occurrence,removedLength:u.end-u.start,insertedLength:u.effectiveReplace.length}))}}function lu(e,t,r={},n=null){if(!e||typeof e!="object")return null;let o=String(e.sourceText??""),a=String(e.desiredText??""),i=Array.isArray(e.replacements)?e.replacements:[],s=0,l=i.map(c=>{let u=c.start+s,f=u+c.replace.length;return s+=c.replace.length-(c.end-c.start),{find:c.find,replace:c.replace,...c.matchMode==="space_equivalent"?{matchMode:c.matchMode}:{},occurrence:c.occurrence,beforeExcerpt:iu(o,c.start,c.end),afterExcerpt:iu(a,u,f)}});return{kind:"localized_replacement",committed:!0,finalDisposition:"applied",target:{...r.paragraphId?{paragraphId:r.paragraphId}:{},...Number.isInteger(r.index)?{index:r.index}:{},...r.fingerprint?{fingerprint:r.fingerprint}:{},...n?.humanReference?{humanReference:n.humanReference}:{}},...n?{context:{...n}}:{},replacements:l,verification:{acceptedViewMatchesCompiledText:typeof t=="string"&&t===a}}}var ag=new Set(["redline","replace","format","character-format","paragraph-format","list-change","table-reconciliation","insert","restore","delete","comment","comment_reply","comment_resolve","highlight"]),cu=Object.freeze(["merge-same-author","slice-cross-author","reject-input","accept-all-first","accept-all-first-keep-normalized"]);function so(e){return cu.includes(e)}function Et(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function we(e){return typeof e=="string"&&e.trim().length>0}function ig(e){return e==="comment_reply"||e==="comment_resolve"}function sg(e){let t=e?.type;return t==="insert"&&e?.target?.revisionView==="rejected"?"rejected-insert":t==="restore"?"restore":t==="comment"||t==="comment_reply"||t==="comment_resolve"||t==="highlight"?t:t==="paragraph-format"?"paragraph-format":t==="character-format"||t==="format"&&(e?.textToFormat!=null||e?.properties!=null)?"format":"redline"}function Sa(e,t=null,r="accepted"){let n=r==="rejected"?"rejected":"accepted";return Et(e)?{text:typeof e.exactText=="string"?e.exactText:typeof e.text=="string"?e.text:"",index:e.index??e.paragraphIndex??t??null,paragraphId:we(e.paragraphId)?e.paragraphId.trim():null,occurrence:Number.isInteger(e.occurrence)&&e.occurrence>0?e.occurrence:null,inTable:typeof e.inTable=="boolean"?e.inTable:null,fingerprint:we(e.fingerprint)?e.fingerprint.trim():we(e.sourceFingerprint)?e.sourceFingerprint.trim():null,revisionView:e.revisionView==="rejected"?"rejected":e.revisionView==="accepted"?"accepted":n,captureRef:we(e.captureRef)?e.captureRef.trim():null,select:typeof e.select=="string"?e.select:null}:{text:typeof e=="string"?e:"",index:t??null,paragraphId:null,occurrence:null,inTable:null,fingerprint:null,revisionView:n}}function rt(e){let t=Et(e)?e:{},r=sg(t),n=r==="restore"?"rejected":"accepted",o=Sa(t.target,t.targetRef,n),a=t.targetEnd!=null?Sa(t.targetEnd,t.targetEndRef,n):null;return{...t,operationId:we(t.operationId)?t.operationId.trim():null,captureKey:we(t.captureKey)?t.captureKey.trim():null,operationKind:r,anchor:Et(t.anchor)?{exactText:typeof t.anchor.exactText=="string"?t.anchor.exactText:"",occurrence:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0?t.anchor.occurrence:1,occurrenceExplicit:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0,offset:Number.isInteger(t.anchor.offset)?t.anchor.offset:null}:null,targetDescriptor:o,targetEndDescriptor:a,target:o.text,targetRef:o.index,targetEndRef:a?.index??t.targetEndRef??null,...t.type==="delete"&&t.modified==null?{modified:""}:{}}}function Ht(e){if(!Et(e))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation must be an object."}};let t=e.type;if(t!=null&&t!==""&&!ag.has(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:`Unsupported operation type: "${String(t)}".`}};let r=rt(e);if(Et(e.target)&&e.target.revisionView!=null&&e.target.revisionView!=="accepted"&&e.target.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(Et(e.targetEnd)&&e.targetEnd.revisionView!=null&&e.targetEnd.revisionView!=="accepted"&&e.targetEnd.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(e.operationId!=null&&(!we(e.operationId)||e.operationId.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"operationId must be a non-empty string under 256 characters when provided."}};if(e.captureKey!=null&&(!we(e.captureKey)||e.captureKey.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"captureKey must be a non-empty string under 256 characters when provided."}};if(Et(e.target)&&e.target.captureRef!=null&&(!we(e.target.captureRef)||e.target.captureRef.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.captureRef must be a non-empty string under 256 characters when provided."}};if(Et(e.target)&&e.target.select!=null&&typeof e.target.select!="string")return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.select must be a string when provided."}};let n=r.targetDescriptor;if(!ig(r.operationKind)&&!we(n.text)&&n.index==null&&!n.paragraphId&&!n.fingerprint&&!n.captureRef)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation target must provide text, a paragraph index, a paragraphId, or a captureRef."}};if(n.occurrence!=null&&!we(n.text))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Target occurrence requires target text."}};if(r.operationKind==="redline"){let o=typeof r.modified=="string",a=r.replacements!==void 0;if(o===a)return{valid:!1,error:{code:"INVALID_OPERATION",message:'Redline operations require exactly one of string "modified" or non-empty "replacements".'}};if(a){if(t!=null&&t!==""&&!["redline","replace"].includes(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements are supported only for redline or replace operations."}};if(n.revisionView!=="accepted"||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||""))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 require one batch-start accepted-view paragraph target without captures, target occurrence, or a target range."}};let i=Ta(r.replacements);if(!i.ok)return{valid:!1,error:i.error};if(i.replacements.some(s=>/\r|\n/.test(s.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 cannot insert paragraph breaks."}};r.replacements=i.replacements}}if(r.operationKind==="rejected-insert"){if(!we(r.modified))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require non-empty string "modified" text.'}};if(!r.anchor||!we(r.anchor.exactText)||!Number.isInteger(r.anchor.offset)||r.anchor.offset<0||r.anchor.offset>r.anchor.exactText.length)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Rejected-view insert operations require anchor.exactText, a positive occurrence, and an offset within the anchor text."}};if(r.existingRevisions!=="slice-cross-author")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require existingRevisions: "slice-cross-author".'}}}if(r.operationKind==="restore"){let o=e.modified!==void 0,a=e.replacements!==void 0,i=we(r.modified),s=Array.isArray(r.modified)&&r.modified.length>0&&r.modified.every(we);if(o&&a)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations accept modified or replacements, not both."}};if(o&&!i&&!s)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore modified must be a non-empty string or non-empty string array."}};if(!o&&(n.revisionView!=="rejected"||!n.paragraphId&&!n.fingerprint||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Verbatim and localized restore require one strong batch-start rejected-view paragraph target without captures, target occurrence, or a target range."}};if(a){let l=Ta(r.replacements);if(!l.ok)return{valid:!1,error:l.error};if(l.replacements.some(c=>/\r|\n/.test(c.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized restore cannot insert paragraph breaks."}};r.replacements=l.replacements}if(r.generateRedlines===!1)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations require tracked changes and cannot set generateRedlines to false."}}}if(r.structuredContent!=null&&typeof r.structuredContent!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"structuredContent must be a boolean when provided."}};if(r.pairReplacements!=null&&typeof r.pairReplacements!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"pairReplacements must be a boolean when provided."}};if(r.existingRevisions!=null&&!so(r.existingRevisions))return{valid:!1,error:{code:"INVALID_OPERATION",message:`existingRevisions must be one of: ${cu.join(", ")}.`}};if(r.insertionAffinity!=null){if(!Et(r.insertionAffinity))return{valid:!1,error:{code:"INVALID_OPERATION",message:"insertionAffinity must be an object when provided."}};let{formatting:o,hyperlink:a,revision:i,bookmark:s,comment:l}=r.insertionAffinity;if(o!=null&&!["left","right","none"].includes(o))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.formatting must be "left", "right", or "none".'}};if(a!=null&&!["inside","outside","preserve"].includes(a))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.hyperlink must be "inside", "outside", or "preserve".'}};if(i!=null&&!["coalesce_same_author","separate"].includes(i))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.revision must be "coalesce_same_author" or "separate".'}};if(s!=null&&!["inside","outside"].includes(s))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.bookmark must be "inside" or "outside".'}};if(l!=null&&!["inside","outside"].includes(l))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.comment must be "inside" or "outside".'}}}if(r.operationKind==="comment"&&!we(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment operations require a non-empty "commentContent" field.'}};if(r.operationKind==="comment_reply"){if(!we(String(r.parentCommentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a "parentCommentId".'}};if(!we(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a non-empty "commentContent" field.'}}}if(r.operationKind==="comment_resolve"){if(!we(String(r.commentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve operations require a "commentId".'}};if(r.resolved!=null&&typeof r.resolved!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve "resolved" must be a boolean when provided.'}}}if(r.operationKind==="highlight"){if(!we(r.textToHighlight))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Highlight operations require a non-empty "textToHighlight" field.'}};if(r.color!=null&&!we(r.color))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Highlight color must be a non-empty string when provided."}}}if(r.operationKind==="format"){if(!we(r.textToFormat))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a non-empty "textToFormat" field.'}};if(!Et(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a "properties" object.'}};if(r.formattingRevisionPolicy!=null&&!["always","coalesce-own-insertion"].includes(r.formattingRevisionPolicy))return{valid:!1,error:{code:"INVALID_OPERATION",message:'formattingRevisionPolicy must be "always" or "coalesce-own-insertion".'}}}return r.operationKind==="paragraph-format"&&!Et(r.properties)?{valid:!1,error:{code:"INVALID_OPERATION",message:'Paragraph-format operations require a "properties" object.'}}:r.author!=null&&!we(r.author)?{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation author must be a non-empty string when provided."}}:{valid:!0,operation:r}}function wt(e,t,r){return we(e?.author)?e.author.trim():we(t)?t.trim():we(r)?r.trim():"Author"}var pr=class{constructor(t,r={}){if(this.originalDocumentXml=typeof t=="string"?t:"",this.currentDocumentXml=this.originalDocumentXml,this.serializer=oe(),this.parseResult=W(this.originalDocumentXml,"application/xml"),this.document=this.parseResult.doc||null,this.revisionIdAllocator=null,this.initialTargetReferenceSnapshot=null,this.paragraphIndex=null,this.invalidated=!1,this.hasChanges=!1,this.documentHasChanges=!1,this.deferSerialization=r?._deferDocumentSerialization===!0,this.instrumentation=r?._sessionInstrumentation||null,this.runtimeContext=null,this.commentsXml=null,this.commentsExtendedXml=null,this.commentsXmlMode="merge",this.commentsExtendedXmlMode="merge",this.numberingXmlParts=[],this.results=[],this.executionOrder=[],this.authorsUsed=new Set,this.captureTable=new Map,this.sourceTargetRegistry=null,this.nextCaptureParaId=1,this.receiptCollector=new oo,this.document){this.instrumentation?.onDocumentParse?.(this.originalDocumentXml),this.revisionIdAllocator=r?._revisionIdAllocator instanceof Ae?r._revisionIdAllocator:new Ae,this.revisionIdAllocator._receiptCollector=this.receiptCollector,Ft(this.document,this.revisionIdAllocator),er(this.document,this.revisionIdAllocator);let n=this.getParagraphMetadataIndex();this.initialTargetReferenceSnapshot=xi(this.document,n)}}get valid(){return!!this.document&&!this.parseResult.error}setDocumentXml(t){this.currentDocumentXml=t,this.invalidateParagraphIndex()}invalidateParagraphIndex(){this.invalidated=!0,this.paragraphIndex=null}serialize(){return this.document?(this.instrumentation?.onDocumentSerialize?.(this.document),this.serializer.serializeToString(this.document)):this.currentDocumentXml}serializeCurrent(){return this.hasChanges?this.documentHasChanges?(this.currentDocumentXml=this.serialize(),this.currentDocumentXml):this.currentDocumentXml:this.originalDocumentXml}markMutationCommitted(t=!0){this.hasChanges=!0,this.documentHasChanges=this.documentHasChanges||t,t&&this.invalidateParagraphIndex()}generateParagraphId(){return(1073741824+this.nextCaptureParaId++).toString(16).toUpperCase()}createSavepoint(){return this.document?{document:this.document.cloneNode(!0),allocatorNextId:this.revisionIdAllocator?.nextId,allocatorOccupiedIds:this.revisionIdAllocator?.occupiedIds instanceof Set?new Set(this.revisionIdAllocator.occupiedIds):null,hasChanges:this.hasChanges,documentHasChanges:this.documentHasChanges,currentDocumentXml:this.currentDocumentXml,commentsXml:this.commentsXml,commentsExtendedXml:this.commentsExtendedXml,commentsXmlMode:this.commentsXmlMode,commentsExtendedXmlMode:this.commentsExtendedXmlMode,captureTable:uu(this.captureTable),sourceTargetRegistry:this.sourceTargetRegistry?.createSavepoint?.(this.document)||null,nextCaptureParaId:this.nextCaptureParaId,receiptCollector:this.receiptCollector?this.receiptCollector.createSavepoint():null}:null}restoreSavepoint(t){t?.document&&(this.document=t.document,this.hasChanges=t.hasChanges,this.documentHasChanges=t.documentHasChanges===!0,this.currentDocumentXml=t.currentDocumentXml,this.commentsXml=t.commentsXml,this.commentsExtendedXml=t.commentsExtendedXml,this.commentsXmlMode=t.commentsXmlMode||"merge",this.commentsExtendedXmlMode=t.commentsExtendedXmlMode||"merge",this.captureTable=t.captureTable?uu(t.captureTable):new Map,this.sourceTargetRegistry?.restoreSavepoint?.(this.document,t.sourceTargetRegistry),typeof t.nextCaptureParaId=="number"&&(this.nextCaptureParaId=t.nextCaptureParaId),this.revisionIdAllocator&&(this.revisionIdAllocator.nextId=t.allocatorNextId,t.allocatorOccupiedIds instanceof Set&&(this.revisionIdAllocator.occupiedIds=new Set(t.allocatorOccupiedIds)),this.revisionIdAllocator._receiptCollector=this.receiptCollector,er(this.document,this.revisionIdAllocator)),t.receiptCollector&&this.receiptCollector&&this.receiptCollector.restoreSavepoint(t.receiptCollector),this.invalidateParagraphIndex())}getParagraphIndex(){return this.getParagraphMetadataIndex().entries}getParagraphMetadataIndex(){return this.paragraphIndex?this.paragraphIndex:(this.paragraphIndex=kt(this.document),this.invalidated=!1,this.paragraphIndex)}rollback(){return this.currentDocumentXml=this.originalDocumentXml,this.hasChanges=!1,this.documentHasChanges=!1,this.captureTable.clear(),this.sourceTargetRegistry=null,this.receiptCollector?.clear(),this.originalDocumentXml}};function uu(e){let t=new Map;if(e instanceof Map)for(let[r,n]of e.entries())t.set(r,JSON.parse(JSON.stringify(n)));return t}function gn(e,t={}){let r=t?._revisionIdAllocator instanceof Ae?t._revisionIdAllocator:new Ae;return t?._documentOperationSession?.receiptCollector&&(r._receiptCollector=t._documentOperationSession.receiptCollector),Ft(e,r),er(e,r),r}function fu(e){if(!e||typeof e!="object")return{};let t={...e};return e.listFallbackSharedNumIdByKey instanceof Map&&(t.listFallbackSharedNumIdByKey=new Map(e.listFallbackSharedNumIdByKey)),e.tableStructuralRedlineKeys instanceof Set&&(t.tableStructuralRedlineKeys=new Set(e.tableStructuralRedlineKeys)),e.numberingIdState&&typeof e.numberingIdState=="object"&&(t.numberingIdState={...e.numberingIdState,usedNumIds:e.numberingIdState.usedNumIds instanceof Set?new Set(e.numberingIdState.usedNumIds):e.numberingIdState.usedNumIds,usedAbstractNumIds:e.numberingIdState.usedAbstractNumIds instanceof Set?new Set(e.numberingIdState.usedAbstractNumIds):e.numberingIdState.usedAbstractNumIds}),e.listFallbackSequenceState&&typeof e.listFallbackSequenceState=="object"&&(t.listFallbackSequenceState={...e.listFallbackSequenceState,explicitByNumberingKey:e.listFallbackSequenceState.explicitByNumberingKey instanceof Map?new Map(e.listFallbackSequenceState.explicitByNumberingKey):e.listFallbackSequenceState.explicitByNumberingKey}),t}function du(e,t){if(!(!e||typeof e!="object")){if(e.listFallbackSharedNumIdByKey instanceof Map&&t.listFallbackSharedNumIdByKey instanceof Map){e.listFallbackSharedNumIdByKey.clear();for(let r of t.listFallbackSharedNumIdByKey)e.listFallbackSharedNumIdByKey.set(...r);t.listFallbackSharedNumIdByKey=e.listFallbackSharedNumIdByKey}if(e.tableStructuralRedlineKeys instanceof Set&&t.tableStructuralRedlineKeys instanceof Set){e.tableStructuralRedlineKeys.clear();for(let r of t.tableStructuralRedlineKeys)e.tableStructuralRedlineKeys.add(r);t.tableStructuralRedlineKeys=e.tableStructuralRedlineKeys}if(e.numberingIdState&&t.numberingIdState){for(let r of["usedNumIds","usedAbstractNumIds"])if(e.numberingIdState[r]instanceof Set&&t.numberingIdState[r]instanceof Set){e.numberingIdState[r].clear();for(let n of t.numberingIdState[r])e.numberingIdState[r].add(n);t.numberingIdState[r]=e.numberingIdState[r]}Object.assign(e.numberingIdState,t.numberingIdState),t.numberingIdState=e.numberingIdState}if(e.listFallbackSequenceState&&t.listFallbackSequenceState){let r=e.listFallbackSequenceState.explicitByNumberingKey,n=t.listFallbackSequenceState.explicitByNumberingKey;if(r instanceof Map&&n instanceof Map){r.clear();for(let o of n)r.set(...o);t.listFallbackSequenceState.explicitByNumberingKey=r}Object.assign(e.listFallbackSequenceState,t.listFallbackSequenceState),t.listFallbackSequenceState=e.listFallbackSequenceState}Object.assign(e,t)}}var lg=new Set(["redline","restore","rejected-insert"]),cg=new Set(["highlight","format","paragraph-format"]);function ug(e){let t={};if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="name"||r==="stack"||r==="message"||r==="code"||(t[r]=n);return{code:typeof e?.code=="string"&&e.code?e.code:"OPERATION_ERROR",message:e?.message||String(e),...t}}function fg(e,t){return!!t&&se(e).includes(t)}function dg(e=[]){let t=[];for(let r of e)if(!(!r||r.nodeType!==1)){r.localName==="p"&&t.push(r);for(let n of Array.from(r.getElementsByTagNameNS?.("*","p")||[]))t.includes(n)||t.push(n)}return t}var rs=class{constructor(t){this.document=t,this.nextId=1,this.entries=new Map,this.idsByNode=new WeakMap}register(t,r={}){let n=this.idsByNode.get(t);if(n)return n;let o=`S${this.nextId++}`;return this.entries.set(o,{sourceId:o,paragraph:t,sourceIndex:r.index||null,paragraphId:r.paragraphId||null,fingerprint:r.fingerprint||null,text:r.text||"",revisionView:r.revisionView==="rejected"?"rejected":"accepted",consumed:!1,consumedByOperation:null}),this.idsByNode.set(t,o),o}describe(t){let r=this.entries.get(t);return r?{sourceId:t,index:r.sourceIndex,paragraphId:r.paragraphId,fingerprint:r.fingerprint,text:r.text,revisionView:r.revisionView}:null}resolve(t,r=this.document){let n=this.entries.get(t);return n?n.consumed?{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} was consumed by operation ${n.consumedByOperation}.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:fg(r,n.paragraph)?{paragraph:n.paragraph,resolvedBy:"batch_source"}:{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} is no longer present in the live document.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:{error:{code:"SOURCE_TARGET_NOT_FOUND",message:`Compiled source target ${String(t)} was not found.`}}}createSavepoint(t=this.document){let r=se(t);return new Map(Array.from(this.entries,([n,o])=>[n,{paragraphIndex:r.indexOf(o.paragraph),consumed:o.consumed,consumedByOperation:o.consumedByOperation}]))}restoreSavepoint(t,r){this.document=t,this.idsByNode=new WeakMap;let n=se(t);for(let[o,a]of this.entries){let i=r instanceof Map?r.get(o):null;a.consumed=i?.consumed===!0,a.consumedByOperation=i?.consumedByOperation||null,a.paragraph=Number.isInteger(i?.paragraphIndex)&&i.paragraphIndex>=0&&n[i.paragraphIndex]||null,a.paragraph&&this.idsByNode.set(a.paragraph,o)}}commitMutation(t,r,n,o){let a=this.entries.get(t);if(!a||!Array.isArray(r)||!r.includes(a.paragraph))return;let i=dg(n),s=a.paragraphId?i.filter(c=>$e(c)===a.paragraphId):[],l=s.length===1?s[0]:i.length===1?i[0]:null;if(l){a.paragraph=l,this.idsByNode.set(l,t);return}a.paragraph=null,a.consumed=!0,a.consumedByOperation=o}};function mg(e,t){return{index:e.index,paragraphId:e.paragraphId,fingerprint:e.fingerprint,text:e.text,inTable:e.inTable,revisionView:t}}function mu(e,t,r,n,o,a={}){let i=t?.revisionView==="rejected"?"rejected":"accepted";o[i]||(o[i]=kt(e,{revisionView:i}));let s=o[i],l=_r(e,{targetText:t.text,targetRef:t.index,targetDescriptor:t,opType:r,strictAmbiguity:n,paragraphMetadataIndex:s,metadataIndices:o,onInfo:a.onInfo,onWarn:a.onWarn}),c=s.byParagraph.get(l.paragraph);return{paragraph:l.paragraph,resolvedBy:l.resolvedBy,metadata:mg(c,i)}}function pu(e,t,r,n,o){return{code:e,message:t,operationIndexes:r.map(a=>a.index).sort((a,i)=>a-i),target:n,recovery:{action:o,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}}}function hn(e,t=[],r={}){let n=Array.isArray(t)?t:[],o=r.strictTargets!==!1,a=new rs(e),i={accepted:kt(e,{revisionView:"accepted"}),rejected:null},s=[],l=[];for(let p=0;p<n.length;p+=1){let g=n[p],h=Ht(g),y=h.operation||rt(g),w={index:p+1,operationKind:y.operationKind,operationId:y.operationId,sourceIds:[],warnings:[]},v={...g},b=y.targetDescriptor?.occurrence!=null&&!y.targetDescriptor?.paragraphId&&!y.targetDescriptor?.fingerprint,x=typeof y.targetDescriptor?.text=="string"&&/\r|\n/.test(y.targetDescriptor.text)&&!y.targetEndDescriptor;if((b||x)&&(w.dynamic=!0),h.valid&&y.operationKind!=="comment_reply"&&y.operationKind!=="comment_resolve"&&!y.targetDescriptor?.captureRef&&!w.dynamic)try{let I=mu(e,y.targetDescriptor,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:E=>w.warnings.push(String(E))}),N=a.register(I.paragraph,I.metadata);if(w.sourceIds.push(N),w.resolvedBy=I.resolvedBy,w.resolvedTarget=I.metadata,v._compiledSourceId=N,v._compiledResolvedBy=I.resolvedBy,w.warnings.length>0&&(v._compiledWarnings=w.warnings),Array.isArray(y.replacements)){let E=su(I.metadata.text,y.replacements);if(!E.ok)throw Object.assign(new Error(E.error.message),E.error);v.modified=E.desiredText,delete v.replacements,v._localizedReplacementCompilation={sourceText:I.metadata.text,desiredText:E.desiredText,replacements:E.replacements};let S=Ht(v);if(!S.valid)throw Object.assign(new Error(S.error.message),S.error)}else if(y.operationKind==="restore"&&g.modified===void 0){v.modified=I.metadata.text;let E=Ht(v);if(!E.valid)throw Object.assign(new Error(E.error.message),E.error)}let T=y.targetEndDescriptor||(y.targetEndRef!=null?Sa(null,y.targetEndRef,y.targetDescriptor.revisionView):null);if(T){let E=mu(e,T,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:_=>w.warnings.push(String(_))}),S=a.register(E.paragraph,E.metadata);v._compiledSourceEndId=S;let O=se(e),A=O.indexOf(I.paragraph),P=O.indexOf(E.paragraph);if(A<0||P<A)throw Object.assign(new Error("Target range is not a forward contiguous paragraph range."),{code:"TARGET_RANGE_INVALID"});for(let _ of O.slice(A,P+1)){let k=(i[y.targetDescriptor.revisionView]||i.accepted).byParagraph.get(_);w.sourceIds.push(a.register(_,k||{}))}w.sourceIds=[...new Set(w.sourceIds)],w.resolvedTargetEnd=E.metadata}}catch(I){w.error=ug(I)}s.push(w),l.push(v)}let c=new Set(l.map(p=>p?.captureKey).filter(Boolean)),u=1;for(let p of s){if(p.error?.code!=="TARGET_NOT_FOUND")continue;let g=p.index-1,y=rt(n[g]).targetDescriptor?.text;if(!y)continue;let w=n.flatMap((I,N)=>N===g||typeof I?.modified!="string"?[]:I.modified.split(/\r?\n/).map(E=>E.trim()).filter(Boolean).includes(y.trim())?[{candidate:I,producerIndex:N}]:[]);if(w.length!==1)continue;let[{candidate:v,producerIndex:b}]=w,x=v.captureKey||l[b].captureKey;if(!x){do x=`__batch_created_${u++}`;while(c.has(x));c.add(x),l[b].captureKey=x}l[g].target={captureRef:x,select:y},delete l[g]._compiledSourceId,delete l[g]._compiledResolvedBy,delete p.error,p.sourceIds=[],p.resolvedBy="created_content_dependency",p.createdByOperation=b+1,p.captureRef=x}let f=new Map;for(let p of s)if(!(p.error||p.dynamic))for(let g of p.sourceIds)f.has(g)||f.set(g,[]),f.get(g).push(p);let d=[],m=new Set;for(let[p,g]of f){let h=g.filter(w=>lg.has(w.operationKind)),y=g.filter(w=>cg.has(w.operationKind));if(h.length>1){let w=`text:${h.map(v=>v.index).sort().join(",")}`;m.has(w)||(m.add(w),d.push(pu("OVERLAPPING_SOURCE_TARGETS",`Operations ${h.map(v=>v.index).join(", ")} contain incompatible text writes to the same batch-start source target.`,h,a.describe(p),"consolidate_operations")))}if(h.length>0&&y.length>0){let w=[...h,...y],v=`format:${w.map(b=>b.index).sort().join(",")}`;m.has(v)||(m.add(v),d.push(pu("REVISION_ORDER_CONFLICT",`Operations ${w.map(b=>b.index).join(", ")} combine text and formatting writes on the same batch-start source target.`,w,a.describe(p),"split_or_consolidate_operations")))}}return{valid:d.length===0&&s.every(p=>!p.error),compiledOperations:l,bindings:s,conflicts:d,registry:a}}function gu(e){return`${e?.source||""}${e?.severity||""}${e?.code||""}${e?.message||""}`}function Ur(e=[],t=[]){let r=new Map;for(let n of t||[]){let o=gu(n);r.set(o,(r.get(o)||0)+1)}return(e||[]).filter(n=>{let o=gu(n),a=r.get(o)||0;return a===0?!0:(r.set(o,a-1),!1)})}function zr(e=[]){return(e||[]).filter(t=>t?.severity==="error")}var pg=/^(\s*)((?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|[ivxlcIVXLC]+\.|[-*+\u2022]))\s+(.*)$/,hu=/(?:^|\s)(?:\d+(?:\.\d+)*\.?|[A-Za-z]\.|[ivxlcIVXLC]+\.)\s+/g;function gg(e){let t=String(e||"").trim();if(!/^\d+(?:\.\d+)+\.?$/.test(t))return null;let r=t.replace(/\.$/,"").split(".");return Math.max(0,r.length-1)}function hg(e){let t=String(e||"").split(/\r?\n/g).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);if(t.length<2)return null;let r=[];for(let n of t){let o=n.match(pg);if(!o)return null;let a=o[2],i=/^[-*+\u2022]$/.test(a)?"bullet":"numbered";r.push({marker:a,markerType:i,level:Math.floor((o[1]||"").length/2),outlineLevel:i==="numbered"?gg(a):null,text:kr(o[3])})}return r.length>=2?r:null}function wu(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=hg(t);if(!r)return null;let n=e.map(d=>J(be(d))),o=r.map(d=>J(d.text));if(n.some(d=>!d)||o.some(d=>!d))return null;let a=e.map(d=>lt(d));if(a.some(d=>!d||!d.numId))return null;let i=String(a[0].numId);if(a.some(d=>String(d.numId)!==i))return null;let s=[],l=0;for(let d=0;d<o.length&&l<n.length;d+=1)o[d]===n[l]&&(s.push({originalIndex:l,modifiedIndex:d}),l+=1);if(l!==n.length)return null;let c=new Set(s.map(d=>d.modifiedIndex)),u=[];for(let d=0;d<r.length;d+=1)c.has(d)||u.push(d);if(u.length===0)return null;let f=r[0]?.level||0;return u.map(d=>{let m=s.find(b=>b.modifiedIndex>d)||null,p=[...s].reverse().find(b=>b.modifiedIndex<d)||null,g=m||p;if(!g)return null;let h=a[g.originalIndex]||a[0];if(!h)return null;let y=r[d],w=Math.max(0,y.level-f),v=Number.isInteger(y.outlineLevel)?y.outlineLevel:null;return{text:y.text,markerType:y.markerType,ilvl:v??Math.max(0,(h.ilvl||0)+w),numId:String(h.numId),insertBeforeOriginalIndex:m?m.originalIndex:null}}).filter(Boolean)}function wg(e){return String(e||"").trim().split(/\s+/).filter(Boolean).length}function yg(e){let t=String(e||"");if(!t)return!1;let r=0,n=new RegExp(hu.source,hu.flags);for(;n.exec(t);)if(r+=1,r>=2)return!0;return!1}function yu(e,t){let r=String(e||"").trim(),n=String(t||"").trim();if(!r||!n||n===r||n.includes(`
|
|
215
|
+
`))return null;let o=J(r),a=l=>kr(String(l||"").trim()).trim(),i=(l,c)=>{let u=a(c),f=J(u);return!u||u===r||wg(u)<6||yg(u)||o&&f.includes(o)?null:{position:l,text:u}};if(n.endsWith(r)){let l=i("before",n.slice(0,-r.length));if(l)return l}if(n.startsWith(r)){let l=i("after",n.slice(r.length));if(l)return l}let s=J(n);if(!o||o===s)return null;if(s.endsWith(o)){let l=i("before",s.slice(0,-o.length));if(l)return l}if(s.startsWith(o)){let l=i("after",s.slice(o.length));if(l)return l}return null}function vu(e,t){let r=String(e||"").trim(),n=String(t||"");if(!r||!n||!n.includes(`
|
|
216
|
+
`))return null;let o=n.split(/\r?\n/g).map(s=>String(s||"").trim()).filter(Boolean);if(o.length<2)return null;let a=s=>J(String(s||"")),i=a(r);if(a(o[o.length-1])===i){let s=o.slice(0,-1).filter(Boolean);if(s.length>0)return{position:"before",paragraphs:s}}if(a(o[0])===i){let s=o.slice(1).filter(Boolean);if(s.length>0)return{position:"after",paragraphs:s}}return null}function Gt(e,t){let r=new Error(t);return r.code=e,r}function xu(e,t,r){let n=[],o=!1,a=!1;for(let m of r||[])m&&(m.localName==="tbl"?(o=!0,n.push(...Array.from(m.getElementsByTagNameNS(L,"p")))):m.localName==="p"&&(m.getElementsByTagNameNS(L,"numPr").length>0&&(a=!0),n.push(m)));let i=o?"table":a?"list":n.length>1?"range":"paragraph",s=[],l=[],c=[],u=[],f=e.document,d=se(f);for(let m of n){let p=$e(m)||"";s.push(p);let g=te(m);c.push(g);let h=d.indexOf(m)+1;l.push(st(m,{text:g,paragraphId:p||null,index:h>0?h:void 0,inTable:o||!!We(m,"tbl")}));let y=m.parentNode?.localName||"body";u.push(`${y}/${m.localName}`)}return{captureKey:t.captureKey,operationIndex:typeof t.index=="number"?t.index:0,kind:i,generatedParagraphIds:s,fingerprints:l,expectedText:c,structuralPathHints:u,stale:!1}}function bu(e,t){if(!e||!(e instanceof Map)||!Array.isArray(t)||t.length===0)return;let r=new Set;for(let n of t)if(n){if(n.localName==="p"){let o=$e(n);o&&r.add(o)}else if(typeof n.getElementsByTagNameNS=="function")for(let o of Array.from(n.getElementsByTagNameNS(L,"p"))){let a=$e(o);a&&r.add(a)}}if(r.size!==0)for(let[,n]of e)n.stale||n.generatedParagraphIds.some(o=>o&&r.has(o))&&(n.stale=!0)}function Nu(e,t,r,n="redline",o={}){let a=r?.captureRef;if(!a)throw Gt("INVALID_OPERATION","Operation target is missing captureRef.");if(!t||!t.captureTable||!t.captureTable.has(a))throw Gt("CAPTURE_NOT_FOUND",`Capture "${a}" was not found in the session capture table.`);let i=t.captureTable.get(a);if(i.stale)throw Gt("CAPTURE_STALE",`Capture "${a}" is stale; the captured content was modified or removed.`);let s=t.getParagraphMetadataIndex(),l=[];for(let d=0;d<i.expectedText.length;d++){let m=i.generatedParagraphIds[d],p=i.expectedText[d],g=null;if(m&&s.byId.has(m)&&(g=s.byId.get(m).paragraph),!g){let y=s.entries.find(w=>w.text===p||w.fingerprint===i.fingerprints[d]);y&&(g=y.paragraph)}if(!g||!g.parentNode)throw i.stale=!0,Gt("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} was removed from the document.`);let h=te(g);if(h!==p)throw i.stale=!0,Gt("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} content drifted from "${p}" to "${h}".`);l.push(g)}if(l.length===0)throw i.stale=!0,Gt("CAPTURE_STALE",`Capture "${a}" is stale; no live paragraphs found.`);let c=r.select;if(c==null||c===""){if(l.length===1)return{paragraph:l[0],resolvedBy:"capture"};throw Gt("AMBIGUOUS_CAPTURE_SELECTION",`Capture "${a}" contains ${l.length} paragraphs; target.select is required to disambiguate.`)}let u=[],f=String(c).trim();if(f===":first"||f==="first")u=[l[0]];else if(f===":last"||f==="last")u=[l[l.length-1]];else if(/^\d+$/.test(f)){let d=parseInt(f,10);d>=1&&d<=l.length&&(u=[l[d-1]])}else{let d=l.filter(m=>te(m).trim()===f);d.length>0?u=d:u=l.filter(m=>te(m).includes(f))}if(u.length===0)throw Gt("TARGET_NOT_FOUND",`Target selection "${c}" was not found in capture "${a}".`);if(u.length>1)throw Gt("AMBIGUOUS_CAPTURE_SELECTION",`Target selection "${c}" matched ${u.length} paragraphs in capture "${a}".`);return{paragraph:u[0],resolvedBy:"capture"}}var ae="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ls="http://schemas.microsoft.com/office/word/2010/wordml";function Iu(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.(ae,r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Tu(e,t){return!t||typeof t!="object"?[]:e.map(r=>t[r]).filter(Boolean)}function Xr(e,t={}){let r=t?._documentOperationSession||null;return r?.valid&&r.document?{xmlDoc:r.document,serializer:r.serializer,operationSession:r}:{xmlDoc:W(e,"application/xml").doc,serializer:oe(),operationSession:null}}function ut(e,t,r,n){return n?r:t.serializeToString(e)}async function co(e,t,r,n={}){let o=await Dn(e,t,r,n);return o?.useNativeApi&&typeof o?.oxml!="string"?xe({...o,oxml:e,hasChanges:!1,warnings:[...Array.isArray(o?.warnings)?o.warnings:[],"Standalone mode cannot execute native Word API fallback for this operation."]}):o}async function vg(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=at(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await co(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}function lo(e){return be(e)}function Su(e,t=96){let r=String(e??"");return(r.length>t?`${r.slice(0,t)}\u2026`:r).replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\u00a0/g,"\\u00A0").replace(/\u202f/g,"\\u202F").replace(/\u2060/g,"\\u2060")}function Ea(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function xg(e,t){let r=String(e??""),n=String(t??"");if(r===n)return{mode:"exact"};let o=[],a=Math.min(r.length,n.length);for(let s=0;s<a&&o.length<8;s++)r[s]!==n[s]&&o.push({offset:s,sourceCodePoint:Ea(r,s),requestedCodePoint:Ea(n,s)});return r.length!==n.length&&o.length<8&&o.push({offset:a,sourceCodePoint:Ea(r,a),requestedCodePoint:Ea(n,a)}),{mode:r.length===n.length&&r.replace(/\u00a0/g," ")===n.replace(/\u00a0/g," ")?"space_equivalent":"normalized",differences:o,sourceExcerpt:Su(r),requestedExcerpt:Su(n)}}function ns(e,t,r,n,o){let a=o?.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",i=r?.revisionView===a?r:null,s=i?.index??se(e).indexOf(t)+1,l=i?.paragraphId??$e(t),c=i?.inTable??!!We(t,"tbl"),u=i?.text??te(t,{revisionView:a}),f=i?.fingerprint??st(t,{text:u,index:s,paragraphId:l,inTable:c,revisionView:a});return{index:s,paragraphId:l,text:u,fingerprint:f,revisionView:a,inTable:c,targetTextMatch:xg(u,o?.targetDescriptor?.text??o?.targetDescriptor?.exactText??n)}}function qt(e,t,r,n,o=null,a={}){let i=typeof a?.onInfo=="function"?a.onInfo:()=>{},s=typeof a?.onWarn=="function"?a.onWarn:()=>{},l=a?._documentOperationSession||null,c=l?.getParagraphMetadataIndex?.()||null;if(a?._compiledSourceId&&a?._sourceTargetRegistry){let f=a._sourceTargetRegistry.resolve(a._compiledSourceId,e);if(f?.error||!f?.paragraph)return f;if(f.resolvedBy=a._compiledResolvedBy||f.resolvedBy,a?._resolutionCapture){let d=f.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:ns(e,d,m,t,a)})}return f}if(a?.targetDescriptor?.captureRef)try{let f=Nu(e,l,a.targetDescriptor,n,a);if(a?._resolutionCapture&&f?.paragraph){let d=f.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:ns(e,d,m,t,a)})}return f}catch(f){return{error:{code:typeof f?.code=="string"&&f.code?f.code:"TARGET_NOT_FOUND",message:f?.message||String(f)}}}let u=$n(e,{targetText:t,targetRef:r,opType:n,targetRefSnapshot:o?.targetRefSnapshot||null,targetDescriptor:a?.targetDescriptor||null,strictAmbiguity:a?.strictTargets===!0,paragraphMetadataIndex:c,onInfo:i,onWarn:s});if(a?._resolutionCapture&&u?.paragraph){let f=u.paragraph,d=c?.byParagraph?.get(f)||null;Object.assign(a._resolutionCapture,{resolvedBy:u.resolvedBy,resolvedTarget:ns(e,f,d,t,a)})}return u}function Vr(e){return qi(e)}function bg(e,t){if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||!t.includes("Paragraph expanded to list fragment"))return e;let r=e[e.length-1];return!r||r.localName!=="p"||Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.localName!=="pPr")?e:e.slice(0,-1)}function ft(e){wa(e)}function Ng(e){for(let t of Array.from(e?.getElementsByTagNameNS?.(ae,"proofErr")||[]))t.parentNode?.removeChild(t)}function Ig(e){e&&Ng(e)}function nt(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI===ae&&r.localName===t)||null}function Tg(e,t){if(!e||!t)return null;let n=Array.from(e.getElementsByTagNameNS(ae,"tbl")).indexOf(t);return n>=0?n+1:null}function Sg(e){return String(e||"").replace(/\r\n/g,`
|
|
217
|
+
`).split(`
|
|
218
|
+
`).map(t=>t.trim()).filter(Boolean).join(`
|
|
219
|
+
`)}function Eg(e,t,r){let n=Tg(e,t);if(!Number.isInteger(n)||n<1)return null;let o=Sg(r);return o?`table:${n}|payload:${o}`:null}function Ag(e,t,r,n){let o=nt(t,"pPr");o||(o=B(e,"w:pPr"),t.insertBefore(o,t.firstChild));let a=nt(o,"numPr");a||(a=B(e,"w:numPr"),o.appendChild(a));let i=nt(a,"ilvl");i||(i=B(e,"w:ilvl"),a.appendChild(i)),i.setAttribute("w:val",String(Math.max(0,Number.parseInt(r,10)||0)));let s=nt(a,"numId");s||(s=B(e,"w:numId"),a.appendChild(s)),s.setAttribute("w:val",String(n))}function as(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,s=B(e,"w:p"),l=nt(t,"pPr");l&&s.appendChild(pt(l)),Ag(e,s,r.ilvl,r.numId),i&&Yr(e,s,o);let c=B(e,"w:r"),u=Array.from(t.getElementsByTagNameNS(ae,"r"))[0]||null,f=u?nt(u,"rPr"):null;f&&c.appendChild(pt(f));let d=B(e,"w:t"),m=String(r.text||"").trim();if(/^\s|\s$/.test(m)&&d.setAttribute("xml:space","preserve"),d.textContent=m,c.appendChild(d),i){let p=n||ie(o,e),g=B(e,"w:ins");g.setAttribute("w:id",String(p.id)),g.setAttribute("w:author",p.author),g.setAttribute("w:date",p.date),g.appendChild(c),s.appendChild(g)}else s.appendChild(c);return s}function os(e,t){let r=(e||[]).map(n=>t.serializeToString(n)).join("");return`<w:document xmlns:w="${ae}"><w:body>${r}</w:body></w:document>`}function Rg({xmlDoc:e,explicitRangeParagraphs:t,insertionEntries:r,generateRedlines:n,author:o}){if(!Array.isArray(t)||t.length===0||!Array.isArray(r)||r.length===0)return!1;let a=t[0].parentNode;if(!a||t.some(s=>s.parentNode!==a))return!1;let i=t[t.length-1].nextSibling;for(let s of r){let l=s.insertBeforeOriginalIndex!=null?t[s.insertBeforeOriginalIndex]:t[t.length-1];if(!l)return!1;let c=as(e,l,{ilvl:s.ilvl,markerType:s.markerType,numId:s.numId,text:s.text},n?ie(o,e):null,o,{generateRedlines:n});s.insertBeforeOriginalIndex!=null?a.insertBefore(c,l):a.insertBefore(c,i)}return ft(e),!0}function Pg(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=B(e,"w:p"),s=B(e,"w:r"),l=B(e,"w:t"),c=String(t||"");if(/^\s|\s$/.test(c)&&l.setAttribute("xml:space","preserve"),l.textContent=c,s.appendChild(l),a){o.trackParagraphMark===!0&&Yr(e,i,n);let u=r||ie(n,e,"ins"),f=B(e,"w:ins");f.setAttribute("w:id",String(u.id)),f.setAttribute("w:author",u.author),f.setAttribute("w:date",u.date),f.appendChild(s),i.appendChild(f)}else i.appendChild(s);return i}function Cg(e,t){let r=B(e,"w:p"),n=nt(t,"pPr");n&&r.appendChild(pt(n));let o=B(e,"w:r"),a=Array.from(t.getElementsByTagNameNS(ae,"r"))[0]||null,i=a?nt(a,"rPr"):null;i&&o.appendChild(pt(i));let s=B(e,"w:t");return s.textContent="",o.appendChild(s),r.appendChild(o),r}function Pu(e,t,r,n,o={}){let a=B(e,"w:p"),i=o.sanitizeParagraphProperties===!0?Cu(e,t):pt(nt(t,"pPr"));i&&a.appendChild(i),o.paragraphId&&a.setAttributeNS(ls,"w14:paraId",o.paragraphId),o.trackParagraphMark===!0&&Yr(e,a,n);let s=B(e,"w:ins"),l=r||ie(n,e,"ins");s.setAttribute("w:id",String(l.id)),s.setAttribute("w:author",l.author),s.setAttribute("w:date",l.date);for(let c of Array.from(t.childNodes||[]))c?.nodeType===1&&c.namespaceURI===ae&&c.localName==="pPr"||s.appendChild(c.cloneNode(!0));return a.appendChild(s),a}async function Og(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,s=oe(),l=Cg(e,t),c=s.serializeToString(l),u=await co(c,"",String(r||""),{author:o,generateRedlines:!1}),f=null;return typeof u?.oxml=="string"&&(f=(Vr(u.oxml).replacementNodes||[]).find(m=>m&&m.nodeType===1&&m.namespaceURI===ae&&m.localName==="p")||null),f?i?Pu(e,f,n,o,a):f:Pg(e,r,n,o,{...a,generateRedlines:i})}function cs(e){let t=new Set;for(let r of e||[]){let n=Array.from(r?.getElementsByTagNameNS?.("*","numId")||[]);for(let o of n){let a=o.getAttribute("w:val")||o.getAttribute("val");a!=null&&a!==""&&t.add(String(a))}}return Array.from(t)}function Eu(e){return Array.from(e?.childNodes||[]).reduce((t,r)=>t+(r?.nodeType===1&&r.namespaceURI===ae&&r.localName==="r"?Ut(r).map(n=>n.text).join(""):""),"")}function _g(e,t,r){let n=0,o=-1;for(let a=0;a<r;a++){if(o=e.indexOf(t,n),o<0)return-1;n=o+Math.max(t.length,1)}return o}function kg(e,t){if(!t)return 0;let r=0,n=0;for(;n<=e.length;){let o=e.indexOf(t,n);if(o<0)break;r+=1,n=o+t.length}return r}function Mg(e,t){let r=new Set(["commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"]);if(Array.from(e.getElementsByTagName?.("*")||[]).some(n=>r.has(n.localName)))return!0;for(let n of Array.from(t?.childNodes||[]))if(n.nodeType===1){if(!(n.namespaceURI===ae&&n.localName==="r"))return!0;for(let o of Array.from(n.childNodes||[]))if(!(o.nodeType!==1||o.namespaceURI!==ae)&&!["rPr","delText","t","tab","br","cr","noBreakHyphen","softHyphen"].includes(o.localName))return!0}return!1}function Lg(e,t){let r=0;for(let n of Array.from(e?.childNodes||[])){if(!(n?.nodeType===1&&n.namespaceURI===ae&&n.localName==="r"))continue;let o=gt(Ut(n));if(t<=r+o)return pt(nt(n,"rPr"));r+=o}return null}var Bg=new Set(["pStyle","numPr","ind","jc","spacing","tabs","keepNext","keepLines","outlineLvl","contextualSpacing"]);function is(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Au(e){return String(e||"").trim().toLowerCase()}function Dg(e,t="nextSibling"){let r=e?.[t]||null;for(;r;){if(r.nodeType===1&&r.namespaceURI===ae&&r.localName==="p")return r;r=r[t]||null}return null}function Cu(e,t){let r=nt(t,"pPr"),n=B(e,"w:pPr");if(!r)return n;for(let o of Array.from(r.childNodes||[]))o.nodeType!==1||o.namespaceURI!==ae||Bg.has(o.localName)&&n.appendChild(e.importNode(o,!0));return n}function Fg(e){let t=[],r=new Set;for(let o of Array.from(e?.getElementsByTagNameNS?.(ae,"bookmarkStart")||[])){let a=is(o,"name")||"(unnamed)";r.add(a)}for(let o of r)t.push(`RESTORATION_DROPPED_BOOKMARK:${o}`);let n=new Set;for(let o of["commentRangeStart","commentRangeEnd","commentReference"])for(let a of Array.from(e?.getElementsByTagNameNS?.(ae,o)||[])){let i=is(a,"id");i!==""&&n.add(i)}for(let o of n)t.push(`RESTORATION_DROPPED_COMMENT:${o}`);return t}function $g(e){let t=["bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference"];for(let r of t)for(let n of Array.from(e?.getElementsByTagNameNS?.(ae,r)||[]))n.parentNode?.removeChild(n);for(let r of Array.from(e?.getElementsByTagNameNS?.(ae,"r")||[]))Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.namespaceURI===ae&&o.localName!=="rPr")||r.parentNode?.removeChild(r)}function Ug(e,t,r){let n=cr(r.serializeToString(t),{allAuthors:!0}),a=W(n.oxml,"application/xml").doc?.getElementsByTagNameNS?.(ae,"p")?.[0]||null;if(!a)return null;let i=B(e,"w:p");i.appendChild(Cu(e,t));for(let s of Array.from(a.childNodes||[]))s.nodeType===1&&s.namespaceURI===ae&&s.localName==="pPr"||i.appendChild(e.importNode(s,!0));return $g(i),i}async function zg(e,t,r,n,o){let a=te(t);if(a===r)return t;let i=await co(o.serializeToString(t),a,r,{author:n,generateRedlines:!1,structuredContent:!1});if(i?.status==="error"||typeof i?.oxml!="string")return null;let l=(Vr(i.oxml).replacementNodes||[]).find(c=>c?.nodeType===1&&c.namespaceURI===ae&&c.localName==="p");return l?e.importNode(l,!0):null}function Xg(e,t){let r=new Set(se(e).map(o=>o.getAttributeNS?.(ls,"paraId")||o.getAttribute?.("w14:paraId")||"").filter(Boolean).map(o=>o.toUpperCase())),n=null;do n=t?.generateParagraphId?.()||(1073741824+r.size+1).toString(16).toUpperCase();while(r.has(n.toUpperCase()));return n}function Vg(e,t,r,n){let o=e.documentElement;return o&&!o.getAttribute("xmlns:w14")&&o.setAttribute("xmlns:w14",ls),Pu(e,t,null,r,{paragraphId:Xg(e,n),sanitizeParagraphProperties:!0,trackParagraphMark:!0})}function Wg(e,t){let r=nt(e,"pPr"),n=nt(r,"rPr"),o=nt(n,"ins");return!!o&&Au(is(o,"author"))===Au(t)}function jg(e,t){let r=[],n=e;for(let o=0;o<t;o++){if(n=Dg(n,"nextSibling"),!n)return[];r.push(n)}return r}function ss(e){let t=W(e,"application/xml");return t.error||!t.doc?null:se(t.doc).map(r=>te(r))}function Kg(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>r===t[n])}function Aa(e,t){let r=t==="accept"?Er(e,{allAuthors:!0}):cr(e,{allAuthors:!0});return ss(r.oxml)}function Hg(e,t,r,n){let o=W(e,"application/xml");if(o.error||!o.doc)return null;let a=o.doc,i=se(a),s=i[t+n.length-1]||null;if(!s?.parentNode)return null;for(let c of[...r].sort((u,f)=>f-u)){let u=i[c];u?.parentNode?.removeChild(u)}let l=s.nextSibling;for(let c of n)s.parentNode.insertBefore(a.importNode(c,!0),l);return oe().serializeToString(a)}function Gg(e,t,r,n,o,a=[]){let i=ct(e),s=ct(t),l=Ur(s.issues,i.issues),c=a.flatMap(m=>ct(oe().serializeToString(m)).issues.filter(p=>p.severity==="error")),u=zr(l);if(u.length>0||c.length>0)return{valid:!1,stage:"validation",code:"GENERATED_OOXML_INVALID",generatedIssues:l,envelopeIssues:c,message:[...u,...c].map(m=>m.message).join(" ")};let f=Hg(e,r,n,o);if(!f)return{valid:!1,stage:"expected-document",message:"Could not construct the restoration lifecycle oracle."};let d=[["current",ss(f),ss(t)],["accept-all",Aa(f,"accept"),Aa(t,"accept")],["reject-all",Aa(e,"reject"),Aa(t,"reject")]];for(let[m,p,g]of d)if(!Kg(p,g))return{valid:!1,stage:m,expected:p,actual:g,message:`Paragraph restoration ${m} lifecycle text did not match the expected body-scoped paragraph sequence.`};return{valid:!0}}async function Ou(e,t,r,n,o,a=null,i=null,s={}){let{serializer:l,xmlDoc:c,operationSession:u}=Xr(e,s);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let f=qt(c,t,a,"insert",i,s);if(f?.error||!f?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:f?.error||{code:"TARGET_NOT_FOUND",message:"Rejected-view insertion target was not found."}};let d=f.paragraph;if(!ur(d,o).matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"REJECTED_INSERTION_STATE_REQUIRED",message:"Rejected-view insertion requires a wholly deleted paragraph owned by another author."}};let p=Rr(d,{requireFollowingParagraph:!1});if(p)return{documentXml:e,hasChanges:!1,status:"error",error:p};if(/\r|\n/.test(n))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Rejected-view insertion supports run-level text only; use restore for paragraph boundaries."}};let g=te(d,{revisionView:"rejected"});if(!r.occurrenceExplicit&&kg(g,r.exactText)>1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"AMBIGUOUS_ANCHOR",message:"The rejected-view insertion anchor is repeated; provide anchor.occurrence explicitly."}};let h=_g(g,r.exactText,r.occurrence);if(h<0)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"ANCHOR_NOT_FOUND",message:"The rejected-view insertion anchor was not found at the requested occurrence."}};let y=h+r.offset,w=Array.from(d.childNodes||[]).filter(C=>C?.nodeType===1&&C.namespaceURI===ae&&C.localName==="del");if(w.some(C=>Mg(d,C)))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_BOUNDARY",message:"The rejected-view insertion boundary contains comments, bookmarks, fields, hyperlinks, moves, or non-text run markup that cannot be split safely."}};let v=0,b=null,x=0;for(let C of w){let M=Eu(C).length;if(y>=v&&y<=v+M){b=C,x=y-v;break}v+=M}if(!b||w.map(Eu).join("")!==g)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"The rejected-view anchor is not contained in a supported direct deletion carrier."}};let I=Lg(b,x),{leftCarrier:N,rightCarrier:T}=ko(c,b,x,s._revisionIdAllocator||null),E=B(c,"w:ins"),S=ie(o,s._revisionIdAllocator||c,"ins");E.setAttribute("w:id",String(S.id)),E.setAttribute("w:author",S.author),E.setAttribute("w:date",S.date);let O=B(c,"w:r");I&&O.appendChild(I);let A=B(c,"w:t");/^\s|\s$/.test(n)&&A.setAttribute("xml:space","preserve"),A.textContent=n,O.appendChild(A),E.appendChild(O);let P=b.parentNode;N&&P.insertBefore(N,b),P.insertBefore(E,b),T&&P.insertBefore(T,b),s?._mutationRemovedNodes?.push(b),P.removeChild(b),s?._mutationLiveNodes?.push(d,E),u?.invalidateParagraphMetadata?.();let _=l.serializeToString(c),R=te(d,{revisionView:"rejected"}),k=te(d,{revisionView:"accepted"});return R!==g||!k.includes(n)?{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Rejected-view insertion did not preserve the deleted source and expose the requested inserted text."}}:{documentXml:_,hasChanges:!0,status:"ok"}}async function _u(e,t,r,n,o=null,a=null,i=null,s={}){let{serializer:l,xmlDoc:c,operationSession:u}=Xr(e,s);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let f=qt(c,t,o,"restore",i,s);if(f?.error||!f?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:f?.error||{code:"TARGET_NOT_FOUND",message:"Restoration target paragraph not found."}};let d=f.paragraph,m=[d];if(s._compiledSourceEndId){let P=qt(c,s.targetEndDescriptor?.text||"",a,"restore",i,{...s,_compiledSourceId:s._compiledSourceEndId}),_=P?.paragraph?se(c):[],R=_.indexOf(d),k=_.indexOf(P?.paragraph);m=R>=0&&k>=R?_.slice(R,k+1):null}else if(a)m=en(c,o,a,{opType:"restore",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:s.onInfo,onWarn:s.onWarn});else if(s.targetEndDescriptor){let P=qt(c,s.targetEndDescriptor.text,s.targetEndDescriptor.index,"restore",i,{...s,targetDescriptor:s.targetEndDescriptor,_compiledSourceId:s._compiledSourceEndId||null}),_=P?.paragraph?se(c):[],R=_.indexOf(d),k=_.indexOf(P?.paragraph);m=R>=0&&k>=R?_.slice(R,k+1):null}if(!Array.isArray(m)||m.length===0||m[0]!==d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:"The restoration range could not be resolved as a contiguous paragraph block."}};let p=Array.isArray(r)?r.map(String):[String(r||"")];if(p.length!==m.length||p.some(P=>P.length===0))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:`Restoration requires exactly one non-empty replacement per source paragraph (${m.length} expected, ${p.length} received).`}};let g=d.parentNode;if(!g||m.some(P=>P.parentNode!==g))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Restoration source paragraphs must be a contiguous block in one structural container."}};for(let P of m){let _=Rr(P);if(_?.code==="UNSUPPORTED_MOVE_REVISION")return{documentXml:e,hasChanges:!1,status:"error",error:_};let R=ur(P,n);if(!R.matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_STATE_REQUIRED",message:R.hasParagraphMarkDeletion&&!R.foreignParagraphMarkDeletion?"Explicit cross-author restoration does not apply to a paragraph deleted by the current author; use merge-same-author.":"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...R.ownerAuthor?{ownerAuthor:R.ownerAuthor}:{}}};let k=_||Rr(P);if(k)return{documentXml:e,hasChanges:!1,status:"error",error:k}}let h=m[m.length-1],y=jg(h,m.length),w=y.length===m.length&&y.every(P=>Wg(P,n));if(w&&y.every((P,_)=>te(P)===p[_]))return{documentXml:e,hasChanges:!1,status:"no-op",warnings:["An identical same-author paragraph restoration already exists."]};let v=l.serializeToString(c),b=se(c),x=b.indexOf(d),I=w?y.map(P=>b.indexOf(P)):[],N=[],T=[];for(let P=0;P<m.length;P++){let _=m[P];T.push(...Fg(_));let R=Ug(c,_,l),k=R?await zg(c,R,p[P],n,l):null;if(!k)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:`Could not reconstruct restoration paragraph ${P+1} from its rejected revision view.`}};N.push(k)}let E=N.map(P=>{let _=c.importNode(P,!0);return Vg(c,_,n,u)}),S=h.nextSibling;for(let P of E)g.insertBefore(P,S);if(w)for(let P of y)s?._mutationRemovedNodes?.push(P),P.parentNode?.removeChild(P);s?._mutationLiveNodes?.push(...E),ft(c);let O=l.serializeToString(c),A=Gg(v,O,x,I,N,E);return A.valid?{documentXml:ut(c,l,e,u),hasChanges:!0,status:"ok",numberingXml:null,...T.length>0?{warnings:[...new Set(T)]}:{}}:{documentXml:e,hasChanges:!1,status:"error",error:{code:A.code||"PATCH_ROUNDTRIP_MISMATCH",message:A.message,stage:A.stage,...A.generatedIssues?{generatedIssues:A.generatedIssues}:{},...A.envelopeIssues?{envelopeIssues:A.envelopeIssues}:{},...A.expected?{expected:A.expected}:{},...A.actual?{actual:A.actual}:{}}}}async function qg({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:s,runtimeContext:l,revisionIdAllocator:c,generateRedlines:u=!0,onInfo:f=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=nn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p||p.numberingKey!=="numbered:decimal:single"||!Number.isInteger(p.startAt)||p.startAt<1)return null;let g=Ti(p.listInput||i);if(!g)return null;f("[List] Applying explicit numeric header conversion with direct list binding.");let h=await co(t.serializeToString(o),a,g,{author:s,generateRedlines:u,_revisionIdAllocator:c});if(!h?.hasChanges||typeof h?.oxml!="string")return null;let w=Vr(h.oxml).replacementNodes,v=qo(p,l?.listFallbackSequenceState||null),b=p.startAt,x=l?.numberingIdState||null,I=null,N=null;if(v.type==="explicitReuse"&&v.numId)I=String(v.numId),f(`[List] Reusing explicit-start list sequence (${v.numberingKey} -> numId ${I}, next ${b+1}).`);else{let E=ta(x);if(!E)return null;I=String(E.numId),N=oa(E.numId,E.abstractNumId,b),v.type==="explicitStartNew"&&f(`[List] Started explicit-start list sequence (${v.numberingKey} -> numId ${I}).`),f(`[List] Using isolated explicit-start numbering (start ${b}, numId ${I}, abstractNumId ${E.abstractNumId}).`)}p.numberingKey&&l?.listFallbackSharedNumIdByKey instanceof Map&&l.listFallbackSharedNumIdByKey.delete(p.numberingKey),v.type==="explicitStartNew"||v.type==="explicitReuse"?Yo(l?.listFallbackSequenceState||null,v.numberingKey||p.numberingKey,I,b):Vn(l?.listFallbackSequenceState||null,v.numberingKey||p.numberingKey),Zo(w,{numId:I,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0});let T=o.parentNode;if(!T)return null;for(let E of w){let S=e.importNode(E,!0);let O=T.insertBefore(S,o);d?._mutationLiveNodes?.push(O)}if(d?._mutationRemovedNodes?.push(o),T.removeChild(o),ft(e),n?.receiptCollector&&N){let E=cs(d?._mutationLiveNodes);for(let S of E)n.receiptCollector.recordNumbering(S)}return{documentXml:ut(e,t,r,n),hasChanges:!0,numberingXml:N}}async function Yg({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:s,runtimeContext:l,revisionIdAllocator:c,generateRedlines:u=!0,onInfo:f=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=nn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p)return null;f("[List] No textual diff but list marker detected; forcing structural list conversion fallback.");let g=await on(p,{author:s,generateRedlines:u,revisionIdAllocator:c,setAbstractStartOverride:!1});if(!g?.hasChanges||!g?.oxml)return f("[List] Structural list fallback produced no valid OOXML payload."),null;let h=Vr(g.oxml),y=h.replacementNodes,w=h.numberingXml||g?.numberingXml||null,v=Number.isInteger(p?.startAt)&&p.startAt>0,b=g?.listStructuralFallbackKey||p?.numberingKey||null,x=qo(p,l?.listFallbackSequenceState||null);if(v){let N=p.startAt,T=null,E=l?.numberingIdState||null;if(x.type==="explicitReuse"&&x.numId)T=String(x.numId),w=null,f(`[List] Reusing explicit-start list sequence (${x.numberingKey} -> numId ${T}, next ${N+1}).`);else if(E){let S=ta(E);if(!S)return null;ra(y,S.numId),T=String(S.numId),w=oa(S.numId,S.abstractNumId,N),x.type==="explicitStartNew"&&f(`[List] Started explicit-start list sequence (${x.numberingKey} -> numId ${S.numId}).`),f(`[List] Using isolated explicit-start numbering (start ${N}, numId ${S.numId}, abstractNumId ${S.abstractNumId}).`)}else{let S=na(y);T=S?String(S):null,f(`[List] Using isolated list numbering with explicit start ${N}${S?` (numId ${S})`:""}.`)}b&&l?.listFallbackSharedNumIdByKey instanceof Map&&l.listFallbackSharedNumIdByKey.delete(b),x.type==="explicitStartNew"||x.type==="explicitReuse"?Yo(l?.listFallbackSequenceState||null,x.numberingKey||b,T,N):Vn(l?.listFallbackSequenceState||null,x.numberingKey||b),T&&Zo(y,{numId:T,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0})}else{if(w&&l?.numberingIdState){let N=aa(w,y,l.numberingIdState);y=N.replacementNodes,w=N.numberingXml}Vn(l?.listFallbackSequenceState||null,x.numberingKey||b)}if(!v&&l?.listFallbackSharedNumIdByKey instanceof Map){let N=b?l.listFallbackSharedNumIdByKey.get(b):null;if(N)ra(y,N),w=null,f(`[List] Reusing shared list numbering (${b} -> numId ${N}).`);else if(b){let T=na(y);T&&(l.listFallbackSharedNumIdByKey.set(b,T),f(`[List] Captured shared list numbering (${b} -> numId ${T}).`))}}let I=o.parentNode;if(!I)return null;for(let N of y){let T=e.importNode(N,!0);let E=I.insertBefore(T,o);d?._mutationLiveNodes?.push(E)}if(d?._mutationRemovedNodes?.push(o),I.removeChild(o),ft(e),n?.receiptCollector&&w){let N=cs(d?._mutationLiveNodes);for(let T of N)n.receiptCollector.recordNumbering(T)}return{documentXml:ut(e,t,r,n),hasChanges:!0,numberingXml:w}}async function ku(e,t,r,n,o=null,a=null,i=null,s={}){let l=s.generateRedlines!==!1,c=typeof s?.onInfo=="function"?s.onInfo:()=>{},u=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=Xr(e,s);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||gn(d,s),g=qt(d,t,o,"redline",i,{...s,onInfo:c,onWarn:u});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph;if(typeof r=="string"&&r.length>0){let U=ur(h,n);if(U.matches){let G=U.ownerAuthor||"unattributed";return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${G}). Use explicit paragraph restoration when supported.`,ownerAuthor:G}}}}Ig(h);let y=lo(h);if(r===""){let U=Iu(h);if(U.length>0){let G=Tu(U,s._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:U,...G.length>0?{comments:G}:{}}}}}let w=jo(h,r,s);if(!w.valid)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:w.code,message:w.message}};let v=or(h),b=s.existingRevisions||"merge-same-author";if(v&&b!=="accept-all-first"&&b!=="accept-all-first-keep-normalized")if(b==="merge-same-author"||b==="slice-cross-author"){let U=vr(h),G=String(n||"").trim().toLowerCase(),ee=U.length>0&&U.every(ot=>ot.trim().toLowerCase()===G);if(!ee&&b==="merge-same-author")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${U.length?U.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:U,currentPolicy:b}};let Ge=ee?Iu(h):[];if(Ge.length>0){let ot=Tu(Ge,s._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:Ge,...ot.length>0?{comments:ot}:{}}}}if(!ee&&(h.getElementsByTagNameNS(ae,"moveFrom").length>0||h.getElementsByTagNameNS(ae,"moveTo").length>0))return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}}}else{let U=h.getElementsByTagNameNS(ae,"del").length>0,G=h.getElementsByTagNameNS(ae,"moveFrom").length>0||h.getElementsByTagNameNS(ae,"moveTo").length>0;return U?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}}:G?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}}:{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}}if(r===""&&y===""&&!(v&&b==="merge-same-author"))return l?(Nr(d,h,n,ie(n,d)),s?._mutationLiveNodes?.push(h)):(s?._mutationRemovedNodes?.push(h),h.parentNode?.removeChild(h)),ft(d),{documentXml:ut(d,f,e,m),hasChanges:!0,numberingXml:null};let x=We(h,"tbl"),N=!!x&&!a&&typeof r=="string"&&r.includes(`
|
|
220
|
+
`)&&!Or(r)?Eg(d,x,r):null,T=i?.tableStructuralRedlineKeys instanceof Set?i.tableStructuralRedlineKeys:null;if(N&&T?.has(N))return c("[Table] Skipping duplicate table-structural redline for the same table/payload in this turn."),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:["Skipped duplicate table-structural redline in the same turn."]};let S=(x?Ei(h,r,{tableElement:x,currentParagraphText:y,onInfo:c,onWarn:u}):null)||r,O=!!x&&Or(S),A=Or(S),P=a?en(d,o,a,{opType:"redline",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:c,onWarn:u}):typeof t=="string"&&/\r?\n/.test(t)?Mo(d,t):null,_=Array.isArray(P)&&P.length>0;if(!O&&_){let U=wu(P,S);if(U&&U.length>0){c(`[List] Applying explicit-range insertion-only heuristic (${U.length} new item(s)).`);for(let ee of U)c(`[List] Explicit-range insertion: ilvl=${ee.ilvl}, markerType=${ee.markerType}, text="${String(ee.text||"").slice(0,80)}${String(ee.text||"").length>80?"\u2026":""}"`);if(Rg({xmlDoc:d,explicitRangeParagraphs:P,insertionEntries:U,generateRedlines:l,author:n}))return{documentXml:ut(d,f,e,m),hasChanges:!0,numberingXml:null}}}let R=null;!P&&!O&&A&&(R=Si(h,{getParagraphText:lo}),R?.length>1&&c(`[Table] Heuristic range expansion selected ${R.length} paragraph(s) for replacement.`));let k=lt(h);if(k&&typeof S=="string"&&!S.includes(`
|
|
221
|
+
`)){let U=kr(S);U&&U!==S.trim()&&(c("[List] Stripped redundant manual list marker prefix from single-line list item edit."),S=U)}O&&c("[Table] Markdown table edit detected in table cell target; applying reconciliation at table scope.");let C=s.explicitStructuredContent===!0,M=!C&&!O&&!_&&k?yu(y,S):null;if(M){c(`[List] Applying single-paragraph list adjacency insertion heuristic (${M.position}).`);let U=h.parentNode;if(!U)throw new Error("Target paragraph has no parent for adjacency list insertion");let G=as(d,h,{ilvl:k.ilvl,numId:k.numId,markerType:"numbered",text:M.text},l?ie(n,d):null,n,{generateRedlines:l}),ee=M.position==="before"?h:h.nextSibling;return U.insertBefore(G,ee),s?._mutationLiveNodes?.push(G),ft(d),{documentXml:ut(d,f,e,m),hasChanges:!0,numberingXml:null}}let $=!C&&!O&&!_&&!k?vu(y,S):null;if($){c(`[Text] Applying single-paragraph plain adjacency insertion heuristic (${$.position}, count=${$.paragraphs.length}).`);let U=h.parentNode;if(!U)throw new Error("Target paragraph has no parent for plain adjacency insertion");let G=$.position==="before"?h:h.nextSibling;for(let ee of $.paragraphs){let Ge=await Og(d,h,ee,l?ie(n,d):null,n,{generateRedlines:l}),ot=d.importNode(Ge,!0);let go=U.insertBefore(ot,G);s?._mutationLiveNodes?.push(go)}return ft(d),{documentXml:ut(d,f,e,m),hasChanges:!0,numberingXml:null}}let X=!C&&!O&&!_?Ni(h,S,{currentParagraphText:y,onInfo:c,onWarn:u}):null;if(X&&X.entries.length>0){c(`[List] Applying insertion-only list redline heuristic (${X.entries.length} new item(s)).`);for(let ee of X.entries)c(`[List] Insertion entry resolved: ilvl=${ee.ilvl}, markerType=${ee.markerType}, text="${String(ee.text||"").slice(0,80)}${String(ee.text||"").length>80?"\u2026":""}"`);let U=h.parentNode;if(!U)throw new Error("Target paragraph has no parent for list insertion");let G=h.nextSibling;for(let ee of X.entries){let Ge=as(d,h,{...ee,numId:X.numId},l?ie(n,d):null,n,{generateRedlines:l});U.insertBefore(Ge,G),s?._mutationLiveNodes?.push(Ge)}return ft(d),{documentXml:ut(d,f,e,m),hasChanges:!0,numberingXml:null}}let V=!C&&!O&&!_?bi(h,S,{currentParagraphText:y,onInfo:c,onWarn:u}):null,Y=!!V&&Array.isArray(V.paragraphs)&&V.paragraphs.length>0;if(Y&&(S=V.modifiedText),!C&&!O&&!Y&&!_){let U=await qg({xmlDoc:d,serializer:f,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:y,modifiedText:S,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:l,onInfo:c,options:s});if(U)return U;let G=await Yg({xmlDoc:d,serializer:f,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:y,modifiedText:S,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:l,onInfo:c,options:s});if(G)return G}let ye=Y?V.originalText:P?P.map(U=>lo(U)).join(`
|
|
222
|
+
`):R?R.map(U=>lo(U)).join(`
|
|
223
|
+
`):y||t,fe=O?f.serializeToString(x):Y?os(V.paragraphs,f):P?os(P,f):R?os(R,f):f.serializeToString(h),H=A?await vg(fe,ye,S,{author:n,generateRedlines:l,existingRevisions:s.existingRevisions||"merge-same-author",structuredContent:s.structuredContent!==!1,explicitStructuredContent:s.explicitStructuredContent===!0,_revisionIdAllocator:p,_isolatedTableCell:O}):await co(fe,ye,S,{author:n,generateRedlines:l,existingRevisions:s.existingRevisions||"merge-same-author",structuredContent:s.structuredContent!==!1,explicitStructuredContent:s.explicitStructuredContent===!0,pairReplacements:s.pairReplacements===!0,insertionAffinity:s.insertionAffinity||null,_revisionIdAllocator:p,_isolatedTableCell:O});if(!H?.hasChanges)return{documentXml:e,hasChanges:!1,numberingXml:null,status:H?.status||"no-op",error:H?.error};if(H.useNativeApi&&!H.oxml){let U="Format-only fallback requires native Word API; browser demo skipped this operation.";return u(`[WARN] ${U}`),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:[U]}}if(typeof H.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed redline operation");let q=Vr(H.oxml),ge=bg(q.replacementNodes,H.warnings),ce=q.numberingXml;if(ce&&i?.numberingIdState){let U=aa(ce,ge,i.numberingIdState);ge=U.replacementNodes,ce=U.numberingXml}let ve=O?[x]:Y?V.paragraphs:P||R||[h],j=ve[0],z=j.parentNode;for(let U of ge){let G=d.importNode(U,!0);let ee=z.insertBefore(G,j);s?._mutationLiveNodes?.push(ee)}for(let U of ve)U&&U.parentNode===z&&(s?._mutationRemovedNodes?.push(U),z.removeChild(U));if(ft(d),N&&T&&(O||x)&&T.add(N),m?.receiptCollector&&ce){let U=cs(s?._mutationLiveNodes);for(let G of U)m.receiptCollector.recordNumbering(G)}return{documentXml:ut(d,f,e,m),hasChanges:!0,numberingXml:ce,status:"ok",...Array.isArray(H.warnings)&&H.warnings.length>0?{warnings:H.warnings}:{}}}async function Mu(e,t,r,n,o,a=null,i=null,s={}){let l=s.generateRedlines!==!1,c=typeof s?.onInfo=="function"?s.onInfo:()=>{},u=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=Xr(e,s);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||gn(d,s),g=qt(d,t,a,"highlight",i,{...s,onInfo:c,onWarn:u});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,y=f.serializeToString(h),w=Ui(y,r,n,{generateRedlines:l,author:o,_revisionIdAllocator:p});if(!w||w===y)return{documentXml:e,hasChanges:!1};let{replacementNodes:v}=Vr(w),b=h.parentNode;for(let x of v){let I=d.importNode(x,!0);let N=b.insertBefore(I,h);s?._mutationLiveNodes?.push(N)}return s?._mutationRemovedNodes?.push(h),b.removeChild(h),ft(d),{documentXml:ut(d,f,e,m),hasChanges:!0}}async function Lu(e,t,r,n,o,a=null,i=null,s={}){let l=typeof s?.onInfo=="function"?s.onInfo:()=>{},c=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:u,xmlDoc:f,operationSession:d}=Xr(e,s);if(!f)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||gn(f,s);let m=qt(f,t,a,"comment",i,{...s,onInfo:l,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=u.serializeToString(p),h=typeof r=="string"&&r.length>0?r:lo(p),y=Fi(g,[{paragraphIndex:1,textToFind:h,commentContent:n}],{author:o,commentIdAllocator:s.commentIdAllocator});if(y.status==="error"||y.error||!y.commentsApplied)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:y.error||{code:"ANCHOR_INSERTION_FAILED",message:"The comment anchor was not applied to the resolved paragraph."},warnings:y.warnings||[]};let{replacementNodes:w}=Vr(y.oxml),v=p.parentNode;for(let b of w){let x=f.importNode(b,!0);let I=v.insertBefore(x,p);s?._mutationLiveNodes?.push(I)}if(s?._mutationRemovedNodes?.push(p),v.removeChild(p),ft(f),d?.receiptCollector&&Array.isArray(y.placedComments))for(let b of y.placedComments)d.receiptCollector.recordComment(b.id);return{documentXml:ut(f,u,e,d),hasChanges:!0,commentsXml:y.commentsXml||null,warnings:y.warnings||[],resolvedAnchor:y.resolvedAnchors?.[0]||null}}function Ru(e,t,r,n){let o=t.cloneNode(!0),a=t.cloneNode(!0);Ot(a,n);let i=d=>{if(d.nodeType!==1)return!1;let m=d.localName||d.nodeName.replace(/^w:/,"");return["t","tab","br","noBreakHyphen","delText"].includes(m)};Array.from(o.childNodes).forEach(d=>{i(d)&&o.removeChild(d)}),Array.from(a.childNodes).forEach(d=>{i(d)&&a.removeChild(d)});let s="";for(let d of Array.from(t.childNodes)){if(d.nodeType!==1)continue;let m=d.localName||d.nodeName.replace(/^w:/,"");m==="t"?s+=d.textContent||"":m==="tab"?s+=" ":m==="br"?s+=`
|
|
224
|
+
`:m==="noBreakHyphen"&&(s+="\u2011")}let l=s.slice(0,r),c=s.slice(r),u=(d,m)=>{let p=m.split(/(\t|\n|\u2011)/);for(let g of p)if(g)if(g===" ")d.appendChild(B(e,"w:tab"));else if(g===`
|
|
225
|
+
`)d.appendChild(B(e,"w:br"));else if(g==="\u2011")d.appendChild(B(e,"w:noBreakHyphen"));else{let h=B(e,"w:t");/^\s|\s$/.test(g)&&h.setAttribute("xml:space","preserve"),h.textContent=g,d.appendChild(h)}};u(o,l),u(a,c);let f=t.parentNode;return f.insertBefore(o,t),f.insertBefore(a,t),f.removeChild(t),[o,a]}async function Bu(e,t,r,n={},o,a=null,i=null,s={}){let l=s.generateRedlines!==!1,c=typeof s?.onInfo=="function"?s.onInfo:()=>{},u=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=Xr(e,s);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||gn(d,s),g=qt(d,t,a,"format",i,{...s,onInfo:c,onWarn:u});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,w=(()=>{let P=[],_=Array.from(h.getElementsByTagNameNS(ae,"r"));for(let R of _){let k=R.parentNode,C=!1;for(;k&&k!==h;){if(k.nodeType===1&&(k.localName==="del"||k.nodeName==="w:del")){C=!0;break}k=k.parentNode}if(C)continue;let M="";for(let $ of Array.from(R.childNodes)){if($.nodeType!==1)continue;let X=$.localName||$.nodeName.replace(/^w:/,"");X==="t"?M+=$.textContent||"":X==="tab"?M+=" ":X==="br"?M+=`
|
|
226
|
+
`:X==="noBreakHyphen"&&(M+="\u2011")}M.length>0&&P.push({run:R,text:M})}return P})(),v="",b=[];for(let P of w){let _=v.length;v+=P.text;let R=v.length;b.push({...P,start:_,end:R})}let I=s.targetDescriptor?.occurrence??null,N=-1;if(I!=null&&I>0){let P=0,_=0;for(;_<=v.length-r.length;){let R=v.indexOf(r,_);if(R===-1)break;if(P++,P===I){N=R;break}_=R+1}}else N=v.indexOf(r);if(N===-1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:`Text to format was not found in target paragraph: "${r}".`}};let T=N+r.length,E=[];for(let P of b)if(P.start<N&&P.end>N){let _=N-P.start,[R,k]=Ru(d,P.run,_,p);E.push({run:R,start:P.start,end:N,text:P.text.slice(0,_)}),E.push({run:k,start:N,end:P.end,text:P.text.slice(_)})}else E.push(P);let S=[];for(let P of E)if(P.start<T&&P.end>T){let _=T-P.start,[R,k]=Ru(d,P.run,_,p);S.push({run:R,start:P.start,end:T,text:P.text.slice(0,_)}),S.push({run:k,start:T,end:P.end,text:P.text.slice(_)})}else S.push(P);let O=S.filter(P=>P.start>=N&&P.end<=T),A=!1;for(let P of O){let _=P.run.getElementsByTagNameNS(ae,"rPr")[0]||null;if(wl(_,n)){A=!0;break}}if(!A)return{documentXml:e,hasChanges:!1,status:"no-op"};for(let P of O){let _=P.run,R=_.getElementsByTagNameNS(ae,"rPr")[0];R||(R=B(d,"w:rPr"),_.insertBefore(R,_.firstChild));let k=_.parentNode,C=!1;for(;k&&k!==h;){if(k.nodeType===1&&(k.localName==="ins"||k.nodeName==="w:ins")){(k.getAttribute("w:author")||k.getAttributeNS(ae,"author"))===(o||re())&&(C=!0);break}k=k.parentNode}let M=C&&s.formattingRevisionPolicy==="coalesce-own-insertion";l&&!M&&On(d,R,o||re()),yl(d,R,n)}return ft(d),s?._mutationLiveNodes?.push(h),{documentXml:ut(d,f,e,m),hasChanges:!0,status:"ok"}}async function Du(e,t,r={},n,o=null,a=null,i={}){let s=i.generateRedlines!==!1,l=typeof i?.onInfo=="function"?i.onInfo:()=>{},c=typeof i?.onWarn=="function"?i.onWarn:()=>{},{serializer:u,xmlDoc:f,operationSession:d}=Xr(e,i);if(!f)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||gn(f,i);let m=qt(f,t,o,"paragraph-format",a,{...i,onInfo:l,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=p.getElementsByTagNameNS(ae,"pPr")[0];return g||(g=B(f,"w:pPr"),p.insertBefore(g,p.firstChild)),vl(g,r)?(s&&Rl(f,g,n||re()),xl(f,g,r),ft(f),i?._mutationLiveNodes?.push(p),{documentXml:ut(f,u,e,d),hasChanges:!0,status:"ok"}):{documentXml:e,hasChanges:!1,status:"no-op"}}function Ee(e,t={}){return Ze(e,t)}async function us(e,t,r,n=null,o={}){let a=typeof o._operationIndex=="number"?o._operationIndex:1,i={operationIndex:a,...typeof t?.operationId=="string"?{operationId:t.operationId}:{}},s=Ht(t);if(!s.valid){let h=wt(t,r,re());return{documentXml:e,hasChanges:!1,status:"error",error:Ee(s.error,i),operationType:rt(t).operationKind,authorUsed:h,receipt:_e(a,t?.operationId,h,"refused")}}let l=s.operation||rt(t),c=wt(l,r,re());if(l.operationKind!=="comment_reply"&&l.operationKind!=="comment_resolve"&&l.operationKind!=="rejected-insert"&&l.operationKind!=="restore"&&(l.targetDescriptor?.revisionView==="rejected"||l.targetEndDescriptor?.revisionView==="rejected"))return{documentXml:e,hasChanges:!1,status:"error",error:Ee({code:"UNSUPPORTED_REVISION_VIEW_MUTATION",message:"Targeting rejected revision view for mutation is not supported yet."},i),operationType:l.operationKind,authorUsed:c,receipt:_e(a,l.operationId,c,"refused")};if(!o?._documentOperationSession&&o?.expectedRevision){let h=Br(o.expectedRevision);if(!h.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ee({code:h.error?.code||"INVALID_REVISION_TOKEN",message:h.error?.message||"Invalid revision token."},i),operationType:l.operationKind,authorUsed:c,receipt:_e(a,l.operationId,c,"refused")};if(o.expectedRevision.scope!=="document-parts")return{documentXml:e,hasChanges:!1,status:"error",error:Ee({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`},i),operationType:l.operationKind,authorUsed:c,receipt:_e(a,l.operationId,c,"refused")};let y=await Yn({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!Dr(y.value,o.expectedRevision.value))return{documentXml:e,hasChanges:!1,status:"error",error:Ee({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${y.value}'.`,expectedRevision:o.expectedRevision,currentRevision:y},i),operationType:l.operationKind,authorUsed:c,receipt:_e(a,l.operationId,c,"refused")}}let u=o?._documentOperationSession instanceof pr?o._documentOperationSession:new pr(e,o);if(!u.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ee(u.parseResult.error,i),warnings:u.parseResult.warnings,operationType:l.operationKind,authorUsed:c,receipt:_e(a,l.operationId,c,"refused")};if(Array.isArray(l.replacements)||l.operationKind==="restore"&&t?.modified===void 0){let h=hn(u.document,[t],{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn}),y=h.bindings[0]?.error||h.conflicts[0]||null;if(y)return{documentXml:e,hasChanges:!1,status:"error",error:Ee(y,i),operationType:l.operationKind,authorUsed:c,receipt:_e(a,l.operationId,c,"refused")};let w=Ht(h.compiledOperations[0]);if(!w.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ee(w.error,i),operationType:l.operationKind,authorUsed:c,receipt:_e(a,l.operationId,c,"refused")};u.sourceTargetRegistry=h.registry,l=w.operation}let f={},d=null,m=u.createSavepoint();u.receiptCollector?.beginOperation(a,l.operationId,c);let p=Array.isArray(l._compiledWarnings)?[...l._compiledWarnings]:[],g={...o,...typeof l.generateRedlines=="boolean"?{generateRedlines:l.generateRedlines}:{},...l.existingRevisions?{existingRevisions:l.existingRevisions}:{},structuredContent:typeof l.structuredContent=="boolean"?l.structuredContent:o.structuredContent!==!1,explicitStructuredContent:l.structuredContent===!0,pairReplacements:typeof l.pairReplacements=="boolean"?l.pairReplacements:o.pairReplacements!==!1,...l.insertionAffinity?{insertionAffinity:l.insertionAffinity}:{},...l.formattingRevisionPolicy?{formattingRevisionPolicy:l.formattingRevisionPolicy}:{},targetDescriptor:l.targetDescriptor,targetEndDescriptor:l.targetEndDescriptor,_compiledSourceId:l._compiledSourceId||null,_compiledSourceEndId:l._compiledSourceEndId||null,_compiledResolvedBy:l._compiledResolvedBy||null,_sourceTargetRegistry:u.sourceTargetRegistry||null,_resolutionCapture:f,_revisionIdAllocator:u.revisionIdAllocator,_documentOperationSession:u,_mutationLiveNodes:[],_mutationRemovedNodes:[],onInfo:h=>{typeof o?.onInfo=="function"&&o.onInfo(h)},onWarn:h=>{p.push(String(h)),typeof o?.onWarn=="function"&&o.onWarn(h)}};try{let h;if(l.operationKind==="comment_reply"){let v=u.commentsXml||n?.commentsXml||o.commentsXml,b=u.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,x=typeof o.commentIdAllocator=="function"?o.commentIdAllocator():null;if(x==null&&v){let I=[...v.matchAll(/<(?:w:)?comment\b[^>]*\b(?:w:)?id=["'](\d+)["']/g)].map(N=>Number(N[1]));x=(I.length?Math.max(...I):-1)+1}x==null?h={documentXml:e,hasChanges:!1,status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing comments part."}}:(h=$i({commentsXml:v,commentsExtendedXml:b,documentXml:e,parentCommentId:l.parentCommentId,commentId:x,commentContent:l.commentContent,author:c,date:l.date||new Date().toISOString()}),h.documentXml=e,h.status!=="error"&&h.hasChanges&&(!u.document||!Pc(u.document,h.threadCommentIds,x)?h={documentXml:e,hasChanges:!1,status:"error",error:{code:"PARENT_ANCHOR_NOT_FOUND",message:`Comment '${l.parentCommentId}' has no anchor in the document body, so a reply cannot be placed.`}}:u.receiptCollector&&u.receiptCollector.recordComment(x)))}else if(l.operationKind==="comment_resolve"){let v=ua({commentsXml:u.commentsXml||n?.commentsXml||o.commentsXml,commentsExtendedXml:u.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,commentId:l.commentId,resolved:l.resolved!==!1});h=v.status==="error"?{documentXml:e,hasChanges:!1,status:"error",error:v.error}:{documentXml:e,hasChanges:v.hasChanges,...v.commentsXml?{commentsXml:v.commentsXml,commentsXmlMode:"replace"}:{},...v.commentsExtendedXml?{commentsExtendedXml:v.commentsExtendedXml,commentsExtendedXmlMode:"replace"}:{},resolved:v.resolved,threadRootId:v.threadRootId,commentIds:v.commentIds}}else l.operationKind==="highlight"?h=await Mu(e,l.target,l.textToHighlight,l.color,c,l.targetRef,n,g):l.operationKind==="comment"?h=await Lu(e,l.target,l.textToComment,l.commentContent,c,l.targetRef,n,g):l.operationKind==="format"?h=await Bu(e,l.target,l.textToFormat,l.properties,c,l.targetRef,n,g):l.operationKind==="paragraph-format"?h=await Du(e,l.target,l.properties,c,l.targetRef,n,g):l.operationKind==="rejected-insert"?h=await Ou(e,l.target,l.anchor,l.modified,c,l.targetRef,n,g):l.operationKind==="restore"?h=await _u(e,l.target,l.modified,c,l.targetRef,l.targetEndRef,n,g):h=await ku(e,l.target,l.modified,c,l.targetRef,l.targetEndRef,n,g);if((l.operationKind==="comment"||l.operationKind==="comment_reply")&&h?.hasChanges!==!0&&h?.status!=="error"&&!h?.error&&(h={...h,status:"error",error:{code:"COMMENT_NOT_APPLIED",message:"The comment operation completed without placing a comment."}}),p.length>0&&h){let v=Array.from(new Set([...Array.isArray(h.warnings)?h.warnings:[],...p]));h.warnings=v}let y=h?.status==="error"||!!h?.error,w=null;if(y||h?.hasChanges!==!0){u.restoreSavepoint(m);let v=y?"refused":"no_change";if(w=_e(a,l.operationId,c,v),Array.isArray(h?.warnings))for(let b of h.warnings)w.warnings.push(String(b))}else{let v=ct(m.document),b=ct(u.document),x=Ur(b.issues,v.issues),I=zr(x);if(I.length>0){u.restoreSavepoint(m),w=_e(a,l.operationId,c,"refused");let N=[...new Set(I.map(T=>T.code))].join(", ");return{documentXml:e,hasChanges:!1,status:"error",error:Ee({code:"GENERATED_OOXML_INVALID",stage:"validation",message:`Operation introduced invalid OOXML (${N}).`,generatedIssues:I},i),operationType:l.operationKind,authorUsed:c,receipt:w,...f}}if(u.markMutationCommitted(!0),l._compiledSourceId&&u.sourceTargetRegistry&&u.sourceTargetRegistry.commitMutation(l._compiledSourceId,g._mutationRemovedNodes,g._mutationLiveNodes,a),l._localizedReplacementCompilation){let N=null;if(l.operationKind==="restore"){let T=g._mutationLiveNodes.find(E=>E?.localName==="p");T&&(N=te(T,{revisionView:"accepted"}))}else if(l._compiledSourceId&&u.sourceTargetRegistry){let T=u.sourceTargetRegistry.resolve(l._compiledSourceId,u.document);T.paragraph&&(N=te(T.paragraph,{revisionView:"accepted"}))}d=lu(l._localizedReplacementCompilation,N,f.resolvedTarget||{},l._speculativeContext||null)}if(l.captureKey&&u.captureTable&&u.captureTable.set(l.captureKey,xu(u,l,g._mutationLiveNodes)),g._mutationRemovedNodes?.length>0&&u.captureTable&&bu(u.captureTable,g._mutationRemovedNodes),f.resolvedTarget&&u.receiptCollector?.recordAffectedTarget(f.resolvedTarget),Array.isArray(h.warnings))for(let N of h.warnings)u.receiptCollector?.recordWarning(N);if(w=u.receiptCollector?.commitOperation("applied"),h.documentXml=u.deferSerialization?u.currentDocumentXml:u.serializeCurrent(),!u.deferSerialization&&w){let N=ao({documentXml:h.documentXml,commentsXml:h.commentsXml||null,numberingXml:h.numberingXml||null},[w]);if(!N.valid)return u.restoreSavepoint(m),w.finalDisposition="rolled_back",w.committed=!1,{documentXml:e,hasChanges:!1,status:"error",error:Ee(N.error,i),warnings:[N.error.message],operationType:l.operationKind,authorUsed:c,receipt:w,...f}}}return h?.error&&(h.error=Ee(h.error,i)),{...h,operationType:l.operationKind,authorUsed:c,receipt:w,...d?{change:d}:{},...f}}catch(h){u.restoreSavepoint(m);let y=Ee(h,i),w=_e(a,l.operationId,c,"refused");return w.warnings.push(y.message),{documentXml:e,hasChanges:!1,status:"error",error:y,warnings:[y.message],operationType:l.operationKind,authorUsed:c,receipt:w,...f}}}var Fu="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function $u(e){return e?.type==="comment"||e?.type==="comment_reply"||e?.type==="comment_resolve"?0:1}function Ra(e=[]){let t=Array.isArray(e)?e:[],r=new Map;for(let c=0;c<t.length;c++){let u=t[c],f=u?.captureKey??u?.targetDescriptor?.captureKey;if(f!=null){if(typeof f!="string"||!f.trim()||f.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} declared an invalid captureKey: must be a non-empty string under 256 characters.`}};let d=f.trim();if(r.has(d)){let m=r.get(d);return{valid:!1,error:{code:"DUPLICATE_CAPTURE_KEY",message:`Duplicate capture key "${d}" declared by operations at indices ${m+1} and ${c+1}.`}}}r.set(d,c)}}let n=new Array(t.length).fill(0),o=Array.from({length:t.length},()=>new Set),a=Array.from({length:t.length},()=>new Set),i=new Map;for(let c=0;c<t.length;c++){let u=t[c],f=u?.target?.captureRef??u?.targetDescriptor?.captureRef;if(f!=null){if(typeof f!="string"||!f.trim()||f.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} referenced an invalid captureRef: must be a non-empty string under 256 characters.`}};let d=f.trim();if(!r.has(d))return{valid:!1,error:{code:"CAPTURE_NOT_FOUND",message:`Capture "${d}" referenced by operation ${c+1} was not found in the batch.`}};let m=r.get(d);if(m===c)return{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:`Capture dependency cycle detected: operation ${c+1} references its own capture "${d}".`}};a[c].has(m)||(a[c].add(m),o[m].add(c),n[c]++);let p=rt(u).operationKind;p!=="comment"&&p!=="comment_reply"&&p!=="comment_resolve"&&(i.has(d)||i.set(d,[]),i.get(d).push({index:c,select:u?.target?.select??u?.targetDescriptor?.select??null}))}}for(let[c,u]of i){if(u.length<2)continue;let f=u.map(m=>m.select),d=new Set(f);if(!(f.every(m=>typeof m=="string"&&m.length>0)&&d.size===f.length))return{valid:!1,error:{code:"CAPTURE_FANOUT_CONFLICT",message:`Capture "${c}" has overlapping or unscoped mutating consumers at operation indices ${u.map(m=>m.index+1).join(", ")}.`,operationIndexes:u.map(m=>m.index+1),captureRef:c}}}let s=[];for(let c=0;c<t.length;c++)n[c]===0&&s.push({operation:t[c],index:c});let l=[];for(;s.length>0;){s.sort((u,f)=>$u(u.operation)-$u(f.operation)||u.index-f.index);let c=s.shift();l.push(c);for(let u of o[c.index])n[u]--,n[u]===0&&s.push({operation:t[u],index:u})}return l.length<t.length?{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:"Capture dependency cycle detected among batch operations."}}:{valid:!0,scheduled:l,captureProducers:r}}function Zg(e,t){if(!t)return e;if(!e)return t;let r=W(e,"application/xml")?.doc,n=W(t,"application/xml")?.doc;if(!r||!n)return e;let o=oe(),a=r.documentElement,i=new Set(Array.from(r.getElementsByTagNameNS(Fu,"comment")).map(s=>s.getAttribute("w:id")||s.getAttribute("id")).filter(Boolean));for(let s of Array.from(n.getElementsByTagNameNS(Fu,"comment"))){let l=s.getAttribute("w:id")||s.getAttribute("id");l&&i.has(l)||(a.appendChild(r.importNode(s,!0)),l&&i.add(l))}return o.serializeToString(r)}async function Pa(e,t,r,n=null,o={}){let a=Array.isArray(t)?t:[],i=re(),s=()=>a.map((A,P)=>_e(P+1,A?.operationId,wt(A,r,i),"not_attempted")),l=(A,P={})=>{let _=s();return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:[],receipts:_,executionOrder:[],authorsUsed:[],...o.atomic===!0?{rolledBack:!0}:{},status:"error",error:Ee(A),retryPlan:Kt({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:[],receipts:_,operationCount:a.length}),...P}};if(o.existingRevisions!=null&&!so(o.existingRevisions))return l({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(o.existingRevisions)}".`,field:"existingRevisions"});if(o?.expectedRevision){let A=Br(o.expectedRevision);if(!A.valid)return l({code:A.error?.code||"INVALID_REVISION_TOKEN",message:A.error?.message||"Invalid revision token."});if(o.expectedRevision.scope!=="document-parts")return l({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`,expectedScope:"document-parts",actualScope:o.expectedRevision.scope});let P=await Yn({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!Dr(P.value,o.expectedRevision.value))return l({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${P.value}'.`,expectedRevision:o.expectedRevision,currentRevision:P})}let c=o?._documentOperationSession instanceof pr?o._documentOperationSession:new pr(e,{...o,_deferDocumentSerialization:!0});if(!c.valid)return l(c.parseResult.error,{warnings:c.parseResult.warnings});let u=hn(c.document,a,{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn});if(c.sourceTargetRegistry=u.registry,u.conflicts.length>0){let A=new Map;for(let R of u.conflicts)for(let k of R.operationIndexes)A.has(k)||A.set(k,R);let P=Array.from(A,([R,k])=>{let C=a[R-1],M=wt(C,r,i),$=Ee(k,{operationIndex:R,...C?.operationId?{operationId:C.operationId}:{}});return{index:R,type:C?.type||"redline",operationType:rt(C).operationKind,status:"error",authorUsed:M,error:$,receipt:_e(R,C?.operationId,M,"refused")}}).sort((R,k)=>R.index-k.index),_=a.map((R,k)=>P.find(M=>M.index===k+1)?.receipt||_e(k+1,R?.operationId,wt(R,r,i),"not_attempted"));return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:P,receipts:_,executionOrder:[],authorsUsed:[],rolledBack:o.atomic===!0,status:"error",error:Ee(u.conflicts[0]),conflicts:u.conflicts.map(R=>Ee(R)),retryPlan:Kt({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:P,receipts:_,operationCount:a.length})}}let f=u.compiledOperations,d=Ra(f);if(!d.valid)return l(d.error);let m=d.scheduled,p=o.atomic===!0,g=o.continueOnError!==!1,h=fu(n);h.targetRefSnapshot instanceof Map||(h.targetRefSnapshot=c.initialTargetReferenceSnapshot),c.runtimeContext=h,a.some(A=>A?.type==="comment_reply"||A?.type==="comment_resolve")&&(c.commentsXml=h.commentsXml||o.commentsXml||null,c.commentsExtendedXml=h.commentsExtendedXml||o.commentsExtendedXml||null,c.commentsXmlMode="replace",c.commentsExtendedXmlMode="replace");let y=!1,w=c.results,v=c.executionOrder,b=c.authorsUsed,x=!1;for(let{operation:A,index:P}of m){v.push(P+1);let _=u.bindings[P];if(_?.error){x=!0;let R=wt(A,r,i),k=_e(P+1,A?.operationId,R,"refused"),C=Ee(_.error,{operationIndex:P+1,...A?.operationId?{operationId:A.operationId}:{}});if(k.warnings.push(C.message),w.push({index:P+1,type:A?.type||"redline",status:"error",operationType:rt(A).operationKind,authorUsed:R,warnings:[C.message],error:C,receipt:k}),!g)break;continue}try{let R=await us(c.currentDocumentXml,A,r,h,{...o,_documentOperationSession:c,_deferDocumentSerialization:!0,_operationIndex:P+1});y=y||R.hasChanges===!0,c.commentsXml=R.commentsXmlMode==="replace"?R.commentsXml||c.commentsXml:Zg(c.commentsXml,R.commentsXml||null),c.commentsExtendedXml=(R.commentsExtendedXmlMode==="replace",R.commentsExtendedXml||c.commentsExtendedXml),R.commentsXmlMode==="replace"&&(c.commentsXmlMode="replace"),R.commentsExtendedXmlMode==="replace"&&(c.commentsExtendedXmlMode="replace"),R.numberingXml&&c.numberingXmlParts.push(R.numberingXml);let k=R.status==="error"||!!R.error;if(x=x||k,!k&&R.hasChanges&&R.authorUsed&&b.add(R.authorUsed),w.push({index:P+1,type:A?.type||"redline",status:k?"error":R.hasChanges?"applied":"no_change",operationType:R.operationType||"redline",authorUsed:R.authorUsed,...R.resolvedBy?{resolvedBy:R.resolvedBy}:{},...R.resolvedTarget?{resolvedTarget:R.resolvedTarget}:{},...R.resolvedAnchor?{resolvedAnchor:R.resolvedAnchor}:{},...R.change?{change:R.change}:{},...R.operationType==="comment_resolve"&&!k?{resolved:R.resolved,threadRootId:R.threadRootId,commentIds:R.commentIds}:{},...Array.isArray(R.warnings)&&R.warnings.length>0?{warnings:R.warnings}:{},...R.error?{error:R.error}:{},...R.receipt?{receipt:R.receipt}:{}}),k&&!g)break}catch(R){let k=Ee(R,{operationIndex:P+1,...A?.operationId?{operationId:A.operationId}:{}});x=!0;let C=wt(A,r,re()),M=_e(P+1,A?.operationId,C,"refused");if(M.warnings.push(k.message),w.push({index:P+1,type:A?.type||"redline",status:"error",operationType:rt(A).operationKind,authorUsed:C,warnings:[k.message],error:k,receipt:M}),!g)break}}w.sort((A,P)=>A.index-P.index);let I=[];for(let A=0;A<a.length;A++){let P=A+1,_=w.find(R=>R.index===P);if(_?.receipt)I.push(_.receipt);else{let R=_e(P,a[A]?.operationId,wt(a[A],r,i),"not_attempted");I.push(R)}}let N=p&&x,T=e,E=null;if(!N&&y)try{T=c.serializeCurrent()}catch(A){E=Ee(A),N=!0}let S=null;if(!N&&y){let A=ao({documentXml:T,commentsXml:c.commentsXml,commentsExtendedXml:c.commentsExtendedXml,numberingXmlParts:c.numberingXmlParts},I);A.valid||(S=A.error,p&&(N=!0))}if(N){for(let A of w)A.receipt&&A.receipt.attemptedDisposition==="applied"&&(A.receipt.finalDisposition="rolled_back",A.receipt.committed=!1),A.change&&(A.change.finalDisposition="rolled_back",A.change.committed=!1);for(let A of I)A.attemptedDisposition==="applied"&&(A.finalDisposition="rolled_back",A.committed=!1)}else{for(let A of w)A.receipt&&A.receipt.attemptedDisposition==="applied"&&(A.receipt.committed=!0,A.receipt.finalDisposition="applied"),A.change&&(A.change.finalDisposition="applied",A.change.committed=!0);for(let A of I)A.attemptedDisposition==="applied"&&(A.committed=!0,A.finalDisposition="applied")}N||du(n,h);let O={documentXml:N?c.rollback():T,hasChanges:N?!1:y,commentsXml:N?null:c.commentsXml,commentsExtendedXml:N?null:c.commentsExtendedXml,commentsXmlMode:c.commentsXmlMode,commentsExtendedXmlMode:c.commentsExtendedXmlMode,numberingXmlParts:N?[]:c.numberingXmlParts,results:[...w].sort((A,P)=>(A.index||0)-(P.index||0)),receipts:I.sort((A,P)=>A.operationIndex-P.operationIndex),executionOrder:v,authorsUsed:N?[]:Array.from(b),...N?{rolledBack:!0,status:"error",error:Ee({code:S?S.code:E?"DOCUMENT_SERIALIZATION_FAILED":"BATCH_OPERATION_FAILED",message:S?.message||E?.message||"Atomic batch rolled back because one or more operations failed."})}:S?{status:"error",error:Ee(S)}:x?{status:y?"partial":"error",error:Ee({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed."})}:{status:"ok"}};return(O.status==="error"||O.status==="partial")&&(O.retryPlan=Kt({atomic:p,rolledBack:N,results:O.results,receipts:O.receipts,operationCount:a.length})),O}function wn(e,t={}){return Ze(e,t)}function Jg(e){return e.operationKind!=="redline"||typeof e.modified!="string"?!1:e.modified.split(/\r?\n/).some(t=>/^\s*(?:[-+*]|\d+[.)])\s+/.test(t))}function Qg(e,t,r,n,o=null,a="accepted"){let i=o?.byParagraph?.get(t)||null,s=i?null:se(e),l=i?.text??te(t,{revisionView:a}),c=J(n||""),u=J(l);return{resolvedBy:r,resolvedTarget:{index:i?.index??s.indexOf(t)+1,paragraphId:i?.paragraphId??$e(t),text:l,fingerprint:i?.fingerprint??st(t,{text:l,revisionView:a}),inTable:i?.inTable??!!We(t,"tbl"),revisionView:a},matchDiagnostics:{exactTextMatch:typeof n=="string"&&n===l,normalizedTextMatch:!!c&&c===u,suppliedText:n||"",actualText:l,revisionView:a}}}function Uu(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.("*",r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Ca(e,t,r,n={}){if(n.existingRevisions!=null&&!so(n.existingRevisions))return{valid:!1,status:"error",error:wn({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(n.existingRevisions)}".`}),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let o=W(e,"application/xml");if(o.error||!o.doc)return{valid:!1,status:"error",error:wn(o.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let a=o.doc,i={accepted:kt(a,{revisionView:"accepted"}),rejected:null},s=Array.isArray(t)?t:[],l=hn(a,s,{strictTargets:n.strictTargets!==!1,onInfo:n.onInfo,onWarn:n.onWarn}),c=Ra(l.compiledOperations);if(!c.valid)return{valid:!1,status:"error",error:wn(c.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let u=n.strictTargets!==!1,f=[],d=new Set,m=!1,p=!1;for(let v=0;v<s.length;v++){let b=s[v],x=l.bindings[v],I=l.compiledOperations[v],N=!x?.error&&I?._localizedReplacementCompilation?I:b,T=Ht(N),E=rt(b),S=T.operation||E,O=wt(S,r,re());if(d.add(O),!T.valid){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"error",authorUsed:O,error:T.error});continue}if(m=m||S.operationKind==="comment"||S.operationKind==="comment_reply",p=p||Jg(S),S.operationKind==="comment_resolve"){let _=String(S.commentId);f.push(n._existingCommentDetails?.[_]?{index:v+1,type:b.type,operationType:S.operationKind,status:"ready",authorUsed:O,resolvedBy:"comment_id",commentId:_}:{index:v+1,type:b.type,operationType:S.operationKind,status:"error",authorUsed:O,error:{code:"COMMENT_NOT_FOUND",message:`Comment '${_}' was not found.`}});continue}if(S.operationKind==="comment_reply"){let _=String(S.parentCommentId),R=n._existingCommentDetails?.[_];f.push(R?{index:v+1,type:b.type,operationType:S.operationKind,status:"ready",authorUsed:O,resolvedBy:"parent_comment",parentCommentId:_}:{index:v+1,type:b.type,operationType:S.operationKind,status:"error",authorUsed:O,error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${_}' was not found.`}});continue}if(S.targetDescriptor?.captureRef){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"deferred",authorUsed:O,resolvedBy:"capture",captureRef:S.targetDescriptor.captureRef,...S.targetDescriptor.select?{select:S.targetDescriptor.select}:{}});continue}if(x?.error){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"error",authorUsed:O,error:x.error});continue}if(x?.createdByOperation){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"deferred",authorUsed:O,resolvedBy:"created_content_dependency",captureRef:x.captureRef,select:S.targetDescriptor.text,createdByOperation:x.createdByOperation});continue}let A=S.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",P=A==="rejected"?i.rejected||(i.rejected=kt(a,{revisionView:"rejected"})):i.accepted;try{let _;if(x.dynamic)_=_r(a,{targetText:S.target,targetRef:S.targetRef,targetDescriptor:S.targetDescriptor,opType:S.operationKind,strictAmbiguity:u,paragraphMetadataIndex:P,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn});else{let q=l.registry.resolve(x.sourceIds[0],a);if(q.error)throw Object.assign(new Error(q.error.message),q.error);_={paragraph:q.paragraph,resolvedBy:x.resolvedBy,warnings:x.warnings}}let R=_.paragraph,k=Qg(a,R,_.resolvedBy,S.target,P,A),C=k.resolvedTarget.text,M=S.operationKind==="comment"?S.textToComment||C:S.operationKind==="highlight"?S.textToHighlight:S.operationKind==="format"?S.textToFormat:null,$=S.operationKind==="comment"&&M!=null?Qn(un(R,{revisionView:A}),M):null,X=M==null||($?$.found:C.includes(M)),V=or(R),Y=S.existingRevisions||n.existingRevisions||"merge-same-author",fe=S.operationKind==="redline"&&S.modified===""?Uu(R):[],H=null;if(S.operationKind==="restore"){let q=S.targetEndRef?en(a,S.targetRef,S.targetEndRef,{opType:"restore",targetRefSnapshot:n.targetRefSnapshot||null,onInfo:n.onInfo,onWarn:n.onWarn}):[R];if(!S.targetEndRef&&S.targetEndDescriptor){let ce=_r(a,{targetText:S.targetEndDescriptor.text,targetRef:S.targetEndDescriptor.index,targetDescriptor:S.targetEndDescriptor,opType:"restore",strictAmbiguity:u,paragraphMetadataIndex:P,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn}),ve=se(a),j=ve.indexOf(R),z=ve.indexOf(ce?.paragraph);q=j>=0&&z>=j?ve.slice(j,z+1):null}let ge=Array.isArray(S.modified)?S.modified:[S.modified];if(!q||q[0]!==R||ge.length!==q.length)H={code:"RESTORATION_COUNT_MISMATCH",message:"Restoration requires one replacement for every paragraph in a contiguous resolved range."};else for(let ce of q){let ve=Rr(ce);if(ve?.code==="UNSUPPORTED_MOVE_REVISION"){H=ve;break}let j=ur(ce,O),z=j.matches?ve||Rr(ce):null;if(!j.matches){H={code:"RESTORATION_STATE_REQUIRED",message:"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...j.ownerAuthor?{ownerAuthor:j.ownerAuthor}:{}};break}if(z){H=z;break}}}else if(!X)H=$?.error||{code:"ANCHOR_NOT_FOUND",message:`Anchor text was not found in target paragraph: "${M}".`};else if(fe.length>0){let q=fe.map(ge=>n._existingCommentDetails?.[ge]).filter(Boolean);H={code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:fe,...q.length>0?{comments:q}:{}}}else if(S.operationKind==="redline"&&V&&Y!=="accept-all-first"&&Y!=="accept-all-first-keep-normalized")if(Y==="merge-same-author"||Y==="slice-cross-author"){let q=vr(R),ge=String(O||"").trim().toLowerCase(),ce=q.length>0&&q.every(ve=>ve.trim().toLowerCase()===ge);if(!ce&&Y==="merge-same-author")H={code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${q.length?q.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:q,currentPolicy:Y};else if(ce){let ve=Uu(R);if(ve.length>0){let j=ve.map(z=>n._existingCommentDetails?.[z]).filter(Boolean);H={code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:ve,...j.length>0?{comments:j}:{}}}}else(R.getElementsByTagNameNS(L,"moveFrom").length>0||R.getElementsByTagNameNS(L,"moveTo").length>0)&&(H={code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."})}else{let q=R.getElementsByTagNameNS(L,"del").length>0,ge=R.getElementsByTagNameNS(L,"moveFrom").length>0||R.getElementsByTagNameNS(L,"moveTo").length>0;q?H={code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}:ge?H={code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}:H={code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}if(!H&&S.operationKind==="redline"){let q=jo(R,S.modified,n);q.valid||(H={code:q.code,message:q.message})}f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:H?"error":"ready",authorUsed:O,...k,anchor:M==null?null:{text:M,found:X,...$?.found?{resolvedBy:$.resolvedBy,start:$.start,end:$.end}:{},...!$?.found&&Array.isArray($?.error?.candidates)?{candidates:$.error.candidates}:{}},hasRevisions:V,existingRevisions:Y,..._?.warnings?.length?{warnings:_.warnings}:{},...H?{error:H}:{}})}catch(_){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"error",authorUsed:O,error:wn(_)})}}let g=l.conflicts,h=f.map(v=>v.error?{...v,error:wn(v.error,{operationIndex:v.index,...s[v.index-1]?.operationId?{operationId:s[v.index-1].operationId}:{}})}:v),y=g.map(v=>wn(v)),w=h.some(v=>v.status==="error");return{valid:!w&&y.length===0,status:!w&&y.length===0?"ok":"error",results:h,conflicts:y,authorsUsed:Array.from(d),requiredArtifacts:{comments:m,numbering:p}}}var He=Uint8Array,dt=Uint16Array,ys=Int32Array,Oa=new He([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]),_a=new He([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]),ps=new He([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Wu=function(e,t){for(var r=new dt(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var o=new ys(r[30]),n=1;n<30;++n)for(var a=r[n];a<r[n+1];++a)o[a]=a-r[n]<<5|n;return{b:r,r:o}},ju=Wu(Oa,2),Ku=ju.b,gs=ju.r;Ku[28]=258,gs[258]=28;var Hu=Wu(_a,0),eh=Hu.b,zu=Hu.r,hs=new dt(32768);for(ue=0;ue<32768;++ue)Yt=(ue&43690)>>1|(ue&21845)<<1,Yt=(Yt&52428)>>2|(Yt&13107)<<2,Yt=(Yt&61680)>>4|(Yt&3855)<<4,hs[ue]=((Yt&65280)>>8|(Yt&255)<<8)>>1;var Yt,ue,Mt=(function(e,t,r){for(var n=e.length,o=0,a=new dt(t);o<n;++o)e[o]&&++a[e[o]-1];var i=new dt(t);for(o=1;o<t;++o)i[o]=i[o-1]+a[o-1]<<1;var s;if(r){s=new dt(1<<t);var l=15-t;for(o=0;o<n;++o)if(e[o])for(var c=o<<4|e[o],u=t-e[o],f=i[e[o]-1]++<<u,d=f|(1<<u)-1;f<=d;++f)s[hs[f]>>l]=c}else for(s=new dt(n),o=0;o<n;++o)e[o]&&(s[o]=hs[i[e[o]-1]++]>>15-e[o]);return s}),gr=new He(288);for(ue=0;ue<144;++ue)gr[ue]=8;var ue;for(ue=144;ue<256;++ue)gr[ue]=9;var ue;for(ue=256;ue<280;++ue)gr[ue]=7;var ue;for(ue=280;ue<288;++ue)gr[ue]=8;var ue,mo=new He(32);for(ue=0;ue<32;++ue)mo[ue]=5;var ue,th=Mt(gr,9,0),rh=Mt(gr,9,1),nh=Mt(mo,5,0),oh=Mt(mo,5,1),fs=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},At=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},ds=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},vs=function(e){return(e+7)/8|0},Gu=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new He(e.subarray(t,r))};var ah=["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"],Jt=function(e,t,r){var n=new Error(t||ah[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Jt),!r)throw n;return n},ih=function(e,t,r,n){var o=e.length,a=n?n.length:0;if(!o||t.f&&!t.l)return r||new He(0);var i=!r,s=i||t.i!=2,l=t.i;i&&(r=new He(o*3));var c=function(z){var U=r.length;if(z>U){var G=new He(Math.max(U*2,z));G.set(r),r=G}},u=t.f||0,f=t.p||0,d=t.b||0,m=t.l,p=t.d,g=t.m,h=t.n,y=o*8;do{if(!m){u=At(e,f,1);var w=At(e,f+1,3);if(f+=3,w)if(w==1)m=rh,p=oh,g=9,h=5;else if(w==2){var I=At(e,f,31)+257,N=At(e,f+10,15)+4,T=I+At(e,f+5,31)+1;f+=14;for(var E=new He(T),S=new He(19),O=0;O<N;++O)S[ps[O]]=At(e,f+O*3,7);f+=N*3;for(var A=fs(S),P=(1<<A)-1,_=Mt(S,A,1),O=0;O<T;){var R=_[At(e,f,P)];f+=R&15;var v=R>>4;if(v<16)E[O++]=v;else{var k=0,C=0;for(v==16?(C=3+At(e,f,3),f+=2,k=E[O-1]):v==17?(C=3+At(e,f,7),f+=3):v==18&&(C=11+At(e,f,127),f+=7);C--;)E[O++]=k}}var M=E.subarray(0,I),$=E.subarray(I);g=fs(M),h=fs($),m=Mt(M,g,1),p=Mt($,h,1)}else Jt(1);else{var v=vs(f)+4,b=e[v-4]|e[v-3]<<8,x=v+b;if(x>o){l&&Jt(0);break}s&&c(d+b),r.set(e.subarray(v,x),d),t.b=d+=b,t.p=f=x*8,t.f=u;continue}if(f>y){l&&Jt(0);break}}s&&c(d+131072);for(var X=(1<<g)-1,V=(1<<h)-1,Y=f;;Y=f){var k=m[ds(e,f)&X],ye=k>>4;if(f+=k&15,f>y){l&&Jt(0);break}if(k||Jt(2),ye<256)r[d++]=ye;else if(ye==256){Y=f,m=null;break}else{var fe=ye-254;if(ye>264){var O=ye-257,H=Oa[O];fe=At(e,f,(1<<H)-1)+Ku[O],f+=H}var q=p[ds(e,f)&V],ge=q>>4;q||Jt(3),f+=q&15;var $=eh[ge];if(ge>3){var H=_a[ge];$+=ds(e,f)&(1<<H)-1,f+=H}if(f>y){l&&Jt(0);break}s&&c(d+131072);var ce=d+fe;if(d<$){var ve=a-$,j=Math.min($,ce);for(ve+d<0&&Jt(3);d<j;++d)r[d]=n[ve+d]}for(;d<ce;++d)r[d]=r[d-$]}}t.l=m,t.p=Y,t.b=d,t.f=u,m&&(u=1,t.m=g,t.d=p,t.n=h)}while(!u);return d!=r.length&&i?Gu(r,0,d):r.subarray(0,d)},Zt=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},uo=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},ms=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var o=r.length,a=r.slice();if(!o)return{t:Yu,l:0};if(o==1){var i=new He(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(x,I){return x.f-I.f}),r.push({s:-1,f:25001});var s=r[0],l=r[1],c=0,u=1,f=2;for(r[0]={s:-1,f:s.f+l.f,l:s,r:l};u!=o-1;)s=r[r[c].f<r[f].f?c++:f++],l=r[c!=u&&r[c].f<r[f].f?c++:f++],r[u++]={s:-1,f:s.f+l.f,l:s,r:l};for(var d=a[0].s,n=1;n<o;++n)a[n].s>d&&(d=a[n].s);var m=new dt(d+1),p=ws(r[u-1],m,0);if(p>t){var n=0,g=0,h=p-t,y=1<<h;for(a.sort(function(I,N){return m[N.s]-m[I.s]||I.f-N.f});n<o;++n){var w=a[n].s;if(m[w]>t)g+=y-(1<<p-m[w]),m[w]=t;else break}for(g>>=h;g>0;){var v=a[n].s;m[v]<t?g-=1<<t-m[v]++-1:++n}for(;n>=0&&g;--n){var b=a[n].s;m[b]==t&&(--m[b],++g)}p=t}return{t:new He(m),l:p}},ws=function(e,t,r){return e.s==-1?Math.max(ws(e.l,t,r+1),ws(e.r,t,r+1)):t[e.s]=r},Xu=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new dt(++t),n=0,o=e[0],a=1,i=function(l){r[n++]=l},s=1;s<=t;++s)if(e[s]==o&&s!=t)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=e[s]}return{c:r.subarray(0,n),n:t}},fo=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},qu=function(e,t,r){var n=r.length,o=vs(t+2);e[o]=n&255,e[o+1]=n>>8,e[o+2]=e[o]^255,e[o+3]=e[o+1]^255;for(var a=0;a<n;++a)e[o+a+4]=r[a];return(o+4+n)*8},Vu=function(e,t,r,n,o,a,i,s,l,c,u){Zt(t,u++,r),++o[256];for(var f=ms(o,15),d=f.t,m=f.l,p=ms(a,15),g=p.t,h=p.l,y=Xu(d),w=y.c,v=y.n,b=Xu(g),x=b.c,I=b.n,N=new dt(19),T=0;T<w.length;++T)++N[w[T]&31];for(var T=0;T<x.length;++T)++N[x[T]&31];for(var E=ms(N,7),S=E.t,O=E.l,A=19;A>4&&!S[ps[A-1]];--A);var P=c+5<<3,_=fo(o,gr)+fo(a,mo)+i,R=fo(o,d)+fo(a,g)+i+14+3*A+fo(N,S)+2*N[16]+3*N[17]+7*N[18];if(l>=0&&P<=_&&P<=R)return qu(t,u,e.subarray(l,l+c));var k,C,M,$;if(Zt(t,u,1+(R<_)),u+=2,R<_){k=Mt(d,m,0),C=d,M=Mt(g,h,0),$=g;var X=Mt(S,O,0);Zt(t,u,v-257),Zt(t,u+5,I-1),Zt(t,u+10,A-4),u+=14;for(var T=0;T<A;++T)Zt(t,u+3*T,S[ps[T]]);u+=3*A;for(var V=[w,x],Y=0;Y<2;++Y)for(var ye=V[Y],T=0;T<ye.length;++T){var fe=ye[T]&31;Zt(t,u,X[fe]),u+=S[fe],fe>15&&(Zt(t,u,ye[T]>>5&127),u+=ye[T]>>12)}}else k=th,C=gr,M=nh,$=mo;for(var T=0;T<s;++T){var H=n[T];if(H>255){var fe=H>>18&31;uo(t,u,k[fe+257]),u+=C[fe+257],fe>7&&(Zt(t,u,H>>23&31),u+=Oa[fe]);var q=H&31;uo(t,u,M[q]),u+=$[q],q>3&&(uo(t,u,H>>5&8191),u+=_a[q])}else uo(t,u,k[H]),u+=C[H]}return uo(t,u,k[256]),u+C[256]},sh=new ys([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Yu=new He(0),lh=function(e,t,r,n,o,a){var i=a.z||e.length,s=new He(n+i+5*(1+Math.ceil(i/7e3))+o),l=s.subarray(n,s.length-o),c=a.l,u=(a.r||0)&7;if(t){u&&(l[0]=a.r>>3);for(var f=sh[t-1],d=f>>13,m=f&8191,p=(1<<r)-1,g=a.p||new dt(32768),h=a.h||new dt(p+1),y=Math.ceil(r/3),w=2*y,v=function(ee){return(e[ee]^e[ee+1]<<y^e[ee+2]<<w)&p},b=new ys(25e3),x=new dt(288),I=new dt(32),N=0,T=0,E=a.i||0,S=0,O=a.w||0,A=0;E+2<i;++E){var P=v(E),_=E&32767,R=h[P];if(g[_]=R,h[P]=_,O<=E){var k=i-E;if((N>7e3||S>24576)&&(k>423||!c)){u=Vu(e,l,0,b,x,I,T,S,A,E-A,u),S=N=T=0,A=E;for(var C=0;C<286;++C)x[C]=0;for(var C=0;C<30;++C)I[C]=0}var M=2,$=0,X=m,V=_-R&32767;if(k>2&&P==v(E-V))for(var Y=Math.min(d,k)-1,ye=Math.min(32767,E),fe=Math.min(258,k);V<=ye&&--X&&_!=R;){if(e[E+M]==e[E+M-V]){for(var H=0;H<fe&&e[E+H]==e[E+H-V];++H);if(H>M){if(M=H,$=V,H>Y)break;for(var q=Math.min(V,H-2),ge=0,C=0;C<q;++C){var ce=E-V+C&32767,ve=g[ce],j=ce-ve&32767;j>ge&&(ge=j,R=ce)}}}_=R,R=g[_],V+=_-R&32767}if($){b[S++]=268435456|gs[M]<<18|zu[$];var z=gs[M]&31,U=zu[$]&31;T+=Oa[z]+_a[U],++x[257+z],++I[U],O=E+M,++N}else b[S++]=e[E],++x[e[E]]}}for(E=Math.max(E,O);E<i;++E)b[S++]=e[E],++x[e[E]];u=Vu(e,l,c,b,x,I,T,S,A,E-A,u),c||(a.r=u&7|l[u/8|0]<<3,u-=7,a.h=h,a.p=g,a.i=E,a.w=O)}else{for(var E=a.w||0;E<i+c;E+=65535){var G=E+65535;G>=i&&(l[u/8|0]=c,G=i),u=qu(l,u+1,e.subarray(E,G))}a.i=i}return Gu(s,0,n+vs(u)+o)};var ch=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),i=new He(a.length+e.length);i.set(a),i.set(e,a.length),e=i,o.w=a.length}return lh(e,t.level==null?6:t.level,t.mem==null?o.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,o)};function Zu(e,t){return ch(e,t||{},0,0)}function Ju(e,t){return ih(e,{i:2},t&&t.out,t&&t.dictionary)}var uh=typeof TextDecoder<"u"&&new TextDecoder,fh=0;try{uh.decode(Yu,{stream:!0}),fh=1}catch{}var ef=new TextEncoder,tf=new TextDecoder("utf-8"),dh=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function mh(e){let t=4294967295;for(let r=0;r<e.length;r++)t=dh[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function yn(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof e=="string")return ef.encode(e);throw new TypeError("Invalid binary input: expected Uint8Array, Buffer, or ArrayBuffer.")}function Qu(e){let t=0;for(let o=0;o<e.length;o++)t+=e[o].length;let r=new Uint8Array(t),n=0;for(let o=0;o<e.length;o++)r.set(e[o],n),n+=e[o].length;return r}function vn(e){let t=yn(e);if(t.length<22)throw new Error("Invalid DOCX: ZIP end record not found.");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=-1,o=Math.max(0,t.length-65535-22);for(let c=t.length-22;c>=o;c--)if(r.getUint32(c,!0)===101010256){n=c;break}if(n<0)throw new Error("Invalid DOCX: ZIP end record not found.");let a=r.getUint16(n+10,!0),i=r.getUint32(n+16,!0);if(a===65535||i===4294967295)throw new Error("Unsupported DOCX: ZIP64 archives are not supported.");let s=new Map,l=i;for(let c=0;c<a;c++){if(l+46>t.length||r.getUint32(l,!0)!==33639248)throw new Error("Invalid DOCX: central directory is corrupt.");let u=r.getUint16(l+8,!0),f=r.getUint16(l+10,!0);if(u&1)throw new Error("Unsupported DOCX: encrypted ZIP entries are not supported.");let d=r.getUint32(l+20,!0),m=r.getUint16(l+28,!0),p=r.getUint16(l+30,!0),g=r.getUint16(l+32,!0),h=r.getUint32(l+42,!0);if(l+46+m>t.length)throw new Error("Invalid DOCX: central directory entry name extends beyond bounds.");let y=tf.decode(t.subarray(l+46,l+46+m));if(h+30>t.length||r.getUint32(h,!0)!==67324752)throw new Error("Invalid DOCX: local entry is corrupt.");let w=r.getUint16(h+26,!0),v=r.getUint16(h+28,!0),b=h+30+w+v;if(b+d>t.length)throw new Error("Invalid DOCX: local entry data extends beyond archive bounds.");let x=t.subarray(b,b+d);if(f!==0&&f!==8)throw new Error(`Unsupported DOCX compression method: ${f}.`);let I=f===8?Ju(x):new Uint8Array(x);s.set(y,I),l+=46+m+p+g}return s}function rf(e){let t=e instanceof Map?Array.from(e.entries()):Symbol.iterator in Object(e)?Array.from(e):Object.entries(e||{}),r=[],n=[],o=0;for(let[l,c]of t){let u=ef.encode(l),f=yn(c),d=Zu(f,{level:9}),m=d.length<f.length?8:0,p=m===8?d:f,g=mh(f),h=new Uint8Array(30),y=new DataView(h.buffer,h.byteOffset,30);y.setUint32(0,67324752,!0),y.setUint16(4,20,!0),y.setUint16(8,m,!0),y.setUint16(12,23585,!0),y.setUint32(14,g,!0),y.setUint32(18,p.length,!0),y.setUint32(22,f.length,!0),y.setUint16(26,u.length,!0),y.setUint16(28,0,!0),r.push(h,u,p);let w=new Uint8Array(46),v=new DataView(w.buffer,w.byteOffset,46);v.setUint32(0,33639248,!0),v.setUint16(4,20,!0),v.setUint16(6,20,!0),v.setUint16(10,m,!0),v.setUint16(14,23585,!0),v.setUint32(16,g,!0),v.setUint32(20,p.length,!0),v.setUint32(24,f.length,!0),v.setUint16(28,u.length,!0),v.setUint16(30,0,!0),v.setUint16(32,0,!0),v.setUint32(42,o,!0),n.push(w,u),o+=h.length+u.length+p.length}let a=Qu(n),i=new Uint8Array(22),s=new DataView(i.buffer,i.byteOffset,22);return s.setUint32(0,101010256,!0),s.setUint16(8,t.length,!0),s.setUint16(10,t.length,!0),s.setUint32(12,a.length,!0),s.setUint32(16,o,!0),Qu([...r,a,i])}var Qt=class{constructor(t){this.entries=t instanceof Map?t:new Map(Object.entries(t||{}))}file(t,r){if(r!==void 0)return this.entries.set(t,yn(r)),this;let n=this.entries.get(t);return n?{async:async o=>o==="string"?tf.decode(n):new Uint8Array(n)}:null}};var Lt=new TextEncoder,lf=new TextDecoder("utf-8"),ne=(e,t)=>{let r=e.get(t);return r?typeof r=="string"?r:lf.decode(r):null};function nf(e){let t=Cc({commentsXml:ne(e,"word/comments.xml"),commentsIdsXml:ne(e,"word/commentsIds.xml"),commentsExtensibleXml:ne(e,"word/commentsExtensible.xml")});t.commentsIdsXml&&e.set("word/commentsIds.xml",Lt.encode(t.commentsIdsXml)),t.commentsExtensibleXml&&e.set("word/commentsExtensible.xml",Lt.encode(t.commentsExtensibleXml))}var xn=e=>new Map([...e].map(([t,r])=>[t,new Uint8Array(r)]));function le(e){return typeof Buffer<"u"&&typeof Buffer.from=="function"?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function po(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function of(e,t){let r=i=>!i||typeof i!="object"?i:i.attemptedDisposition!=="applied"&&i.committed!==!0?{...i}:{...i,committed:!1,finalDisposition:"rolled_back"},n=(e?.receipts||[]).map(r),o=new Map(n.map(i=>[i.operationIndex,i])),a=(e?.results||[]).map(i=>({...i,...i.receipt?{receipt:o.get(i.index)||r(i.receipt)}:{}}));return{results:a,receipts:n,executionOrder:e?.executionOrder||[],authorsUsed:[],rolledBack:!0,retryPlan:Kt({atomic:!0,rolledBack:!0,results:a,receipts:n,operationCount:t})}}function xs(e){let t;if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer?.(e))t=vn(e);else if(e instanceof Map)t=e;else if(e?.entries instanceof Map)t=e.entries;else if(typeof e?.toUint8Array=="function")t=vn(e.toUint8Array());else if(typeof e?.toBuffer=="function")t=vn(e.toBuffer());else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=vn(yn(e));else throw new TypeError("computePackageRevisionToken requires a Uint8Array, Buffer, Map of entries, or DocxDocument.");return qn({scope:"package",entries:t})}var af=new Set(["comment","comment_reply","comment_resolve"]);function ph(e){let r=(`${ne(e,"word/document.xml")||""} ${ne(e,"word/comments.xml")||""}`.match(/(?:w:)?id=["'](\d+)["']/g)||[]).reduce((n,o)=>Math.max(n,Number(o.match(/\d+/)?.[0]||0)),0)+1;return()=>r++}function sf(e){let t=ne(e,"word/comments.xml");if(!t)return{};let r=W(t,"application/xml");if(!r.doc||r.error)return{};let n={};for(let o of Array.from(r.doc.getElementsByTagNameNS("*","comment"))){let a=o.getAttribute("w:id")||o.getAttribute("id");a!==""&&(n[a]={id:a,author:o.getAttribute("w:author")||o.getAttribute("author")||"",text:String(o.textContent||"").trim(),paraId:tt(o)||null})}return n}function yt(e,t,r){let n=le(e);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,error:Ze({code:t,message:r}),retryPlan:Kt({atomic:!0,rolledBack:!0}),artifactsChanged:[],uint8Array:e,toUint8Array:()=>new Uint8Array(e),buffer:n,toBuffer:()=>le(e)}}var ka=class{constructor(t){this.originalBytes=yn(t),this.entries=vn(this.originalBytes)}get originalBuffer(){return le(this.originalBytes)}inspect(t={}){let r=t.digestFn||(o=>Gn(o)),n=ma({documentXml:ne(this.entries,"word/document.xml"),commentsXml:ne(this.entries,"word/comments.xml"),commentsExtendedXml:ne(this.entries,"word/commentsExtended.xml"),numberingXml:ne(this.entries,"word/numbering.xml"),stylesXml:ne(this.entries,"word/styles.xml")},{...t,digestFn:r});return n.status==="error"?n:{...n,headersFooters:this.inspectHeadersFooters()}}inspectHeadersFooters(){return Qi({documentXml:ne(this.entries,"word/document.xml"),relsXml:ne(this.entries,"word/_rels/document.xml.rels"),settingsXml:ne(this.entries,"word/settings.xml")}).map(t=>{let r=ne(this.entries,t.path)||"",n=r?ma({documentXml:r}):{paragraphs:[]};return{...t,hasFields:/<w:fldChar\b|<w:fldSimple\b/.test(r),paragraphs:(n.paragraphs||[]).map(o=>({index:o.index,text:o.text}))}})}getRevisionToken(){return xs(this.entries)}get revisionToken(){return this.getRevisionToken()}preflight(t,r=re(),n={}){let o=Array.isArray(t)?t:[],a=p=>Ca(ne(this.entries,"word/document.xml"),p,r||re(),{...n,_existingCommentDetails:sf(this.entries)});if(!o.some(p=>p&&typeof p=="object"&&p.part!=null))return a(t);let i=this.inspectHeadersFooters(),s=[],l=[],c=[],u=new Set,f=!0;o.forEach((p,g)=>{if(!p||typeof p!="object"||p.part==null){s.push({operation:p,origIndex:g});return}let h=es(i,p.part),y=af.has(p.type)?{code:"COMMENT_IN_HEADER_FOOTER",message:"Word does not support comments in headers or footers."}:h.error;if(y){f=!1,l.push({index:g+1,type:p.type||"redline",status:"error",error:Ze({...y,operationIndex:g+1})});return}let{part:w,...v}=p,b=Ca(ne(this.entries,h.part.path),[v],r||re(),{...n,_existingCommentDetails:{}});f=f&&b.valid;for(let x of b.results||[])l.push({...x,index:g+1,part:h.part.path});c.push(...b.conflicts||[]);for(let x of b.authorsUsed||[])u.add(x)});let d={comments:!1,numbering:!1};if(s.length){let p=a(s.map(g=>g.operation));f=f&&p.valid;for(let g of p.results||[])l.push({...g,index:s[g.index-1].origIndex+1});c.push(...p.conflicts||[]);for(let g of p.authorsUsed||[])u.add(g);d=p.requiredArtifacts||d}l.sort((p,g)=>p.index-g.index);let m=f&&c.length===0;return{valid:m,status:m?"ok":"error",results:l,conflicts:c,authorsUsed:[...u],requiredArtifacts:d}}toUint8Array(){return rf(this.entries)}toBuffer(){return le(this.toUint8Array())}async applyOperations(t,r={}){let n=Array.isArray(t)?t:[];return n.some(o=>o&&typeof o=="object"&&o.part!=null)?this.applyOperationsWithParts(n,r):this.applyBodyOperations(t,r)}async applyOperationsWithParts(t,r={}){let n=r.author||re(),o=r.atomic===!0,a=this.entries,i=this.originalBytes,s=t.length,l=()=>{this.entries=a,this.originalBytes=i},c=()=>({uint8Array:i,toUint8Array:()=>new Uint8Array(i),buffer:le(i),toBuffer:()=>le(i)}),u=(C,M=[],$=[],X={})=>({status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:M,receipts:$,executionOrder:[],authorsUsed:[],artifactsChanged:[],error:Ze(C),retryPlan:Kt({atomic:!0,rolledBack:!0,results:M,receipts:$,operationCount:s}),validation:{originalIssues:[],generatedIssues:[]},...X,...c()});if(r.expectedRevision){let C=await this.applyBodyOperations([],{expectedRevision:r.expectedRevision});if(C.status==="error")return C}let f=Qi({documentXml:ne(this.entries,"word/document.xml"),relsXml:ne(this.entries,"word/_rels/document.xml.rels"),settingsXml:ne(this.entries,"word/settings.xml")}),d=[],m=[];for(let C=0;C<t.length;C++){let M=t[C];if(!M||typeof M!="object"||M.part==null){d.push({operation:M,origIndex:C});continue}if(af.has(M.type))return u({code:"COMMENT_IN_HEADER_FOOTER",message:`Operation ${C+1}: Word does not support comments in headers or footers.`,operationIndex:C+1});let $=es(f,M.part);if($.error)return u({...$.error,message:`Operation ${C+1}: ${$.error.message}`,operationIndex:C+1});let{part:X,...V}=M;m.push({operation:V,origIndex:C,part:$.part})}let p=[],g=[],h=[],y=new Set,w=[],v=!1,b=!1,x=null;if(d.length){x=await this.applyBodyOperations(d.map(M=>M.operation),{...r,expectedRevision:void 0});let C=M=>d[M-1]?.origIndex+1;for(let M of x.results||[])p.push({...M,index:C(M.index),...M.receipt?{receipt:{...M.receipt,operationIndex:C(M.receipt.operationIndex)}}:{}});for(let M of x.receipts||[])g.push({...M,operationIndex:C(M.operationIndex)});for(let M of x.executionOrder||[])h.push(C(M));for(let M of x.authorsUsed||[])y.add(M);if(w.push(...x.validation?.originalIssues||[]),(x.status==="error"||x.rolledBack)&&(b=!0,o))return l(),{...x,results:p,receipts:g,executionOrder:h,written:!1,artifactsChanged:[],rolledBack:!0,...c()};v=x.hasChanges===!0}let I=xn(this.entries),N=new Qt(I),T=new Set,{expectedRevision:E,...S}=r,O=(C,M)=>{b=!0;let $=Ze({...M,operationIndex:C.origIndex+1});p.push({index:C.origIndex+1,type:C.operation.type||"redline",status:"error",authorUsed:n,part:C.part.path,error:$})};for(let C of m){let M=C.part.path,$=ne(I,M);if(!$){if(O(C,{code:"PART_NOT_FOUND",message:`Part '${M}' is referenced but missing from the package.`}),o)break;continue}let X=ne(I,"word/numbering.xml"),V=await Pa($,[C.operation],n,{numberingIdState:ea(X||void 0)},{...S,atomic:!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:{}}),Y=V.results?.[0];if(V.rolledBack||V.status==="error"){if(O(C,Y?.error||V.error||{code:"OPERATION_FAILED",message:"Operation failed."}),o)break;continue}if(!V.hasChanges){p.push({...Y,index:C.origIndex+1,part:M});continue}if(ts(V.documentXml)>ts($)){if(O(C,{code:"FIELD_EDIT_REFUSED",message:`The edit would change a field (for example PAGE or NUMPAGES) in ${M}. Word recomputes fields; edit the text around them instead.`}),o)break;continue}let ye=new Set;for(let[q,ge]of I)if(!(q===M||!(q==="word/document.xml"||nu(q))))for(let ce of ou(lf.decode(ge)))ye.add(ce);let fe=au(V.documentXml,ye);I.set(M,Lt.encode(fe.xml));let H=q=>q?.revisionItems?{...q,revisionItems:q.revisionItems.map(ge=>({...ge,id:fe.idMap.get(String(ge.id))??ge.id,partName:M}))}:q;V.numberingXmlParts?.length&&await ya(N,V.numberingXmlParts,{mergeNumberingXml:ia}),T.add(M),v=!0,p.push({...Y,index:C.origIndex+1,part:M,partSections:C.part.appliesToSections,...Y?.receipt?{receipt:{...H(Y.receipt),operationIndex:C.origIndex+1}}:{}}),V.receipts?.[0]&&g.push({...H(V.receipts[0]),operationIndex:C.origIndex+1}),h.push(C.origIndex+1);for(let q of V.authorsUsed||[])y.add(q)}let A=[];if(!(o&&b)){for(let C of T){let M=ct(ne(this.entries,C)).issues.map(X=>({source:C,...X})),$=ct(ne(I,C)).issues.map(X=>({source:C,...X}));A.push(...zr(Ur($,M)))}if(r.validate!==!1&&T.size)try{await mr(N)}catch(C){A.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:C.message})}}if(o&&b||A.length){l();let C=A.length?{code:"PACKAGE_OPERATION_FAILED",message:`Applied operations introduced invalid markup (${[...new Set(A.map(X=>X.code))].join(", ")}).`,issues:A}:{code:"BATCH_OPERATION_FAILED",message:"Atomic batch rolled back because one or more operations failed."},M=p.map(X=>X.receipt?{...X,receipt:{...X.receipt,committed:!1,finalDisposition:"rolled_back"}}:X).sort((X,V)=>X.index-V.index),$=g.map(X=>({...X,committed:!1,finalDisposition:"rolled_back"}));return u(C,M,$,{validation:{originalIssues:w,generatedIssues:A},issues:A})}p.sort((C,M)=>C.index-M.index),g.sort((C,M)=>C.operationIndex-M.operationIndex);let P=b?v?"partial":"error":"ok",_=b?{error:Ze({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed; the others were applied."})}:{};if(!T.size){let C=le(this.originalBytes);return{...x||{},results:p,receipts:g,executionOrder:h,authorsUsed:[...y],status:P,hasChanges:v,written:x?.written===!0,artifactsChanged:x?.artifactsChanged||[],validation:{originalIssues:w,generatedIssues:[]},..._,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:C,toBuffer:()=>le(this.originalBytes)}}this.entries=I;let R=this.toUint8Array();this.originalBytes=R;let k=[...I].filter(([C,M])=>!a.has(C)||!po(M,a.get(C))).map(([C])=>C);return{...x||{},status:P,hasChanges:!0,written:!0,results:p,receipts:g,executionOrder:h,authorsUsed:[...y],artifactsChanged:k,validation:{originalIssues:w,generatedIssues:[]},..._,uint8Array:R,toUint8Array:()=>new Uint8Array(R),buffer:le(R),inspection:this.inspect(),toBuffer:()=>le(R)}}async applyBodyOperations(t,r={}){let n=u=>{let f=[],d=[],m=le(this.originalBytes);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:f,receipts:d,artifactsChanged:[],error:Ze(u),retryPlan:Kt({atomic:!0,rolledBack:!0,results:f,receipts:d,operationCount:Array.isArray(t)?t.length:0}),validation:{originalIssues:[],generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>le(this.originalBytes)}};if(r?.expectedRevision){let u=Br(r.expectedRevision);if(!u.valid)return n({code:u.error?.code||"INVALID_REVISION_TOKEN",message:u.error?.message||"Invalid revision token."});if(r.expectedRevision.scope!=="package")return n({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'package', got '${r.expectedRevision.scope}'.`,expectedScope:"package",actualScope:r.expectedRevision.scope});let f=xs(this.entries);if(!Dr(f.value,r.expectedRevision.value))return n({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${r.expectedRevision.value}', current is '${f.value}'.`,expectedRevision:r.expectedRevision,currentRevision:f})}let o=this.entries,a=xn(o),i=new Qt(a),s=ne(a,"word/document.xml"),l=[],c=null;try{if(!s)throw new Error("Missing word/document.xml.");l=ct(s).issues.map(I=>({source:"word/document.xml",...I}));try{await mr(new Qt(xn(o)))}catch(I){l.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:I.message})}let f={numberingIdState:ea(ne(a,"word/numbering.xml")||void 0),commentsXml:ne(a,"word/comments.xml"),commentsExtendedXml:ne(a,"word/commentsExtended.xml")},{expectedRevision:d,...m}=r,p=r.author||re(),g=c=await Pa(s,t,p,f,{...m,atomic:r.atomic===!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:sf(a),commentIdAllocator:ph(a)});if(g.rolledBack||g.status==="error"){let I=le(this.originalBytes);return{...g,...of(g,Array.isArray(t)?t.length:0),written:!1,artifactsChanged:[],validation:{originalIssues:l,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:I,toBuffer:()=>le(this.originalBytes)}}if(!g.hasChanges){let I=le(this.originalBytes);return{...g,status:g.status||"ok",written:!1,artifactsChanged:[],validation:{originalIssues:l,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:I,toBuffer:()=>le(this.originalBytes)}}(g.results||[]).some(I=>I?.status!=="error"&&I?.operationType!=="comment_resolve")&&a.set("word/document.xml",Lt.encode(g.documentXml)),await ya(i,g.numberingXmlParts,{mergeNumberingXml:ia});let y=ne(a,"word/comments.xml"),w=g.commentsXml||y;if(await Ji(i,w,{replaceExisting:g.commentsXmlMode==="replace"||!g.commentsXml&&!!y}),g.commentsExtendedXml&&await va(i,g.commentsExtendedXml,{replaceExisting:g.commentsExtendedXmlMode==="replace"}),await mn(i),nf(a),r.validate!==!1){let N=ct(g.documentXml).issues.map(S=>({source:"word/document.xml",...S}));try{await mr(i)}catch(S){N.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:S.message})}let T=Ur(N,l),E=zr(T);if(E.length){let S=[...new Set(E.map(O=>O.code))].join(", ");throw Object.assign(new Error(`Applied operations introduced invalid revision markup (${S}); these are generated-output issues, not pre-existing input issues.`),{issues:E})}}this.entries=a;let v=this.toUint8Array();this.originalBytes=v;let b=le(v),x=[...a].filter(([I,N])=>!o.has(I)||!po(N,o.get(I))).map(([I])=>I);return{...g,status:g.status||"ok",written:!0,artifactsChanged:x,validation:{originalIssues:l,generatedIssues:[]},uint8Array:v,toUint8Array:()=>new Uint8Array(v),buffer:b,inspection:this.inspect(),toBuffer:()=>le(v)}}catch(u){this.entries=o;let f=u.issues||[{source:"package",code:"PACKAGE_OPERATION_FAILED",severity:"error",message:u.message}],d=of(c,Array.isArray(t)?t.length:0),m=le(this.originalBytes);return{...d,status:"error",hasChanges:!1,written:!1,artifactsChanged:[],error:Ze({code:"PACKAGE_OPERATION_FAILED",message:u.message,stage:"package",issues:f}),validation:{originalIssues:l,generatedIssues:f},issues:f,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>le(this.originalBytes)}}}async resolveRevisions(t,r={}){let n=t==="accept"?Er:t==="reject"?cr:null;if(!n)return yt(this.originalBytes,"INVALID_ACTION",`Unknown revision action: ${t}`);let o=this.originalBytes,a=this.entries,i=xn(this.entries),s=new Qt(i),l=n(ne(i,"word/document.xml"),{author:r.author,allAuthors:r.allAuthors===!0});if(l.status==="error"||l.error)return yt(o,l.error?.code||"REVISION_OPERATION_FAILED",l.error?.message||"Revision operation failed.");let c=new Map;for(let m of this.inspectHeadersFooters()){let p=ne(i,m.path);if(!p)continue;let g=n(p,{author:r.author,allAuthors:r.allAuthors===!0});if(g.status==="error"||g.error)return yt(o,g.error?.code||"REVISION_OPERATION_FAILED",`${m.path}: ${g.error?.message||"Revision operation failed."}`);g.hasChanges&&c.set(m.path,g.oxml)}if(!(l.hasChanges||c.size>0)){let m=le(o);return{...l,status:"ok",written:!1,artifactsChanged:[],uint8Array:o,toUint8Array:()=>new Uint8Array(o),buffer:m,toBuffer:()=>le(o)}}l.hasChanges&&i.set("word/document.xml",Lt.encode(l.oxml));for(let[m,p]of c)i.set(m,Lt.encode(p));try{await mn(s),r.validate!==!1&&await mr(s)}catch(m){return yt(o,"PACKAGE_VALIDATION",m.message)}this.entries=i;let f=this.toUint8Array();this.originalBytes=f;let d=le(f);return{...l,status:"ok",written:!0,hasChanges:!0,artifactsChanged:[...i].filter(([m,p])=>!a.has(m)||!po(p,a.get(m))).map(([m])=>m),uint8Array:f,toUint8Array:()=>new Uint8Array(f),buffer:d,toBuffer:()=>le(f)}}async resolveComment(t,r={}){let n=this.originalBytes,o=xn(this.entries),a=r.resolved!==!1,i=f=>{let d=le(n);return{status:"ok",hasChanges:!1,written:!1,artifactsChanged:[],...f,uint8Array:n,toUint8Array:()=>new Uint8Array(n),buffer:d,toBuffer:()=>le(n)}},s=ua({commentsXml:ne(o,"word/comments.xml"),commentsExtendedXml:ne(o,"word/commentsExtended.xml"),commentId:t,resolved:a});if(s.status==="error")return yt(n,s.error.code,s.error.message);if(!s.hasChanges)return i({resolved:a,threadRootId:s.threadRootId,commentIds:s.commentIds});let l=new Qt(o);try{s.commentsXml&&o.set("word/comments.xml",Lt.encode(s.commentsXml)),await va(l,s.commentsExtendedXml,{replaceExisting:!0}),await mn(l),r.validate!==!1&&await mr(l)}catch(f){return yt(n,"PACKAGE_VALIDATION",f.message)}let c=[...o].filter(([f,d])=>!this.entries.has(f)||!po(d,this.entries.get(f))).map(([f])=>f);this.entries=o;let u=this.toUint8Array();return this.originalBytes=u,{status:"ok",hasChanges:!0,written:!0,resolved:a,threadRootId:s.threadRootId,commentIds:s.commentIds,artifactsChanged:c,uint8Array:u,toUint8Array:()=>new Uint8Array(u),buffer:le(u),toBuffer:()=>le(u)}}async deleteComments(t={}){let r=this.originalBytes,n=xn(this.entries),o=ne(n,"word/comments.xml"),a=le(r);if(!o)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>le(r)};let i=W(o,"application/xml");if(!i.doc||i.error)return yt(r,"PARSE_ERROR",i.error?.message||"Could not parse comments.xml.");let s=Array.isArray(t.ids)?new Set(t.ids.map(String)):null;if(s){let x=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).map(N=>N.getAttribute("w:id")||N.getAttribute("id"))),I=[...s].filter(N=>!x.has(N));if(I.length)return yt(r,"COMMENT_NOT_FOUND",`Comment id(s) not found: ${I.join(", ")}.`)}let l=x=>s?s.has(x.getAttribute("w:id")||x.getAttribute("id")):t.allAuthors===!0||(x.getAttribute("w:author")||x.getAttribute("author"))===t.author,c=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).filter(l).map(x=>x.getAttribute("w:id")||x.getAttribute("id")).filter(Boolean));if(!c.size)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>le(r)};let u=ne(n,"word/commentsExtended.xml"),f=null,d=new Set;if(u){if(f=W(u,"application/xml"),!f.doc||f.error)return yt(r,"PARSE_ERROR",f.error?.message||"Could not parse commentsExtended.xml.");let x=new Map;for(let N of Array.from(i.doc.getElementsByTagNameNS("*","comment"))){let T=N.getAttribute("w:id")||N.getAttribute("id"),E=tt(N);E&&x.set(E,T)}for(let[N,T]of x)c.has(T)&&d.add(N);let I=!0;for(;I;){I=!1;for(let N of Array.from(f.doc.getElementsByTagNameNS("*","commentEx"))){let T=(N.getAttribute("w15:paraId")||N.getAttribute("paraId")||"").toUpperCase(),E=(N.getAttribute("w15:paraIdParent")||N.getAttribute("paraIdParent")||"").toUpperCase();E&&d.has(E)&&!d.has(T)&&(d.add(T),x.has(T)&&c.add(x.get(T)),I=!0)}}}let m=s?o:pi(o,{author:t.author,allAuthors:t.allAuthors===!0}).oxml,p=W(m,"application/xml");if(!p.doc||p.error)return yt(r,"PARSE_ERROR",p.error?.message||"Could not parse updated comments.xml.");for(let x of Array.from(p.doc.getElementsByTagNameNS("*","comment"))){let I=x.getAttribute("w:id")||x.getAttribute("id");c.has(I)&&x.parentNode?.removeChild(x)}let g=W(ne(n,"word/document.xml"),"application/xml");if(!g.doc||g.error)return yt(r,"PARSE_ERROR",g.error?.message||"Could not parse document.xml.");let h=0;for(let x of["commentRangeStart","commentRangeEnd","commentReference"])for(let I of Array.from(g.doc.getElementsByTagNameNS("*",x))){let N=I.getAttribute("w:id")||I.getAttribute("id");if(!c.has(N)||!I.parentNode)continue;let T=I.parentNode;T.removeChild(I),h+=1,x==="commentReference"&&T.localName==="r"&&!Array.from(T.childNodes||[]).some(E=>E.nodeType===1&&E.localName!=="rPr")&&T.parentNode?.removeChild(T)}let y=oe();if(n.set("word/comments.xml",Lt.encode(y.serializeToString(p.doc))),f?.doc){for(let x of Array.from(f.doc.getElementsByTagNameNS("*","commentEx"))){let I=(x.getAttribute("w15:paraId")||x.getAttribute("paraId")||"").toUpperCase();d.has(I)&&x.parentNode?.removeChild(x)}n.set("word/commentsExtended.xml",Lt.encode(y.serializeToString(f.doc)))}n.set("word/document.xml",Lt.encode(y.serializeToString(g.doc)));try{nf(n);let x=new Qt(n);await mn(x),t.validate!==!1&&await mr(x)}catch(x){return yt(r,"PACKAGE_VALIDATION",x.message)}let w=[...n].filter(([x,I])=>!this.entries.has(x)||!po(I,this.entries.get(x))).map(([x])=>x);this.entries=n;let v=this.toUint8Array();this.originalBytes=v;let b=le(v);return{status:"ok",hasChanges:!0,written:!0,commentsRemoved:c.size,referencesRemoved:h,artifactsChanged:w,uint8Array:v,toUint8Array:()=>new Uint8Array(v),buffer:b,toBuffer:()=>le(v)}}};function gh(e){return new ka(e)}async function cf(e,t,r,n={}){let o=await Dn(e,t,r,n);if(o?.useNativeApi&&typeof o?.oxml!="string"){let a=Array.isArray(o?.warnings)?o.warnings:[];return xe({...o,oxml:e,hasChanges:!1,warnings:[...a,"Standalone mode cannot execute native Word API fallback for this operation."]})}return o}async function AT(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=at(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await cf(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function RT(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,a=n.sanitizeInput===!0?wi(r):r,i=a!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],s=nn({oxml:e,originalText:t,modifiedText:a,allowExistingList:o}),l=n.preferListStructuralFallback!==!1,c=[];if(s&&l){let g=await on(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(g?.hasChanges&&g?.oxml){let h=nr(g.oxml,{includeNumbering:g.includeNumbering??!0,numberingXml:g.numberingXml}),y=Array.isArray(g?.warnings)?g.warnings:[];return xe({oxml:h,hasChanges:!0,warnings:[...i,...y],listStructuralFallbackApplied:!0,listStructuralFallbackKey:g.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:g.numberingXml||null})}c=Array.isArray(g?.warnings)?g.warnings:[]}let u=await cf(e,t,r,n);if(!s)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(l)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(u?.hasChanges)return{...u,listStructuralFallbackApplied:!1};let f=await on(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let g=Array.isArray(u?.warnings)?u.warnings:[],h=Array.isArray(f?.warnings)?f.warnings:[];return{...u,warnings:[...g,...h],listStructuralFallbackApplied:!1}}let d=nr(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),m=Array.isArray(u?.warnings)?u.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return xe({...u,oxml:d,hasChanges:!0,warnings:[...m,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{Wr as ContainerKind,Ls as ContentType,mt as DiffOp,ka as DocxDocument,L as NS_W,$t as NumberingService,oo as ReceiptCollector,Pn as ReconciliationPipeline,pn as RoutePlanKind,Z as RunKind,Pe as WORD_MAIN_NS,Er as acceptTrackedChangesInOoxml,Eo as analyzeStructuredContent,$i as applyCommentReplyToParts,Lp as applyFormattingRemovalToOoxml,Ui as applyHighlightToOoxml,cf as applyRedlineToOxml,RT as applyRedlineToOxmlWithListFallback,Dr as areRevisionTokensEqual,Hn as buildCommentElement,_i as buildCommentsPartXml,oa as buildExplicitDecimalMultilevelNumberingXml,Wm as buildListMarkdown,jp as buildReconciliationPlan,Di as buildRevisionTokenFraming,nn as buildSingleLineListStructuralFallbackPlan,xi as buildTargetReferenceSnapshot,Vn as clearSingleLineListFallbackExplicitSequence,hc as collectContiguousListParagraphBlock,Yn as computeDocumentPartsRevisionToken,xs as computePackageRevisionToken,_c as computeRevisionToken,qn as computeRevisionTokenSync,vf as configureLogger,Nf as configureXmlProvider,or as containsTrackedChanges,ea as createDynamicNumberingIdState,_e as createEmptyReceipt,st as createParagraphFingerprint,pi as deleteCommentsByAuthorInOoxml,Zo as enforceListBindingOnParagraphNodes,Ji as ensureCommentsArtifactsInZip,va as ensureCommentsExtendedArtifactsInZip,ya as ensureNumberingArtifactsInZip,ze as escapeXml,on as executeSingleLineListStructuralFallback,te as extractCanonicalParagraphText,fa as extractDocumentPartsEntries,na as extractFirstParagraphNumId,Kp as extractParagraphIdFromOoxml,Co as extractParagraphRevisionSegments,qi as extractReplacementNodesFromOoxml,We as findContainingWordElement,yi as findParagraphByBestTextMatch,dc as findParagraphByReference,Vo as findParagraphByStrictText,Wo as findStrictTargetCandidates,yr as generateTableOoxml,Gi as getBodyElementFromDocument,re as getDefaultAuthor,se as getDocumentParagraphNodes,Wi as getPackagePartName,$e as getParagraphId,lt as getParagraphListInfo,be as getParagraphText,Da as getPlatform,vr as getTrackedChangeAuthors,Ii as hasListItems,Nn as inferNumberingStyleFromMarker,Si as inferTableReplacementParagraphBlock,Hr as ingestOoxml,yp as ingestWordOoxmlToMarkdown,Ac as ingestWordOoxmlToMarkdownResult,wp as ingestWordOoxmlToPlainText,Ec as ingestWordOoxmlToPlainTextResult,Fi as injectCommentsIntoOoxml,kp as injectCommentsIntoPackage,Xp as insertBodyElementBeforeSectPr,ma as inspectDocumentParts,xc as isLikelyStructuredTableSourceParagraph,Or as isMarkdownTableText,Ir as isNodeVisibleInRevisionView,ia as mergeNumberingXmlBySchemaOrder,wa as normalizeBodySectionOrderStandalone,tu as normalizeContentEscapesForRouting,jm as normalizeListItemsWithLevels,Oc as normalizeOpcEntryName,J as normalizeWhitespaceForTargeting,gh as openDocx,ra as overwriteParagraphNumIds,Xn as parseMarkdownListContent,Vt as parseOoxml,W as parseOoxmlSafe,vi as parseParagraphReference,Ni as planListInsertionOnlyEdit,Od as planStructuredReplacement,Je as preprocessMarkdown,Tr as readCanonicalRunText,AT as reconcileMarkdownTableOoxml,ao as reconcileReceiptsAgainstOutput,Yo as recordSingleLineListFallbackExplicitSequence,cr as rejectTrackedChangesInOoxml,aa as remapNumberingPayloadForDocument,Wc as removeFormattingFromRPr,mn as repairKnownContentTypes,jn as reserveNextNumberingId,ta as reserveNextNumberingIdPair,en as resolveParagraphRangeByRefs,qo as resolveSingleLineListFallbackNumberingAction,_r as resolveTargetParagraph,$n as resolveTargetParagraphWithSnapshot,wi as sanitizeAiResponse,Vp as sanitizeNestedParagraphsInTables,Cr as serializeOoxml,bt as serializeToOoxml,Af as setDefaultAuthor,Rf as setPlatform,Dm as splitLeadingParagraphMarker,Bm as stripLeadingParagraphMarker,kr as stripRedundantLeadingListMarkers,Ti as stripSingleLineListMarkerPrefix,bi as synthesizeExpandedListScopeEdit,Ei as synthesizeTableMarkdownFromMultilineCellEdit,mr as validateDocxPackage,ct as validateRedlineOoxml,Br as validateRevisionToken,nr as wrapInDocumentFragment};
|
|
214
227
|
//# sourceMappingURL=docx-redline-js.esm.min.js.map
|