@ansonlai/docx-redline-js 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENTS.md +78 -697
  2. package/ARCHITECTURE.md +13 -1
  3. package/CHANGELOG.md +5 -0
  4. package/README.md +140 -30
  5. package/core/paragraph-targeting.js +14 -2
  6. package/dist/docx-redline-js.esm.js +113 -33
  7. package/dist/docx-redline-js.esm.js.map +3 -3
  8. package/dist/docx-redline-js.esm.min.js +75 -75
  9. package/dist/docx-redline-js.esm.min.js.map +4 -4
  10. package/docs/AGENT_FAST_START.md +59 -0
  11. package/docs/AGENT_KNOWLEDGE_BASE.md +868 -0
  12. package/docs/TESTING.md +20 -1
  13. package/docs/schemas/document-operations.schema.json +5 -1
  14. package/docs/validation-reports/2026-09-12-agent-protocol-rollout.md +82 -0
  15. package/engine/oxml-engine.js +80 -13
  16. package/engine/run-builders.js +5 -15
  17. package/index.d.ts +17 -1
  18. package/node/cli.js +111 -27
  19. package/node/docx-document.js +120 -69
  20. package/node/index.d.ts +6 -2
  21. package/package.json +10 -3
  22. package/scripts/generate-cross-author-slicing-fixtures.ps1 +25 -25
  23. package/services/batch-operation-orchestrator.js +215 -120
  24. package/services/document-inspection.js +5 -3
  25. package/services/document-operation-applier.js +52 -34
  26. package/services/document-operation-contract.js +10 -6
  27. package/services/document-operation-mutations.js +51 -5
  28. package/services/document-operation-session.js +4 -0
  29. package/services/error-recovery.js +174 -0
  30. package/services/operation-batch-compiler.js +394 -0
  31. package/services/operation-preflight.js +91 -72
  32. package/services/standalone-operation-runner.d.ts +17 -1
  33. package/docs/plans/2026-09-05-structural-revisions-and-fidelity-oracles.md +0 -1669
  34. package/docs/plans/2026-09-08-cross-author-revision-slicing.md +0 -1399
  35. package/docs/plans/completed/2026-03-01-release-0.1.4-design.md +0 -33
  36. package/docs/plans/completed/2026-03-01-release-0.1.4.md +0 -110
  37. package/docs/plans/completed/2026-05-31-architectural changes.md +0 -593
  38. package/docs/plans/completed/2026-08-02-reliability-improvements.md +0 -1155
  39. package/docs/plans/completed/2026-08-30-reliability-testing-improvements.md +0 -488
  40. package/docs/plans/completed/2026-09-01-performance-and-complexity-reduction.md +0 -669
  41. package/docs/plans/completed/2026-09-03-agent-friendly-document-workflows.md +0 -427
  42. package/docs/plans/completed/2026-09-04-comment-anchor-and-cli-reliability.md +0 -519
  43. package/docs/plans/completed/PERFORMANCE-CONSOLIDATION.md +0 -69
  44. package/docs/plans/completed/structural-revision-capability-matrix.md +0 -115
  45. package/docs/test-comparison-dashboard.html +0 -4338
  46. package/docs/validation-reports/2026-08-30-phase-1-word-visual-preflight.md +0 -22
  47. package/docs/validation-reports/2026-08-30-phase-2-word-visual-preflight.md +0 -24
  48. package/docs/validation-reports/2026-08-30-phase-3-coverage.md +0 -73
  49. package/docs/validation-reports/2026-09-02-multilevel-bullets-visual-review.md +0 -82
  50. package/docs/validation-reports/2026-09-02-multimodal-visual-samples.md +0 -114
  51. package/docs/validation-reports/2026-09-02-visual-failures-preflight.md +0 -79
@@ -1,16 +1,16 @@
1
- var ds=Object.create;var _o=Object.defineProperty;var ps=Object.getOwnPropertyDescriptor;var gs=Object.getOwnPropertyNames;var hs=Object.getPrototypeOf,ws=Object.prototype.hasOwnProperty;var bs=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var xs=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gs(t))!ws.call(e,o)&&o!==r&&_o(e,o,{get:()=>t[o],enumerable:!(n=ps(t,o))||n.enumerable});return e};var Lo=(e,t,r)=>(r=e!=null?ds(hs(e)):{},xs(t||!e||!e.__esModule?_o(r,"default",{value:e,enumerable:!0}):r,e));var kn=bs((Vf,Ct)=>{var P=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},J=-1,Q=1,W=0;P.Diff=function(e,t){return[e,t]};P.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 P.Diff(W,e)]:[];typeof r>"u"&&(r=!0);var i=r,a=this.diff_commonPrefix(e,t),s=e.substring(0,a);e=e.substring(a),t=t.substring(a),a=this.diff_commonSuffix(e,t);var l=e.substring(e.length-a);e=e.substring(0,e.length-a),t=t.substring(0,t.length-a);var c=this.diff_compute_(e,t,i,o);return s&&c.unshift(new P.Diff(W,s)),l&&c.push(new P.Diff(W,l)),this.diff_cleanupMerge(c),c};P.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new P.Diff(Q,t)];if(!t)return[new P.Diff(J,e)];var i=e.length>t.length?e:t,a=e.length>t.length?t:e,s=i.indexOf(a);if(s!=-1)return o=[new P.Diff(Q,i.substring(0,s)),new P.Diff(W,a),new P.Diff(Q,i.substring(s+a.length))],e.length>t.length&&(o[0][0]=o[2][0]=J),o;if(a.length==1)return[new P.Diff(J,e),new P.Diff(Q,t)];var l=this.diff_halfMatch_(e,t);if(l){var c=l[0],u=l[1],f=l[2],m=l[3],d=l[4],p=this.diff_main(c,f,r,n),b=this.diff_main(u,m,r,n);return p.concat([new P.Diff(W,d)],b)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};P.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var o=n.lineArray,i=this.diff_main(e,t,!1,r);this.diff_charsToLines_(i,o),this.diff_cleanupSemantic(i),i.push(new P.Diff(W,""));for(var a=0,s=0,l=0,c="",u="";a<i.length;){switch(i[a][0]){case Q:l++,u+=i[a][1];break;case J:s++,c+=i[a][1];break;case W:if(s>=1&&l>=1){i.splice(a-s-l,s+l),a=a-s-l;for(var f=this.diff_main(c,u,!1,r),m=f.length-1;m>=0;m--)i.splice(a,0,f[m]);a=a+f.length}l=0,s=0,c="",u="";break}a++}return i.pop(),i};P.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,o=t.length,i=Math.ceil((n+o)/2),a=i,s=2*i,l=new Array(s),c=new Array(s),u=0;u<s;u++)l[u]=-1,c[u]=-1;l[a+1]=0,c[a+1]=0;for(var f=n-o,m=f%2!=0,d=0,p=0,b=0,h=0,g=0;g<i&&!(new Date().getTime()>r);g++){for(var w=-g+d;w<=g-p;w+=2){var x=a+w,y;w==-g||w!=g&&l[x-1]<l[x+1]?y=l[x+1]:y=l[x-1]+1;for(var N=y-w;y<n&&N<o&&e.charAt(y)==t.charAt(N);)y++,N++;if(l[x]=y,y>n)p+=2;else if(N>o)d+=2;else if(m){var T=a+f-w;if(T>=0&&T<s&&c[T]!=-1){var v=n-c[T];if(y>=v)return this.diff_bisectSplit_(e,t,y,N,r)}}}for(var S=-g+b;S<=g-h;S+=2){var T=a+S,v;S==-g||S!=g&&c[T-1]<c[T+1]?v=c[T+1]:v=c[T-1]+1;for(var I=v-S;v<n&&I<o&&e.charAt(n-v-1)==t.charAt(o-I-1);)v++,I++;if(c[T]=v,v>n)h+=2;else if(I>o)b+=2;else if(!m){var x=a+f-S;if(x>=0&&x<s&&l[x]!=-1){var y=l[x],N=a+y-x;if(v=n-v,y>=v)return this.diff_bisectSplit_(e,t,y,N,r)}}}}return[new P.Diff(J,e),new P.Diff(Q,t)]};P.prototype.diff_bisectSplit_=function(e,t,r,n,o){var i=e.substring(0,r),a=t.substring(0,n),s=e.substring(r),l=t.substring(n),c=this.diff_main(i,a,!1,o),u=this.diff_main(s,l,!1,o);return c.concat(u)};P.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(l){for(var c="",u=0,f=-1,m=r.length;f<l.length-1;){f=l.indexOf(`
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,b,h){for(var g=p.substring(h,h+Math.floor(p.length/4)),w=-1,x="",y,N,T,v;(w=b.indexOf(g,w+1))!=-1;){var S=o.diff_commonPrefix(p.substring(h),b.substring(w)),I=o.diff_commonSuffix(p.substring(0,h),b.substring(0,w));x.length<I+S&&(x=b.substring(w-I,w)+b.substring(w,w+S),y=p.substring(0,h-I),N=p.substring(h+S),T=b.substring(0,w-I),v=b.substring(w+S))}return x.length*2>=p.length?[y,N,T,v,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]==W?(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(W,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(W,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 b=d.charAt(d.length-1),h=p.charAt(0),g=b.match(P.nonAlphaNumericRegex_),w=h.match(P.nonAlphaNumericRegex_),x=g&&b.match(P.whitespaceRegex_),y=w&&h.match(P.whitespaceRegex_),N=x&&b.match(P.linebreakRegex_),T=y&&h.match(P.linebreakRegex_),v=N&&d.match(P.blanklineEndRegex_),S=T&&p.match(P.blanklineStartRegex_);return v||S?5:N||T?4:g&&!x&&y?3:x||y?2:g||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==W&&e[r+1][0]==W){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]==W?(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(W,""));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 W: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]==W?e[t-r-n-1][1]+=i.substring(0,a):(e.splice(0,0,new P.Diff(W,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]==W?(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]==W&&e[t+1][0]==W&&(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,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(i,"&para;<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 W: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 W: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 W: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(W,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(y,N){var T=y/t.length,v=Math.abs(r-N);return o.Match_Distance?T+v/o.Match_Distance:v?1:T}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),b=Math.min(r+u,e.length)+t.length,h=Array(b+2);h[b+1]=(1<<d)-1;for(var g=b;g>=p;g--){var w=n[e.charAt(g-1)];if(d===0?h[g]=(h[g+1]<<1|1)&w:h[g]=(h[g+1]<<1|1)&w|((m[g+1]|m[g])<<1|1)|m[g+1],h[g]&l){var x=i(d,g-1);if(x<=a)if(a=x,s=g-1,s>r)p=Math.max(1,2*r-s);else break}}if(i(d+1,r)>a)break;m=h}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(W,o));var i=t.substring(e.start2+e.length1,e.start2+e.length1+n);i&&e.diffs.push(new P.Diff(W,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!==W&&(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 W: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 b=e[i].diffs[p];b[0]!==W&&(d=this.diff_xIndex(f,m)),b[0]===Q?t=t.substring(0,l+d)+b[1]+t.substring(l+d):b[0]===J&&(t=t.substring(0,l+d)+t.substring(l+this.diff_xIndex(f,m+b[1].length))),b[0]!==J&&(m+=b[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]!=W)i.unshift(new P.Diff(W,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]!=W)i.push(new P.Diff(W,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(W,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]==W&&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===W?(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]===W?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new P.Diff(W,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(`
1
+ var ws=Object.create;var $o=Object.defineProperty;var bs=Object.getOwnPropertyDescriptor;var xs=Object.getOwnPropertyNames;var Ns=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var ys=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Ts=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xs(t))!vs.call(e,o)&&o!==r&&$o(e,o,{get:()=>t[o],enumerable:!(n=bs(t,o))||n.enumerable});return e};var Xo=(e,t,r)=>(r=e!=null?ws(Ns(e)):{},Ts(t||!e||!e.__esModule?$o(r,"default",{value:e,enumerable:!0}):r,e));var Ln=ys((em,Mt)=>{var P=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},J=-1,Q=1,W=0;P.Diff=function(e,t){return[e,t]};P.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 P.Diff(W,e)]:[];typeof r>"u"&&(r=!0);var i=r,a=this.diff_commonPrefix(e,t),s=e.substring(0,a);e=e.substring(a),t=t.substring(a),a=this.diff_commonSuffix(e,t);var l=e.substring(e.length-a);e=e.substring(0,e.length-a),t=t.substring(0,t.length-a);var c=this.diff_compute_(e,t,i,o);return s&&c.unshift(new P.Diff(W,s)),l&&c.push(new P.Diff(W,l)),this.diff_cleanupMerge(c),c};P.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new P.Diff(Q,t)];if(!t)return[new P.Diff(J,e)];var i=e.length>t.length?e:t,a=e.length>t.length?t:e,s=i.indexOf(a);if(s!=-1)return o=[new P.Diff(Q,i.substring(0,s)),new P.Diff(W,a),new P.Diff(Q,i.substring(s+a.length))],e.length>t.length&&(o[0][0]=o[2][0]=J),o;if(a.length==1)return[new P.Diff(J,e),new P.Diff(Q,t)];var l=this.diff_halfMatch_(e,t);if(l){var c=l[0],u=l[1],f=l[2],m=l[3],d=l[4],p=this.diff_main(c,f,r,n),h=this.diff_main(u,m,r,n);return p.concat([new P.Diff(W,d)],h)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};P.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var o=n.lineArray,i=this.diff_main(e,t,!1,r);this.diff_charsToLines_(i,o),this.diff_cleanupSemantic(i),i.push(new P.Diff(W,""));for(var a=0,s=0,l=0,c="",u="";a<i.length;){switch(i[a][0]){case Q:l++,u+=i[a][1];break;case J:s++,c+=i[a][1];break;case W:if(s>=1&&l>=1){i.splice(a-s-l,s+l),a=a-s-l;for(var f=this.diff_main(c,u,!1,r),m=f.length-1;m>=0;m--)i.splice(a,0,f[m]);a=a+f.length}l=0,s=0,c="",u="";break}a++}return i.pop(),i};P.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,o=t.length,i=Math.ceil((n+o)/2),a=i,s=2*i,l=new Array(s),c=new Array(s),u=0;u<s;u++)l[u]=-1,c[u]=-1;l[a+1]=0,c[a+1]=0;for(var f=n-o,m=f%2!=0,d=0,p=0,h=0,w=0,b=0;b<i&&!(new Date().getTime()>r);b++){for(var g=-b+d;g<=b-p;g+=2){var x=a+g,N;g==-b||g!=b&&l[x-1]<l[x+1]?N=l[x+1]:N=l[x-1]+1;for(var v=N-g;N<n&&v<o&&e.charAt(N)==t.charAt(v);)N++,v++;if(l[x]=N,N>n)p+=2;else if(v>o)d+=2;else if(m){var T=a+f-g;if(T>=0&&T<s&&c[T]!=-1){var y=n-c[T];if(N>=y)return this.diff_bisectSplit_(e,t,N,v,r)}}}for(var S=-b+h;S<=b-w;S+=2){var T=a+S,y;S==-b||S!=b&&c[T-1]<c[T+1]?y=c[T+1]:y=c[T-1]+1;for(var I=y-S;y<n&&I<o&&e.charAt(n-y-1)==t.charAt(o-I-1);)y++,I++;if(c[T]=y,y>n)w+=2;else if(I>o)h+=2;else if(!m){var x=a+f-S;if(x>=0&&x<s&&l[x]!=-1){var N=l[x],v=a+N-x;if(y=n-y,N>=y)return this.diff_bisectSplit_(e,t,N,v,r)}}}}return[new P.Diff(J,e),new P.Diff(Q,t)]};P.prototype.diff_bisectSplit_=function(e,t,r,n,o){var i=e.substring(0,r),a=t.substring(0,n),s=e.substring(r),l=t.substring(n),c=this.diff_main(i,a,!1,o),u=this.diff_main(s,l,!1,o);return c.concat(u)};P.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(l){for(var c="",u=0,f=-1,m=r.length;f<l.length-1;){f=l.indexOf(`
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="",N,v,T,y;(g=h.indexOf(b,g+1))!=-1;){var S=o.diff_commonPrefix(p.substring(w),h.substring(g)),I=o.diff_commonSuffix(p.substring(0,w),h.substring(0,g));x.length<I+S&&(x=h.substring(g-I,g)+h.substring(g,g+S),N=p.substring(0,w-I),v=p.substring(w+S),T=h.substring(0,g-I),y=h.substring(g+S))}return x.length*2>=p.length?[N,v,T,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]==W?(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(W,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(W,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_),N=g&&w.match(P.whitespaceRegex_),v=x&&h.match(P.linebreakRegex_),T=N&&w.match(P.linebreakRegex_),y=v&&d.match(P.blanklineEndRegex_),S=T&&p.match(P.blanklineStartRegex_);return y||S?5:v||T?4:b&&!x&&N?3:x||N?2:b||g?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==W&&e[r+1][0]==W){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]==W?(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(W,""));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 W: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]==W?e[t-r-n-1][1]+=i.substring(0,a):(e.splice(0,0,new P.Diff(W,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]==W?(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]==W&&e[t+1][0]==W&&(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,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(i,"&para;<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 W: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 W: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 W: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(W,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(N,v){var T=N/t.length,y=Math.abs(r-v);return o.Match_Distance?T+y/o.Match_Distance:y?1:T}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(W,o));var i=t.substring(e.start2+e.length1,e.start2+e.length1+n);i&&e.diffs.push(new P.Diff(W,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!==W&&(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 W: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]!==W&&(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]!=W)i.unshift(new P.Diff(W,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]!=W)i.push(new P.Diff(W,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(W,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]==W&&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===W?(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]===W?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new P.Diff(W,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
3
  `),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var i=r[n].match(o);if(!i)throw new Error("Invalid patch string: "+r[n]);var a=new P.patch_obj;for(t.push(a),a.start1=parseInt(i[1],10),i[2]===""?(a.start1--,a.length1=1):i[2]=="0"?a.length1=0:(a.start1--,a.length1=parseInt(i[2],10)),a.start2=parseInt(i[3],10),i[4]===""?(a.start2--,a.length2=1):i[4]=="0"?a.length2=0:(a.start2--,a.length2=parseInt(i[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=="-")a.diffs.push(new P.Diff(J,l));else if(s=="+")a.diffs.push(new P.Diff(Q,l));else if(s==" ")a.diffs.push(new P.Diff(W,l));else{if(s=="@")break;if(s!=="")throw new Error('Invalid patch mode "'+s+'" in: '+l)}n++}}return t};P.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};P.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
4
  `],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case Q:n="+";break;case J:n="-";break;case W:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
5
- `}return r.join("").replace(/%20/g," ")};Ct.exports=P;Ct.exports.diff_match_patch=P;Ct.exports.DIFF_DELETE=J;Ct.exports.DIFF_INSERT=Q;Ct.exports.DIFF_EQUAL=W});var Pr=console,xn=Object.freeze({silent:0,error:1,warn:2,info:3}),Ns=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",Nn=Ns;function vs(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(xn,t)?t:Nn}function vn(e){return xn[Nn]>=xn[e]}function ys(e,t={}){Pr=e||console,t.level&&(Nn=vs(t.level))}function k(...e){vn("info")&&(Pr.log||(()=>{}))(...e)}function Fe(...e){vn("warn")&&(Pr.warn||(()=>{}))(...e)}function ee(...e){vn("error")&&(Pr.error||(()=>{}))(...e)}var Yt=globalThis.DOMParser,Jt=globalThis.XMLSerializer;function Ts(e={}){e.DOMParser&&(Yt=e.DOMParser),e.XMLSerializer&&(Jt=e.XMLSerializer)}function Ss(e={}){if(!Yt&&globalThis.DOMParser&&(Yt=globalThis.DOMParser),!Yt)throw new Error("DOMParser is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Yt(e)}function me(){if(!Jt&&globalThis.XMLSerializer&&(Jt=globalThis.XMLSerializer),!Jt)throw new Error("XMLSerializer is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Jt}function Bo(e,t="text/xml"){let r=j(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function Es(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function j(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,i)=>{let a=String(i||"XML parser diagnostic.");o==="fatalError"?ee("[XmlAdapter] XML fatal parse error:",a):(r.push(a),Fe(`[XmlAdapter] XML ${o||"warning"}:`,a))};try{let i=Ss({onError:n}).parseFromString(e,t),a=Es(i);if(!i?.documentElement||a){let s=a?.textContent||"Could not parse XML input.";return ee("[XmlAdapter] XML parse error:",s),{doc:null,error:{code:"PARSE_ERROR",message:s},warnings:r}}return{doc:i,error:null,warnings:r}}catch(o){let i=o?.message||String(o||"Could not parse XML input.");return ee("[XmlAdapter] XML parse error:",i),{doc:null,error:{code:"PARSE_ERROR",message:i},warnings:r}}}function ne(e){return me().serializeToString(e)}var Fo=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",$o=Fo(),Xo="Unknown";function As(e){$o=typeof e=="string"&&e.trim()?e.trim():Fo()}function de(){return $o}function Is(e){Xo=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function yn(){return Xo}var Ps=[{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:/&lt;b&gt;(.+?)&lt;\/b&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;strong&gt;(.+?)&lt;\/strong&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;i&gt;(.+?)&lt;\/i&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;em&gt;(.+?)&lt;\/em&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;u&gt;(.+?)&lt;\/u&gt;/i,format:{underline:!0},isEscaped:!0},{regex:/&lt;s&gt;(.+?)&lt;\/s&gt;/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 Ie(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let s of Ps){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?Rs(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=[],i=0;for(let s of n)s.start>=i&&(o.push(s),i=s.end);let a=0;for(let s of o){r+=e.slice(a,s.start);let l=Ie(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});a=s.end}return r+=e.slice(a),{cleanText:r,formatHints:t}}function Ye(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function Tn(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function Rs(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var Rr=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,Do=new RegExp(`^(\\s*)((?:${Rr})\\s+)`),zo=new RegExp(`^(\\s*)((?:${Rr})\\s*)`),Cs=new RegExp(`^(\\s*)((?:${Rr})\\s+)`,"m"),Os=new RegExp(`^(\\s*)((?:${Rr})\\s*)`,"m");function Sn(e){return typeof e!="string"?!1:e.includes(`
6
- `)&&Cs.test(e)}function qt(e){return typeof e!="string"?!1:e.includes(`
7
- `)&&Os.test(e.trim())}function $e(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?zo:Do;return e.match(n)}function He(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?zo:Do;return e.replace(n,"")}function Wo(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function Zt(e){let t=String(e||"").trim();return Wo(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 ks(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function Qt(e,t={}){let r=$e(String(e||""),t);if(!r)return null;let n=r[2].trim(),o=(r[1]||"").length,i=Math.max(1,Number(t.indentSpaces)||2),a=Wo(n);return{line:String(e||""),text:He(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/i)),markerType:a,listType:a,numberingStyle:Zt(n),outlineLevel:a==="numbered"?ks(n):null}}var E="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var ke=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),D=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"}),Et=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),Ho=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),G=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),we=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function Ne(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var En=1e3,Uo=2147483647,jo=1e4,Ms=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Vo=new WeakMap;function _s(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return Ms.has(t)?!e.namespaceURI||e.namespaceURI===E||String(e.nodeName||"").startsWith("w:"):!1}function Ls(e){let t=e?.getAttributeNS?.(E,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var he=class{constructor(t=En){this.startValue=Number.isInteger(t)&&t>=0?t:En,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(_s(o)){let a=Ls(o);a!=null&&(this.occupiedIds.add(a),r=Math.max(r,a))}if(o.firstChild){o=o.firstChild;continue}for(;o&&o!==n&&!o.nextSibling;)o=o.parentNode;o=o&&o!==n?o.nextSibling:null}let i=Uo-jo;return this.nextId=r>=i?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=Uo-jo;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}},er=new he;function Cr(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof he&&Vo.set(r,t),t}function Je(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Vo.get(t)||null}function ot(e,t=En){let r=new he(t);return r.seed(e),Cr(e,r),r}function Go(){return er.next()}function Or(e=new Date){return e.toISOString()}function oe(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():de(),o=t instanceof he?t:Je(t)||er,i=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(i,r||"structural"),{id:i,author:n,date:Or()}}function tr(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():de(),n=t instanceof he?t:Je(t)||er,o=Or(),i=n.next(),a=n.next();return n._receiptCollector&&(n._receiptCollector.recordRevision(i,"del"),n._receiptCollector.recordRevision(a,"ins")),{deletionId:i,insertionId:a,author:r,date:o}}function At(e,t=er){let r=t instanceof he?t:er,n=r.seed(e);return Cr(e,r),n}function Ko(e,t){return e<t-1}function It(e,t,r){return Ko(t,r)?e+`
8
- `:e}function pt(e,t,r){return Ko(t,r)?e+1:e}function rr(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function ie(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 ve(e,t,r,n=`w:${r}`){let o=ce(e,t,r);return o.length>0?o:rr(e,n)}function ye(e,t,r,n=`w:${r}`){let o=te(e,t,r);return o||ie(e,n)}function re(e){return ie(e,"parsererror")}function An(e){return Array.from(e?.childNodes||[])}function Yo(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function In(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var Pn=0;function Rt(e,t={}){let r=[],n="",o=t.xmlDoc||null;if(!e&&!o)return{runModel:r,acceptedText:n,pPr:null};try{let i=o?{doc:o,error:null}:j(e,"application/xml"),a=i.doc;if(i.error||!a)return ee("OOXML parse error:",i.error?.message),{runModel:r,acceptedText:n,pPr:null,error:i.error};let s=re(a);if(s)return ee("OOXML parse error:",s.textContent),{runModel:r,acceptedText:n,pPr:null};let l=ce(a,E,"p");return l.length===0?(Fe("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):qo(l,{includeParagraphBoundaries:!0})}catch(i){return ee("Error ingesting OOXML:",i),{runModel:r,acceptedText:n,pPr:null}}}function Rn(e){return e?qo([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function nr(e){let t=te(e,E,"pPr");if(!t)return null;let r=te(t,E,"numPr");if(!r)return null;let n=te(r,E,"numId"),o=te(r,E,"ilvl");if(!n)return null;let i=n.getAttribute("w:val");if(!/^\d+$/.test(i)||Number.parseInt(i,10)===0)return null;let a=i==="1"?"bullet":i==="2"?"numbered":"unknown";return{numId:i,ilvl:parseInt(o?.getAttribute("w:val")||"0",10),type:a}}function qo(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],o="",i=0,a=null;for(let s=0;s<e.length;s++){let l=e[s],c=te(l,E,"pPr");s===0&&(a=c),n.push({kind:D.PARAGRAPH_START,pPrElement:c||null,startOffset:i,endOffset:i,text:""});let u=Pt(l,i,n);o+=u.text,i=o.length,r&&(o=It(o,s,e.length),i=pt(i,s,e.length))}return{runModel:n,acceptedText:o,pPr:a}}function Pt(e,t,r){let n=t,o="",i=Bs(r);for(let a of An(e)){if(In(a,E,"pPr")||In(a,E,"proofErr"))continue;let s=i.get(a.localName);if(!s)continue;let l=s(a,n);n=l.offset,o+=l.text}return{offset:n,text:o}}function Bs(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${Pn++}`,i=te(r,E,"sdtPr"),a=te(r,E,"sdtContent");e.push({kind:D.CONTAINER_START,containerKind:Et.SDT,containerId:o,propertiesXml:i?ne(i):"",startOffset:n,endOffset:n,text:""});let s=a?Pt(a,n,e):{offset:n,text:""};return e.push({kind:D.CONTAINER_END,containerKind:Et.SDT,containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("smartTag",(r,n)=>{let o=`smartTag_${Pn++}`;e.push({kind:D.CONTAINER_START,containerKind:Et.SMART_TAG,containerId:o,propertiesXml:Yo(r),startOffset:n,endOffset:n,text:""});let i=Pt(r,n,e);return e.push({kind:D.CONTAINER_END,containerKind:Et.SMART_TAG,containerId:o,startOffset:i.offset,endOffset:i.offset,text:""}),i}),t.set("del",(r,n)=>{let o=Jo(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=Jo(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>Pt(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:D.BOOKMARK,nodeXml:ne(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:D.BOOKMARK,nodeXml:ne(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:D.BOOKMARK,nodeXml:ne(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>Pt(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${Pn++}`,i=r.getAttribute("r:id")||"",a=r.getAttribute("w:anchor")||"";e.push({kind:D.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:i,anchor:a}),startOffset:n,endOffset:n,text:""});let s=Pt(r,n,e);return e.push({kind:D.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("r",(r,n)=>{let o=Fs(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function Fs(e,t){let r=ye(e,E,"rPr"),n=r?ne(r):"",o="";for(let i of An(e)){let a=i.nodeName;a.endsWith(":t")||a==="t"?o+=i.textContent||"":a.endsWith(":br")||a==="br"||a.endsWith(":cr")||a==="cr"?o+=`
9
- `:a.endsWith(":tab")||a==="tab"?o+=" ":a.endsWith(":noBreakHyphen")||a==="noBreakHyphen"?o+="\u2011":(a.endsWith(":softHyphen")||a==="softHyphen")&&(o+="\xAD")}return o?{kind:D.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function Jo(e,t){let r=e.getAttribute("w:author")||"",n="",o=ce(e,E,"delText");for(let a of o)n+=a.textContent||"";let i=ce(e,E,"r");for(let a of i){let s=ce(a,E,"delText");for(let l of s)n+=l.textContent||""}return n?{kind:D.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:ne(e)}:null}function On(e){let t=te(e,E,"tblGrid"),r=t?ce(t,E,"gridCol"):[],n=ve(e,E,"tr"),o=n.length,i=n.reduce((u,f)=>{let m=ve(f,E,"tc");return Math.max(u,m.length)},0),a=r.length||i,s=Array.from({length:o},()=>Array.from({length:a},()=>null)),l=new Map,c=new Map;for(let u=0;u<n.length;u++){let f=n[u],m=ve(f,E,"tc"),d=0;for(let p=0;p<m.length;p++){let b=m[p],h=te(b,E,"tcPr");for(;d<a&&s[u][d]!==null;)d++;if(d>=a)break;let g=h?te(h,E,"gridSpan")||ie(h,"w:gridSpan"):null,w=parseInt(g?.getAttribute("w:val")||"1",10),x=h?te(h,E,"vMerge")||ie(h,"w:vMerge"):null,y=x?.getAttribute("w:val"),N=x!==null,T;if(N&&y!=="restart"){let v=c.get(d);v?(v.cell.rowSpan++,T={gridRow:u,gridCol:d,rowSpan:0,colSpan:w,tcNode:b,blocks:[],tcPrXml:Cn(h),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:v.cell}):T=$s(u,d,w,b,h)}else{let v=Zo(b);if(T={gridRow:u,gridCol:d,rowSpan:1,colSpan:w,tcNode:b,blocks:v,tcPrXml:Cn(h),isMergeOrigin:N&&y==="restart",isMergeContinuation:!1,getText:()=>v.map(S=>S.acceptedText).join(`
10
- `)},N&&y==="restart")for(let S=0;S<w;S++)c.set(d+S,{originRow:u,cell:T});else for(let S=0;S<w;S++)c.delete(d+S)}for(let v=0;v<w;v++){let S=d+v;S<a&&(s[u][S]=T,l.set(`${u},${S}`,T))}d+=w}}return{rowCount:o,colCount:a,grid:s,cellMap:l,tblPrXml:Xs(e),tblGridXml:Ds(e),trPrList:Array.from(n).map(u=>zs(u))}}function $s(e,t,r,n,o){let i=Zo(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:i,tcPrXml:Cn(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>i.map(a=>a.acceptedText).join(`
11
- `)}}function Zo(e){return ve(e,E,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:i}=Rn(r);return{runModel:n,acceptedText:o,pPr:i}})}function Cn(e){return e?ne(e):"<w:tcPr/>"}function Xs(e){let t=te(e,E,"tblPr");return t?ne(t):"<w:tblPr/>"}function Ds(e){let t=te(e,E,"tblGrid");return t?ne(t):"<w:tblGrid/>"}function zs(e){let t=te(e,E,"trPr");return t?ne(t):"<w:trPr/>"}var ti=Lo(kn(),1);var Ws=65536,kr=262144,Mr=1,_r=55296-Mr,Us=8192,js=_r+Us,Mn=class extends Error{constructor(t=kr){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function ri(e){return e?.code==="DIFF_TOKEN_LIMIT"}function _n(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 ti.diff_match_patch;return r.Diff_Timeout=t,r}function Qo(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 Hs(e,t,r={}){let n=[],o=new Map,i=r.maxTokens??kr;if(!Number.isInteger(i)||i<1||i>kr)throw new RangeError(`maxTokens must be an integer from 1 to ${kr}.`);function a(f){let m="",d=[];for(let p of f){let b=o.get(p);if(b===void 0){if(n.length>=i)throw new Mn(i);b=n.length,n.push(p),o.set(p,b)}d.push(b),m+=String.fromCodePoint(Ws+b)}return{chars:m,tokenIds:d}}let s=Qo(e),l=Qo(t),c=a(s),u=a(l);return{chars1:c.chars,chars2:u.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:u.tokenIds}}function Vs(e){let t=e<_r?Mr+e:57344+(e-_r);return String.fromCharCode(t)}function Gs(e){if(e>=Mr&&e<55296)return e-Mr;if(e>=57344&&e<=65535)return _r+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function ei(e){let t="";for(let r of e)t+=Vs(r);return t}function Ks(e,t){return e.map(([r,n])=>{let o=[];for(let i=0;i<n.length;i++){let a=Gs(n.charCodeAt(i));if(a>=t.length)throw new RangeError(`BMP diff token ${a} has no mapping.`);o.push(t[a])}return[r,o.join("")]})}function Ys(e,t,r){let n=0,o=Math.min(e.length,t.length);for(;n<o&&e[n]===t[n];)n++;let i=0;for(;i<o-n&&e[e.length-1-i]===t[t.length-1-i];)i++;let a=u=>u.map(f=>r[f]).join(""),s=[];n&&s.push([0,a(e.slice(0,n))]);let l=e.slice(n,e.length-i),c=t.slice(n,t.length-i);return l.length&&s.push([-1,a(l)]),c.length&&s.push([1,a(c)]),i&&s.push([0,a(e.slice(e.length-i))]),s}function or(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:i,tokenIds2:a}=Hs(e,t,r);if(o.length>js)return Ys(i,a,o);let s=_n(r),l=s.diff_main(ei(i),ei(a));return n&&s.diff_cleanupSemantic(l),Ks(l,o)}function ni(e,t,r={}){return e===t?[[0,e]]:_n(r).diff_main(e,t)}function oi(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=_n().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function Lr(e,t,r={}){if(e===t)return[{type:ke.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:ke.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:ke.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=or(e,t,r),o=[],i=0;for(let[a,s]of n)a===0?(o.push({type:ke.EQUAL,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===-1?(o.push({type:ke.DELETE,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===1&&o.push({type:ke.INSERT,startOffset:i,endOffset:i,text:s});return o}var Js=/\s+xmlns:[^=]+="[^"]*"/g;function Br(e,t){let r=rl(t),n=[],o=0;for(let i of e){if(i.kind!==D.TEXT&&i.kind!==D.HYPERLINK){n.push(i);continue}for(;o<r.length&&r[o]<=i.startOffset;)o++;let a=o,s=i.startOffset,l=!1;for(;a<r.length;){let c=r[a];if(c>=i.endOffset)break;c>s&&(l=!0,n.push({...i,text:i.text.slice(s-i.startOffset,c-i.startOffset),startOffset:s,endOffset:c}),s=c),a++}if(o=a,!l){n.push(i);continue}n.push({...i,text:i.text.slice(s-i.startOffset),startOffset:s,endOffset:i.endOffset})}return n}function Fr(e,t,r){let{generateRedlines:n,author:o}=r,i=[],a=new Set,s=nl(t),l=el(e),c=tl(s.nonInsertOps),u={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let m of e){if(m.kind===D.CONTAINER_START){u.containerStack.push(m.containerId),i.push({...m});continue}if(m.kind===D.CONTAINER_END){u.containerStack.pop(),i.push({...m});continue}if(m.kind===D.PARAGRAPH_START){u.currentParagraphPPrXml=typeof m.pPrXml=="string"?m.pPrXml:"",u.currentParagraphPPrElement=m.pPrElement||null,i.push({...m}),u.lastParagraphStartIndex=i.length-1;continue}if(m.kind===D.BOOKMARK||m.kind===D.DELETION){i.push({...m});continue}let d=c(m.startOffset,m.endOffset),p=s.insertOpsByStartOffset.get(m.startOffset)||[];for(let b of p)a.has(b)||(a.add(b),qs({insertOp:b,splitModel:e,styleLookup:l,patchedModel:i,state:u,options:r,generateRedlines:n,author:o}));if(!d||d.type===ke.EQUAL){i.push({...m,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null});continue}d.type===ke.DELETE&&n&&i.push({...m,kind:D.DELETION,author:o,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null})}let f=e.length>0?Math.max(...e.map(m=>m.endOffset)):0;for(let m of s.sortedInsertOps){if(m.startOffset<f||a.has(m))continue;let d=e[e.length-1];i.push({kind:n?D.INSERTION:D.TEXT,text:m.text,rPrXml:d?.rPrXml||"",startOffset:m.startOffset,endOffset:m.startOffset+m.text.length,author:n?o:void 0})}return i}function qs(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:i,generateRedlines:a,author:s}=e,l=t.text.split(`
12
- `),c=Qs(r,t.startOffset,t.text);for(let u=0;u<l.length;u++){let f=Zs(l[u],i.numberingService,o),m=f.lineText;if(u>0){let d=ii(o);f.isListLine&&f.numId&&(d=i.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:D.PARAGRAPH_START,pPrXml:d,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),o.currentParagraphPPrXml=d,o.currentParagraphPPrElement=null,o.lastParagraphStartIndex=n.length-1}else if(f.isListLine&&f.numId&&o.lastParagraphStartIndex>=0){let d=i.numberingService.buildListPPr(f.numId,f.ilvl);n[o.lastParagraphStartIndex].pPrXml=d,n[o.lastParagraphStartIndex].pPrElement=null,o.currentParagraphPPrXml=d,o.currentParagraphPPrElement=null,k(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(m.length>0||u>0)&&n.push({kind:a?D.INSERTION:D.TEXT,text:m,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+m.length,author:a?s:void 0,containerContext:o.containerStack.length>0?o.containerStack[o.containerStack.length-1]:null})}}function Zs(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=$e(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let o=n[2].trim(),i=t.detectNumberingFormat(o),a=e.match(/^(\s*)/),s=a?a[1].length:0,l=s>=4?4:2,c=Math.floor(s/l),u=ii(r),f=He(e,{allowZeroSpaceAfterMarker:!0}),m=u.match(/w:numId w:val="(\d+)"/),d=u.match(/w:ilvl w:val="(\d+)"/),p=m?m[1]:null,b=d?parseInt(d[1],10):0,h=t.getOrCreateNumId({type:i.format},{numId:p,type:"unknown"}),g=i.format==="outline"?Math.min(8,i.depth):Math.min(8,c+b);return{lineText:f,isListLine:!0,numId:h,ilvl:g}}function ii(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=ne(e.currentParagraphPPrElement).replace(Js,""),e.currentParagraphPPrXml):""}function Qs(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 el(e){let t=e.filter(o=>o.kind===D.TEXT),r=t.map(o=>o.startOffset),n=t.map(o=>o.endOffset);return{findRunBefore(o){let i=0,a=n.length-1,s=-1;for(;i<=a;){let l=i+a>>1;n[l]<=o?(s=l,i=l+1):a=l-1}return s>=0?t[s]:null},findRunAfter(o){let i=0,a=r.length-1,s=-1;for(;i<=a;){let l=i+a>>1;r[l]>=o?(s=l,a=l-1):i=l+1}return s>=0?t[s]:null}}}function tl(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 rl(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 nl(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===ke.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,i)=>o.startOffset-i.startOffset||o.endOffset-i.endOffset),n.sort((o,i)=>o.startOffset-i.startOffset||o.endOffset-i.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var ci="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ol="http://schemas.openxmlformats.org/officeDocument/2006/relationships",il="http://schemas.microsoft.com/office/2006/xmlPackage",ai="http://schemas.openxmlformats.org/package/2006/relationships",al='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',si='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var sl=`
13
- <w:numbering xmlns:w="${ci}">
5
+ `}return r.join("").replace(/%20/g," ")};Mt.exports=P;Mt.exports.diff_match_patch=P;Mt.exports.DIFF_DELETE=J;Mt.exports.DIFF_INSERT=Q;Mt.exports.DIFF_EQUAL=W});var Or=console,yn=Object.freeze({silent:0,error:1,warn:2,info:3}),Ss=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",Tn=Ss;function Es(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(yn,t)?t:Tn}function Sn(e){return yn[Tn]>=yn[e]}function As(e,t={}){Or=e||console,t.level&&(Tn=Es(t.level))}function M(...e){Sn("info")&&(Or.log||(()=>{}))(...e)}function Be(...e){Sn("warn")&&(Or.warn||(()=>{}))(...e)}function ee(...e){Sn("error")&&(Or.error||(()=>{}))(...e)}var Jt=globalThis.DOMParser,qt=globalThis.XMLSerializer;function Is(e={}){e.DOMParser&&(Jt=e.DOMParser),e.XMLSerializer&&(qt=e.XMLSerializer)}function Ps(e={}){if(!Jt&&globalThis.DOMParser&&(Jt=globalThis.DOMParser),!Jt)throw new Error("DOMParser is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Jt(e)}function me(){if(!qt&&globalThis.XMLSerializer&&(qt=globalThis.XMLSerializer),!qt)throw new Error("XMLSerializer is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new qt}function Do(e,t="text/xml"){let r=j(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function Rs(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function j(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,i)=>{let a=String(i||"XML parser diagnostic.");o==="fatalError"?ee("[XmlAdapter] XML fatal parse error:",a):(r.push(a),Be(`[XmlAdapter] XML ${o||"warning"}:`,a))};try{let i=Ps({onError:n}).parseFromString(e,t),a=Rs(i);if(!i?.documentElement||a){let s=a?.textContent||"Could not parse XML input.";return ee("[XmlAdapter] XML parse error:",s),{doc:null,error:{code:"PARSE_ERROR",message:s},warnings:r}}return{doc:i,error:null,warnings:r}}catch(o){let i=o?.message||String(o||"Could not parse XML input.");return ee("[XmlAdapter] XML parse error:",i),{doc:null,error:{code:"PARSE_ERROR",message:i},warnings:r}}}function te(e){return me().serializeToString(e)}var zo=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",Wo=zo(),Uo="Unknown";function Cs(e){Wo=typeof e=="string"&&e.trim()?e.trim():zo()}function de(){return Wo}function Os(e){Uo=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function En(){return Uo}var ks=[{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:/&lt;b&gt;(.+?)&lt;\/b&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;strong&gt;(.+?)&lt;\/strong&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;i&gt;(.+?)&lt;\/i&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;em&gt;(.+?)&lt;\/em&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;u&gt;(.+?)&lt;\/u&gt;/i,format:{underline:!0},isEscaped:!0},{regex:/&lt;s&gt;(.+?)&lt;\/s&gt;/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 Ie(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let s of ks){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?Ms(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=[],i=0;for(let s of n)s.start>=i&&(o.push(s),i=s.end);let a=0;for(let s of o){r+=e.slice(a,s.start);let l=Ie(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});a=s.end}return r+=e.slice(a),{cleanText:r,formatHints:t}}function Ke(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function An(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function Ms(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var kr=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,jo=new RegExp(`^(\\s*)((?:${kr})\\s+)`),Ho=new RegExp(`^(\\s*)((?:${kr})\\s*)`),_s=new RegExp(`^(\\s*)((?:${kr})\\s+)`,"m"),Ls=new RegExp(`^(\\s*)((?:${kr})\\s*)`,"m");function In(e){return typeof e!="string"?!1:e.includes(`
6
+ `)&&_s.test(e)}function Zt(e){return typeof e!="string"?!1:e.includes(`
7
+ `)&&Ls.test(e.trim())}function Fe(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Ho:jo;return e.match(n)}function je(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Ho:jo;return e.replace(n,"")}function Vo(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function Qt(e){let t=String(e||"").trim();return Vo(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 Bs(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function er(e,t={}){let r=Fe(String(e||""),t);if(!r)return null;let n=r[2].trim(),o=(r[1]||"").length,i=Math.max(1,Number(t.indentSpaces)||2),a=Vo(n);return{line:String(e||""),text:je(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/i)),markerType:a,listType:a,numberingStyle:Qt(n),outlineLevel:a==="numbered"?Bs(n):null}}var E="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var ke=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),X=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"}),Pt=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),Yo=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),G=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),be=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function Ne(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var Pn=1e3,Go=2147483647,Ko=1e4,Fs=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Jo=new WeakMap;function $s(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return Fs.has(t)?!e.namespaceURI||e.namespaceURI===E||String(e.nodeName||"").startsWith("w:"):!1}function Xs(e){let t=e?.getAttributeNS?.(E,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var we=class{constructor(t=Pn){this.startValue=Number.isInteger(t)&&t>=0?t:Pn,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($s(o)){let a=Xs(o);a!=null&&(this.occupiedIds.add(a),r=Math.max(r,a))}if(o.firstChild){o=o.firstChild;continue}for(;o&&o!==n&&!o.nextSibling;)o=o.parentNode;o=o&&o!==n?o.nextSibling:null}let i=Go-Ko;return this.nextId=r>=i?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=Go-Ko;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}},tr=new we;function Mr(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof we&&Jo.set(r,t),t}function Ye(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Jo.get(t)||null}function nt(e,t=Pn){let r=new we(t);return r.seed(e),Mr(e,r),r}function qo(){return tr.next()}function _r(e=new Date){return e.toISOString()}function ie(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():de(),o=t instanceof we?t:Ye(t)||tr,i=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(i,r||"structural"),{id:i,author:n,date:_r()}}function rr(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():de(),n=t instanceof we?t:Ye(t)||tr,o=_r(),i=n.next(),a=n.next();return n._receiptCollector&&(n._receiptCollector.recordRevision(i,"del"),n._receiptCollector.recordRevision(a,"ins")),{deletionId:i,insertionId:a,author:r,date:o}}function Rt(e,t=tr){let r=t instanceof we?t:tr,n=r.seed(e);return Mr(e,r),n}function Zo(e,t){return e<t-1}function Ct(e,t,r){return Zo(t,r)?e+`
8
+ `:e}function pt(e,t,r){return Zo(t,r)?e+1:e}function nr(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function ae(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 re(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 ve(e,t,r,n=`w:${r}`){let o=ce(e,t,r);return o.length>0?o:nr(e,n)}function ye(e,t,r,n=`w:${r}`){let o=re(e,t,r);return o||ae(e,n)}function ne(e){return ae(e,"parsererror")}function Rn(e){return Array.from(e?.childNodes||[])}function Qo(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Cn(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var On=0;function kt(e,t={}){let r=[],n="",o=t.xmlDoc||null;if(!e&&!o)return{runModel:r,acceptedText:n,pPr:null};try{let i=o?{doc:o,error:null}:j(e,"application/xml"),a=i.doc;if(i.error||!a)return ee("OOXML parse error:",i.error?.message),{runModel:r,acceptedText:n,pPr:null,error:i.error};let s=ne(a);if(s)return ee("OOXML parse error:",s.textContent),{runModel:r,acceptedText:n,pPr:null};let l=ce(a,E,"p");return l.length===0?(Be("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):ti(l,{includeParagraphBoundaries:!0})}catch(i){return ee("Error ingesting OOXML:",i),{runModel:r,acceptedText:n,pPr:null}}}function kn(e){return e?ti([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function or(e){let t=re(e,E,"pPr");if(!t)return null;let r=re(t,E,"numPr");if(!r)return null;let n=re(r,E,"numId"),o=re(r,E,"ilvl");if(!n)return null;let i=n.getAttribute("w:val");if(!/^\d+$/.test(i)||Number.parseInt(i,10)===0)return null;let a=i==="1"?"bullet":i==="2"?"numbered":"unknown";return{numId:i,ilvl:parseInt(o?.getAttribute("w:val")||"0",10),type:a}}function ti(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],o="",i=0,a=null;for(let s=0;s<e.length;s++){let l=e[s],c=re(l,E,"pPr");s===0&&(a=c),n.push({kind:X.PARAGRAPH_START,pPrElement:c||null,startOffset:i,endOffset:i,text:""});let u=Ot(l,i,n);o+=u.text,i=o.length,r&&(o=Ct(o,s,e.length),i=pt(i,s,e.length))}return{runModel:n,acceptedText:o,pPr:a}}function Ot(e,t,r){let n=t,o="",i=Ds(r);for(let a of Rn(e)){if(Cn(a,E,"pPr")||Cn(a,E,"proofErr"))continue;let s=i.get(a.localName);if(!s)continue;let l=s(a,n);n=l.offset,o+=l.text}return{offset:n,text:o}}function Ds(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${On++}`,i=re(r,E,"sdtPr"),a=re(r,E,"sdtContent");e.push({kind:X.CONTAINER_START,containerKind:Pt.SDT,containerId:o,propertiesXml:i?te(i):"",startOffset:n,endOffset:n,text:""});let s=a?Ot(a,n,e):{offset:n,text:""};return e.push({kind:X.CONTAINER_END,containerKind:Pt.SDT,containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("smartTag",(r,n)=>{let o=`smartTag_${On++}`;e.push({kind:X.CONTAINER_START,containerKind:Pt.SMART_TAG,containerId:o,propertiesXml:Qo(r),startOffset:n,endOffset:n,text:""});let i=Ot(r,n,e);return e.push({kind:X.CONTAINER_END,containerKind:Pt.SMART_TAG,containerId:o,startOffset:i.offset,endOffset:i.offset,text:""}),i}),t.set("del",(r,n)=>{let o=ei(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=ei(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>Ot(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:X.BOOKMARK,nodeXml:te(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:X.BOOKMARK,nodeXml:te(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:X.BOOKMARK,nodeXml:te(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>Ot(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${On++}`,i=r.getAttribute("r:id")||"",a=r.getAttribute("w:anchor")||"";e.push({kind:X.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:i,anchor:a}),startOffset:n,endOffset:n,text:""});let s=Ot(r,n,e);return e.push({kind:X.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("r",(r,n)=>{let o=zs(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function zs(e,t){let r=ye(e,E,"rPr"),n=r?te(r):"",o="";for(let i of Rn(e)){let a=i.nodeName;a.endsWith(":t")||a==="t"?o+=i.textContent||"":a.endsWith(":br")||a==="br"||a.endsWith(":cr")||a==="cr"?o+=`
9
+ `:a.endsWith(":tab")||a==="tab"?o+=" ":a.endsWith(":noBreakHyphen")||a==="noBreakHyphen"?o+="\u2011":(a.endsWith(":softHyphen")||a==="softHyphen")&&(o+="\xAD")}return o?{kind:X.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function ei(e,t){let r=e.getAttribute("w:author")||"",n="",o=ce(e,E,"delText");for(let a of o)n+=a.textContent||"";let i=ce(e,E,"r");for(let a of i){let s=ce(a,E,"delText");for(let l of s)n+=l.textContent||""}return n?{kind:X.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:te(e)}:null}function _n(e){let t=re(e,E,"tblGrid"),r=t?ce(t,E,"gridCol"):[],n=ve(e,E,"tr"),o=n.length,i=n.reduce((u,f)=>{let m=ve(f,E,"tc");return Math.max(u,m.length)},0),a=r.length||i,s=Array.from({length:o},()=>Array.from({length:a},()=>null)),l=new Map,c=new Map;for(let u=0;u<n.length;u++){let f=n[u],m=ve(f,E,"tc"),d=0;for(let p=0;p<m.length;p++){let h=m[p],w=re(h,E,"tcPr");for(;d<a&&s[u][d]!==null;)d++;if(d>=a)break;let b=w?re(w,E,"gridSpan")||ae(w,"w:gridSpan"):null,g=parseInt(b?.getAttribute("w:val")||"1",10),x=w?re(w,E,"vMerge")||ae(w,"w:vMerge"):null,N=x?.getAttribute("w:val"),v=x!==null,T;if(v&&N!=="restart"){let y=c.get(d);y?(y.cell.rowSpan++,T={gridRow:u,gridCol:d,rowSpan:0,colSpan:g,tcNode:h,blocks:[],tcPrXml:Mn(w),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:y.cell}):T=Ws(u,d,g,h,w)}else{let y=ri(h);if(T={gridRow:u,gridCol:d,rowSpan:1,colSpan:g,tcNode:h,blocks:y,tcPrXml:Mn(w),isMergeOrigin:v&&N==="restart",isMergeContinuation:!1,getText:()=>y.map(S=>S.acceptedText).join(`
10
+ `)},v&&N==="restart")for(let S=0;S<g;S++)c.set(d+S,{originRow:u,cell:T});else for(let S=0;S<g;S++)c.delete(d+S)}for(let y=0;y<g;y++){let S=d+y;S<a&&(s[u][S]=T,l.set(`${u},${S}`,T))}d+=g}}return{rowCount:o,colCount:a,grid:s,cellMap:l,tblPrXml:Us(e),tblGridXml:js(e),trPrList:Array.from(n).map(u=>Hs(u))}}function Ws(e,t,r,n,o){let i=ri(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:i,tcPrXml:Mn(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>i.map(a=>a.acceptedText).join(`
11
+ `)}}function ri(e){return ve(e,E,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:i}=kn(r);return{runModel:n,acceptedText:o,pPr:i}})}function Mn(e){return e?te(e):"<w:tcPr/>"}function Us(e){let t=re(e,E,"tblPr");return t?te(t):"<w:tblPr/>"}function js(e){let t=re(e,E,"tblGrid");return t?te(t):"<w:tblGrid/>"}function Hs(e){let t=re(e,E,"trPr");return t?te(t):"<w:trPr/>"}var ii=Xo(Ln(),1);var Vs=65536,Lr=262144,Br=1,Fr=55296-Br,Gs=8192,Ks=Fr+Gs,Bn=class extends Error{constructor(t=Lr){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function ai(e){return e?.code==="DIFF_TOKEN_LIMIT"}function Fn(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 ii.diff_match_patch;return r.Diff_Timeout=t,r}function ni(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 Ys(e,t,r={}){let n=[],o=new Map,i=r.maxTokens??Lr;if(!Number.isInteger(i)||i<1||i>Lr)throw new RangeError(`maxTokens must be an integer from 1 to ${Lr}.`);function a(f){let m="",d=[];for(let p of f){let h=o.get(p);if(h===void 0){if(n.length>=i)throw new Bn(i);h=n.length,n.push(p),o.set(p,h)}d.push(h),m+=String.fromCodePoint(Vs+h)}return{chars:m,tokenIds:d}}let s=ni(e),l=ni(t),c=a(s),u=a(l);return{chars1:c.chars,chars2:u.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:u.tokenIds}}function Js(e){let t=e<Fr?Br+e:57344+(e-Fr);return String.fromCharCode(t)}function qs(e){if(e>=Br&&e<55296)return e-Br;if(e>=57344&&e<=65535)return Fr+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function oi(e){let t="";for(let r of e)t+=Js(r);return t}function Zs(e,t){return e.map(([r,n])=>{let o=[];for(let i=0;i<n.length;i++){let a=qs(n.charCodeAt(i));if(a>=t.length)throw new RangeError(`BMP diff token ${a} has no mapping.`);o.push(t[a])}return[r,o.join("")]})}function Qs(e,t,r){let n=0,o=Math.min(e.length,t.length);for(;n<o&&e[n]===t[n];)n++;let i=0;for(;i<o-n&&e[e.length-1-i]===t[t.length-1-i];)i++;let a=u=>u.map(f=>r[f]).join(""),s=[];n&&s.push([0,a(e.slice(0,n))]);let l=e.slice(n,e.length-i),c=t.slice(n,t.length-i);return l.length&&s.push([-1,a(l)]),c.length&&s.push([1,a(c)]),i&&s.push([0,a(e.slice(e.length-i))]),s}function ir(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:i,tokenIds2:a}=Ys(e,t,r);if(o.length>Ks)return Qs(i,a,o);let s=Fn(r),l=s.diff_main(oi(i),oi(a));return n&&s.diff_cleanupSemantic(l),Zs(l,o)}function si(e,t,r={}){return e===t?[[0,e]]:Fn(r).diff_main(e,t)}function li(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=Fn().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function $r(e,t,r={}){if(e===t)return[{type:ke.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:ke.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:ke.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=ir(e,t,r),o=[],i=0;for(let[a,s]of n)a===0?(o.push({type:ke.EQUAL,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===-1?(o.push({type:ke.DELETE,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===1&&o.push({type:ke.INSERT,startOffset:i,endOffset:i,text:s});return o}var el=/\s+xmlns:[^=]+="[^"]*"/g;function Xr(e,t){let r=al(t),n=[],o=0;for(let i of e){if(i.kind!==X.TEXT&&i.kind!==X.HYPERLINK){n.push(i);continue}for(;o<r.length&&r[o]<=i.startOffset;)o++;let a=o,s=i.startOffset,l=!1;for(;a<r.length;){let c=r[a];if(c>=i.endOffset)break;c>s&&(l=!0,n.push({...i,text:i.text.slice(s-i.startOffset,c-i.startOffset),startOffset:s,endOffset:c}),s=c),a++}if(o=a,!l){n.push(i);continue}n.push({...i,text:i.text.slice(s-i.startOffset),startOffset:s,endOffset:i.endOffset})}return n}function Dr(e,t,r){let{generateRedlines:n,author:o}=r,i=[],a=new Set,s=sl(t),l=ol(e),c=il(s.nonInsertOps),u={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let m of e){if(m.kind===X.CONTAINER_START){u.containerStack.push(m.containerId),i.push({...m});continue}if(m.kind===X.CONTAINER_END){u.containerStack.pop(),i.push({...m});continue}if(m.kind===X.PARAGRAPH_START){u.currentParagraphPPrXml=typeof m.pPrXml=="string"?m.pPrXml:"",u.currentParagraphPPrElement=m.pPrElement||null,i.push({...m}),u.lastParagraphStartIndex=i.length-1;continue}if(m.kind===X.BOOKMARK||m.kind===X.DELETION){i.push({...m});continue}let d=c(m.startOffset,m.endOffset),p=s.insertOpsByStartOffset.get(m.startOffset)||[];for(let h of p)a.has(h)||(a.add(h),tl({insertOp:h,splitModel:e,styleLookup:l,patchedModel:i,state:u,options:r,generateRedlines:n,author:o}));if(!d||d.type===ke.EQUAL){i.push({...m,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null});continue}d.type===ke.DELETE&&n&&i.push({...m,kind:X.DELETION,author:o,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null})}let f=e.length>0?Math.max(...e.map(m=>m.endOffset)):0;for(let m of s.sortedInsertOps){if(m.startOffset<f||a.has(m))continue;let d=e[e.length-1];i.push({kind:n?X.INSERTION:X.TEXT,text:m.text,rPrXml:d?.rPrXml||"",startOffset:m.startOffset,endOffset:m.startOffset+m.text.length,author:n?o:void 0})}return i}function tl(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:i,generateRedlines:a,author:s}=e,l=t.text.split(`
12
+ `),c=nl(r,t.startOffset,t.text);for(let u=0;u<l.length;u++){let f=rl(l[u],i.numberingService,o),m=f.lineText;if(u>0){let d=ci(o);f.isListLine&&f.numId&&(d=i.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:X.PARAGRAPH_START,pPrXml:d,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),o.currentParagraphPPrXml=d,o.currentParagraphPPrElement=null,o.lastParagraphStartIndex=n.length-1}else if(f.isListLine&&f.numId&&o.lastParagraphStartIndex>=0){let d=i.numberingService.buildListPPr(f.numId,f.ilvl);n[o.lastParagraphStartIndex].pPrXml=d,n[o.lastParagraphStartIndex].pPrElement=null,o.currentParagraphPPrXml=d,o.currentParagraphPPrElement=null,M(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(m.length>0||u>0)&&n.push({kind:a?X.INSERTION:X.TEXT,text:m,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+m.length,author:a?s:void 0,containerContext:o.containerStack.length>0?o.containerStack[o.containerStack.length-1]:null})}}function rl(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=Fe(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let o=n[2].trim(),i=t.detectNumberingFormat(o),a=e.match(/^(\s*)/),s=a?a[1].length:0,l=s>=4?4:2,c=Math.floor(s/l),u=ci(r),f=je(e,{allowZeroSpaceAfterMarker:!0}),m=u.match(/w:numId w:val="(\d+)"/),d=u.match(/w:ilvl w:val="(\d+)"/),p=m?m[1]:null,h=d?parseInt(d[1],10):0,w=t.getOrCreateNumId({type:i.format},{numId:p,type:"unknown"}),b=i.format==="outline"?Math.min(8,i.depth):Math.min(8,c+h);return{lineText:f,isListLine:!0,numId:w,ilvl:b}}function ci(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=te(e.currentParagraphPPrElement).replace(el,""),e.currentParagraphPPrXml):""}function nl(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 ol(e){let t=e.filter(o=>o.kind===X.TEXT),r=t.map(o=>o.startOffset),n=t.map(o=>o.endOffset);return{findRunBefore(o){let i=0,a=n.length-1,s=-1;for(;i<=a;){let l=i+a>>1;n[l]<=o?(s=l,i=l+1):a=l-1}return s>=0?t[s]:null},findRunAfter(o){let i=0,a=r.length-1,s=-1;for(;i<=a;){let l=i+a>>1;r[l]>=o?(s=l,a=l-1):i=l+1}return s>=0?t[s]:null}}}function il(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 al(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 sl(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===ke.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,i)=>o.startOffset-i.startOffset||o.endOffset-i.endOffset),n.sort((o,i)=>o.startOffset-i.startOffset||o.endOffset-i.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var di="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ll="http://schemas.openxmlformats.org/officeDocument/2006/relationships",cl="http://schemas.microsoft.com/office/2006/xmlPackage",ui="http://schemas.openxmlformats.org/package/2006/relationships",ul='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',fi='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var fl=`
13
+ <w:numbering xmlns:w="${di}">
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="&#8226;"/><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 ds=Object.create;var _o=Object.defineProperty;var ps=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 ll(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function ui(e,t=!0){let r=t?` xmlns:r="${ol}"`:"";return`<w:document xmlns:w="${ci}"${r}><w:body>${e}</w:body></w:document>`}function li(e){return`
22
+ </w:numbering>`.trim();function ml(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function pi(e,t=!0){let r=t?` xmlns:r="${ll}"`:"";return`<w:document xmlns:w="${di}"${r}><w:body>${e}</w:body></w:document>`}function mi(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
- ${ll(e)}
25
+ ${ml(e)}
26
26
  </pkg:xmlData>
27
- </pkg:part>`}function fi(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
- <pkg:package xmlns:pkg="${il}">
27
+ </pkg:part>`}function gi(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
+ <pkg:package xmlns:pkg="${cl}">
29
29
  <pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
30
30
  <pkg:xmlData>
31
- <Relationships xmlns="${ai}">
32
- ${al}
31
+ <Relationships xmlns="${ui}">
32
+ ${ul}
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="${ai}">
38
+ <Relationships xmlns="${ui}">
39
39
  ${t}
40
40
  </Relationships>
41
41
  </pkg:xmlData>
@@ -45,7 +45,7 @@ var ds=Object.create;var _o=Object.defineProperty;var ps=Object.getOwnPropertyDe
45
45
  ${e}
46
46
  </pkg:xmlData>
47
47
  </pkg:part>
48
- </pkg:package>`}function mi(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:o=!0}=t,i=o?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,a=ui(i,!0),s="",l="";return n?(s=si,l+=li(n)):r&&(s=si,l+=li(sl)),fi(a,s,l)}function di(e){let t=ui(e,!0);return fi(t)}var cl=/\s+xmlns:[^=]+="[^"]*"/g;function Xe(e,t,r=[],n={}){let o=ul(n),{generateRedlines:i}=o,a=[],s="",l=null,c=[];function u(){if(c.length>0||a.length===0){let f="";s?f=gt(s):l?(s=gt(ne(l)),f=s):t&&(typeof t=="string"?f=t:f=ne(t),f=gt(f)),a.push(`<w:p>${f}${c.join("")}</w:p>`),c=[]}}for(let f of e)switch(f.kind){case D.PARAGRAPH_START:(c.length>0||a.length>0)&&u(),s=f.pPrXml||"",l=f.pPrElement||null;break;case D.TEXT:c.push(pi(f,r,o));break;case D.DELETION:i&&c.push(fl(f,o));break;case D.INSERTION:i?c.push(ml(f,r,o)):c.push(pi(f,r,o));break;case D.BOOKMARK:case D.HYPERLINK:f.nodeXml&&c.push(gt(f.nodeXml));break;case D.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 m=JSON.parse(f.propertiesXml),d=m.rId?` r:id="${m.rId}"`:"",p=m.anchor?` w:anchor="${m.anchor}"`:"";c.push(`<w:hyperlink${d}${p}>`)}break;case D.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:Fe("Unknown run kind:",f.kind)}return u(),a.join("")}function ul(e){if(typeof e=="string")return{author:de(),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():de(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function pi(e,t,r={}){let n=Ye(t,e.startOffset,e.endOffset),o=r?.font??null,i=e.rPrXml?gt(e.rPrXml):"";if(o&&(i=Ln(i,o)),n.length===0)return it(e.text,i);let a=[],s=0,l=e.text,c=e.startOffset;for(let u of n){let f=Math.max(0,u.start-c),m=Math.min(l.length,u.end-c);f>s&&a.push(it(l.slice(s,f),i));let d=gi(i,u.format);a.push(it(l.slice(f,m),d)),s=m}return s<l.length&&a.push(it(l.slice(s),i)),a.join("")}function it(e,t){return e?`<w:r>${t||""}<w:t xml:space="preserve">${Ne(e)}</w:t></w:r>`:""}function fl(e,t={}){let r=oe(t.author??de(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?gt(e.rPrXml):"";return n&&(o=Ln(o,n)),`<w:del w:id="${r.id}" w:author="${Ne(r.author)}" w:date="${r.date}"><w:r>${o}<w:delText xml:space="preserve">${Ne(e.text)}</w:delText></w:r></w:del>`}function ml(e,t,r={}){let n=oe(r.author??de(),r.revisionIdAllocator,"ins"),o=r.font??null,i=Ye(t,e.startOffset,e.endOffset),a="",s=e.rPrXml?gt(e.rPrXml):"";if(o&&(s=Ln(s,o)),i.length===0)a=it(e.text,s);else{let l=0,c=e.text,u=e.startOffset;for(let f of i){let m=Math.max(0,f.start-u),d=Math.min(c.length,f.end-u);m>l&&(a+=it(c.slice(l,m),s));let p=gi(s,f.format);a+=it(c.slice(m,d),p),l=d}l<c.length&&(a+=it(c.slice(l),s))}return`<w:ins w:id="${n.id}" w:author="${Ne(n.author)}" w:date="${n.date}">`+a+"</w:ins>"}function Ln(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 gi(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 at(e,t={}){let r=dl(t);return mi(e,r)}function dl(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function gt(e){return e?e.replace(cl,""):""}function Bn(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var qe=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){Bn(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||G.BULLET;if(r&&Bn(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let i=this.contextMap.get(n);if(Bn(i))return i;this.contextMap.delete(n)}if(n===G.OUTLINE)return"3";if(n===G.DECIMAL)return"2";if(n===G.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==G.DECIMAL&&n!==G.BULLET){let i=`custom_${n}`;if(this.contextMap.has(i))return this.contextMap.get(i);let a=String(this.nextNumId++);return this.customConfigs.push({numId:a,levels:[{format:n,suffix:t.suffix||we.PERIOD}]}),this.contextMap.set(i,a),a}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:G.BULLET,suffix:we.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:G.BULLET,suffix:we.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:G.OUTLINE,suffix:we.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:G.LOWER_ALPHA,suffix:we.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:we.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:G.DECIMAL,suffix:we.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:G.DECIMAL,suffix:we.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:G.LOWER_ALPHA,suffix:we.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:G.UPPER_ALPHA,suffix:we.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:we.PERIOD,depth:0}:/^\d+/.test(r)?{format:G.DECIMAL,suffix:we.PERIOD,depth:0}:{format:G.BULLET,suffix:we.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[G.DECIMAL]:"decimal",[G.LOWER_ALPHA]:"lowerLetter",[G.UPPER_ALPHA]:"upperLetter",[G.LOWER_ROMAN]:"lowerRoman",[G.UPPER_ROMAN]:"upperRoman",[G.BULLET]:"bullet",[G.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===G.BULLET)return"\u2022";let o=`%${n+1}`;if(t===G.OUTLINE)return Array(n+1).fill(0).map((i,a)=>`%${a+1}`).join(".")+".";switch(r){case we.PERIOD:return`${o}.`;case we.PAREN_RIGHT:return`${o})`;case we.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
48
+ </pkg:package>`}function hi(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:o=!0}=t,i=o?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,a=pi(i,!0),s="",l="";return n?(s=fi,l+=mi(n)):r&&(s=fi,l+=mi(fl)),gi(a,s,l)}function wi(e){let t=pi(e,!0);return gi(t)}var dl=/\s+xmlns:[^=]+="[^"]*"/g;function $e(e,t,r=[],n={}){let o=pl(n),{generateRedlines:i}=o,a=[],s="",l=null,c=[];function u(){if(c.length>0||a.length===0){let f="";s?f=gt(s):l?(s=gt(te(l)),f=s):t&&(typeof t=="string"?f=t:f=te(t),f=gt(f)),a.push(`<w:p>${f}${c.join("")}</w:p>`),c=[]}}for(let f of e)switch(f.kind){case X.PARAGRAPH_START:(c.length>0||a.length>0)&&u(),s=f.pPrXml||"",l=f.pPrElement||null;break;case X.TEXT:c.push(bi(f,r,o));break;case X.DELETION:i&&c.push(gl(f,o));break;case X.INSERTION:i?c.push(hl(f,r,o)):c.push(bi(f,r,o));break;case X.BOOKMARK:case X.HYPERLINK:f.nodeXml&&c.push(gt(f.nodeXml));break;case X.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 m=JSON.parse(f.propertiesXml),d=m.rId?` r:id="${m.rId}"`:"",p=m.anchor?` w:anchor="${m.anchor}"`:"";c.push(`<w:hyperlink${d}${p}>`)}break;case X.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:Be("Unknown run kind:",f.kind)}return u(),a.join("")}function pl(e){if(typeof e=="string")return{author:de(),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():de(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function bi(e,t,r={}){let n=Ke(t,e.startOffset,e.endOffset),o=r?.font??null,i=e.rPrXml?gt(e.rPrXml):"";if(o&&(i=$n(i,o)),n.length===0)return ot(e.text,i);let a=[],s=0,l=e.text,c=e.startOffset;for(let u of n){let f=Math.max(0,u.start-c),m=Math.min(l.length,u.end-c);f>s&&a.push(ot(l.slice(s,f),i));let d=xi(i,u.format);a.push(ot(l.slice(f,m),d)),s=m}return s<l.length&&a.push(ot(l.slice(s),i)),a.join("")}function ot(e,t){return e?`<w:r>${t||""}<w:t xml:space="preserve">${Ne(e)}</w:t></w:r>`:""}function gl(e,t={}){let r=ie(t.author??de(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?gt(e.rPrXml):"";return n&&(o=$n(o,n)),`<w:del w:id="${r.id}" w:author="${Ne(r.author)}" w:date="${r.date}"><w:r>${o}<w:delText xml:space="preserve">${Ne(e.text)}</w:delText></w:r></w:del>`}function hl(e,t,r={}){let n=ie(r.author??de(),r.revisionIdAllocator,"ins"),o=r.font??null,i=Ke(t,e.startOffset,e.endOffset),a="",s=e.rPrXml?gt(e.rPrXml):"";if(o&&(s=$n(s,o)),i.length===0)a=ot(e.text,s);else{let l=0,c=e.text,u=e.startOffset;for(let f of i){let m=Math.max(0,f.start-u),d=Math.min(c.length,f.end-u);m>l&&(a+=ot(c.slice(l,m),s));let p=xi(s,f.format);a+=ot(c.slice(m,d),p),l=d}l<c.length&&(a+=ot(c.slice(l),s))}return`<w:ins w:id="${n.id}" w:author="${Ne(n.author)}" w:date="${n.date}">`+a+"</w:ins>"}function $n(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 xi(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 it(e,t={}){let r=wl(t);return hi(e,r)}function wl(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function gt(e){return e?e.replace(dl,""):""}function Xn(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var Je=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){Xn(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||G.BULLET;if(r&&Xn(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let i=this.contextMap.get(n);if(Xn(i))return i;this.contextMap.delete(n)}if(n===G.OUTLINE)return"3";if(n===G.DECIMAL)return"2";if(n===G.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==G.DECIMAL&&n!==G.BULLET){let i=`custom_${n}`;if(this.contextMap.has(i))return this.contextMap.get(i);let a=String(this.nextNumId++);return this.customConfigs.push({numId:a,levels:[{format:n,suffix:t.suffix||be.PERIOD}]}),this.contextMap.set(i,a),a}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:G.BULLET,suffix:be.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:G.BULLET,suffix:be.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:G.OUTLINE,suffix:be.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:G.LOWER_ALPHA,suffix:be.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:be.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:G.DECIMAL,suffix:be.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:G.DECIMAL,suffix:be.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:G.LOWER_ALPHA,suffix:be.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:G.UPPER_ALPHA,suffix:be.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:be.PERIOD,depth:0}:/^\d+/.test(r)?{format:G.DECIMAL,suffix:be.PERIOD,depth:0}:{format:G.BULLET,suffix:be.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[G.DECIMAL]:"decimal",[G.LOWER_ALPHA]:"lowerLetter",[G.UPPER_ALPHA]:"upperLetter",[G.LOWER_ROMAN]:"lowerRoman",[G.UPPER_ROMAN]:"upperRoman",[G.BULLET]:"bullet",[G.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===G.BULLET)return"\u2022";let o=`%${n+1}`;if(t===G.OUTLINE)return Array(n+1).fill(0).map((i,a)=>`%${a+1}`).join(".")+".";switch(r){case be.PERIOD:return`${o}.`;case be.PAREN_RIGHT:return`${o})`;case be.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>
@@ -110,7 +110,7 @@ var ds=Object.create;var _o=Object.defineProperty;var ps=Object.getOwnPropertyDe
110
110
  <w:abstractNumId w:val="2"/>
111
111
  </w:num>
112
112
  ${s}
113
- </w:numbering>`}};function ht(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:o=null,trackAsBlock:i=!1}=t,a=r&&i?oe(n,o):null,s=e.headers?.length||e.rows?.[0]?.length||1,l=`
113
+ </w:numbering>`}};function ht(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:o=null,trackAsBlock:i=!1}=t,a=r&&i?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,55 @@ var ds=Object.create;var _o=Object.defineProperty;var ps=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,m="";for(let p=0;p<f.length;p++){let b=e.hasHeader&&p===0,h=f[p]||[],g="";for(let x=0;x<s;x++){let y=h[x]||"",{cleanText:N,formatHints:T}=Ie(y),v=[{kind:r&&!i?D.INSERTION:D.TEXT,text:N,rPrXml:b?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:N.length}],S=Xe(v,null,T,{author:n,generateRedlines:r,revisionIdAllocator:o});g+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${S}</w:tc>`}m+=`<w:tr>${b?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>"}${g}</w:tr>`}let d=`<w:tbl>${l}${u}${m}</w:tbl>`;return a&&(d=`<w:ins w:id="${a.id}" w:author="${Ne(a.author)}" w:date="${a.date}">${d}</w:ins>`),d}function hi(e,t){let r=[],{headers:n,rows:o,hasHeader:i}=t,a=i?[n,...o]:o,s=Math.max(e.rowCount,a.length);for(let l=0;l<s;l++){if(l>=e.rowCount&&a[l]){r.push({type:"row_insert",gridRow:l,cells:a[l]});continue}if(l<e.rowCount&&!a[l]){r.push({type:"row_delete",gridRow:l});continue}let c=a[l];for(let u=0;u<e.colCount;u++){let f=e.grid[l]?.[u],m=c?.[u];f&&(f.isMergeContinuation||u>f.gridCol||m!==void 0&&f.getText()!==m&&r.push({type:"cell_modify",gridRow:l,gridCol:u,originalCell:f,newText:m}))}}return r}function wi(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,a=pl(t),s="";for(let c=0;c<e.rowCount;c++){let u=a.rowDeleteByRow.get(c)||null;if(u&&!n)continue;let f="",m=0;for(;m<e.colCount;){let p=e.grid[c][m];if(!p){m++;continue}if(p.isMergeContinuation){m++;continue}let b=a.cellModifyByCoordinate.get(`${c}:${m}`)||null,h;b?h=gl(p,b.newText,r):h=hl(p.blocks),f+=wl(p,h,r),m+=p.colSpan}let d=e.trPrList[c]||"<w:trPr/>";if(u&&n){let p=oe(o,i),b=`<w:del w:id="${p.id}" w:author="${Ne(p.author)}" w:date="${p.date}"/>`;d.includes("</w:trPr>")?d=d.replace("</w:trPr>",`${b}</w:trPr>`):d=`<w:trPr>${b}</w:trPr>`}s+=`<w:tr>${d}${f}</w:tr>`}let l=a.rowInsertOperations;for(let c of l){let u="",f=n?oe(o,i):null;for(let d of c.cells){let{cleanText:p,formatHints:b}=Ie(d),h=[{kind:n?D.INSERTION:D.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],g=Xe(h,null,b,{author:o,generateRedlines:n,revisionIdAllocator:i});u+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${g}</w:tc>`}let m="<w:trPr/>";n&&(m=`<w:trPr><w:ins w:id="${f.id}" w:author="${Ne(f.author)}" w:date="${f.date}"/></w:trPr>`),s+=`<w:tr>${m}${u}</w:tr>`}return`
126
+ `.trim(),u=`<w:tblGrid>${Array(s).fill("<w:gridCol/>").join("")}</w:tblGrid>`,f=e.hasHeader?[e.headers,...e.rows]:e.rows,m="";for(let p=0;p<f.length;p++){let h=e.hasHeader&&p===0,w=f[p]||[],b="";for(let x=0;x<s;x++){let N=w[x]||"",{cleanText:v,formatHints:T}=Ie(N),y=[{kind:r&&!i?X.INSERTION:X.TEXT,text:v,rPrXml:h?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:v.length}],S=$e(y,null,T,{author:n,generateRedlines:r,revisionIdAllocator:o});b+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${S}</w:tc>`}m+=`<w:tr>${h?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>"}${b}</w:tr>`}let d=`<w:tbl>${l}${u}${m}</w:tbl>`;return a&&(d=`<w:ins w:id="${a.id}" w:author="${Ne(a.author)}" w:date="${a.date}">${d}</w:ins>`),d}function Ni(e,t){let r=[],{headers:n,rows:o,hasHeader:i}=t,a=i?[n,...o]:o,s=Math.max(e.rowCount,a.length);for(let l=0;l<s;l++){if(l>=e.rowCount&&a[l]){r.push({type:"row_insert",gridRow:l,cells:a[l]});continue}if(l<e.rowCount&&!a[l]){r.push({type:"row_delete",gridRow:l});continue}let c=a[l];for(let u=0;u<e.colCount;u++){let f=e.grid[l]?.[u],m=c?.[u];f&&(f.isMergeContinuation||u>f.gridCol||m!==void 0&&f.getText()!==m&&r.push({type:"cell_modify",gridRow:l,gridCol:u,originalCell:f,newText:m}))}}return r}function vi(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,a=bl(t),s="";for(let c=0;c<e.rowCount;c++){let u=a.rowDeleteByRow.get(c)||null;if(u&&!n)continue;let f="",m=0;for(;m<e.colCount;){let p=e.grid[c][m];if(!p){m++;continue}if(p.isMergeContinuation){m++;continue}let h=a.cellModifyByCoordinate.get(`${c}:${m}`)||null,w;h?w=xl(p,h.newText,r):w=Nl(p.blocks),f+=vl(p,w,r),m+=p.colSpan}let d=e.trPrList[c]||"<w:trPr/>";if(u&&n){let p=ie(o,i),h=`<w:del w:id="${p.id}" w:author="${Ne(p.author)}" w:date="${p.date}"/>`;d.includes("</w:trPr>")?d=d.replace("</w:trPr>",`${h}</w:trPr>`):d=`<w:trPr>${h}</w:trPr>`}s+=`<w:tr>${d}${f}</w:tr>`}let l=a.rowInsertOperations;for(let c of l){let u="",f=n?ie(o,i):null;for(let d of c.cells){let{cleanText:p,formatHints:h}=Ie(d),w=[{kind:n?X.INSERTION:X.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],b=$e(w,null,h,{author:o,generateRedlines:n,revisionIdAllocator:i});u+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${b}</w:tc>`}let m="<w:trPr/>";n&&(m=`<w:trPr><w:ins w:id="${f.id}" w:author="${Ne(f.author)}" w:date="${f.date}"/></w:trPr>`),s+=`<w:tr>${m}${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 pl(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,i)=>o.gridRow-i.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function gl(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,{cleanText:a,formatHints:s}=Ie(t),l=e.getText(),c=Lr(l,a),u=e.blocks[0]||{runModel:[],pPr:null},f=Br(u.runModel,c),m=Fr(f,c,{generateRedlines:n,author:o,formatHints:s});return Xe(m,u.pPr,s,{author:o,generateRedlines:n,revisionIdAllocator:i})}function hl(e){return e.map(t=>Xe(t.runModel,t.pPr,[],{})).join("")}function wl(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 De(e){let t=e.split(`
133
- `).map(a=>a.trim()).filter(a=>a.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=a=>{let s=a.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(s)},n=t.some(r),i=t.filter(a=>!r(a)).map(a=>a.split("|").slice(1,-1).map(s=>s.trim()));return n?{headers:i[0]||[],rows:i.slice(1),hasHeader:!0}:{headers:[],rows:i,hasHeader:!1}}function A(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===E&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function O(e,t){return typeof e.createElementNS=="function"?e.createElementNS(E,t):e.createElement(t)}function bi(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(E,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>A(n,t))}var xi=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function $r(e){return xi.some(t=>bi(e,t).length>0)}function Fn(e){if(!e)return[];let t=new Set;for(let r of xi)for(let n of bi(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(E,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function bl(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 ae(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:bl(e.oxml)}}async function Ot(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:i=!0,author:a="AI",font:s=null,revisionIdAllocator:l=null,numberingService:c}=e,u=Nl(t),f=xl(u),m=f.map(v=>v.raw),d=[],p=Tl(n),b=Ni(n,p),h=Ni(n,p,["rFonts","kern","position","rtl","cs","lang"]),g=[];if(i){if(n&&n.length>0)g=n.filter(v=>v.kind==="text"||v.kind==="run").map(v=>({...v,kind:"deletion",author:a}));else if(o&&o.trim().length>0){let v=o.trim();g=[{kind:"deletion",text:v,author:a,startOffset:0,endOffset:v.length}]}}if(i&&g.length>0){let v=vi(p,"del",a,l),S=Xe(g,v,[],{author:a,generateRedlines:i,revisionIdAllocator:l});d.push(S)}let w=$n(m);k(`[ListGen] Detected indentation step: ${w} spaces/chars`);let x=f.find(v=>v.marker)?.marker||"",{format:y}=c.detectNumberingFormat(x);k(`[ListGen] Detected primary marker: "${x}", format: ${y}`);for(let v=0;v<f.length;v++){let S=vl(f,v);if(S){let L=De(S.tableText);if(L.headers.length>0||L.rows.length>0){d.push(ht(L,{generateRedlines:i,author:a,revisionIdAllocator:l,trackAsBlock:!0})),v=S.endIndex;continue}}let I=f[v],_=yl(I,w,r,c,i,a,s,l,b,h);d.push(_.ooxml)}let N=c.generateNumberingXml(),T=d.join("");return k(`[ListGen] \u2705 Generated OOXML for ${d.length} paragraphs, total length: ${T.length}`),k(`[ListGen] First 200 chars: ${T.substring(0,200)}...`),{ooxml:T,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:N}}function $n(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 xl(e){return e.split(`
134
- `).filter(t=>t.trim().length>0).map(t=>{let r=$e(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 Nl(e){let t=String(e||"").split(`
135
- `),r=t.map((a,s)=>({line:a,index:s})).filter(a=>a.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:a,index:s}of r){let l=$e(a);if(!l)return e;let c=He(a),u=$e(c);if(!u)return e;let f=(l[2]||"").trim(),m=(u[2]||"").trim();if(!f||!m||f===m)return e;let p=`${l[1]||""}${c.trimStart()}`;n.push({index:s,rewritten:p}),o++}if(o<2)return e;let i=t.slice();for(let a of n)i[a.index]=a.rewritten;return k(`[ListGen] Normalized ${o} composite list markers (e.g., "- A." -> "A.").`),i.join(`
136
- `)}function vl(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let o=[],i=t;for(;i<e.length&&e[i].isTableLine;)o.push(e[i].raw),i++;return{tableText:o.join(`
137
- `),endIndex:i-1}}function yl(e,t,r,n,o,i,a,s,l,c){let u="",f="",m=l;if(e.headerMatch){let h=Math.min(e.headerMatch[1].length,9),g=Math.min(h-1,8),w=[32,28,26,24,22,20,20,20,20],x=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="${g}"/><w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr></w:pPr>`,m=Sl(c,`<w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr>`)}else if(e.marker){let h=n.detectNumberingFormat(e.marker),g=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,x=h.format==="outline"?Math.min(8,h.depth):Math.min(8,g+w);f=He(e.raw);let y=n.getOrCreateNumId({type:h.format},r);u=n.buildListPPr(y,x)}else f=e.raw;o&&(u=vi(u||"<w:pPr/>","ins",i,s));let{cleanText:d,formatHints:p}=Ie(f),b=[];return b.push({kind:o?"insertion":"run",text:d,rPrXml:m,author:i,startOffset:0,endOffset:d.length}),{ooxml:Xe(b,u,p,{author:i,generateRedlines:o,font:a,revisionIdAllocator:s})}}function Tl(e){let t=(e||[]).find(r=>r.kind===D.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function Ni(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(i=>(i.kind===D.TEXT||i.kind==="text")&&i.rPrXml).map(i=>i.rPrXml);t&&n.push(typeof t=="string"?t:ne(t));let o=[];for(let i of r){let a=null;for(let s of n)if(a=String(s||"").match(new RegExp(`<w:${i}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${i}>)`)),a)break;a&&o.push(a[0])}return o.length>0?`<w:rPr>${o.join("")}</w:rPr>`:""}function Sl(...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 vi(e,t,r,n){let o=oe(r,n),i,a;if(e?.nodeType===1)i=e.cloneNode(!0),a=i.ownerDocument;else{let c=typeof e=="string"&&e.trim()?e:"<w:pPr/>",u=j(`<w:root xmlns:w="${E}">${c}</w:root>`);if(!u.doc)throw new Error(u.error?.message||"Could not parse paragraph properties for list revision");a=u.doc,i=Array.from(a.documentElement.childNodes||[]).find(f=>f.nodeType===1&&f.localName==="pPr")}if(!i||!a)throw new Error("List paragraph properties are unavailable");let s=Array.from(i.childNodes||[]).find(c=>c.nodeType===1&&c.localName==="rPr");s||(s=O(a,"w:rPr"),i.appendChild(s));let l=O(a,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),ne(i)}var El=new Set(["officeonline","officeweb","web"]);function Al(e){return e?El.has(String(e).toLowerCase()):!1}function Il(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function Pl(){return new Promise(e=>setTimeout(e,0))}var ir=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 qe,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??yn(),this.isWebPlatform=t.isWebPlatform??Al(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 i=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:j(t,"application/xml");if(i.error||!i.doc)return{ooxml:t,isValid:!1,status:"error",error:i.error,warnings:i.warnings||[]};o.push(...i.warnings||[]);let a=i.doc,s=te(a,"*","p"),{runModel:l,acceptedText:c,pPr:u}=Rt(t,{xmlDoc:a}),f=s?nr(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:m,formatHints:d}=Ie(r);k(`[Reconcile] Preprocessed: ${d.length} format hints`),await this.maybeYield(l.length,Math.max(c.length,m.length));let p=Sn(m),b=qt(m),h=p||b;if(!p&&b&&k("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===m&&d.length===0&&!h)return k("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let g=Math.max(c.length,m.length)<this.disableSemanticCleanupOverChars,w=Lr(c,m,{cleanupSemantic:g});g||k("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(l.length,Math.max(c.length,m.length));let x=l.filter(I=>I.kind===D.PARAGRAPH_START).length,y=Sn(c)||qt(c),N=h&&y&&x>1&&c!==m;if(k(`[Reconcile] isTargetList: ${h}, paragraphCount: ${x}`),N)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: ${m.substring(0,100)}...`),k(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(m,f,l);k(`[Reconcile] Computed ${w.length} diff operations`);let T=Br(l,w);k(`[Reconcile] Split into ${T.length} runs`);let v=Fr(T,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:d,numberingService:this.numberingService});k(`[Reconcile] Patched model has ${v.length} runs`),await this.maybeYield(v.length,Math.max(c.length,m.length));let S=Xe(v,u,d,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let I=this.validateBasic(S);I.isValid||o.push(...I.errors)}return{ooxml:S,isValid:o.length===0,warnings:o}}catch(i){return ee("[Reconcile] Pipeline error:",i),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${i.message}`],error:i?.code?{code:i.code,message:i.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=j(n,"application/xml"),i=o.doc;if(o.error||!i)return r.push("Generated OOXML is not well-formed XML: "+(o.error?.message||"parse error")),{isValid:!1,errors:r};let a=re(i);a&&r.push("Generated OOXML is not well-formed XML: "+a.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&&Il()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await Pl())}wrapForInsertion(t,r={}){return at(t,r)}async executeListGeneration(t,r,n,o=""){return Ot({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 $n(t)}executeTableGeneration(t){let r=De(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:ht(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var yi=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function Ti(e){return!e||e.trim().length===0}function Si(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function Rl(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function Xn(e){return Ti(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":Si(e)?"table":$e(e)?"list":"paragraph"}function Xr(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
132
+ `}function bl(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,i)=>o.gridRow-i.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function xl(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,{cleanText:a,formatHints:s}=Ie(t),l=e.getText(),c=$r(l,a),u=e.blocks[0]||{runModel:[],pPr:null},f=Xr(u.runModel,c),m=Dr(f,c,{generateRedlines:n,author:o,formatHints:s});return $e(m,u.pPr,s,{author:o,generateRedlines:n,revisionIdAllocator:i})}function Nl(e){return e.map(t=>$e(t.runModel,t.pPr,[],{})).join("")}function vl(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 Xe(e){let t=e.split(`
133
+ `).map(a=>a.trim()).filter(a=>a.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=a=>{let s=a.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(s)},n=t.some(r),i=t.filter(a=>!r(a)).map(a=>a.split("|").slice(1,-1).map(s=>s.trim()));return n?{headers:i[0]||[],rows:i.slice(1),hasHeader:!0}:{headers:[],rows:i,hasHeader:!1}}function A(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===E&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function C(e,t){return typeof e.createElementNS=="function"?e.createElementNS(E,t):e.createElement(t)}function yi(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(E,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>A(n,t))}var Ti=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function zr(e){return Ti.some(t=>yi(e,t).length>0)}function Dn(e){if(!e)return[];let t=new Set;for(let r of Ti)for(let n of yi(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(E,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function yl(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 se(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:yl(e.oxml)}}async function _t(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:i=!0,author:a="AI",font:s=null,revisionIdAllocator:l=null,numberingService:c}=e,u=Sl(t),f=Tl(u),m=f.map(y=>y.raw),d=[],p=Il(n),h=Si(n,p),w=Si(n,p,["rFonts","kern","position","rtl","cs","lang"]),b=[];if(i){if(n&&n.length>0)b=n.filter(y=>y.kind==="text"||y.kind==="run").map(y=>({...y,kind:"deletion",author:a}));else if(o&&o.trim().length>0){let y=o.trim();b=[{kind:"deletion",text:y,author:a,startOffset:0,endOffset:y.length}]}}if(i&&b.length>0){let y=Ei(p,"del",a,l),S=$e(b,y,[],{author:a,generateRedlines:i,revisionIdAllocator:l});d.push(S)}let g=zn(m);M(`[ListGen] Detected indentation step: ${g} spaces/chars`);let x=f.find(y=>y.marker)?.marker||"",{format:N}=c.detectNumberingFormat(x);M(`[ListGen] Detected primary marker: "${x}", format: ${N}`);for(let y=0;y<f.length;y++){let S=El(f,y);if(S){let _=Xe(S.tableText);if(_.headers.length>0||_.rows.length>0){d.push(ht(_,{generateRedlines:i,author:a,revisionIdAllocator:l,trackAsBlock:!0})),y=S.endIndex;continue}}let I=f[y],L=Al(I,g,r,c,i,a,s,l,h,w);d.push(L.ooxml)}let v=c.generateNumberingXml(),T=d.join("");return M(`[ListGen] \u2705 Generated OOXML for ${d.length} paragraphs, total length: ${T.length}`),M(`[ListGen] First 200 chars: ${T.substring(0,200)}...`),{ooxml:T,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:v}}function zn(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 Tl(e){return e.split(`
134
+ `).filter(t=>t.trim().length>0).map(t=>{let r=Fe(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 Sl(e){let t=String(e||"").split(`
135
+ `),r=t.map((a,s)=>({line:a,index:s})).filter(a=>a.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:a,index:s}of r){let l=Fe(a);if(!l)return e;let c=je(a),u=Fe(c);if(!u)return e;let f=(l[2]||"").trim(),m=(u[2]||"").trim();if(!f||!m||f===m)return e;let p=`${l[1]||""}${c.trimStart()}`;n.push({index:s,rewritten:p}),o++}if(o<2)return e;let i=t.slice();for(let a of n)i[a.index]=a.rewritten;return M(`[ListGen] Normalized ${o} composite list markers (e.g., "- A." -> "A.").`),i.join(`
136
+ `)}function El(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let o=[],i=t;for(;i<e.length&&e[i].isTableLine;)o.push(e[i].raw),i++;return{tableText:o.join(`
137
+ `),endIndex:i-1}}function Al(e,t,r,n,o,i,a,s,l,c){let u="",f="",m=l;if(e.headerMatch){let w=Math.min(e.headerMatch[1].length,9),b=Math.min(w-1,8),g=[32,28,26,24,22,20,20,20,20],x=g[w-1]||g[g.length-1];f=e.headerMatch[2].trim(),u=`<w:pPr><w:pStyle w:val="Heading${w}"/><w:outlineLvl w:val="${b}"/><w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr></w:pPr>`,m=Pl(c,`<w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr>`)}else if(e.marker){let w=n.detectNumberingFormat(e.marker),b=t>0?Math.floor(e.indentSize/t):0,g=r?.ilvl||0,x=w.format==="outline"?Math.min(8,w.depth):Math.min(8,b+g);f=je(e.raw);let N=n.getOrCreateNumId({type:w.format},r);u=n.buildListPPr(N,x)}else f=e.raw;o&&(u=Ei(u||"<w:pPr/>","ins",i,s));let{cleanText:d,formatHints:p}=Ie(f),h=[];return h.push({kind:o?"insertion":"run",text:d,rPrXml:m,author:i,startOffset:0,endOffset:d.length}),{ooxml:$e(h,u,p,{author:i,generateRedlines:o,font:a,revisionIdAllocator:s})}}function Il(e){let t=(e||[]).find(r=>r.kind===X.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function Si(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(i=>(i.kind===X.TEXT||i.kind==="text")&&i.rPrXml).map(i=>i.rPrXml);t&&n.push(typeof t=="string"?t:te(t));let o=[];for(let i of r){let a=null;for(let s of n)if(a=String(s||"").match(new RegExp(`<w:${i}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${i}>)`)),a)break;a&&o.push(a[0])}return o.length>0?`<w:rPr>${o.join("")}</w:rPr>`:""}function Pl(...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 Ei(e,t,r,n){let o=ie(r,n),i,a;if(e?.nodeType===1)i=e.cloneNode(!0),a=i.ownerDocument;else{let c=typeof e=="string"&&e.trim()?e:"<w:pPr/>",u=j(`<w:root xmlns:w="${E}">${c}</w:root>`);if(!u.doc)throw new Error(u.error?.message||"Could not parse paragraph properties for list revision");a=u.doc,i=Array.from(a.documentElement.childNodes||[]).find(f=>f.nodeType===1&&f.localName==="pPr")}if(!i||!a)throw new Error("List paragraph properties are unavailable");let s=Array.from(i.childNodes||[]).find(c=>c.nodeType===1&&c.localName==="rPr");s||(s=C(a,"w:rPr"),i.appendChild(s));let l=C(a,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),te(i)}var Rl=new Set(["officeonline","officeweb","web"]);function Cl(e){return e?Rl.has(String(e).toLowerCase()):!1}function Ol(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function kl(){return new Promise(e=>setTimeout(e,0))}var ar=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 Je,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??En(),this.isWebPlatform=t.isWebPlatform??Cl(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 i=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:j(t,"application/xml");if(i.error||!i.doc)return{ooxml:t,isValid:!1,status:"error",error:i.error,warnings:i.warnings||[]};o.push(...i.warnings||[]);let a=i.doc,s=re(a,"*","p"),{runModel:l,acceptedText:c,pPr:u}=kt(t,{xmlDoc:a}),f=s?or(s):null;M(`[Reconcile] Ingested ${l.length} runs, ${c.length} chars, numbering:`,f),await this.maybeYield(l.length,Math.max(c.length,r?.length||0));let{cleanText:m,formatHints:d}=Ie(r);M(`[Reconcile] Preprocessed: ${d.length} format hints`),await this.maybeYield(l.length,Math.max(c.length,m.length));let p=In(m),h=Zt(m),w=p||h;if(!p&&h&&M("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===m&&d.length===0&&!w)return M("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let b=Math.max(c.length,m.length)<this.disableSemanticCleanupOverChars,g=$r(c,m,{cleanupSemantic:b});b||M("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(l.length,Math.max(c.length,m.length));let x=l.filter(I=>I.kind===X.PARAGRAPH_START).length,N=In(c)||Zt(c),v=w&&N&&x>1&&c!==m;if(M(`[Reconcile] isTargetList: ${w}, paragraphCount: ${x}`),v)M("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(w)return M("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),M(`[Reconcile] cleanText preview: ${m.substring(0,100)}...`),M(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(m,f,l);M(`[Reconcile] Computed ${g.length} diff operations`);let T=Xr(l,g);M(`[Reconcile] Split into ${T.length} runs`);let y=Dr(T,g,{generateRedlines:this.generateRedlines,author:this.author,formatHints:d,numberingService:this.numberingService});M(`[Reconcile] Patched model has ${y.length} runs`),await this.maybeYield(y.length,Math.max(c.length,m.length));let S=$e(y,u,d,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let I=this.validateBasic(S);I.isValid||o.push(...I.errors)}return{ooxml:S,isValid:o.length===0,warnings:o}}catch(i){return ee("[Reconcile] Pipeline error:",i),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${i.message}`],error:i?.code?{code:i.code,message:i.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=j(n,"application/xml"),i=o.doc;if(o.error||!i)return r.push("Generated OOXML is not well-formed XML: "+(o.error?.message||"parse error")),{isValid:!1,errors:r};let a=ne(i);a&&r.push("Generated OOXML is not well-formed XML: "+a.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&&Ol()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await kl())}wrapForInsertion(t,r={}){return it(t,r)}async executeListGeneration(t,r,n,o=""){return _t({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 zn(t)}executeTableGeneration(t){let r=Xe(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:ht(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var Ai=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function Ii(e){return!e||e.trim().length===0}function Pi(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function Ml(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function Wn(e){return Ii(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":Pi(e)?"table":Fe(e)?"list":"paragraph"}function Wr(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
138
138
  `):String(e??"")).split(`
139
- `),n=[],o=[],i=0;for(;i<r.length;){if(Ti(r[i])){i++;continue}let l=Xn(r[i]),c=i+1;if(l==="heading"){let m=r[i].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:m[1].length,text:m[2],markdown:r[i].trim()}),i++;continue}if(l==="table"){let m=[];for(;i<r.length&&Si(r[i]);)m.push(r[i].trim()),i++;let d=m.length>1&&yi.test(m[1]),p=m.filter(b=>!yi.test(b)).map(b=>Rl(b).length);d||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:d,markdown:m.join(`
140
- `)});continue}if(l==="list"){let m=[];for(;i<r.length&&Xn(r[i])==="list";)m.push(r[i].trimEnd()),i++;n.push({type:"list",items:m.length,markdown:m.join(`
141
- `)});continue}let u=[];for(;i<r.length&&Xn(r[i])==="paragraph";)u.push(r[i].trim()),i++;let f=u.join(" ").trim();n.push({type:"paragraph",text:f,markdown:f})}let a={heading:0,paragraph:0,list:0,table:0};for(let l of n)a[l.type]=(a[l.type]||0)+1;let s=n.map(l=>l.markdown).join(`
139
+ `),n=[],o=[],i=0;for(;i<r.length;){if(Ii(r[i])){i++;continue}let l=Wn(r[i]),c=i+1;if(l==="heading"){let m=r[i].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:m[1].length,text:m[2],markdown:r[i].trim()}),i++;continue}if(l==="table"){let m=[];for(;i<r.length&&Pi(r[i]);)m.push(r[i].trim()),i++;let d=m.length>1&&Ai.test(m[1]),p=m.filter(h=>!Ai.test(h)).map(h=>Ml(h).length);d||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:d,markdown:m.join(`
140
+ `)});continue}if(l==="list"){let m=[];for(;i<r.length&&Wn(r[i])==="list";)m.push(r[i].trimEnd()),i++;n.push({type:"list",items:m.length,markdown:m.join(`
141
+ `)});continue}let u=[];for(;i<r.length&&Wn(r[i])==="paragraph";)u.push(r[i].trim()),i++;let f=u.join(" ").trim();n.push({type:"paragraph",text:f,markdown:f})}let a={heading:0,paragraph:0,list:0,table:0};for(let l of n)a[l.type]=(a[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 Cl(e,t,r={}){let n=Xr(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 ar=["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 kt(e,t){let r=ar.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=ar.indexOf(i.nodeName);if((a===-1?999:a)>n){e.insertBefore(t,i),o=!0;break}}o||e.appendChild(t)}function Ol(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"),kt(t,c);let u=O(e,"w:bCs");u.setAttribute("w:val",n==="add"?"1":"0"),kt(t,u)}if(i){let c=O(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),kt(t,c);let u=O(e,"w:iCs");u.setAttribute("w:val",n==="add"?"1":"0"),kt(t,u)}if(a){let c=O(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),kt(t,c)}if(s){let c=O(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),kt(t,c)}}function Ei(e,t,r){Ol(e,t,r,"remove")}function Ze(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=Dr(r,!1)),r.nodeName==="w:i"&&(t.italic=Dr(r,!1)),r.nodeName==="w:u"&&(t.underline=Dr(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=Dr(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 Dr(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 Ai="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Ve(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Ai&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function kl(e){return!e||e.nodeType!==1||e.namespaceURI!==Ai?!1:e.localName==="del"||e.localName==="moveFrom"}function Ii(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||kl(n))continue;if(Ve(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 Re(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 Pi(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],i=Ii(o);for(let a of i){let s=ie(a,"w:rPr");Array.from(a.childNodes||[]).forEach(l=>{if(Ve(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(Ve(l,"br")||Ve(l,"cr")||Ve(l,"tab")||Ve(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 Ml(e,t,r,n,o,i=null){let a=null;for(let c of Array.from(e.childNodes))if(Ve(c,"rPr")){a=c;break}let s=Ze(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(Ve(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 Ri(e){let t=[],r=[],n=0,o=Re(e);for(let i=0;i<o.length;i++){let a=o[i],s=null;for(let u of Array.from(a.childNodes))if(Ve(u,"pPr")){for(let f of Array.from(u.childNodes))if(Ve(f,"rPr")){s=f;break}break}let l=Ze(s);l.hasFormatting&&k(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let c=Ii(a);for(let u of c)n=Ml(u,a,n,r,t,l);n=pt(n,i,o.length)}return k(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}function wt(e,t,r,n,o=null){let i=O(e,t==="ins"?"w:ins":"w:del"),a=o||oe(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 Ci(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function _l(e,t){let r=Ci(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 Ll(e,t){let r=Ci(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=O(e,"w:rPr"),t.appendChild(r)),r}function Oi(e,t,r,n,o=null){let i=_l(e,t),a=Ll(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||oe(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 ki(e,t,r,n=null){return Oi(e,t,r,"ins",n)}function sr(e,t,r,n=null){return Oi(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 Mi(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 zr(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,b=o+m,h=n.filter(x=>x.start<=p&&x.end>=b),g={...Ze(r)};h.forEach(x=>{x.format&&Object.assign(g,x.format)});let w=h.length>0?Mt(e,r,g,i,a):r?.cloneNode(!0)||null;c.push(Dn(e,d,w,!1))}return c}function Dn(e,t,r,n){let o=O(e,"w:r");if(r&&o.appendChild(r),!n)return Mi(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 Mi(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(O(e,"w:br"));continue}if(i==="\u2011"){t.appendChild(O(e,"w:noBreakHyphen"));continue}let a=O(e,"w:t");/^\s|\s$/.test(i)&&a.setAttribute("xml:space","preserve"),a.textContent=i,t.appendChild(a)}}function Mt(e,t,r,n,o){let i=O(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)||i.appendChild(l.cloneNode(!0))});let a=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&o&&Bl(e,i,n,t);let s=(l,c,u=null,f="0")=>{let m=O(e,l);c?u&&m.setAttribute("w:val",u):f&&m.setAttribute("w:val",f);let d=ar.indexOf(l),p=d===-1?999:d,b=!1;for(let h of Array.from(i.childNodes)){if(h.nodeType!==1)continue;let g=ar.indexOf(h.nodeName);if((g===-1?999:g)>p){i.insertBefore(m,h),b=!0;break}}b||i.appendChild(m)};return s("w:b",!!a.bold,"1","0"),s("w:bCs",!!a.bold,"1","0"),s("w:i",!!a.italic,"1","0"),s("w:iCs",!!a.italic,"1","0"),s("w:u",!!a.underline,"single","none"),s("w:strike",!!a.strikethrough,"1","0"),i}function zn(e,t,r,n,o){let i=O(e,"w:rPrChange"),a=oe(r,e,"rPrChange");i.setAttribute("w:id",String(a.id)),i.setAttribute("w:author",a.author),i.setAttribute("w:date",n||a.date);let s=O(e,"w:rPr");Array.from((o||t).childNodes).forEach(u=>{u.nodeName!=="w:rPrChange"&&s.appendChild(u.cloneNode(!0))}),i.appendChild(s);let c=ie(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(i),i}function Bl(e,t,r,n){zn(e,t,r,null,n||t)}var Fl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function _t(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Fl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Wr(e,t,r){let n=new Map;for(let a of r)!a||!a.paragraph||(n.has(a.paragraph)||n.set(a.paragraph,[]),n.get(a.paragraph).push(a));let o=[],i=0;return t.forEach((a,s)=>{let l=(n.get(a)||[]).slice().sort((m,d)=>m.charStart-d.charStart),c=$l(l),u=Wn(c),f=u.trim();o.push({paragraph:a,spans:l,text:c,normalizedText:u,normalizedTrim:f,startOffset:i}),i+=u.length,i=pt(i,s,t.length)}),o}function _i(e,t){if(!t)return null;let r=Wn(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 Li(e,t){let r=Wn(t),n=r.trim(),o=null,i=0;for(let a of e)if(a.normalizedText===r)return o=a,{targetInfo:o,matchOffset:i};if(n.length>0){for(let a of e)if(a.normalizedTrim===n)return o=a,{targetInfo:o,matchOffset:i}}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,i=s-c;break}}}if(!o&&e.length===1&&r.length>0){let a=e[0],s=a.normalizedTrim||"";if(s.length>0){let l=r.indexOf(s);l>=0&&(o=a,i=-l)}}return{targetInfo:o,matchOffset:i}}function Bi(e){let t=e;for(;t;){if(_t(t,"p"))return t;t=t.parentNode}return null}function $l(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;_t(n,"t")?t+=r.textElement.textContent||"":_t(n,"tab")?t+=" ":_t(n,"br")||_t(n,"cr")?t+=`
146
- `:_t(n,"noBreakHyphen")&&(t+="\u2011")}return t}function Wn(e){return e?e.replace(/\r/g,`
147
- `).replace(/\u00a0/g," "):""}function Fi(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),i=[],a=0;for(let s of o){for(;a<n.length&&n[a]<=s.charStart;)a++;let l=s;for(;a<n.length&&n[a]<l.charEnd;){let c=n[a],u=Xl(e,l,c);if(!u){a++;continue}i.push(u[0]),l=u[1],a++}i.push(l)}return i}function Xl(e,t,r){let n=t.runElement,o=n.parentNode;if(!o)return null;let i=t.textElement.textContent||"",a=r-t.charStart,s=i.substring(0,a),l=i.substring(a);if(s.length===0||l.length===0)return null;let c=st(e,s,t.rPr,!1),u=st(e,l,t.rPr,!1);o.insertBefore(c,n),o.insertBefore(u,n),o.removeChild(n);let f=c.getElementsByTagName("w:t")[0],m=u.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:c},{...t,charStart:r,textElement:m,runElement:u}]}var Dl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function zl(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Dl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Wl(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 $i(e,t,r,n,o,i=!0){let a=!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=ie(c,"w:rPr");u||(u=O(e,"w:rPr"),c.insertBefore(u,c.firstChild)),i&&zn(e,u,o||de()),Ei(e,u,l.format),a=!0}return a?(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 Ul(e,t,r,n,o,i=!0){let a=!1,s=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let l=[];for(let m of r)l.push(m.start,m.end);let u=Fi(e,t,l).slice().sort((m,d)=>m.charStart-d.charStart||m.charEnd-d.charEnd),f=jl(r);for(let m of u){if(!m||!m.textElement||!zl(m.textElement,"t"))continue;let d=f(m.charStart,m.charEnd);if(d.length===0)continue;let p=Tn(...d.map(_=>_.format)),b={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},h=m.format||Ze(m.rPr),g={bold:!!h.bold,italic:!!h.italic,underline:!!h.underline,strikethrough:!!h.strikethrough};if(!["bold","italic","underline","strikethrough"].some(_=>b[_]!==g[_])||s.has(m.runElement)||(s.add(m.runElement),!(m.textElement.textContent||""))||!m.runElement.parentNode)continue;let T=m.runElement,v=ie(T,"w:rPr"),S=Mt(e,v,b,o||de(),i),I=v;if(!I)T.insertBefore(S,T.firstChild);else{for(;I.firstChild;)I.removeChild(I.firstChild);Array.from(S.childNodes).forEach(_=>I.appendChild(_))}a=!0}return{oxml:n.serializeToString(e),hasChanges:a}}function Xi(e,t,r,n,o,i=!0,a=null){let s=Wl(a),l=s.paragraphs||Re(e),c=s.textSpans||[];if(s.textSpans||({textSpans:c}=Pi(l)),!c||c.length===0)return Fe("[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||Wr(e,l,c),{targetInfo:f,matchOffset:m}=Li(u,t);if(!f||!f.spans||f.spans.length===0)return Fe("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let d=f.spans[0].charStart,p=f.spans.map(h=>({...h,charStart:h.charStart-d,charEnd:h.charEnd-d})),b=r.map(h=>({...h,start:h.start+m,end:h.end+m}));return Ul(e,p,b,n,o,i)}function jl(e){let t=(e||[]).slice().sort((o,i)=>o.start-i.start||o.end-i.end),r=[],n=0;return(o,i)=>{for(;n<t.length&&t[n].start<i;)r.push(t[n]),n++;for(let a=r.length-1;a>=0;a--)r[a].end<=o&&r.splice(a,1);return r.filter(a=>a.start<i&&a.end>o)}}function Ur(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function bt(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let i=Ur(o);if(n==="accepted"&&(i==="del"||i==="moveFrom")||n==="rejected"&&(i==="ins"||i==="moveTo"))return!1;o=o.parentNode}return!0}function xt(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!bt(e,n,r))return"";let o="",i=a=>{for(let s of Array.from(a?.childNodes||[])){if(s?.nodeType!==1||s.namespaceURI&&s.namespaceURI!==E||!bt(s,n,r))continue;let l=Ur(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":i(s)}};return i(e),o}var lt=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function jr(e,t={}){if(!e)return[];let r=[];function n(f,m,d){for(let p of Array.from(f?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==E)continue;let b=Ur(p);if(b==="pPr"||b==="rPr")continue;let h=m;b==="ins"?h={kind:"insertion",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:b==="del"?h={kind:"deletion",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:b==="moveFrom"?h={kind:"move_from",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:b==="moveTo"&&(h={kind:"move_to",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0});let g=d;b==="r"&&(g=p);let w=null,x=h?h.kind:"baseline",y=h?.author,N=h?.revisionId;b==="t"?w=p.textContent||"":b==="delText"?(w=p.textContent||"",h||(x="deletion")):b==="tab"?w=" ":b==="br"||b==="cr"?w=`
149
- `:b==="noBreakHyphen"?w="\u2011":b==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:x,author:y,revisionId:N,carrier:g||p,carrierContainer:(g||p)?.parentNode||null}):n(p,h,g)}}let o=Ur(e)==="r"?e:null;if(n(e,null,o),r.length===0)return[];let i=t.mergeRuns!==!1,a=[],s=null;for(let f of r){if(!s){s={...f};continue}let m=s.kind===f.kind,d=s.author===f.author,p=s.revisionId===f.revisionId,b=s.carrier===f.carrier,h=i&&s.carrierContainer===f.carrierContainer;m&&d&&p&&(b||h)?s.text+=f.text:(a.push(s),s={...f})}s&&a.push(s);let l=0,c=0,u=[];for(let f of a){let m=f.kind!=="deletion"&&f.kind!=="move_from",d=f.kind!=="insertion"&&f.kind!=="move_to",p=m?l:null,b=d?c:null;m&&(l+=f.text.length),d&&(c+=f.text.length);let h={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:b};f.author!==void 0&&(h.author=f.author),f.revisionId!==void 0&&(h.revisionId=f.revisionId),u.push(h)}return u}function be(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=jr(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 Hl="http://schemas.microsoft.com/office/word/2010/wordml";function Di(e,t,r={}){let{targetParagraphId:n=null}=r,o=ve(e,E,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let a=Re(e).filter(l=>{let c=l.parentNode;for(;c;){if(A(c,"tc"))return!0;c=c.parentNode}return!1});k(`[OxmlEngine] Table wrapper detected: ${o.length} tables, ${a.length} paragraphs in cells`);let s=null;if(n){let l=String(n).toUpperCase();s=a.find(c=>{let u=Gl(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 a)if(be(c).trim()===l){s=c,k(`[OxmlEngine] Found target paragraph by text match: "${l.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:a.length>0,targetParagraph:s,paragraphs:a,paragraph:s||a[0]||null,tableElement:o[0]}}function lr(e,t,r){let n=Array.isArray(t)?t:[t],o="";for(let i of n){if(!i)continue;let a=r.serializeToString(i);a=a.replace(/\s+xmlns:w="[^"]*"/g,""),a=a.replace(/\s+xmlns:r="[^"]*"/g,""),a=a.replace(/\s+xmlns:wp="[^"]*"/g,""),o+=a}return k(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),k(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),Vl(o)}function Vl(e){return di(e)}function Gl(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(Hl,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function Un(e){return A(e,"t")||A(e,"delText")?e.textContent||"":A(e,"br")||A(e,"cr")?`
150
- `:A(e,"tab")?" ":A(e,"noBreakHyphen")?"\u2011":A(e,"softHyphen")?"\xAD":""}function jn(e){return A(e,"t")||A(e,"delText")||A(e,"br")||A(e,"cr")||A(e,"tab")||A(e,"noBreakHyphen")||A(e,"softHyphen")}function Hr(e){let t="",r=[];return e.forEach((n,o)=>{let i=n.parentNode;for(let a=n.firstChild;a;a=a.nextSibling)if(A(a,"r"))t+=cr(a,n,i,t.length,r).text;else if(A(a,"hyperlink"))for(let s=a.firstChild;s;s=s.nextSibling)A(s,"r")&&(t+=cr(s,n,i,t.length,r).text);else if(A(a,"ins"))for(let s=a.firstChild;s;s=s.nextSibling)A(s,"r")&&(t+=cr(s,n,i,t.length,r).text);else if(A(a,"sdt")){let s=Array.from(a.childNodes||[]).find(l=>A(l,"sdtContent"));if(s)for(let l=s.firstChild;l;l=l.nextSibling)A(l,"r")&&(t+=cr(l,n,i,t.length,r).text)}else if(A(a,"smartTag"))for(let s=a.firstChild;s;s=s.nextSibling)A(s,"r")&&(t+=cr(s,n,i,t.length,r).text);t=It(t,o,e.length)}),{fullText:t,textSpans:r}}function cr(e,t,r,n,o){let i=ie(e,"w:rPr"),a=n,s=[];for(let l=e.firstChild;l;l=l.nextSibling)if(A(l,"t")){let c=l.textContent||"";if(c.length===0)continue;o.push({charStart:a,charEnd:a+c.length,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=c.length,s.push(c)}else if(jn(l)){let c=Un(l);o.push({charStart:a,charEnd:a+1,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=1,s.push(c)}return{text:s.join("")}}function Vr(e){let t=e.slice().sort((o,i)=>o.charStart-i.charStart||o.charEnd-i.charEnd),r=t.map(o=>o.charStart),n=t.map(o=>o.charEnd);return{spans:t,starts:r,ends:n}}function ur(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=Kn(e.ends,t);for(;o<e.spans.length;){let i=e.spans[o];if(i.charStart>=r)break;n(i),o++}}function Hn(e,t){if(e.spans.length===0)return null;let r=Kn(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function Vn(e,t){let r=Kl(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function Gn(e,t){let r=Kn(e.ends,t)-1;return r>=0?e.spans[r]:null}function Kn(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 Kl(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 zi(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=Hn(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,i=Vn(e,t)||(t>0?Gn(e,t):null),a=e.spans.find(s=>s.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:i,rightSpan:a,containingSpan:n,isInterior:o,fallbackParagraph:r}}function ct(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof he?t:Je(r)||ot(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let i of o){if(!A(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}var Yl=new Set(["ins","del"]);function Lt(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(A(n,"rPr")||!jn(n))continue;let o=Un(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function Ge(e){return e.length===0?0:e[e.length-1].end}function Ke(e,t,r,n,o){let i=[];return n<=r||t.forEach(a=>{let s=Math.max(r,a.start),l=Math.min(n,a.end);if(l<=s)return;let c=s-a.start,u=l-a.start,f=a.text.slice(c,u);i.push(Ql(e,a.node,f,o))}),i}function fr(e,t,r){let n=O(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function Nt(e,t,r,n,o){if(n.length===0)return null;let i=fr(e,n,o);return t.insertBefore(i,r),i}function Wi(e,t,r,n=null){let o=Zl(t);if(!Yl.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 i=Array.from(t.childNodes||[]),a=i.reduce((m,d)=>m+(A(d,"r")?Ge(Lt(d)):0),0);if(r>a)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${a}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===a)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let s=t.cloneNode(!1),l=t.cloneNode(!1),c=0;for(let m of i){if(!A(m,"r")){(c<=r?s:l).appendChild(m.cloneNode(!0));continue}let d=Lt(m),p=Ge(d),b=c+p;if(b<=r)s.appendChild(m.cloneNode(!0));else if(c>=r)l.appendChild(m.cloneNode(!0));else{let h=r-c,g=Array.from(m.childNodes||[]).find(T=>A(T,"rPr"))||null,w=o==="del",x=Ke(e,d,0,h,w),y=Ke(e,d,h,p,w);s.appendChild(fr(e,x,g));let N=fr(e,y,g);l.appendChild(N)}c=b}let u=Jl(e,n);ct(l,u);let f=u.next();return ql(l,"id",String(f)),u._receiptCollector?.recordRevision(f,o),{leftCarrier:s,rightCarrier:l}}function Jl(e,t){return t instanceof he?t:Je(e)||ot(e)}function ql(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(E,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function Zl(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Ql(e,t,r,n){if(n&&(A(t,"delText")||A(t,"t"))){let i=O(e,"w:delText");return i.setAttribute("xml:space","preserve"),i.textContent=r,i}if(A(t,"t")){let i=t.cloneNode(!1);return i.textContent=r,/^\s|\s$/.test(r)&&i.setAttribute("xml:space","preserve"),i}if(r===`
151
- `&&(A(t,"br")||A(t,"cr"))||r===" "&&A(t,"tab")||r==="\u2011"&&A(t,"noBreakHyphen")||r==="\xAD"&&A(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 Hi(e,t,r,n,o,i,a){if(o.length===0)return!1;let s=t.rPr,l=Ze(s),c={...l};if(o.forEach(T=>Object.assign(c,T.format)),!["bold","italic","underline","strikethrough"].some(T=>!!c[T]!==l[T]))return!1;let m=t.runElement.parentNode;if(!m)return!1;let d=t.textElement.textContent||"",p=t.charStart,b=r-p,h=n-p,g=d.substring(0,b),w=d.substring(b,h),x=d.substring(h);if(g.length>0){let T=st(e,g,s,!1);m.insertBefore(T,t.runElement)}let y=Mt(e,s,c,i,a),N=Dn(e,w,y,!1);if(m.insertBefore(N,t.runElement),x.length>0){let T=st(e,x,s,!1);m.insertBefore(T,t.runElement)}return m.removeChild(t.runElement),!0}function qn(e,t,r,n,o,i,a=null){let s=[];if(ur(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 b=p.parentNode;if(!b)return;let h=Lt(p);if(h.length===0)return;let g=1/0,w=-1/0;d.forEach(x=>{let y=h.find(v=>v.node===x.textElement);if(!y)return;let N=Math.max(0,r-x.charStart),T=Math.min(x.charEnd-x.charStart,n-x.charStart);T<=N||(g=Math.min(g,y.start+N),w=Math.max(w,y.start+T))}),!(!Number.isFinite(g)||w<=g)&&c.push({runElement:p,parent:b,rPr:d[0].rPr,beforePieces:Ke(e,h,0,g,!1),deletedPieces:Ke(e,h,g,w,!0),afterPieces:Ke(e,h,w,Ge(h),!1),globalStart:Math.max(r,Math.min(...d.map(x=>x.charStart))),globalEnd:Math.min(n,Math.max(...d.map(x=>x.charEnd))),carrierGlobalStart:A(b,"ins")?Vi(t,b):null})});let u=[];for(let d of c){let p=u[u.length-1],b=p?.[p.length-1];b&&b.parent===d.parent&&rc(b.runElement)===d.runElement?p.push(d):u.push([d])}let f=!1,m=!1;for(let d of u){let p=d[0],b=null;if(i&&d.some(w=>w.deletedPieces.length>0)){let w=a?m?{...a,id:oe(o,e,"del").id}:a:null;m=!0,b=wt(e,"del",null,o,w)}for(let w of d){let{parent:x,runElement:y}=w;Nt(e,x,y,w.beforePieces,w.rPr),b&&w===p&&x.insertBefore(b,y),b&&w.deletedPieces.length>0&&b.appendChild(fr(e,w.deletedPieces,w.rPr));let N=Nt(e,x,y,w.afterPieces,w.rPr);w.globalEnd===n&&!A(x,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:x,referenceNode:N||y.nextSibling,rPr:w.rPr})),x.removeChild(y),f=!0}let h=A(p.parent,"ins")?p.parent:null,g=Math.max(...d.map(w=>w.globalEnd));if(h&&g===n){let w=p.carrierGlobalStart,x=d.filter(N=>N.globalStart<n).reduce((N,T)=>N+T.deletedPieces.reduce((v,S)=>v+(S.textContent||"").length,0),0),y=Math.max(0,n-w-x);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:y,rPr:p.rPr})}}return f}function Bt(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"&&ji(m.carrier)&&Jn(m.carrier,o))return t.revisionInsertionAnchors.delete(r),Yn(e,m.carrier,m.splitOffset,n,m.rPr,o,i,a,s,c);let d=t.replacementInsertionAnchors?.get(r)||null;if(d&&!u&&ji(d.parent)&&(!d.referenceNode||d.referenceNode.parentNode===d.parent))return t.replacementInsertionAnchors.delete(r),ut(e,d.parent,d.referenceNode,n,d.rPr,o,i,a,s,c),!0;if(!u){let N=Hn(t,r);if(!N&&r>0&&(N=Vn(t,r)),!N&&r>0&&(N=Gn(t,r)),!N&&t.spans.length>0&&(N=t.spans[t.spans.length-1]),!N)return l?(ut(e,l,null,n,null,o,i,a,s,c),!0):!1;let T=N.runElement.parentNode;if(!T)return l?(ut(e,l,null,n,N.rPr,o,i,a,s,c),!0):!1;let v=!(s&&f==="slice-cross-author"&&tc(T,o));if(s&&f==="slice-cross-author"&&Jn(T,o))return Yn(e,T,Ui(t,T,r),n,N.rPr,o,i,a,s,c);let S=Lt(N.runElement),I=S.find(F=>F.node===N.textElement),_=I?I.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:Ge(S);if(_>0&&_<Ge(S)){let F=Ke(e,S,0,_,!1),X=Ke(e,S,_,Ge(S),!1);return Nt(e,T,N.runElement,F,N.rPr),ut(e,T,N.runElement,n,N.rPr,o,i,a,v,c),Nt(e,T,N.runElement,X,N.rPr),T.removeChild(N.runElement),!0}let L=r<=N.charStart?N.runElement:N.runElement.nextSibling;return ut(e,T,L,n,N.rPr,o,i,a,v,c),!0}let p=zi(t,r,l),b=p.leftSpan&&A(p.leftSpan.runElement?.parentNode,"hyperlink"),h=p.rightSpan&&A(p.rightSpan.runElement?.parentNode,"hyperlink"),g=p.containingSpan&&A(p.containingSpan.runElement?.parentNode,"hyperlink");if(u.hyperlink==="outside"){if(p.isInterior&&g)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(u.hyperlink==="inside"&&!b&&!h&&!g)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 N=p.containingSpan,T=N.runElement.parentNode||l;if(!T)return!1;let v=Lt(N.runElement),S=v.find(_=>_.node===N.textElement),I=S?S.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:Ge(v);if(I>0&&I<Ge(v)){let _=Ke(e,v,0,I,!1),L=Ke(e,v,I,Ge(v),!1);return Nt(e,T,N.runElement,_,N.rPr),ut(e,T,N.runElement,n,w,o,i,a,s,c),Nt(e,T,N.runElement,L,N.rPr),T.removeChild(N.runElement),!0}}let x=null,y=null;if(u.hyperlink==="outside"){if(h){let N=p.rightSpan.runElement.parentNode;x=N.parentNode||l,y=N}else if(b){let N=p.leftSpan.runElement.parentNode;x=N.parentNode||l,y=N.nextSibling}}else u.hyperlink==="inside"&&(h?(x=p.rightSpan.runElement.parentNode,y=p.rightSpan.runElement):b&&(x=p.leftSpan.runElement.parentNode,y=p.leftSpan.runElement.nextSibling));if(x||(p.rightSpan?(x=p.rightSpan.runElement.parentNode||l,y=p.rightSpan.runElement):p.leftSpan?(x=p.leftSpan.runElement.parentNode||l,y=p.leftSpan.runElement.nextSibling):(x=l,y=null)),u.bookmark&&x&&(u.bookmark==="outside"?(y&&A(y.previousSibling,"bookmarkStart")&&(y=y.previousSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(y=p.leftSpan.runElement.nextSibling.nextSibling)):u.bookmark==="inside"&&(y&&A(y,"bookmarkStart")&&(y=y.nextSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(y=p.leftSpan.runElement.nextSibling))),u.comment&&x)if(u.comment==="outside"){if(y&&A(y.previousSibling,"commentRangeStart")&&(y=y.previousSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let N=p.leftSpan.runElement.nextSibling.nextSibling;N&&(A(N,"commentReference")||A(N,"r"))&&Array.from(N.childNodes||[]).some(v=>A(v,"commentReference"))&&(N=N.nextSibling),y=N}}else u.comment==="inside"&&(y&&A(y,"commentRangeStart")&&(y=y.nextSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(y=p.leftSpan.runElement.nextSibling));if(s&&u.revision==="coalesce_same_author"){let N=null,T=null;if(p.leftSpan&&A(p.leftSpan.runElement.parentNode,"ins")){let v=p.leftSpan.runElement.parentNode;(v.getAttribute("w:author")||v.getAttributeNS(E,"author"))===o&&(N=v,T=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&A(p.rightSpan.runElement.parentNode,"ins")){let v=p.rightSpan.runElement.parentNode;(v.getAttribute("w:author")||v.getAttributeNS(E,"author"))===o&&(N=v,T=p.rightSpan.runElement)}if(N){let v=st(e,n,w,!1);return N.insertBefore(v,T),!0}}return s&&f==="slice-cross-author"&&Jn(x,o)?Yn(e,x,Ui(t,x,r),n,w,o,i,a,s,c):(ut(e,x,y,n,w,o,i,a,s,c),!0)}function Yn(e,t,r,n,o,i,a,s,l,c){let u=t.parentNode;if(!u)return!1;let{leftCarrier:f,rightCarrier:m}=Wi(e,t,r);return f&&u.insertBefore(f,t),ut(e,u,t,n,ec(o),i,a,s,l,c),m&&u.insertBefore(m,t),u.removeChild(t),!0}function ec(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>A(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Ui(e,t,r){let n=Vi(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 Vi(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 Jn(e,t){return A(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function tc(e,t){return A(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function rc(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function ji(e){return!!e?.parentNode}function ut(e,t,r,n,o,i,a,s,l,c=null){let u=Ye(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=zr(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 Gi(e,t,r,n=!1){let o=[];if(ur(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 b of Array.from(p.childNodes||[]))if(b.nodeType===1){let h=b.localName||b.nodeName.replace(/^.*:/,"");if(c.has(h)||h==="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 b of Array.from(d.childNodes||[]))if(b.nodeType===1&&m(b))return!0;return!1}return m(i.previousSibling)||m(u.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function Ji(e,t,r,n,o,i,a=!0,s=null,l={},c={}){let u=s?[s]:Re(e),{fullText:f,textSpans:m}=Hr(u),d=c.existingRevisions==="slice-cross-author"?oi(f,r):null,p=d||oc(or(f,r,l),l),b=Vr(m),h=c.pairReplacements===!0,g=[],w=0,x=0,y=!1,N=d?ac(d):[];if(N.length>1&&i.length===0)for(let S of N.slice().reverse()){let I=Hr(u).textSpans,_=Vr(I),L=S.text.replace(/\n/g," ");if(L.length===0)continue;let F=Bt(e,_,S.originalPos,L,o,i,S.newPos,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(F&&typeof F=="object"&&F.error)return ae({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:F.error});F===!0&&(y=!0)}else if(i.length===0){let S=ic(p);for(let I of S.reverse()){let _=Vr(Hr(u).textSpans);if(I.type==="insert"){let X=Bt(e,_,I.start,I.text.replace(/\n/g," "),o,i,I.newPos,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(X&&typeof X=="object"&&X.error)return ae({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:X.error});X===!0&&(y=!0);continue}let L=null,F=null;if(I.type==="replace"&&h&&a&&I.text.replace(/\n/g," ")){let X=Gi(_,I.start,I.end,c?.existingRevisions==="slice-cross-author");if(X.safe){let C=tr(o,e);L={id:C.deletionId,author:C.author,date:C.date},F={id:C.insertionId,author:C.author,date:C.date}}else X.structuralBoundary&&g.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(qn(e,_,I.start,I.end,o,a,L)&&(y=!0),I.type==="replace"){let X=Bt(e,_,I.end,I.text.replace(/\n/g," "),o,i,I.newPos,a,u[0]||null,F,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(X&&typeof X=="object"&&X.error)return ae({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:X.error});X===!0&&(y=!0)}}}else for(let S=0;S<p.length;S++){let[I,_]=p[S];if(I===0){let L=_.length,F=w,X=w+L;ur(b,F,X,C=>{let U=Math.max(C.charStart,F),R=Math.min(C.charEnd,X),B=R-U,$=U-F,Y=x+$,V=Y+B,K=Ye(i,Y,V);Hi(e,C,U,R,K,o,a)&&(y=!0)}),w+=L,x+=L}else if(I===-1){let L=S+1<p.length&&p[S+1][0]===1,F=!1,X=null,C=null;if(h&&a&&L&&p[S+1][1].replace(/\n/g," ").length>0){let B=Gi(b,w,w+_.length,c?.existingRevisions==="slice-cross-author");if(B.safe){let $=tr(o,e);X={id:$.deletionId,author:$.author,date:$.date},C={id:$.insertionId,author:$.author,date:$.date},F=!0}else B.structuralBoundary&&g.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(qn(e,b,w,w+_.length,o,a,X)&&(y=!0),w+=_.length,F){S++;let[,U]=p[S],R=U.replace(/\n/g," ");if(R.length>0){let B=Bt(e,b,w,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 ae({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:B.error});B===!0&&(y=!0)}x+=U.length}}else if(I===1){let L=_.replace(/\n/g," ");if(L.length>0){let F=Bt(e,b,w,L,o,i,x,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(F&&typeof F=="object"&&F.error)return ae({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:F.error});F===!0&&(y=!0)}x+=_.length}}let T=u.map(S=>be(S)).join(`
152
- `),v=String(r).replace(/\r\n/g,`
153
- `);if(c.existingRevisions==="slice-cross-author"&&T!==v){let S=nc(v,T);return ae({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:S,expectedExcerpt:Ki(v,S),actualExcerpt:Ki(T,S),expectedCodePoint:Yi(v,S),actualCodePoint:Yi(T,S)},...g.length>0?{warnings:[...new Set(g)]}:{}})}return ae({oxml:n.serializeToString(e),hasChanges:y,...g.length>0?{warnings:[...new Set(g)]}:{}})}function nc(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 Ki(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}function Yi(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function oc(e,t){let r=[];for(let n=0;n<e.length;n++){let[o,i]=e[n],a=e[n+1];if(o===-1&&a?.[0]===1&&i!==a[1]&&i.length===a[1].length&&i.replace(/\u00a0/g," ")===a[1].replace(/\u00a0/g," ")){r.push(...ni(i,a[1],t)),n++;continue}r.push([o,i])}return r}function ic(e){let t=[],r=0,n=0;for(let o=0;o<e.length;o++){let[i,a]=e[o];if(i===0){r+=a.length,n+=a.length;continue}if(i===-1){let s=e[o+1];s?.[0]===1?(t.push({type:"replace",start:r,end:r+a.length,newPos:n,text:s[1]}),r+=a.length,n+=s[1].length,o++):(t.push({type:"delete",start:r,end:r+a.length,newPos:n,text:""}),r+=a.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:a}),n+=a.length}return t}function ac(e){let t=[],r=0,n=0;for(let[o,i]of e)o===0?(r+=i.length,n+=i.length):o===-1?r+=i.length:o===1&&(t.push({originalPos:r,newPos:n,text:i}),n+=i.length);return t}var Zi=Lo(kn(),1);var Qi=new Zi.diff_match_patch;function ea(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function sc(e,t){return e?.getAttributeNS?.(E,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function qi(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let o=0,i=t-1;for(;o<=i;){let a=Math.floor((o+i)/2);e[a].end<=r?o=a+1:i=a-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 lc(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 ta(e,t,r=null){let n=e.documentElement,o=A(n,"body")||ea(n)==="package",i=r||Re(e),a=ye(e,E,"body");!a&&o&&(a=n);let s="",l=[],c=[],u=[],f=new Map,m=new Map,d=new Set,p={nextCharCode:57344},b=new Set;i.forEach((L,F)=>{let X=s.length;Array.from(L.childNodes).forEach(B=>{s=dc(B,s,l,u,f,m,p,d)}),s=It(s,F,i.length);let C=s.length,U=ye(L,E,"pPr"),R=L.parentNode;R&&b.add(R),c.push({start:X,end:C,pPr:U,container:R||a})});let h="";for(let L=0;L<s.length;L++){let F=s[L];h+=d.has(F)?`
154
- `:F}let g=fc(h,t,u);g=uc(h,s,g,d),m.forEach((L,F)=>{let X=F.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");g=g.replace(new RegExp(X,"g"),L)}),g=mc(s,g,f);let w=new Map;b.forEach(L=>{w.set(L,e.createDocumentFragment())}),a&&!w.has(a)&&w.set(a,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let x=new Map,y=new Set(c.map(L=>L.start)),N=qi(c),T=qi(l),v=lc(u);return{paragraphs:i,body:a||e,paragraphMap:c,paragraphStarts:y,propertyMap:l,sentinelMap:u,sentinelMapByStart:v,referenceMap:f,tokenToCharMap:m,containerFragments:w,replacementContainers:x,originalFullText:s,processedModifiedText:g,getParagraphInfo:L=>{let F=N.at(L);return F||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:a||e})},getRunProperties:L=>{let F=T.at(L);return F?{rPr:F.rPr,wrapper:F.wrapper}:{rPr:null}},getPropertySpanLength:(L,F)=>{let X=T.at(L);return X?Math.min(X.end-L,F):1},isParagraphStart:L=>y.has(L)}}function ra(e,t){let r=Re(e);if(r.length===0)return[];let n=na(t),o=r.map(cc);if(!n){let a=o.findIndex(s=>s==="");return a>=0?[r[a]]:null}if(r.length===1&&o[0]==="")return r;let i=[a=>a,a=>a.trim(),a=>a.replace(/\s+/g," ").trim()];for(let a of i){let s=a(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],a(c)===s)return r.slice(l,u+1)}}return null}function na(e){return String(e??"").replace(/\r\n?/g,`
156
- `).replace(/\u00a0/g," ")}function cc(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&(A(o,"pPr")||A(o,"del")||A(o,"moveFrom")||(A(o,"t")?t+=o.textContent||"":A(o,"tab")?t+=" ":A(o,"br")||A(o,"cr")?t+=`
157
- `:A(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),na(t)}function uc(e,t,r,n){if(n.size===0)return r;let o=Qi.diff_main(e,r),i=0,a="";for(let[s,l]of o)if(s===0){for(let c=0;c<l.length;c++){let u=t[i+c];a+=n.has(u)?u:l[c]}i+=l.length}else s===-1?i+=l.length:a+=l;return a}function fc(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="",i=0,a=new Map;for(let f=0;f<e.length;f++){let m=n.get(f);if(m){a.has(i)||a.set(i,[]),a.get(i).push({char:e[f],affinity:m.affinity||"right",emitted:!1});continue}o+=e[f],i++}let s=Qi.diff_main(o,t),l=0,c="",u=(f,m)=>{let d=a.get(f)||[];for(let p of d)p.emitted||m&&p.affinity!==m||(c+=p.char,p.emitted=!0)};for(let[f,m]of s){if(f===1){u(l,"left"),c+=m;continue}for(let d=0;d<m.length;d++)u(l),f===0&&(c+=m[d]),l++}return u(l),c}function mc(e,t,r){let n=t;for(let o of r.keys()){if(n.includes(o))continue;let i=e.indexOf(o);if(i<0)continue;let a=e.slice(0,i),s=e.slice(i+o.length);if(a&&n.startsWith(a)){n=`${n.slice(0,a.length)}${o}${n.slice(a.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 dc(e,t,r,n,o,i,a,s){return A(e,"r")?pc(e,t,r,n,o,i,a,s):A(e,"hyperlink")?gc(e,t,r):A(e,"sdt")||A(e,"oMath")||ea(e)==="oMath"||A(e,"bookmarkStart")||A(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((A(e,"commentRangeStart")||A(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function pc(e,t,r,n,o,i,a,s){let l=t,c=ye(e,E,"rPr");return Array.from(e.childNodes).forEach(u=>{if(A(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(A(u,"br")||A(u,"cr")){let f=String.fromCharCode(a.nextCharCode++);o.set(f,u),s.add(f),l+=f,r.push({start:l.length-1,end:l.length,rPr:c})}else if(A(u,"tab"))l+=" ",r.push({start:l.length-1,end:l.length,rPr:c});else if(A(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=>A(u,f))){let f=ye(u,E,"txbxContent"),m=A(u,"pict")&&!!f,d=A(u,"fldChar")||A(u,"instrText"),p=A(u,"fldChar")?u.getAttributeNS?.(E,"fldCharType")||u.getAttribute("w:fldCharType")||u.getAttribute("fldCharType"):null;n.push({start:l.length,node:u,wrapInRun:!0,rPr:c,zeroWidth:d,affinity:p==="end"?"left":"right",isTextBox:m,originalContainer:m?f:void 0}),l+="\uFFFC",r.push({start:l.length-1,end:l.length,rPr:c})}else if(A(u,"footnoteReference")||A(u,"endnoteReference")){let f=sc(u,"id");if(f){let d=`{{__${A(u,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(a.nextCharCode++);o.set(p,u),i.set(d,p),l+=p,r.push({start:l.length-1,end:l.length,rPr:c})}}else A(u,"commentReference")&&n.push({start:l.length,node:u,isCommentMarker:!0})}),l}function gc(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!A(o,"r"))return;let i=ye(o,E,"rPr");ve(o,E,"t").forEach(s=>{let l=s.textContent||"";l.length!==0&&(r.push({start:n.length,end:n.length+l.length,rPr:i,wrapper:e}),n+=l)})}),n}function ia(e,t,r,n,o,i,a=!0,s={}){let{paragraphs:l,containerFragments:c,sentinelMapByStart:u,referenceMap:f,replacementContainers:m,getParagraphInfo:d,getRunProperties:p,getPropertySpanLength:b,isParagraphStart:h}=r,g=R=>{let B=O(e,"w:p");if(R){let $=R.cloneNode(!0),Y=ye($,E,"sectPr");Y&&$.removeChild(Y),B.appendChild($)}return B},w=d(0),x=g(w.pPr),y=c.get(w.container);y&&y.appendChild(x);let N=0,T=0,v=s?.pairReplacements===!0,S=null,I=null,_=new WeakSet;for(let R=0;R<t.length;R++){let[B,$]=t[R];if(B===0||B===-1){let Y=B===0?"equal":"delete";if(B===0)S=null,I=null;else if(S===null){S=N;let K=!1;for(let se=R+1;se<t.length;se++){if(t[se][0]===1){K=!0;break}if(t[se][0]===0)break}v&&a&&K&&(I=tr(o,e))}let V=0;for(;V<$.length;){let K=N+V,se=p(K),Be=b(K,$.length-V),Gt=$.substring(V,V+Be);x=oa(e,Gt,Y,se.rPr,se.wrapper,K,x,c,u,f,m,d,g,o,i,T,a,_,I).currentParagraph,B===0&&(T+=Be),V+=Be}N+=$.length;continue}if(B===1){let Y=S!==null?S:N>0&&!h(N)?N-1:N,V=p(Y);x=oa(e,$,"insert",V.rPr,V.wrapper,N,x,c,u,f,m,d,g,o,i,T,a,_,I,S!==null).currentParagraph,T+=$.length,S=null,I=null}}a&&c.forEach(R=>{Array.from(R.childNodes).forEach(B=>{if(A(B,"p")){let $=Array.from(B.getElementsByTagNameNS(E,"t")).length>0,Y=Array.from(B.getElementsByTagNameNS(E,"delText")).length>0;l.length===1&&!$&&(Y||r.originalFullText.trim()!=="")&&sr(e,B,o)}})}),c.forEach(R=>{let B=Array.from(R.childNodes).filter($=>A($,"p"));if(B.length>1){let $=B[0],Y=B[B.length-1],V=ye($,E,"pPr"),K=V?ye(V,E,"sectPr"):null;if(K){V.removeChild(K);let se=ye(Y,E,"pPr");se||(se=O(e,"w:pPr"),Y.insertBefore(se,Y.firstChild||null)),se.appendChild(K)}}});let L=new Set(l),F=new Map;l.forEach(R=>{let B=R.parentNode;if(!B||F.has(B))return;let $=R.nextSibling;for(;$&&L.has($);)$=$.nextSibling;F.set(B,$)}),l.forEach(R=>{R.parentNode&&R.parentNode.removeChild(R)});let X=!1,C="";return c.forEach((R,B)=>{let $=m.get(B),Y=$||B;if(Y.nodeType===9){X=!0,R.childNodes.length===1?Y.appendChild(R.firstChild):C=Array.from(R.childNodes).map(K=>n.serializeToString(K)).join("");return}let V=$?null:F.get(B);V&&V.parentNode===Y?Y.insertBefore(R,V):Y.appendChild(R)}),{oxml:X&&C?C:n.serializeToString(e),hasChanges:!0}}function oa(e,t,r,n,o,i,a,s,l,c,u,f,m,d,p=[],b=0,h=!0,g=new WeakSet,w=null,x=!1){let y=i,N=b,T=a,v=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(I=>{let _=l.get(y)||[],L=_.filter(C=>C.isCommentMarker&&!g.has(C.node)),F=x?new Set(L.filter(C=>A(C.node,"commentRangeEnd")).map(C=>C.node.getAttributeNS?.(E,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id"))):new Set;if(L.forEach(C=>{g.add(C.node);let U=C.node.getAttributeNS?.(E,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id");if(x&&F.has(U)&&(A(C.node,"commentRangeEnd")||A(C.node,"commentReference"))){v.push(C.node);return}if(A(C.node,"commentReference")){let R=O(e,"w:r");R.appendChild(C.node.cloneNode(!0)),T.appendChild(R)}else T.appendChild(C.node.cloneNode(!0))}),I===`
158
- `){let C=f(y+1),U=m(C.pPr);h&&r==="insert"?ki(e,T,d):h&&r==="delete"&&sr(e,T,d);let R=s.get(C.container);R&&(R.appendChild(U),T=U),y++,r!=="delete"&&N++;return}if(I==="\uFFFC"){let C=_.find(U=>!U.isCommentMarker)||_[0];if(C){let U=C.node.cloneNode(!0);if(C.isTextBox&&C.originalContainer){let R=ye(U,E,"txbxContent");if(R){for(;R.firstChild;)R.removeChild(R.firstChild);u.set(C.originalContainer,R)}}if(C.wrapInRun){let R=O(e,"w:r");C.rPr&&R.appendChild(C.rPr.cloneNode(!0)),R.appendChild(U),T.appendChild(R)}else T.appendChild(U)}y++,r!=="delete"&&N++;return}if(c.has(I)){if(r!=="delete"){let C=c.get(I);if(C){let U=C.cloneNode(!0),R=O(e,"w:r");n&&R.appendChild(n.cloneNode(!0)),R.appendChild(U),T.appendChild(R)}}y++,r!=="delete"&&N++;return}if(I.length===0)return;let X=T;if(o){let C=o.cloneNode(!1);X=C,T.appendChild(C)}if(r==="delete"){let C=O(e,"w:r");n&&C.appendChild(n.cloneNode(!0));let U=O(e,"w:delText");if(U.setAttribute("xml:space","preserve"),U.textContent=I,C.appendChild(U),h){let R=null;if(w){let $=w.usedDeletionId?oe(d,e,"del").id:w.deletionId;w.usedDeletionId=!0,R={id:$,author:w.author,date:w.date}}let B=wt(e,"del",C,d,R);X.appendChild(B)}}else{let C=Ye(p,N,N+I.length),U=zr(e,I,n,C,N,d,h);if(r==="insert"&&h){let R=null;if(w){let $=w.usedInsertionId?oe(d,e,"ins").id:w.insertionId;w.usedInsertionId=!0,R={id:$,author:w.author,date:w.date}}let B=wt(e,"ins",null,d,R);U.forEach($=>B.appendChild($)),X.appendChild(B)}else U.forEach(R=>X.appendChild(R))}r!=="delete"&&(N+=I.length),y+=I.length}),v.forEach(I=>{if(A(I,"commentReference")){let _=O(e,"w:r");_.appendChild(I.cloneNode(!0)),T.appendChild(_)}else T.appendChild(I.cloneNode(!0))}),{currentParagraph:T}}function Zn(e,t,r,n,o,i,a=!0,s={},l={}){let c=ra(e,t);if(c===null)return ae({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=ta(e,r,c);if(u.paragraphs.length===0)return ae({oxml:n.serializeToString(e),hasChanges:!1});let f=or(u.originalFullText,u.processedModifiedText,s);return ae(ia(e,f,u,n,o,i,a,l))}function ze(e,t){return ae({oxml:e.serializeToString(t),hasChanges:!1})}function aa(e,t,r,n,o,i=!0){let a=ve(e,E,"tbl"),s=De(t),l=s.rows.length>0||s.headers.length>0;if(a.length===0||!l)return ze(r,e);let c=a[0],u=On(c),f=hi(u,s);if(f.length===0)return ze(r,e);let m={generateRedlines:i,author:o,revisionIdAllocator:Je(e)},d=wi(u,f,m),p=`<root xmlns:w="${E}">${d}</root>`,b=j(p,"application/xml").doc;if(!b)return ze(r,e);let h=re(b);if(h)return ee("[OxmlEngine] Failed to parse reconciled table OOXML:",h.textContent),ze(r,e);let g=ye(b,E,"tbl");if(!g)return ee("[OxmlEngine] No table found in reconciled OOXML"),ze(r,e);let w=e.importNode(g,!0);return c.parentNode.replaceChild(w,c),ae({oxml:r.serializeToString(e),hasChanges:!0})}function sa(e,t,r,n,o,i){let a=Je(e),s=De(t);if(!s||s.rows.length===0&&s.headers.length===0)return k("[OxmlEngine] Failed to parse table data from Markdown"),ze(r,e);let l=ht(s,{generateRedlines:i,author:o,revisionIdAllocator:a}),c=j(`<root xmlns:w="${E}">${l}</root>`,"application/xml").doc;if(!c)return ze(r,e);let u=re(c);if(u)return ee("[OxmlEngine] Failed to parse generated table OOXML:",u.textContent),ze(r,e);let f=te(c,E,"tbl");if(f||(f=te(c,E,"ins")),!f)return ee("[OxmlEngine] No table element found in generated OOXML"),ze(r,e);let m=e,d=ce(m,E,"p");if(d.length===0)return k("[OxmlEngine] No paragraphs found to replace"),ze(r,m);let p=d[0],b=p.parentNode;if(b&&b.nodeType===9){let g=j(`<w:document xmlns:w="${E}"><w:body/></w:document>`,"application/xml").doc;if(!g)return ze(r,m);let w=te(g,E,"body");d.forEach(x=>w.appendChild(g.importNode(x,!0))),m=g,Cr(m,a),d=ce(m,E,"p"),p=d[0],b=p.parentNode}let h=m.importNode(f,!0);return i?d.forEach(g=>{sr(m,g,o),ce(g,E,"r").forEach(x=>{ce(x,E,"t").forEach(v=>{let S=v.textContent||"";if(S.trim()){let I=O(m,"w:delText");I.textContent=S,v.parentNode.replaceChild(I,v)}});let N=O(m,"w:del"),T=oe(o,m,"del");N.setAttribute("w:id",String(T.id)),N.setAttribute("w:author",T.author),N.setAttribute("w:date",T.date),x.parentNode.insertBefore(N,x),N.appendChild(x)})}):d.slice(1).forEach(g=>g.parentNode.removeChild(g)),b.insertBefore(h,p),i||b.removeChild(p),k("[OxmlEngine] Text-to-table transformation complete"),ae({oxml:r.serializeToString(m),hasChanges:!0})}function Qe(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 Gr(e){return typeof e=="string"?e.trim().toLowerCase():""}function hc(e){return!!e&&e.nodeType===1}function We(e,t){return hc(e)&&e.namespaceURI===E&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function xe(e,t){return Array.from(e.getElementsByTagNameNS(E,t))}function Qn(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=Gr(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 Ce(e,t){if(t.allAuthors)return!0;let r=Gr(Qe(e,"author"));return!!r&&r===t.normalizedAuthor}function eo(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=j(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let a=`<w:body xmlns:w="${E}">${r}</w:body>`,s=j(a,"application/xml");s.error||(o=s,n=!0)}let i=o.doc?re(o.doc):null;if(o.error||i){let a=o.error?.message||i?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${a}`,warnings:o.warnings,error:{code:"PARSE_ERROR",message:a}}}return{xmlDoc:o.doc,serializer:me(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function fe(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Kr(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function la(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function ca(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 wc(e){let t=0,r=xe(e,"ins");for(let n of r){if(!n.parentNode||Jr(n))continue;let o=la(n);for(;We(o,"ins")&&Gr(Qe(o,"author"))===Gr(Qe(n,"author"))&&ca(o)===ca(n);){let i=la(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=i}}return t}function Yr(e){let t=e?.parentNode;return We(t,"trPr")&&We(t?.parentNode,"tr")}function Jr(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return We(t,"rPr")&&We(r,"pPr")&&We(n,"p")}function ma(e){return Jr(e)?e.parentNode.parentNode.parentNode:null}function bc(e){let t=e?.nextSibling||null;for(;t;){if(We(t,"p"))return t;t=t.nextSibling}return null}function da(e){if(!e?.parentNode)return!1;let t=bc(e);if(!t)return We(e.parentNode,"tc")&&xe(e.parentNode,"p").length<=1?!1:fe(e);let r=Array.from(e.childNodes||[]).filter(o=>!We(o,"pPr")),n=t.firstChild||null;We(n,"pPr")&&(n=n.nextSibling||null);for(let o of r)t.insertBefore(o,n);return fe(e)}function to(e,t={}){let r=[],n=Qn(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=eo(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(Jr(u)){fe(u)&&(s+=1);continue}if(Yr(u)){fe(u)&&(s+=1);continue}Kr(u)&&(s+=1)}for(let u of xe(i,"del")){if(!u.parentNode||!Ce(u,n))continue;let f=ma(u);if(f){da(f)&&(s+=1);continue}if(Yr(u)){let m=u.parentNode?.parentNode;fe(m)&&(s+=1);continue}fe(u)&&(s+=1)}for(let u of xe(i,"moveFrom"))!u.parentNode||!Ce(u,n)||fe(u)&&(s+=1);for(let u of xe(i,"moveTo"))!u.parentNode||!Ce(u,n)||Kr(u)&&(s+=1);s+=pa(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)||fe(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 ua(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 xc(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 fe(e);let o=Array.from(e.childNodes||[]).find(a=>a.nodeType===1&&a.namespaceURI===E&&String(a.localName||"").toLowerCase()===n.toLowerCase());if(!o)return fe(e);let i=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let a of i){let s=Nc(r.ownerDocument,a);r.appendChild(s)}return!0}function Nc(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function fa(e,t,r){let n=new Set;for(let o of xe(e,t)){if(!Ce(o,r))continue;let i=Qe(o,"id");i&&n.add(i)}return n}function pa(e,t){let r=0,n=fa(e,"moveFromRangeStart",t),o=fa(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=Qe(c,"id");u&&(t.allAuthors||s.has(u)||l&&Ce(c,t))&&fe(c)&&(r+=1)}return r}function ro(e,t={}){let r=[],n=Qn(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=eo(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=ma(u);if(f){da(f)&&(s+=1);continue}if(Yr(u)){let m=u.parentNode?.parentNode;fe(m)&&(s+=1);continue}fe(u)&&(s+=1)}for(let u of xe(i,"del"))if(!(!u.parentNode||!Ce(u,n))){if(Jr(u)){fe(u)&&(s+=1);continue}if(Yr(u)){fe(u)&&(s+=1);continue}ua(i,u),Kr(u)&&(s+=1)}for(let u of xe(i,"moveFrom"))!u.parentNode||!Ce(u,n)||(ua(i,u),Kr(u)&&(s+=1));for(let u of xe(i,"moveTo"))!u.parentNode||!Ce(u,n)||fe(u)&&(s+=1);s+=pa(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)||xc(f,u)&&(s+=1);return wc(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 vc(e,t){let r=new Set,n=xe(e,"comment");for(let o of n){if(!Ce(o,t))continue;let i=Qe(o,"id");i&&r.add(i)}return{targetIds:r,commentNodes:n}}function yc(e,t){let r=0;for(let n of e){let o=Qe(n,"id");!o||!t.has(o)||fe(n)&&(r+=1)}return r}function Tc(e){return We(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 Sc(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=Qe(i,"id");if(!(!a||!t.has(a))){if(o==="commentReference"&&Tc(i.parentNode)){fe(i.parentNode)&&(r+=1);continue}fe(i)&&(r+=1)}}return r}function Ec(e,t={}){let r=[],n=Qn(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=eo(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}=vc(i,n);if(n.allAuthors)for(let f of["commentRangeStart","commentRangeEnd","commentReference"])for(let m of xe(i,f)){let d=Qe(m,"id");d&&s.add(d)}let c=yc(l,s),u=Sc(i,s);return{oxml:a.serializeToString(i),hasChanges:c>0||u>0,commentsRemoved:c,referencesRemoved:u,warnings:r}}var Ac=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 et(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:Ac[t]||null,...r}))}var Ic=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 mr(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function no(e,t){return mr(e).find(r=>Me(r)===t)||null}function oo(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function qr(e){return String(e||"").trim().toLowerCase()}function Pc(e){return Me(e)!=="r"?!1:mr(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(Me(t)))}function io(e){return Ic.has(Me(e))||Pc(e)}function ao(e){return Me(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(Me(e))?mr(e).filter(r=>!io(r)&&Me(r)!=="sdtPr").every(ao):!1}function ga(e){let t=no(e,"pPr"),r=no(t,"rPr");return no(r,"del")}function Rc(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 ha(e,t){let r=ga(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=oo(r,"author")||null,o=!n||qr(n)!==qr(t),a=mr(e).filter(s=>!io(s)).every(ao);return{matches:o&&a,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:a,ownerAuthor:n,markDeletion:r}}function wa(e){let t=Me(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>Me(n)==="p"),r=[];for(let n of t){let o=ga(n);if(!o)continue;let i=oo(o,"author")||null,a=mr(n).filter(c=>!io(c)),s=a.filter(c=>Me(c)!=="ins"||!Rc(c)?!1:qr(oo(c,"author"))!==qr(i)),l=a.every(c=>ao(c)||s.includes(c));s.length>0&&l&&r.push({paragraph:n,markDeletion:o,ownerAuthor:i,foreignInsertions:s})}return r}function Cc(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))}async function so(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||de(),l=me(),c=[],u=[],f=!1,m=n.existingRevisions||"merge-same-author",d=m==="accept-all-first-keep-normalized",p=z=>{let M={...z};f&&M.hasChanges===!1&&M.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(M.oxml=i,M.hasChanges=!0,M.warnings=[...Array.isArray(M.warnings)?M.warnings:[],"Previous revisions by the same author were reverted to baseline."]):d?(M.oxml=i,M.hasChanges=!0,M.warnings=[...Array.isArray(M.warnings)?M.warnings:[],"Existing revisions were accepted before redlining."]):M.oxml=o);let Z=[...c,...u,...Array.isArray(M.warnings)?M.warnings:[]];return Z.length>0&&(M.warnings=[...new Set(Z)]),M.status||(M.status=M.hasChanges?"ok":"no-op"),ae(M)},b=()=>p(f&&d?{oxml:i,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),h=j(o,"text/xml");c=h.warnings;let g=h.doc,w=g?re(g):null;if(h.error||w){let z=h.error?.message||w?.textContent||"Could not parse OOXML input.";return ee("[OxmlEngine] XML parse error:",z),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:z}})}let x=n?._revisionIdAllocator instanceof he?n._revisionIdAllocator:new he;At(g,x);let y=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Re(g);if(y.length===1&&r.length>0){let z=ha(y[0],s);if(z.matches){let M=z.ownerAuthor||"unattributed";return p({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 (${M}). Use explicit paragraph restoration when supported.`,ownerAuthor:M}})}}if($r(g))if(m==="merge-same-author"||m==="slice-cross-author"){let z=Fn(g),M=String(s||"").trim().toLowerCase();if(z.length>0&&z.every(le=>le.trim().toLowerCase()===M)){let le=Cc(g);if(le.length>0)return p({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}});k("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let Te=ro(o,{author:s});if(Te.status==="error")return p(Te);i=Te.oxml,f=!0;let Kt=j(i,"text/xml");c.push(...Kt.warnings),g=Kt.doc;let ko=g?re(g):null;if(Kt.error||ko){let Ir=Kt.error?.message||ko?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return ee("[OxmlEngine] XML parse error after rejecting same-author revisions:",Ir),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Ir}})}if($r(g))return p({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."}});At(g,x);let Mo=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Re(g);t=Mo.length>0?Mo.map(Ir=>be(Ir)).join(`
160
- `):""}else{if(m==="merge-same-author")return k("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${z.length?z.join(", "):"unattributed"}). Pass existingRevisions: "accept-all-first" or resolve revisions first.`}});if(["moveFrom","moveTo"].some(Te=>ve(g,E,Te).length>0))return p({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 z=to(o,{allAuthors:!0});if(z.status==="error")return p(z);i=z.oxml,f=!0;let M=j(i,"text/xml");c.push(...M.warnings),g=M.doc;let Z=g?re(g):null;if(M.error||Z){let le=M.error?.message||Z?.textContent||"Could not parse OOXML after accepting existing revisions.";return ee("[OxmlEngine] XML parse error after accepting existing revisions:",le),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:le}})}At(g,x)}else return k("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let N=Di(g,t,n);if(N.hasTableWrapper&&N.targetParagraph&&!n._isolatedTableCell){k("[OxmlEngine] Isolating table-cell paragraph before diff");let z=lr(g,N.targetParagraph,l),M=await so(z,t,r,{...n,_isolatedTableCell:!0});return!M.hasChanges&&M.status==="no-op"?b():M}let T=n.sanitizeInput===!0?lo(r):r;T!==r&&u.push("Input was sanitized; pass sanitizeInput: false to disable.");let v=null;if(n.structuredContent!==!1)if(v=Xr(T),v.valid)v.requiresStructuredContent&&(T=v.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let z=v.issues.map(M=>`${M.code}: ${M.message}`).join(" ");return p({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:z},warnings:v.issues.map(M=>M.message)})}v=null}let{cleanText:S,formatHints:I}=Ie(T),_=m==="slice-cross-author"?S!==t:S.trim()!==t.trim(),L=I.length>0,{existingFormatHints:F,textSpans:X,paragraphs:C}=Ri(g),U=F.length>0,R=X.map(z=>ba(z)).join(""),B=t.includes(`
161
- `)||t.includes("\r")?t.split(/\r?\n/).map(Zr).filter(Boolean).every(z=>C.some(M=>{let Z=X.filter(le=>le.paragraph===M).map(ba).join("");return Zr(Z).includes(z)})):R.includes(t.trim())||R.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||Zr(R).includes(Zr(t));if(_&&typeof t=="string"&&t.trim()&&!B)return k("[OxmlEngine] Target text not found in OOXML"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let $=null,Y=()=>($||($=Wr(g,C,X)),$),V=(z=null)=>{let M=Xi(g,t,I,l,s,a,z);return M.useNativeApi?(k("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),Zn(g,t,S,l,s,I,a)):M};k(`[OxmlEngine] Text changes: ${_}, New format hints: ${I.length}, Existing format hints: ${F.length}`);let K=n.removeFormatting===!0&&!_&&!L&&U;if(!_&&!L&&!U)return et(n,"noChange"),k("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),b();if(!_&&!L&&U&&!K)return k("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),b();if(K){et(n,"formatOnly",{removeFormatting:!0}),k("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let z=N,M=z.targetParagraph||null;if(!M){let Te=_i(Y(),t);Te&&(M=Te.paragraph)}let Z=F;M&&(Z=F.filter(Te=>Bi(Te.run)===M));let le=$i(g,X,Z,l,s,a);return z.hasTableWrapper&&M?p({oxml:lr(g,M,l),hasChanges:le.hasChanges}):p(le)}if(!_&&L){et(n,"formatOnly",{removeFormatting:!1}),k(`[OxmlEngine] Format-only change detected: ${I.length} format hints`);let z=N,M={textSpans:X,paragraphs:C,paragraphInfos:Y()};if(z.hasTableWrapper&&z.targetParagraph){k("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let Z=V(M);return k("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),p({oxml:lr(g,z.targetParagraph,l),hasChanges:Z.hasChanges})}return p(V(M))}let Be=ve(g,E,"tbl").length>0,Gt=/^\|.+\|/.test(S.trim())&&S.includes(`
162
- `),bn=qt(S),ms=n.structuredContent!==!1&&v?.requiresStructuredContent===!0,dt=N,Oo=Be||m==="slice-cross-author";k(`[OxmlEngine] Mode: ${Oo?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${I.length}, isMarkdownTable: ${Gt}, isTargetList: ${bn}, isTableCellParagraph: ${dt.isTableCellParagraph}`);try{if(Gt&&!Be)return et(n,"table",{transformation:"text-to-table"}),k("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),p(sa(g,S,l,null,s,a));if(Be&&Gt)return et(n,"table",{transformation:"table-reconciliation"}),p(aa(g,S,l,null,s,a));if(Oo){et(n,"surgical",{tableScoped:Be});let z=dt.hasTableWrapper&&dt.targetParagraph?dt.targetParagraph:null;z&&k("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let M=Ji(g,t,S,l,s,I,a,z,{},n);return M.status==="error"&&M.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?p({...M,oxml:o,hasChanges:!1}):dt.hasTableWrapper&&M.hasChanges&&dt.targetParagraph?(k("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),p({oxml:lr(g,dt.targetParagraph,l),hasChanges:!0})):p(M)}if(bn||ms){let z=ve(g,E,"p"),M=z.length===1;et(n,M?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:z.length}),k(`[OxmlEngine] \u{1F3AF} Using ${M?"direct list generation":"compatibility pipeline"} for list reconciliation`);let Z;if(M){let le=Rt(i,{xmlDoc:g}),Te=nr(z[0]);Z=await Ot({cleanText:S,numberingContext:Te,originalRunModel:le.runModel,originalText:le.acceptedText,generateRedlines:a,author:s,font:n.font||null,revisionIdAllocator:x,numberingService:new qe})}else Z=await new ir({author:s,generateRedlines:a,revisionIdAllocator:x}).execute(i,T,{xmlDoc:g});if(Z.error?.code==="DIFF_TOKEN_LIMIT")return p({oxml:o,hasChanges:!1,status:"error",error:Z.error});if(Z.isValid&&Z.ooxml&&Z.ooxml!==i){let le=Z.includeNumbering===!0;k(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${le}`);let Te=at(Z.ooxml,{includeNumbering:le,numberingXml:Z.numberingXml});return k(`[OxmlEngine] \u2705 Wrapped OOXML length: ${Te.length}`),p({oxml:Te,hasChanges:!0,...Array.isArray(Z.warnings)?{warnings:Z.warnings}:{}})}return b()}return et(n,"reconstruction"),p(Zn(g,t,S,l,s,I,a,{},n))}catch(z){if(ri(z))return p({oxml:o,hasChanges:!1,status:"error",error:{code:z.code,message:z.message}});throw z}}function Zr(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function ba(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 lo(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 tt(e){return j(e,"application/xml").doc}function vt(e){return ne(e)}function Qr(e){return Array.from(e||[])}function dr(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function Se(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var Oe="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function xa(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=Qr(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=Qr(e.getElementsByTagName(`w:${t}`));return r.length>0?r:Qr(e.getElementsByTagName(t))}function ue(e){return e?be(e):""}function Ee(e){if(!e)return[];let t=xa(e,"body"),r=t.length>0?t[0]:e;return xa(r,"p")}function yt(e){return e&&Qr(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function Ft(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:be(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:Ee(e.ownerDocument||e).indexOf(e)+1,i=t.paragraphId===void 0?yt(e):t.paragraphId,a=typeof t.inTable=="boolean"?t.inTable:pr(e),l=`${i||""}${o}${a?"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 Na(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=Ee(e),o=[],i=new Map,a=new Map,s=new Map;for(let l=0;l<n.length;l++){let c=n[l],u=be(c,{revisionView:r}),f=yt(c),m=pr(c),d=H(u),p=Object.freeze({paragraph:c,index:l+1,paragraphId:f,text:u,normalizedText:d,revisionView:r,fingerprint:Ft(c,{text:u,index:l+1,paragraphId:f,inTable:m,revisionView:r}),inTable:m});o.push(p),i.set(c,p),f&&!a.has(f)&&a.set(f,p),d&&(s.has(d)||s.set(d,[]),s.get(d).push(p))}for(let[l,c]of s)s.set(l,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:i,byId:a,byNormalizedText:s})}function H(e){return String(e||"").replace(/\s+/g," ").trim()}function fo(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
164
- `)}function mo(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 Oc(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function kc(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 va(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:Ee(e)[t-1]||null}function $t(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 en(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,i=o?null:Ee(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 co(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,i=o?.entries||null,a=i?null:Ee(e),s=String(t||"").trim();if(!s)return null;let l=en(e,s,{paragraphMetadataIndex:o});if(l)return l;let c=H(s),u=i?i.find(h=>h.normalizedText.length>10&&c.startsWith(h.normalizedText))?.paragraph||null:a.find(h=>{let g=H(ue(h));return g.length>10&&c.startsWith(g)});if(u)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${ue(u).trim().slice(0,60)}..."`),u;let f=i?i.find(h=>h.normalizedText.length>15&&c.includes(h.normalizedText))?.paragraph||null:a.find(h=>{let g=H(ue(h));return g.length>15&&c.includes(g)});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(h=>h.length>2)),b=i?.length??a.length;for(let h=0;h<b;h++){let g=i?.[h]?.paragraph??a[h],w=(i?.[h]?.text??ue(g)).trim();if(!w)continue;let N=H(w).toLowerCase().split(/\s+/).filter(T=>T.length>2).filter(T=>p.has(T)).length/Math.max(p.size,1);N>m&&N>.5&&(m=N,d=g)}return d?(n(`[Fuzzy] Best word-overlap match (${(m*100).toFixed(0)}%): "${ue(d).trim().slice(0,60)}..."`),d):null}function ya(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=mo(i?.index??i?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,u=t.paragraphMetadataIndex||null;if(u&&u.revisionView!==a?u=t.metadataIndices?.[a]||Na(e,{revisionView:a}):u||(u=Na(e,{revisionView:a})),i?.paragraphId){let m=_c(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??Ee(e).indexOf(m)+1,b=d?.fingerprint||Ft(m,{revisionView:a}),h=d?.inTable??pr(m),g=d?.normalizedText||H(be(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?[Ue(d)]:null);if(i.fingerprint&&i.fingerprint!==b)throw Se("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches its source fingerprint.`,d?[Ue(d)]:null);if(typeof i.inTable=="boolean"&&i.inTable!==h)throw Se("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" does not match the requested table context.`,d?[Ue(d)]:null);if(s&&g!==H(s))throw Se("TARGET_TEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches the supplied text.`,d?[Ue(d)]:null);if(i.occurrence!=null){let x=tn(e,s||g,u),y=x.findIndex(N=>N.paragraph===m)+1;if(y===0||y!==i.occurrence)throw Se("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${i.paragraphId}" matches occurrence ${y}, not requested occurrence ${i.occurrence}.`,x.map(Ue))}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(Ue)):Se("TARGET_NOT_FOUND",`Target fingerprint not found: "${i.fingerprint}".`)}let f=[];if(s){let m=tn(e,s,u);if(f=Mc(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(Ue));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(Ue));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(Ue));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(Ue));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(Ue));if(f.length===0)throw dr(`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=va(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=en(e,s,{paragraphMetadataIndex:u}),b=(d?.text||be(m,{revisionView:a})).trim(),h=H(b),g=H(s),w=h!==g;if(w&&p&&p!==m)return r(`[Target] [P${l}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let x=co(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=en(e,s,{paragraphMetadataIndex:u});if(m){let p=f.length;if(p>1){let b=`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(b),{paragraph:m,resolvedBy:"strict_text",warnings:[b]}}return{paragraph:m,resolvedBy:"strict_text"}}let d=co(e,s,{onInfo:r,paragraphMetadataIndex:u});if(d)return{paragraph:d,resolvedBy:"fuzzy_text"}}throw dr(s?`Target paragraph not found: "${s}"`:l?`Target paragraph reference not found: [P${l}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function pr(e){return!!$t(e,"tbl")}function tn(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=Ee(e),s=[];for(let l=0;l<a.length;l++){let c=a[l],u=be(c,{revisionView:i}).trim();u&&H(u)===n&&s.push({paragraph:c,index:l+1,inTable:pr(c),paragraphId:yt(c),fingerprint:Ft(c,{text:u,index:l+1,revisionView:i}),text:u,revisionView:i})}return s}function Ue(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function Mc(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 _c(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:Ee(e).find(n=>yt(n)===t)||null:null}function Lc(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 Bc(e,t=null){let r=t?.entries||null,n=r?null:Ee(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??pr(s)})}return o}function uo(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=ya(e,t),o=mo(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=tn(e,m,t.paragraphMetadataIndex||null),p=Lc(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 dr(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function Fc(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=uo(e,{targetRef:t,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!l)return null;let c=uo(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(b=>b&&b.parentNode===p)?null:d}function rn(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 Ta(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 Ea(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=He(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function Aa(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=Qt(i,{indentSpaces:2});if(a){n=!0,r.push({kind:"list",markerType:a.markerType,level:a.level,marker:a.marker,outlineLevel:a.outlineLevel,text:Ea(a.text)});continue}r.push({kind:"text",text:i.trim()})}return{items:r,hasListMarkers:n}}function Sa(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function gr(e,t){return H(e)===H(t)}function nn(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function $c(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 gr(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let i=n.level||0;return o.some(s=>(s.level||0)>i)?!1:gr(n.text,t)}return!1}function Xc(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 Dc(e,t,r,n){let o=e[0],i=e.slice(1).filter(a=>a.kind==="list");if(o?.kind==="text"&&gr(o.text,t)&&i.length>0){let a=i[0].level;return i.map(s=>({ilvl:nn(s,r,a),markerType:s.markerType||n,text:s.text}))}if(e.every(a=>a.kind==="list")){let a=e[0];if(!a||!gr(a.text,t))return null;let s=a.level;return e.slice(1).map(l=>({ilvl:nn(l,r,s),markerType:l.markerType||n,text:l.text})).filter(l=>l.text)}return null}function rt(e){if(!e)return null;let t=rn(e,"pPr");if(!t)return null;let r=rn(t,"numPr");if(!r)return null;let n=rn(r,"numId");if(!n)return null;let o=Ta(n);if(!o||o==="0")return null;let i=rn(r,"ilvl"),a=Ta(i),s=Number.parseInt(a||"0",10);return{numId:String(o),ilvl:Number.isFinite(s)?s:0}}function Ia(e){let t=rt(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=rt(n[i-1]);if(!s||s.numId!==t.numId)break;i--}let a=o;for(;a<n.length-1;){let s=rt(n[a+1]);if(!s||s.numId!==t.numId)break;a++}return n.slice(i,a+1)}function zc(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
- `)||!rt(e))return null;let s=Ia(e);if(!s||s.length===0)return null;let l=Aa(i);if(!l.hasListMarkers||l.items.length<2)return null;let c=H(r.currentParagraphText||ue(e)),f=l.items.filter(v=>v.kind==="list")[0]?.markerType||"bullet",m=s.map(v=>({paragraph:v,list:rt(v),text:String(ue(v)||"").trim()})),d=s.indexOf(e);if(d<0)return null;let p=Math.min(...m.map(v=>v.list?.ilvl??0)),b=m.map(v=>Sa((v.list?.ilvl??0)-p,f,v.text)),h=null,g=l.items[0],w=l.items.slice(1).filter(v=>v.kind==="list");if(g?.kind==="text"&&gr(g.text,c)&&w.length>0){let v=Math.max(0,(m[d].list?.ilvl??0)-p),S=w[0].level;h=[{level:v,markerType:f,text:m[d].text},...w.map(I=>({level:nn(I,v,S),markerType:I.markerType||f,text:I.text}))]}else if(l.items.every(v=>v.kind==="list")){let v=Math.max(0,(m[d].list?.ilvl??0)-p),S=l.items[0].level;h=l.items.map(I=>({level:nn(I,v,S),markerType:I.markerType||f,text:I.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let x=h.map(v=>Sa(v.level,v.markerType,v.text)),y=b.slice(0,d).concat(x).concat(b.slice(d+1)),N=b.join(`
166
- `),T=y.join(`
167
- `);return T===N?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:s,originalText:N,modifiedText:T})}function Wc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
168
- `))return null;let a=rt(e);if(!a)return null;let s=Aa(i);if(!s.hasListMarkers||s.items.length<2)return null;let l=H(r.currentParagraphText||ue(e)),u=s.items.filter(d=>d.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,a.ilvl),m=Dc(s.items,l,f,u);return!m||m.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):($c(s.items,l,f)&&(m=Xc(m,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:a.numId,entries:m})}function hr(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
169
- `),n=[];for(let a of r){if(!a.trim())continue;let s=Qt(a,{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:a.trim()})}if(n.length===0)return null;let o=n.some(a=>a.type==="numbered"),i=n.some(a=>a.type==="bullet");return{type:o?"numbered":i?"bullet":"text",items:n}}function po(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function Uc(e,t,r){let n=new Map,o=[];for(let i of e){let a=Math.max(0,Number(i?.level)||0);for(let u of Array.from(n.keys()))u>a&&n.delete(u);let s=(n.get(a)||0)+1;n.set(a,s);let l=Hc(s,t,r),c=" ".repeat(a*4);o.push(`${c}${l} ${i.text||""}`.trimEnd())}return o.join(`
170
- `)}function jc(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let o=String(n??""),i=o.match(/^(\s*)/),a=i?i[1].length:0,s=Math.floor(a/r),l=o.trim(),c=null,u=$e(l,{allowZeroSpaceAfterMarker:!0});return u&&(c=u[2].trim()||null,l=He(l,{allowZeroSpaceAfterMarker:!0})),{text:l.trim(),level:s,removedMarker:c}})}function Hc(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${Pa(e,!1)}.`;case"upperAlpha":return`${Pa(e,!0)}.`;case"lowerRoman":return`${Ra(e,!1)}.`;case"upperRoman":return`${Ra(e,!0)}.`;default:return`${e}.`}}function Pa(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 Ra(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[i,a]of n)for(;r>=i;)o+=a,r-=i;return t?o:o.toLowerCase()}function on(e){let t=String(e||"");if(!t.trim()||t.includes(`
171
- `))return null;let r=hr(t);if(!r||!po(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"?Zt(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:i,startAt:Gc(o,i),contentText:String(n.text||"").trim(),normalizedContent:H(String(n.text||""))}}function Vc(e){let t=on(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function Gc(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 Kc(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 Yc(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 Jc(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function Xt(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 qc(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=Xt(l,"pPr");if(u||(u=O(c,"w:pPr"),l.insertBefore(u,l.firstChild)),o){let p=Xt(u,"pPrChange");p&&u.removeChild(p)}if(i){let p=Xt(u,"listPr");p&&u.removeChild(p)}let f=Xt(u,"numPr");f||(f=O(c,"w:numPr"),u.appendChild(f));let m=Xt(f,"ilvl");m||(m=O(c,"w:ilvl"),f.appendChild(m)),m.setAttribute("w:val",String(n));let d=Xt(f,"numId");d||(d=O(c,"w:numId"),f.appendChild(d)),d.setAttribute("w:val",String(r)),s++}return s}function Zc(e){let t=j(e,"application/xml").doc;return!t||re(t)?null:Ee(t)[0]||null}function Qc(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function eu(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function Dt(e,t){let r=eu(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Ca(e,t){e.setAttribute("w:val",String(t))}function tu(e){let t=j(e,"application/xml").doc;if(!t||re(t))return null;let o=Ee(t)[0]||null;if(!o)return null;let i=Array.from(o.getElementsByTagNameNS("*","numId"));for(let a of i){let s=Dt(a,["w:val","val"]);if(s!=null)return String(s)}return null}function ru(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,i=me(),a=j(e,"application/xml").doc;if(!a||re(a))return e;let c=Array.from(a.getElementsByTagNameNS("*","num")).find(p=>{let b=Dt(p,["w:numId","numId"]);return b!=null&&String(b)===String(t)});if(!c)return e;let u=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=Dt(u,["w:val","val"]),m=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>Dt(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)),Ca(d,r),o&&f!=null){let b=Array.from(a.getElementsByTagNameNS("*","abstractNum")).find(h=>{let g=Dt(h,["w:abstractNumId","abstractNumId"]);return g!=null&&g===f})||null;if(b){let h=Array.from(b.getElementsByTagNameNS("*","lvl")).find(w=>Dt(w,["w:ilvl","ilvl"])===0)||null;h||(h=O(a,"w:lvl"),h.setAttribute("w:ilvl","0"),b.appendChild(h));let g=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;g||(g=O(a,"w:start"),h.insertBefore(g,h.firstChild)),Ca(g,r)}}return i.serializeToString(a)}function go(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=Zc(t);if(!i)return null;let a=rt(i);if(a&&!o)return null;let s=Ie(n).cleanText||n,l=on(n)||on(s);if(!l)return null;let c=on(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 an(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 Ot({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new qe}),i=o?.oxml||o?.ooxml||"",a=Qc(i),s=tu(a),l=ru(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 nu=new Set(["ins","del","rPrChange","pPrChange"]),ou=/^\d{4}-\d{2}-\d{2}T/;function ft(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Tt(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>ft(r)===t)}function St(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function iu(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function au(e){return ft(e.parentNode)==="rPr"}function su(e){let t=r=>{let n=Bo(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 lu(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}:su(e);if(!o)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${i}`),{valid:!1,issues:t};let a=Tt(o,"ins"),s=Tt(o,"del"),l=a.concat(s);for(let f of Tt(o,"p")){let m=Array.from(f.getElementsByTagName("*")).find(d=>d!==f&&ft(d)==="p");m&&r("NESTED_PARAGRAPH","error",`<${f.nodeName}> contains nested <${m.nodeName}>.`)}for(let f of Tt(o,"body")){let m=Array.from(f.childNodes||[]).filter(p=>p.nodeType===1),d=m.map((p,b)=>ft(p)==="sectPr"?b:-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(ft(p))).find(p=>ft(f)!=="ins"||ft(p)!=="del"?!0:p.parentNode!==f);d&&r("NESTED_REVISION","error",`<${f.nodeName}> (w:id="${St(f,"id")}") contains invalid nested <${d.nodeName}>.`)}for(let f of s)Tt(f,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${St(f,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let f of l){let m=[];St(f,"id")||m.push("w:id"),St(f,"author")||m.push("w:author"),ou.test(St(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(!nu.has(ft(f)))continue;let m=St(f,"id");m&&(c.has(m)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${m} appears more than once.`),c.add(m))}let u=Tt(o,"t").concat(Tt(o,"delText"));for(let f of u){let m=f.textContent||"";/^\s|\s$/.test(m)&&iu(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(au(f))continue;Array.from(f.childNodes||[]).some(d=>d.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${f.nodeName}> (w:id="${St(f,"id")}") wraps no content.`)}for(let f of wa(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 sn(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Oe&&r.localName===t):[]}function cu(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function uu(e){let t=sn(e,"tr"),r=t.map(o=>sn(o,"tc").map(a=>{let s=sn(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 fu(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=>cu(l)).join(" | ")} |`;return[a(n),a(o),...i.map(a)].join(`
173
- `)}function mu(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>H(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function Oa(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 du(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:ue;if(!e||!e.parentNode)return null;let o=[e],i=e.nextSibling,a=0;for(;i&&a<r;){a+=1;let s=i.nextSibling;if(i.nodeType!==1||i.namespaceURI!==Oe||i.localName!=="p"){i=s;continue}let l=String(n(i)||"").trim();if(!l){if(o.length>1)break;i=s;continue}if(!Oa(l))break;o.push(i),i=s}return o.length>1?o:null}function pu(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
174
- `)||fo(i))return null;let a=i.split(/\r?\n/g).map(y=>y.trim()).filter(Boolean);if(a.length<2)return null;let s=r.tableElement||$t(e,"tbl"),l=$t(e,"tr"),c=$t(e,"tc");if(!s||!l||!c)return null;let u=H(r.currentParagraphText||ue(e)),f=H(a[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:m,rowElements:d,columnCount:p}=uu(s);if(m.length===0||p===0)return null;let b=d.indexOf(l),g=sn(l,"tc").indexOf(c);if(b<0||g<0||g>=p)return null;m[b][g]=a[0];let w=mu(m[b]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let y=1;y<a.length;y++){let N=b+y,T=a[y];if(N<m.length&&!H(m[N][g]))if(w)for(let v=0;v<p;v++)H(m[N][v])||(m[N][v]=T);else m[N][g]=T;else{let v=new Array(p).fill("");if(w)for(let S=0;S<p;S++)v[S]=T;else v[g]=T;m.splice(Math.min(N,m.length),0,v)}}let x=fu(m,p);return x?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),x):null}function zt(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 Wt(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 i=1;i<=r;i+=1)if(!o.has(i))return i}return n}function gu(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,i=new Set;if(String(e||"").trim())try{let u=tt(e),f=Array.from(u.getElementsByTagNameNS("*","abstractNum")),m=Array.from(u.getElementsByTagNameNS("*","num"));for(let d of f){let p=zt(d,["w:abstractNumId","abstractNumId"]);p!=null&&i.add(p)}for(let d of m){let p=zt(d,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let a=o.size>0?Math.max(...o):0,s=i.size>0?Math.max(...i):0,l=Math.max(r,a+1),c=Math.max(r,s+1);return{nextNumId:Wt(l,o,n),nextAbstractNumId:Wt(c,i,n),usedNumIds:o,usedAbstractNumIds:i,minId:r,maxPreferred:n}}function hu(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=Wt(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=Wt(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function br(e,t="num"){let r=hu(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=Wt(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=Wt(o+1,r.usedNumIds,r.maxPreferred)),o)}function wu(e){let t=br(e,"num"),r=br(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function ho(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function ln(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Oe&&e.localName===t)}function ka(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(i=>i&&i.nodeType===1&&i.namespaceURI===Oe),o=null;r==="abstract"?o=n.find(i=>i.localName==="num"||i.localName==="numIdMacAtCleanup")||null:o=n.find(i=>i.localName==="numIdMacAtCleanup")||null,o?e.insertBefore(t,o):e.appendChild(t)}function bu(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function wr(e,t){let r=bu(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Ma(e,t,r){e?.setAttribute?.(t,String(r))}function wo(e,t){e?.setAttribute?.("w:val",String(t))}function xu(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)wo(o,t)}}function Nu(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let o=wr(n,["w:val","val"]);if(o!=null)return String(o)}}return null}function vu(e,t,r){let n=String(e),o=String(t),i=Number.isInteger(r)&&r>0?r:1,a=Array.from({length:9},(s,l)=>{let c=Array.from({length:l+1},(f,m)=>`%${m+1}`).join(".")+".",u=720*(l+1);return`
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 _l(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 Ll(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=C(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c);let u=C(e,"w:bCs");u.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,u)}if(i){let c=C(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c);let u=C(e,"w:iCs");u.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,u)}if(a){let c=C(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),Lt(t,c)}if(s){let c=C(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c)}}function Ri(e,t,r){Ll(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 Bl(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||Bl(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 Fl(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&&M(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let c=Oi(a);for(let u of c)n=Fl(u,a,n,r,t,l);n=pt(n,i,o.length)}return M(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var $l=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())$l.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(!A(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=C(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 Xl(e,t){let r=_i(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=C(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function Dl(e,t){let r=_i(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=C(e,"w:rPr"),t.appendChild(r)),r}function Li(e,t,r,n,o=null){let i=Xl(e,t),a=Dl(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=C(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=C(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Fi(e,o,t),o;let i=C(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=C(e,"w:r");if(r&&o.appendChild(r),!n)return Fi(e,o,t),o;let i=C(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(C(e,"w:tab"));continue}if(i===`
144
+ `){t.appendChild(C(e,"w:br"));continue}if(i==="\u2011"){t.appendChild(C(e,"w:noBreakHyphen"));continue}let a=C(e,"w:t");/^\s|\s$/.test(i)&&a.setAttribute("xml:space","preserve"),a.textContent=i,t.appendChild(a)}}function Bt(e,t,r,n,o){let i=C(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)||i.appendChild(l.cloneNode(!0))});let a=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&o&&zl(e,i,n,t);let s=(l,c,u=null,f="0")=>{let m=C(e,l);c?u&&m.setAttribute("w:val",u):f&&m.setAttribute("w:val",f);let d=sr.indexOf(l),p=d===-1?999:d,h=!1;for(let w of Array.from(i.childNodes)){if(w.nodeType!==1)continue;let b=sr.indexOf(w.nodeName);if((b===-1?999:b)>p){i.insertBefore(m,w),h=!0;break}}h||i.appendChild(m)};return s("w:b",!!a.bold,"1","0"),s("w:bCs",!!a.bold,"1","0"),s("w:i",!!a.italic,"1","0"),s("w:iCs",!!a.italic,"1","0"),s("w:u",!!a.underline,"single","none"),s("w:strike",!!a.strikethrough,"1","0"),i}function jn(e,t,r,n,o){let i=C(e,"w:rPrChange"),a=ie(r,e,"rPrChange");i.setAttribute("w:id",String(a.id)),i.setAttribute("w:author",a.author),i.setAttribute("w:date",n||a.date);let l=jr(o||t)||C(e,"w:rPr");i.appendChild(l);let c=ae(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(i),i}function zl(e,t,r,n){jn(e,t,r,null,n||t)}var Wl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Ft(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Wl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Vr(e,t,r){let n=new Map;for(let a of r)!a||!a.paragraph||(n.has(a.paragraph)||n.set(a.paragraph,[]),n.get(a.paragraph).push(a));let o=[],i=0;return t.forEach((a,s)=>{let l=(n.get(a)||[]).slice().sort((m,d)=>m.charStart-d.charStart),c=Ul(l),u=Hn(c),f=u.trim();o.push({paragraph:a,spans:l,text:c,normalizedText:u,normalizedTrim:f,startOffset:i}),i+=u.length,i=pt(i,s,t.length)}),o}function $i(e,t){if(!t)return null;let r=Hn(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 Xi(e,t){let r=Hn(t),n=r.trim(),o=null,i=0;for(let a of e)if(a.normalizedText===r)return o=a,{targetInfo:o,matchOffset:i};if(n.length>0){for(let a of e)if(a.normalizedTrim===n)return o=a,{targetInfo:o,matchOffset:i}}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,i=s-c;break}}}if(!o&&e.length===1&&r.length>0){let a=e[0],s=a.normalizedTrim||"";if(s.length>0){let l=r.indexOf(s);l>=0&&(o=a,i=-l)}}return{targetInfo:o,matchOffset:i}}function Di(e){let t=e;for(;t;){if(Ft(t,"p"))return t;t=t.parentNode}return null}function Ul(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;Ft(n,"t")?t+=r.textElement.textContent||"":Ft(n,"tab")?t+=" ":Ft(n,"br")||Ft(n,"cr")?t+=`
146
+ `:Ft(n,"noBreakHyphen")&&(t+="\u2011")}return t}function Hn(e){return e?e.replace(/\r/g,`
147
+ `).replace(/\u00a0/g," "):""}function zi(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),i=[],a=0;for(let s of o){for(;a<n.length&&n[a]<=s.charStart;)a++;let l=s;for(;a<n.length&&n[a]<l.charEnd;){let c=n[a],u=jl(e,l,c);if(!u){a++;continue}i.push(u[0]),l=u[1],a++}i.push(l)}return i}function jl(e,t,r){let n=t.runElement,o=n.parentNode;if(!o)return null;let i=t.textElement.textContent||"",a=r-t.charStart,s=i.substring(0,a),l=i.substring(a);if(s.length===0||l.length===0)return null;let c=st(e,s,t.rPr,!1),u=st(e,l,t.rPr,!1);o.insertBefore(c,n),o.insertBefore(u,n),o.removeChild(n);let f=c.getElementsByTagName("w:t")[0],m=u.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:c},{...t,charStart:r,textElement:m,runElement:u}]}var Hl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Vl(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Hl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Gl(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 Wi(e,t,r,n,o,i=!0){let a=!1,s=new Set;M(`[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;M("[OxmlEngine] Processing run for surgical format removal, format:",l.format);let u=ae(c,"w:rPr");u||(u=C(e,"w:rPr"),c.insertBefore(u,c.firstChild)),i&&jn(e,u,o||de()),Ri(e,u,l.format),a=!0}return a?(M("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(M("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function Kl(e,t,r,n,o,i=!0){let a=!1,s=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let l=[];for(let m of r)l.push(m.start,m.end);let u=zi(e,t,l).slice().sort((m,d)=>m.charStart-d.charStart||m.charEnd-d.charEnd),f=Yl(r);for(let m of u){if(!m||!m.textElement||!Vl(m.textElement,"t"))continue;let d=f(m.charStart,m.charEnd);if(d.length===0)continue;let p=An(...d.map(L=>L.format)),h={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},w=m.format||qe(m.rPr),b={bold:!!w.bold,italic:!!w.italic,underline:!!w.underline,strikethrough:!!w.strikethrough};if(!["bold","italic","underline","strikethrough"].some(L=>h[L]!==b[L])||s.has(m.runElement)||(s.add(m.runElement),!(m.textElement.textContent||""))||!m.runElement.parentNode)continue;let T=m.runElement,y=ae(T,"w:rPr"),S=Bt(e,y,h,o||de(),i),I=y;if(!I)T.insertBefore(S,T.firstChild);else{for(;I.firstChild;)I.removeChild(I.firstChild);Array.from(S.childNodes).forEach(L=>I.appendChild(L))}a=!0}return{oxml:n.serializeToString(e),hasChanges:a}}function Ui(e,t,r,n,o,i=!0,a=null){let s=Gl(a),l=s.paragraphs||Pe(e),c=s.textSpans||[];if(s.textSpans||({textSpans:c}=ki(l)),!c||c.length===0)return Be("[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||Vr(e,l,c),{targetInfo:f,matchOffset:m}=Xi(u,t);if(!f||!f.spans||f.spans.length===0)return Be("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let d=f.spans[0].charStart,p=f.spans.map(w=>({...w,charStart:w.charStart-d,charEnd:w.charEnd-d})),h=r.map(w=>({...w,start:w.start+m,end:w.end+m}));return Kl(e,p,h,n,o,i)}function Yl(e){let t=(e||[]).slice().sort((o,i)=>o.start-i.start||o.end-i.end),r=[],n=0;return(o,i)=>{for(;n<t.length&&t[n].start<i;)r.push(t[n]),n++;for(let a=r.length-1;a>=0;a--)r[a].end<=o&&r.splice(a,1);return r.filter(a=>a.start<i&&a.end>o)}}function Gr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function bt(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let i=Gr(o);if(n==="accepted"&&(i==="del"||i==="moveFrom")||n==="rejected"&&(i==="ins"||i==="moveTo"))return!1;o=o.parentNode}return!0}function xt(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!bt(e,n,r))return"";let o="",i=a=>{for(let s of Array.from(a?.childNodes||[])){if(s?.nodeType!==1||s.namespaceURI&&s.namespaceURI!==E||!bt(s,n,r))continue;let l=Gr(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":i(s)}};return i(e),o}var lt=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Kr(e,t={}){if(!e)return[];let r=[];function n(f,m,d){for(let p of Array.from(f?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==E)continue;let h=Gr(p);if(h==="pPr"||h==="rPr")continue;let w=m;h==="ins"?w={kind:"insertion",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:h==="del"?w={kind:"deletion",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:h==="moveFrom"?w={kind:"move_from",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:h==="moveTo"&&(w={kind:"move_to",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0});let b=d;h==="r"&&(b=p);let g=null,x=w?w.kind:"baseline",N=w?.author,v=w?.revisionId;h==="t"?g=p.textContent||"":h==="delText"?(g=p.textContent||"",w||(x="deletion")):h==="tab"?g=" ":h==="br"||h==="cr"?g=`
149
+ `:h==="noBreakHyphen"?g="\u2011":h==="softHyphen"&&(g="\xAD"),g!==null?g.length>0&&r.push({text:g,kind:x,author:N,revisionId:v,carrier:b||p,carrierContainer:(b||p)?.parentNode||null}):n(p,w,b)}}let o=Gr(e)==="r"?e:null;if(n(e,null,o),r.length===0)return[];let i=t.mergeRuns!==!1,a=[],s=null;for(let f of r){if(!s){s={...f};continue}let m=s.kind===f.kind,d=s.author===f.author,p=s.revisionId===f.revisionId,h=s.carrier===f.carrier,w=i&&s.carrierContainer===f.carrierContainer;m&&d&&p&&(h||w)?s.text+=f.text:(a.push(s),s={...f})}s&&a.push(s);let l=0,c=0,u=[];for(let f of a){let m=f.kind!=="deletion"&&f.kind!=="move_from",d=f.kind!=="insertion"&&f.kind!=="move_to",p=m?l:null,h=d?c:null;m&&(l+=f.text.length),d&&(c+=f.text.length);let w={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:h};f.author!==void 0&&(w.author=f.author),f.revisionId!==void 0&&(w.revisionId=f.revisionId),u.push(w)}return u}function pe(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Kr(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 Jl="http://schemas.microsoft.com/office/word/2010/wordml";function ji(e,t,r={}){let{targetParagraphId:n=null}=r,o=ve(e,E,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let a=Pe(e).filter(l=>{let c=l.parentNode;for(;c;){if(A(c,"tc"))return!0;c=c.parentNode}return!1});M(`[OxmlEngine] Table wrapper detected: ${o.length} tables, ${a.length} paragraphs in cells`);let s=null;if(n){let l=String(n).toUpperCase();s=a.find(c=>{let u=Zl(c);return u&&u.toUpperCase()===l})||null,s?M(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):M(`[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 a)if(pe(c).trim()===l){s=c,M(`[OxmlEngine] Found target paragraph by text match: "${l.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:a.length>0,targetParagraph:s,paragraphs:a,paragraph:s||a[0]||null,tableElement:o[0]}}function cr(e,t,r){let n=Array.isArray(t)?t:[t],o="";for(let i of n){if(!i)continue;let a=r.serializeToString(i);a=a.replace(/\s+xmlns:w="[^"]*"/g,""),a=a.replace(/\s+xmlns:r="[^"]*"/g,""),a=a.replace(/\s+xmlns:wp="[^"]*"/g,""),o+=a}return M(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),M(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),ql(o)}function ql(e){return wi(e)}function Zl(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(Jl,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function Vn(e){return A(e,"t")||A(e,"delText")?e.textContent||"":A(e,"br")||A(e,"cr")?`
150
+ `:A(e,"tab")?" ":A(e,"noBreakHyphen")?"\u2011":A(e,"softHyphen")?"\xAD":""}function Gn(e){return A(e,"t")||A(e,"delText")||A(e,"br")||A(e,"cr")||A(e,"tab")||A(e,"noBreakHyphen")||A(e,"softHyphen")}function Yr(e){let t="",r=[];return e.forEach((n,o)=>{let i=n.parentNode;for(let a=n.firstChild;a;a=a.nextSibling)if(A(a,"r"))t+=ur(a,n,i,t.length,r).text;else if(A(a,"hyperlink"))for(let s=a.firstChild;s;s=s.nextSibling)A(s,"r")&&(t+=ur(s,n,i,t.length,r).text);else if(A(a,"ins"))for(let s=a.firstChild;s;s=s.nextSibling)A(s,"r")&&(t+=ur(s,n,i,t.length,r).text);else if(A(a,"sdt")){let s=Array.from(a.childNodes||[]).find(l=>A(l,"sdtContent"));if(s)for(let l=s.firstChild;l;l=l.nextSibling)A(l,"r")&&(t+=ur(l,n,i,t.length,r).text)}else if(A(a,"smartTag"))for(let s=a.firstChild;s;s=s.nextSibling)A(s,"r")&&(t+=ur(s,n,i,t.length,r).text);t=Ct(t,o,e.length)}),{fullText:t,textSpans:r}}function ur(e,t,r,n,o){let i=ae(e,"w:rPr"),a=n,s=[];for(let l=e.firstChild;l;l=l.nextSibling)if(A(l,"t")){let c=l.textContent||"";if(c.length===0)continue;o.push({charStart:a,charEnd:a+c.length,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=c.length,s.push(c)}else if(Gn(l)){let c=Vn(l);o.push({charStart:a,charEnd:a+1,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=1,s.push(c)}return{text:s.join("")}}function Jr(e){let t=e.slice().sort((o,i)=>o.charStart-i.charStart||o.charEnd-i.charEnd),r=t.map(o=>o.charStart),n=t.map(o=>o.charEnd);return{spans:t,starts:r,ends:n}}function fr(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=qn(e.ends,t);for(;o<e.spans.length;){let i=e.spans[o];if(i.charStart>=r)break;n(i),o++}}function Kn(e,t){if(e.spans.length===0)return null;let r=qn(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function Yn(e,t){let r=Ql(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function Jn(e,t){let r=qn(e.ends,t)-1;return r>=0?e.spans[r]:null}function qn(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 Ql(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 Hi(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=Kn(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,i=Yn(e,t)||(t>0?Jn(e,t):null),a=e.spans.find(s=>s.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:i,rightSpan:a,containingSpan:n,isInterior:o,fallbackParagraph:r}}var ec=new Set(["ins","del"]);function $t(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(A(n,"rPr")||!Gn(n))continue;let o=Vn(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function Ve(e){return e.length===0?0:e[e.length-1].end}function Ge(e,t,r,n,o){let i=[];return n<=r||t.forEach(a=>{let s=Math.max(r,a.start),l=Math.min(n,a.end);if(l<=s)return;let c=s-a.start,u=l-a.start,f=a.text.slice(c,u);i.push(oc(e,a.node,f,o))}),i}function mr(e,t,r){let n=C(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function Nt(e,t,r,n,o){if(n.length===0)return null;let i=mr(e,n,o);return t.insertBefore(i,r),i}function Vi(e,t,r,n=null){let o=nc(t);if(!ec.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 i=Array.from(t.childNodes||[]),a=i.reduce((m,d)=>m+(A(d,"r")?Ve($t(d)):0),0);if(r>a)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${a}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===a)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let s=t.cloneNode(!1),l=t.cloneNode(!1),c=0;for(let m of i){if(!A(m,"r")){(c<=r?s:l).appendChild(m.cloneNode(!0));continue}let d=$t(m),p=Ve(d),h=c+p;if(h<=r)s.appendChild(m.cloneNode(!0));else if(c>=r)l.appendChild(m.cloneNode(!0));else{let w=r-c,b=Array.from(m.childNodes||[]).find(T=>A(T,"rPr"))||null,g=o==="del",x=Ge(e,d,0,w,g),N=Ge(e,d,w,p,g);s.appendChild(mr(e,x,b));let v=mr(e,N,b);l.appendChild(v)}c=h}let u=tc(e,n);at(l,u);let f=u.next();return rc(l,"id",String(f)),u._receiptCollector?.recordRevision(f,o),{leftCarrier:s,rightCarrier:l}}function tc(e,t){return t instanceof we?t:Ye(e)||nt(e)}function rc(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(E,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function nc(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function oc(e,t,r,n){if(n&&(A(t,"delText")||A(t,"t"))){let i=C(e,"w:delText");return i.setAttribute("xml:space","preserve"),i.textContent=r,i}if(A(t,"t")){let i=t.cloneNode(!1);return i.textContent=r,/^\s|\s$/.test(r)&&i.setAttribute("xml:space","preserve"),i}if(r===`
151
+ `&&(A(t,"br")||A(t,"cr"))||r===" "&&A(t,"tab")||r==="\u2011"&&A(t,"noBreakHyphen")||r==="\xAD"&&A(t,"softHyphen"))return t.cloneNode(!0);if(n){let i=C(e,"w:delText");return i.setAttribute("xml:space","preserve"),i.textContent=r,i}let o=C(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(T=>Object.assign(c,T.format)),!["bold","italic","underline","strikethrough"].some(T=>!!c[T]!==l[T]))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 T=st(e,b,s,!1);m.insertBefore(T,t.runElement)}let N=Bt(e,s,c,i,a),v=Un(e,g,N,!1);if(m.insertBefore(v,t.runElement),x.length>0){let T=st(e,x,s,!1);m.insertBefore(T,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 N=w.find(y=>y.node===x.textElement);if(!N)return;let v=Math.max(0,r-x.charStart),T=Math.min(x.charEnd-x.charStart,n-x.charStart);T<=v||(b=Math.min(b,N.start+v),g=Math.max(g,N.start+T))}),!(!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:A(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&&sc(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:N}=g;Nt(e,x,N,g.beforePieces,g.rPr),h&&g===p&&x.insertBefore(h,N),h&&g.deletedPieces.length>0&&h.appendChild(mr(e,g.deletedPieces,g.rPr));let v=Nt(e,x,N,g.afterPieces,g.rPr);g.globalEnd===n&&!A(x,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:x,referenceNode:v||N.nextSibling,rPr:g.rPr})),x.removeChild(N),f=!0}let w=A(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(v=>v.globalStart<n).reduce((v,T)=>v+T.deletedPieces.reduce((y,S)=>y+(S.textContent||"").length,0),0),N=Math.max(0,n-g-x);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:w,splitOffset:N,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 v=Kn(t,r);if(!v&&r>0&&(v=Yn(t,r)),!v&&r>0&&(v=Jn(t,r)),!v&&t.spans.length>0&&(v=t.spans[t.spans.length-1]),!v)return l?(ct(e,l,null,n,null,o,i,a,s,c),!0):!1;let T=v.runElement.parentNode;if(!T)return l?(ct(e,l,null,n,v.rPr,o,i,a,s,c),!0):!1;let y=!(s&&f==="slice-cross-author"&&ac(T,o));if(s&&f==="slice-cross-author"&&Qn(T,o))return Zn(e,T,Gi(t,T,r),n,v.rPr,o,i,a,s,c);let S=$t(v.runElement),I=S.find(F=>F.node===v.textElement),L=I?I.start+Math.max(0,Math.min(r-v.charStart,v.charEnd-v.charStart)):r<=v.charStart?0:Ve(S);if(L>0&&L<Ve(S)){let F=Ge(e,S,0,L,!1),D=Ge(e,S,L,Ve(S),!1);return Nt(e,T,v.runElement,F,v.rPr),ct(e,T,v.runElement,n,v.rPr,o,i,a,y,c),Nt(e,T,v.runElement,D,v.rPr),T.removeChild(v.runElement),!0}let _=r<=v.charStart?v.runElement:v.runElement.nextSibling;return ct(e,T,_,n,v.rPr,o,i,a,y,c),!0}let p=Hi(t,r,l),h=p.leftSpan&&A(p.leftSpan.runElement?.parentNode,"hyperlink"),w=p.rightSpan&&A(p.rightSpan.runElement?.parentNode,"hyperlink"),b=p.containingSpan&&A(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 v=p.containingSpan,T=v.runElement.parentNode||l;if(!T)return!1;let y=$t(v.runElement),S=y.find(L=>L.node===v.textElement),I=S?S.start+Math.max(0,Math.min(r-v.charStart,v.charEnd-v.charStart)):r<=v.charStart?0:Ve(y);if(I>0&&I<Ve(y)){let L=Ge(e,y,0,I,!1),_=Ge(e,y,I,Ve(y),!1);return Nt(e,T,v.runElement,L,v.rPr),ct(e,T,v.runElement,n,g,o,i,a,s,c),Nt(e,T,v.runElement,_,v.rPr),T.removeChild(v.runElement),!0}}let x=null,N=null;if(u.hyperlink==="outside"){if(w){let v=p.rightSpan.runElement.parentNode;x=v.parentNode||l,N=v}else if(h){let v=p.leftSpan.runElement.parentNode;x=v.parentNode||l,N=v.nextSibling}}else u.hyperlink==="inside"&&(w?(x=p.rightSpan.runElement.parentNode,N=p.rightSpan.runElement):h&&(x=p.leftSpan.runElement.parentNode,N=p.leftSpan.runElement.nextSibling));if(x||(p.rightSpan?(x=p.rightSpan.runElement.parentNode||l,N=p.rightSpan.runElement):p.leftSpan?(x=p.leftSpan.runElement.parentNode||l,N=p.leftSpan.runElement.nextSibling):(x=l,N=null)),u.bookmark&&x&&(u.bookmark==="outside"?(N&&A(N.previousSibling,"bookmarkStart")&&(N=N.previousSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(N=p.leftSpan.runElement.nextSibling.nextSibling)):u.bookmark==="inside"&&(N&&A(N,"bookmarkStart")&&(N=N.nextSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(N=p.leftSpan.runElement.nextSibling))),u.comment&&x)if(u.comment==="outside"){if(N&&A(N.previousSibling,"commentRangeStart")&&(N=N.previousSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let v=p.leftSpan.runElement.nextSibling.nextSibling;v&&(A(v,"commentReference")||A(v,"r"))&&Array.from(v.childNodes||[]).some(y=>A(y,"commentReference"))&&(v=v.nextSibling),N=v}}else u.comment==="inside"&&(N&&A(N,"commentRangeStart")&&(N=N.nextSibling),p.leftSpan&&A(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(N=p.leftSpan.runElement.nextSibling));if(s&&u.revision==="coalesce_same_author"){let v=null,T=null;if(p.leftSpan&&A(p.leftSpan.runElement.parentNode,"ins")){let y=p.leftSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(E,"author"))===o&&(v=y,T=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&A(p.rightSpan.runElement.parentNode,"ins")){let y=p.rightSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(E,"author"))===o&&(v=y,T=p.rightSpan.runElement)}if(v){let y=st(e,n,g,!1);return v.insertBefore(y,T),!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,N,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,ic(o),i,a,s,l,c),m&&u.insertBefore(m,t),u.removeChild(t),!0}function ic(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>A(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 A(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function ac(e,t){return A(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function sc(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||cc(ir(f,r,l),l),h=Jr(m),w=c.pairReplacements===!0,b=[],g=0,x=0,N=!1,v=d?fc(d):[];if(v.length>1&&i.length===0)for(let S of v.slice().reverse()){let I=Yr(u).textSpans,L=Jr(I),_=S.text.replace(/\n/g," ");if(_.length===0)continue;let F=Xt(e,L,S.originalPos,_,o,i,S.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&&(N=!0)}else if(i.length===0){let S=uc(p);for(let I of S.reverse()){let L=Jr(Yr(u).textSpans);if(I.type==="insert"){let D=Xt(e,L,I.start,I.text.replace(/\n/g," "),o,i,I.newPos,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(D&&typeof D=="object"&&D.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:D.error});D===!0&&(N=!0);continue}let _=null,F=null;if(I.type==="replace"&&w&&a&&I.text.replace(/\n/g," ")){let D=qi(L,I.start,I.end,c?.existingRevisions==="slice-cross-author");if(D.safe){let O=rr(o,e);_={id:O.deletionId,author:O.author,date:O.date},F={id:O.insertionId,author:O.author,date:O.date}}else D.structuralBoundary&&b.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(eo(e,L,I.start,I.end,o,a,_)&&(N=!0),I.type==="replace"){let D=Xt(e,L,I.end,I.text.replace(/\n/g," "),o,i,I.newPos,a,u[0]||null,F,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(D&&typeof D=="object"&&D.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:D.error});D===!0&&(N=!0)}}}else for(let S=0;S<p.length;S++){let[I,L]=p[S];if(I===0){let _=L.length,F=g,D=g+_;fr(h,F,D,O=>{let U=Math.max(O.charStart,F),R=Math.min(O.charEnd,D),B=R-U,$=U-F,K=x+$,V=K+B,Y=Ke(i,K,V);Yi(e,O,U,R,Y,o,a)&&(N=!0)}),g+=_,x+=_}else if(I===-1){let _=S+1<p.length&&p[S+1][0]===1,F=!1,D=null,O=null;if(w&&a&&_&&p[S+1][1].replace(/\n/g," ").length>0){let B=qi(h,g,g+L.length,c?.existingRevisions==="slice-cross-author");if(B.safe){let $=rr(o,e);D={id:$.deletionId,author:$.author,date:$.date},O={id:$.insertionId,author:$.author,date:$.date},F=!0}else B.structuralBoundary&&b.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(eo(e,h,g,g+L.length,o,a,D)&&(N=!0),g+=L.length,F){S++;let[,U]=p[S],R=U.replace(/\n/g," ");if(R.length>0){let B=Xt(e,h,g,R,o,i,x,a,u[0]||null,O,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&&(N=!0)}x+=U.length}}else if(I===1){let _=L.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&&(N=!0)}x+=L.length}}let T=u.map(S=>pe(S)).join(`
152
+ `),y=String(r).replace(/\r\n/g,`
153
+ `);if(c.existingRevisions==="slice-cross-author"&&T!==y){let S=lc(y,T);return se({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:S,expectedExcerpt:Zi(y,S),actualExcerpt:Zi(T,S),expectedCodePoint:Qi(y,S),actualCodePoint:Qi(T,S)},...b.length>0?{warnings:[...new Set(b)]}:{}})}return se({oxml:n.serializeToString(e),hasChanges:N,...b.length>0?{warnings:[...new Set(b)]}:{}})}function lc(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 Zi(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}function Qi(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function cc(e,t){let r=[];for(let n=0;n<e.length;n++){let[o,i]=e[n],a=e[n+1];if(o===-1&&a?.[0]===1&&i!==a[1]&&i.length===a[1].length&&i.replace(/\u00a0/g," ")===a[1].replace(/\u00a0/g," ")){r.push(...si(i,a[1],t)),n++;continue}r.push([o,i])}return r}function uc(e){let t=[],r=0,n=0;for(let o=0;o<e.length;o++){let[i,a]=e[o];if(i===0){r+=a.length,n+=a.length;continue}if(i===-1){let s=e[o+1];s?.[0]===1?(t.push({type:"replace",start:r,end:r+a.length,newPos:n,text:s[1]}),r+=a.length,n+=s[1].length,o++):(t.push({type:"delete",start:r,end:r+a.length,newPos:n,text:""}),r+=a.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:a}),n+=a.length}return t}function fc(e){let t=[],r=0,n=0;for(let[o,i]of e)o===0?(r+=i.length,n+=i.length):o===-1?r+=i.length:o===1&&(t.push({originalPos:r,newPos:n,text:i}),n+=i.length);return t}var ra=Xo(Ln(),1);var na=new ra.diff_match_patch;function oa(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function mc(e,t){return e?.getAttributeNS?.(E,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function ta(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let o=0,i=t-1;for(;o<=i;){let a=Math.floor((o+i)/2);e[a].end<=r?o=a+1:i=a-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 dc(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 ia(e,t,r=null){let n=e.documentElement,o=A(n,"body")||oa(n)==="package",i=r||Pe(e),a=ye(e,E,"body");!a&&o&&(a=n);let s="",l=[],c=[],u=[],f=new Map,m=new Map,d=new Set,p={nextCharCode:57344},h=new Set;i.forEach((_,F)=>{let D=s.length;Array.from(_.childNodes).forEach(B=>{s=bc(B,s,l,u,f,m,p,d)}),s=Ct(s,F,i.length);let O=s.length,U=ye(_,E,"pPr"),R=_.parentNode;R&&h.add(R),c.push({start:D,end:O,pPr:U,container:R||a})});let w="";for(let _=0;_<s.length;_++){let F=s[_];w+=d.has(F)?`
154
+ `:F}let b=hc(w,t,u);b=gc(w,s,b,d),m.forEach((_,F)=>{let D=F.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");b=b.replace(new RegExp(D,"g"),_)}),b=wc(s,b,f);let g=new Map;h.forEach(_=>{g.set(_,e.createDocumentFragment())}),a&&!g.has(a)&&g.set(a,e.createDocumentFragment()),g.has(e)||g.set(e,e.createDocumentFragment());let x=new Map,N=new Set(c.map(_=>_.start)),v=ta(c),T=ta(l),y=dc(u);return{paragraphs:i,body:a||e,paragraphMap:c,paragraphStarts:N,propertyMap:l,sentinelMap:u,sentinelMapByStart:y,referenceMap:f,tokenToCharMap:m,containerFragments:g,replacementContainers:x,originalFullText:s,processedModifiedText:b,getParagraphInfo:_=>{let F=v.at(_);return F||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:a||e})},getRunProperties:_=>{let F=T.at(_);return F?{rPr:F.rPr,wrapper:F.wrapper}:{rPr:null}},getPropertySpanLength:(_,F)=>{let D=T.at(_);return D?Math.min(D.end-_,F):1},isParagraphStart:_=>N.has(_)}}function aa(e,t){let r=Pe(e);if(r.length===0)return[];let n=sa(t),o=r.map(pc);if(!n){let a=o.findIndex(s=>s==="");return a>=0?[r[a]]:null}if(r.length===1&&o[0]==="")return r;let i=[a=>a,a=>a.trim(),a=>a.replace(/\s+/g," ").trim()];for(let a of i){let s=a(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],a(c)===s)return r.slice(l,u+1)}}return null}function sa(e){return String(e??"").replace(/\r\n?/g,`
156
+ `).replace(/\u00a0/g," ")}function pc(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&(A(o,"pPr")||A(o,"del")||A(o,"moveFrom")||(A(o,"t")?t+=o.textContent||"":A(o,"tab")?t+=" ":A(o,"br")||A(o,"cr")?t+=`
157
+ `:A(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),sa(t)}function gc(e,t,r,n){if(n.size===0)return r;let o=na.diff_main(e,r),i=0,a="";for(let[s,l]of o)if(s===0){for(let c=0;c<l.length;c++){let u=t[i+c];a+=n.has(u)?u:l[c]}i+=l.length}else s===-1?i+=l.length:a+=l;return a}function hc(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="",i=0,a=new Map;for(let f=0;f<e.length;f++){let m=n.get(f);if(m){a.has(i)||a.set(i,[]),a.get(i).push({char:e[f],affinity:m.affinity||"right",emitted:!1});continue}o+=e[f],i++}let s=na.diff_main(o,t),l=0,c="",u=(f,m)=>{let d=a.get(f)||[];for(let p of d)p.emitted||m&&p.affinity!==m||(c+=p.char,p.emitted=!0)};for(let[f,m]of s){if(f===1){u(l,"left"),c+=m;continue}for(let d=0;d<m.length;d++)u(l),f===0&&(c+=m[d]),l++}return u(l),c}function wc(e,t,r){let n=t;for(let o of r.keys()){if(n.includes(o))continue;let i=e.indexOf(o);if(i<0)continue;let a=e.slice(0,i),s=e.slice(i+o.length);if(a&&n.startsWith(a)){n=`${n.slice(0,a.length)}${o}${n.slice(a.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 bc(e,t,r,n,o,i,a,s){return A(e,"r")?xc(e,t,r,n,o,i,a,s):A(e,"hyperlink")?Nc(e,t,r):A(e,"sdt")||A(e,"oMath")||oa(e)==="oMath"||A(e,"bookmarkStart")||A(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((A(e,"commentRangeStart")||A(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function xc(e,t,r,n,o,i,a,s){let l=t,c=ye(e,E,"rPr");return Array.from(e.childNodes).forEach(u=>{if(A(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(A(u,"br")||A(u,"cr")){let f=String.fromCharCode(a.nextCharCode++);o.set(f,u),s.add(f),l+=f,r.push({start:l.length-1,end:l.length,rPr:c})}else if(A(u,"tab"))l+=" ",r.push({start:l.length-1,end:l.length,rPr:c});else if(A(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=>A(u,f))){let f=ye(u,E,"txbxContent"),m=A(u,"pict")&&!!f,d=A(u,"fldChar")||A(u,"instrText"),p=A(u,"fldChar")?u.getAttributeNS?.(E,"fldCharType")||u.getAttribute("w:fldCharType")||u.getAttribute("fldCharType"):null;n.push({start:l.length,node:u,wrapInRun:!0,rPr:c,zeroWidth:d,affinity:p==="end"?"left":"right",isTextBox:m,originalContainer:m?f:void 0}),l+="\uFFFC",r.push({start:l.length-1,end:l.length,rPr:c})}else if(A(u,"footnoteReference")||A(u,"endnoteReference")){let f=mc(u,"id");if(f){let d=`{{__${A(u,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(a.nextCharCode++);o.set(p,u),i.set(d,p),l+=p,r.push({start:l.length-1,end:l.length,rPr:c})}}else A(u,"commentReference")&&n.push({start:l.length,node:u,isCommentMarker:!0})}),l}function Nc(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!A(o,"r"))return;let i=ye(o,E,"rPr");ve(o,E,"t").forEach(s=>{let l=s.textContent||"";l.length!==0&&(r.push({start:n.length,end:n.length+l.length,rPr:i,wrapper:e}),n+=l)})}),n}function ca(e,t,r,n,o,i,a=!0,s={}){let{paragraphs:l,containerFragments:c,sentinelMapByStart:u,referenceMap:f,replacementContainers:m,getParagraphInfo:d,getRunProperties:p,getPropertySpanLength:h,isParagraphStart:w}=r,b=R=>{let B=C(e,"w:p");if(R){let $=R.cloneNode(!0),K=ye($,E,"sectPr");K&&$.removeChild(K),B.appendChild($)}return B},g=d(0),x=b(g.pPr),N=c.get(g.container);N&&N.appendChild(x);let v=0,T=0,y=s?.pairReplacements===!0,S=null,I=null,L=new WeakSet;for(let R=0;R<t.length;R++){let[B,$]=t[R];if(B===0||B===-1){let K=B===0?"equal":"delete";if(B===0)S=null,I=null;else if(S===null){S=v;let Y=!1;for(let oe=R+1;oe<t.length;oe++){if(t[oe][0]===1){Y=!0;break}if(t[oe][0]===0)break}y&&a&&Y&&(I=rr(o,e))}let V=0;for(;V<$.length;){let Y=v+V,oe=p(Y),mt=h(Y,$.length-V),It=$.substring(V,V+mt);x=la(e,It,K,oe.rPr,oe.wrapper,Y,x,c,u,f,m,d,b,o,i,T,a,L,I).currentParagraph,B===0&&(T+=mt),V+=mt}v+=$.length;continue}if(B===1){let K=S!==null?S:v>0&&!w(v)?v-1:v,V=p(K);x=la(e,$,"insert",V.rPr,V.wrapper,v,x,c,u,f,m,d,b,o,i,T,a,L,I,S!==null).currentParagraph,T+=$.length,S=null,I=null}}a&&c.forEach(R=>{Array.from(R.childNodes).forEach(B=>{if(A(B,"p")){let $=Array.from(B.getElementsByTagNameNS(E,"t")).length>0,K=Array.from(B.getElementsByTagNameNS(E,"delText")).length>0;l.length===1&&!$&&(K||r.originalFullText.trim()!=="")&&lr(e,B,o)}})}),c.forEach(R=>{let B=Array.from(R.childNodes).filter($=>A($,"p"));if(B.length>1){let $=B[0],K=B[B.length-1],V=ye($,E,"pPr"),Y=V?ye(V,E,"sectPr"):null;if(Y){V.removeChild(Y);let oe=ye(K,E,"pPr");oe||(oe=C(e,"w:pPr"),K.insertBefore(oe,K.firstChild||null)),oe.appendChild(Y)}}});let _=new Set(l),F=new Map;l.forEach(R=>{let B=R.parentNode;if(!B||F.has(B))return;let $=R.nextSibling;for(;$&&_.has($);)$=$.nextSibling;F.set(B,$)}),l.forEach(R=>{R.parentNode&&R.parentNode.removeChild(R)});let D=!1,O="";return c.forEach((R,B)=>{let $=m.get(B),K=$||B;if(K.nodeType===9){D=!0,R.childNodes.length===1?K.appendChild(R.firstChild):O=Array.from(R.childNodes).map(Y=>n.serializeToString(Y)).join("");return}let V=$?null:F.get(B);V&&V.parentNode===K?K.insertBefore(R,V):K.appendChild(R)}),{oxml:D&&O?O:n.serializeToString(e),hasChanges:!0}}function la(e,t,r,n,o,i,a,s,l,c,u,f,m,d,p=[],h=0,w=!0,b=new WeakSet,g=null,x=!1){let N=i,v=h,T=a,y=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(I=>{let L=l.get(N)||[],_=L.filter(O=>O.isCommentMarker&&!b.has(O.node)),F=x?new Set(_.filter(O=>A(O.node,"commentRangeEnd")).map(O=>O.node.getAttributeNS?.(E,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id"))):new Set;if(_.forEach(O=>{b.add(O.node);let U=O.node.getAttributeNS?.(E,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id");if(x&&F.has(U)&&(A(O.node,"commentRangeEnd")||A(O.node,"commentReference"))){y.push(O.node);return}if(A(O.node,"commentReference")){let R=C(e,"w:r");R.appendChild(O.node.cloneNode(!0)),T.appendChild(R)}else T.appendChild(O.node.cloneNode(!0))}),I===`
158
+ `){let O=f(N+1),U=m(O.pPr);w&&r==="insert"?Bi(e,T,d):w&&r==="delete"&&lr(e,T,d);let R=s.get(O.container);R&&(R.appendChild(U),T=U),N++,r!=="delete"&&v++;return}if(I==="\uFFFC"){let O=L.find(U=>!U.isCommentMarker)||L[0];if(O){let U=O.node.cloneNode(!0);if(O.isTextBox&&O.originalContainer){let R=ye(U,E,"txbxContent");if(R){for(;R.firstChild;)R.removeChild(R.firstChild);u.set(O.originalContainer,R)}}if(O.wrapInRun){let R=C(e,"w:r");O.rPr&&R.appendChild(O.rPr.cloneNode(!0)),R.appendChild(U),T.appendChild(R)}else T.appendChild(U)}N++,r!=="delete"&&v++;return}if(c.has(I)){if(r!=="delete"){let O=c.get(I);if(O){let U=O.cloneNode(!0),R=C(e,"w:r");n&&R.appendChild(n.cloneNode(!0)),R.appendChild(U),T.appendChild(R)}}N++,r!=="delete"&&v++;return}if(I.length===0)return;let D=T;if(o){let O=o.cloneNode(!1);D=O,T.appendChild(O)}if(r==="delete"){let O=C(e,"w:r");n&&O.appendChild(n.cloneNode(!0));let U=C(e,"w:delText");if(U.setAttribute("xml:space","preserve"),U.textContent=I,O.appendChild(U),w){let R=null;if(g){let $=g.usedDeletionId?ie(d,e,"del").id:g.deletionId;g.usedDeletionId=!0,R={id:$,author:g.author,date:g.date}}let B=wt(e,"del",O,d,R);D.appendChild(B)}}else{let O=Ke(p,v,v+I.length),U=Hr(e,I,n,O,v,d,w);if(r==="insert"&&w){let R=null;if(g){let $=g.usedInsertionId?ie(d,e,"ins").id:g.insertionId;g.usedInsertionId=!0,R={id:$,author:g.author,date:g.date}}let B=wt(e,"ins",null,d,R);U.forEach($=>B.appendChild($)),D.appendChild(B)}else U.forEach(R=>D.appendChild(R))}r!=="delete"&&(v+=I.length),N+=I.length}),y.forEach(I=>{if(A(I,"commentReference")){let L=C(e,"w:r");L.appendChild(I.cloneNode(!0)),T.appendChild(L)}else T.appendChild(I.cloneNode(!0))}),{currentParagraph:T}}function to(e,t,r,n,o,i,a=!0,s={},l={}){let c=aa(e,t);if(c===null)return se({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=ia(e,r,c);if(u.paragraphs.length===0)return se({oxml:n.serializeToString(e),hasChanges:!1});let f=ir(u.originalFullText,u.processedModifiedText,s);return se(ca(e,f,u,n,o,i,a,l))}function De(e,t){return se({oxml:e.serializeToString(t),hasChanges:!1})}function ua(e,t,r,n,o,i=!0){let a=ve(e,E,"tbl"),s=Xe(t),l=s.rows.length>0||s.headers.length>0;if(a.length===0||!l)return De(r,e);let c=a[0],u=_n(c),f=Ni(u,s);if(f.length===0)return De(r,e);let m={generateRedlines:i,author:o,revisionIdAllocator:Ye(e)},d=vi(u,f,m),p=`<root xmlns:w="${E}">${d}</root>`,h=j(p,"application/xml").doc;if(!h)return De(r,e);let w=ne(h);if(w)return ee("[OxmlEngine] Failed to parse reconciled table OOXML:",w.textContent),De(r,e);let b=ye(h,E,"tbl");if(!b)return ee("[OxmlEngine] No table found in reconciled OOXML"),De(r,e);let g=e.importNode(b,!0);return c.parentNode.replaceChild(g,c),se({oxml:r.serializeToString(e),hasChanges:!0})}function fa(e,t,r,n,o,i){let a=Ye(e),s=Xe(t);if(!s||s.rows.length===0&&s.headers.length===0)return M("[OxmlEngine] Failed to parse table data from Markdown"),De(r,e);let l=ht(s,{generateRedlines:i,author:o,revisionIdAllocator:a}),c=j(`<root xmlns:w="${E}">${l}</root>`,"application/xml").doc;if(!c)return De(r,e);let u=ne(c);if(u)return ee("[OxmlEngine] Failed to parse generated table OOXML:",u.textContent),De(r,e);let f=re(c,E,"tbl");if(f||(f=re(c,E,"ins")),!f)return ee("[OxmlEngine] No table element found in generated OOXML"),De(r,e);let m=e,d=ce(m,E,"p");if(d.length===0)return M("[OxmlEngine] No paragraphs found to replace"),De(r,m);let p=d[0],h=p.parentNode;if(h&&h.nodeType===9){let b=j(`<w:document xmlns:w="${E}"><w:body/></w:document>`,"application/xml").doc;if(!b)return De(r,m);let g=re(b,E,"body");d.forEach(x=>g.appendChild(b.importNode(x,!0))),m=b,Mr(m,a),d=ce(m,E,"p"),p=d[0],h=p.parentNode}let w=m.importNode(f,!0);return i?d.forEach(b=>{lr(m,b,o),ce(b,E,"r").forEach(x=>{ce(x,E,"t").forEach(y=>{let S=y.textContent||"";if(S.trim()){let I=C(m,"w:delText");I.textContent=S,y.parentNode.replaceChild(I,y)}});let v=C(m,"w:del"),T=ie(o,m,"del");v.setAttribute("w:id",String(T.id)),v.setAttribute("w:author",T.author),v.setAttribute("w:date",T.date),x.parentNode.insertBefore(v,x),v.appendChild(x)})}):d.slice(1).forEach(b=>b.parentNode.removeChild(b)),h.insertBefore(w,p),i||h.removeChild(p),M("[OxmlEngine] Text-to-table transformation complete"),se({oxml:r.serializeToString(m),hasChanges:!0})}function Ze(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 qr(e){return typeof e=="string"?e.trim().toLowerCase():""}function vc(e){return!!e&&e.nodeType===1}function ze(e,t){return vc(e)&&e.namespaceURI===E&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function xe(e,t){return Array.from(e.getElementsByTagNameNS(E,t))}function ro(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=qr(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 Ce(e,t){if(t.allAuthors)return!0;let r=qr(Ze(e,"author"));return!!r&&r===t.normalizedAuthor}function no(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=j(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let a=`<w:body xmlns:w="${E}">${r}</w:body>`,s=j(a,"application/xml");s.error||(o=s,n=!0)}let i=o.doc?ne(o.doc):null;if(o.error||i){let a=o.error?.message||i?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${a}`,warnings:o.warnings,error:{code:"PARSE_ERROR",message:a}}}return{xmlDoc:o.doc,serializer:me(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function fe(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Zr(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function ma(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function da(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 yc(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 Tc(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=Tc(e);if(!t)return ze(e.parentNode,"tc")&&xe(e.parentNode,"p").length<=1?!1:fe(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 fe(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)){fe(u)&&(s+=1);continue}if(Qr(u)){fe(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;fe(m)&&(s+=1);continue}fe(u)&&(s+=1)}for(let u of xe(i,"moveFrom"))!u.parentNode||!Ce(u,n)||fe(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)||fe(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=C(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 Sc(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 fe(e);let o=Array.from(e.childNodes||[]).find(a=>a.nodeType===1&&a.namespaceURI===E&&String(a.localName||"").toLowerCase()===n.toLowerCase());if(!o)return fe(e);let i=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let a of i){let s=Ec(r.ownerDocument,a);r.appendChild(s)}return!0}function Ec(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))&&fe(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;fe(m)&&(s+=1);continue}fe(u)&&(s+=1)}for(let u of xe(i,"del"))if(!(!u.parentNode||!Ce(u,n))){if(en(u)){fe(u)&&(s+=1);continue}if(Qr(u)){fe(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)||fe(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)||Sc(f,u)&&(s+=1);return yc(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 Ac(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 Ic(e,t){let r=0;for(let n of e){let o=Ze(n,"id");!o||!t.has(o)||fe(n)&&(r+=1)}return r}function Pc(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 Rc(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"&&Pc(i.parentNode)){fe(i.parentNode)&&(r+=1);continue}fe(i)&&(r+=1)}}return r}function Cc(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}=Ac(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=Ic(l,s),u=Rc(i,s);return{oxml:a.serializeToString(i),hasChanges:c>0||u>0,commentsRemoved:c,referencesRemoved:u,warnings:r}}var Oc=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:Oc[t]||null,...r}))}var kc=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 Mc(e){return Me(e)!=="r"?!1:dr(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(Me(t)))}function lo(e){return kc.has(Me(e))||Mc(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 _c(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"||!_c(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 Lc(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 Bc(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 Fc(e,t){let r=e.cloneNode(!1),n=vt(e,"pPr");return n&&r.appendChild(jr(n)),t.serializeToString(r)}function $c(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=C(r.doc,"w:pPr"),n.insertBefore(o,n.firstChild));let i=vt(o,"rPr");if(i||(i=C(r.doc,"w:rPr"),o.appendChild(i)),!vt(i,"ins")){let a=C(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||de(),l=me(),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=$c(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 N=n?._revisionIdAllocator instanceof we?n._revisionIdAllocator:new we;Rt(g,N);let v=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Pe(g);if(v.length===1&&r.length>0){let z=Na(v[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=Lc(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}});M("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let Ae=v.length===1?v[0]:null;m=Bc(Ae,s);let Yt=io(o,{author:s});if(Yt.status==="error")return h(Yt);i=m&&!String(Yt.oxml||"").trim()?Fc(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,N);let Fo=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Pe(g);t=Fo.length>0?Fo.map(Cr=>pe(Cr)).join(`
160
+ `):""}else{if(d==="merge-same-author")return M("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),h({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${z.length?z.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:z,currentPolicy:d}});if(["moveFrom","moveTo"].some(Ae=>ve(g,E,Ae).length>0))return h({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});M("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(d==="accept-all-first"||d==="accept-all-first-keep-normalized"){M("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let z=oo(o,{allAuthors:!0});if(z.status==="error")return h(z);i=z.oxml,f=!0;let k=j(i,"text/xml");c.push(...k.warnings),g=k.doc;let Z=g?ne(g):null;if(k.error||Z){let le=k.error?.message||Z?.textContent||"Could not parse OOXML after accepting existing revisions.";return ee("[OxmlEngine] XML parse error after accepting existing revisions:",le),h({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:le}})}Rt(g,N)}else return M("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),h({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let T=ji(g,t,n);if(T.hasTableWrapper&&T.targetParagraph&&!n._isolatedTableCell){M("[OxmlEngine] Isolating table-cell paragraph before diff");let z=cr(g,T.targetParagraph,l),k=await uo(z,t,r,{...n,_isolatedTableCell:!0});return!k.hasChanges&&k.status==="no-op"?w():k}let y=n.sanitizeInput===!0?fo(r):r;y!==r&&u.push("Input was sanitized; pass sanitizeInput: false to disable.");let S=null;if(n.structuredContent!==!1)if(S=Wr(y),S.valid)S.requiresStructuredContent&&(y=S.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let z=S.issues.map(k=>`${k.code}: ${k.message}`).join(" ");return h({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:z},warnings:S.issues.map(k=>k.message)})}S=null}let{cleanText:I,formatHints:L}=Ie(y),_=d==="slice-cross-author"?I!==t:I.trim()!==t.trim(),F=L.length>0,{existingFormatHints:D,textSpans:O,paragraphs:U}=Mi(g),R=D.length>0,B=O.map(z=>ya(z)).join(""),$=t.includes(`
161
+ `)||t.includes("\r")?t.split(/\r?\n/).map(rn).filter(Boolean).every(z=>U.some(k=>{let Z=O.filter(le=>le.paragraph===k).map(ya).join("");return rn(Z).includes(z)})):B.includes(t.trim())||B.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||rn(B).includes(rn(t));if(_&&typeof t=="string"&&t.trim()&&!$)return M("[OxmlEngine] Target text not found in OOXML"),h({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let K=null,V=()=>(K||(K=Vr(g,U,O)),K),Y=(z=null)=>{let k=Ui(g,t,L,l,s,a,z);return k.useNativeApi?(M("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),to(g,t,I,l,s,L,a)):k};M(`[OxmlEngine] Text changes: ${_}, New format hints: ${L.length}, Existing format hints: ${D.length}`);let oe=n.removeFormatting===!0&&!_&&!F&&R;if(!_&&!F&&!R)return Qe(n,"noChange"),M("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),w();if(!_&&!F&&R&&!oe)return M("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),w();if(oe){Qe(n,"formatOnly",{removeFormatting:!0}),M("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let z=T,k=z.targetParagraph||null;if(!k){let Ae=$i(V(),t);Ae&&(k=Ae.paragraph)}let Z=D;k&&(Z=D.filter(Ae=>Di(Ae.run)===k));let le=Wi(g,O,Z,l,s,a);return z.hasTableWrapper&&k?h({oxml:cr(g,k,l),hasChanges:le.hasChanges}):h(le)}if(!_&&F){Qe(n,"formatOnly",{removeFormatting:!1}),M(`[OxmlEngine] Format-only change detected: ${L.length} format hints`);let z=T,k={textSpans:O,paragraphs:U,paragraphInfos:V()};if(z.hasTableWrapper&&z.targetParagraph){M("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let Z=Y(k);return M("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),h({oxml:cr(g,z.targetParagraph,l),hasChanges:Z.hasChanges})}return h(Y(k))}let It=ve(g,E,"tbl").length>0,Pr=/^\|.+\|/.test(I.trim())&&I.includes(`
162
+ `),_o=Zt(I),hs=n.structuredContent!==!1&&S?.requiresStructuredContent===!0,dt=T,Lo=It||d==="slice-cross-author";M(`[OxmlEngine] Mode: ${Lo?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${L.length}, isMarkdownTable: ${Pr}, isTargetList: ${_o}, isTableCellParagraph: ${dt.isTableCellParagraph}`);try{if(Pr&&!It)return Qe(n,"table",{transformation:"text-to-table"}),M("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),h(fa(g,I,l,null,s,a));if(It&&Pr)return Qe(n,"table",{transformation:"table-reconciliation"}),h(ua(g,I,l,null,s,a));if(Lo){Qe(n,"surgical",{tableScoped:It});let z=dt.hasTableWrapper&&dt.targetParagraph?dt.targetParagraph:null;z&&M("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let k=ea(g,t,I,l,s,L,a,z,{},n);return k.status==="error"&&k.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?h({...k,oxml:o,hasChanges:!1}):dt.hasTableWrapper&&k.hasChanges&&dt.targetParagraph?(M("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),h({oxml:cr(g,dt.targetParagraph,l),hasChanges:!0})):h(k)}if(_o||hs){let z=ve(g,E,"p"),k=z.length===1;Qe(n,k?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:z.length}),M(`[OxmlEngine] \u{1F3AF} Using ${k?"direct list generation":"compatibility pipeline"} for list reconciliation`);let Z;if(k){let le=kt(i,{xmlDoc:g}),Ae=or(z[0]);Z=await _t({cleanText:I,numberingContext:Ae,originalRunModel:le.runModel,originalText:le.acceptedText,generateRedlines:a,author:s,font:n.font||null,revisionIdAllocator:N,numberingService:new Je})}else Z=await new ar({author:s,generateRedlines:a,revisionIdAllocator:N}).execute(i,y,{xmlDoc:g});if(Z.error?.code==="DIFF_TOKEN_LIMIT")return h({oxml:o,hasChanges:!1,status:"error",error:Z.error});if(Z.isValid&&Z.ooxml&&Z.ooxml!==i){let le=Z.includeNumbering===!0;M(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${le}`);let Ae=it(Z.ooxml,{includeNumbering:le,numberingXml:Z.numberingXml});return M(`[OxmlEngine] \u2705 Wrapped OOXML length: ${Ae.length}`),h({oxml:Ae,hasChanges:!0,...Array.isArray(Z.warnings)?{warnings:Z.warnings}:{}})}return w()}return Qe(n,"reconstruction"),h(to(g,t,I,l,s,L,a,{},n))}catch(z){if(ai(z))return h({oxml:o,hasChanges:!1,status:"error",error:{code:z.code,message:z.message}});throw z}}function rn(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function ya(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 fo(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 et(e){return j(e,"application/xml").doc}function yt(e){return te(e)}function nn(e){return Array.from(e||[])}function pr(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function Te(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var Oe="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Ta(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=nn(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=nn(e.getElementsByTagName(`w:${t}`));return r.length>0?r:nn(e.getElementsByTagName(t))}function ue(e){return e?pe(e):""}function Se(e){if(!e)return[];let t=Ta(e,"body"),r=t.length>0?t[0]:e;return Ta(r,"p")}function St(e){return e&&nn(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function Tt(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:pe(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:Se(e.ownerDocument||e).indexOf(e)+1,i=t.paragraphId===void 0?St(e):t.paragraphId,a=typeof t.inTable=="boolean"?t.inTable:gr(e),l=`${i||""}${o}${a?"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 Sa(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=Se(e),o=[],i=new Map,a=new Map,s=new Map;for(let l=0;l<n.length;l++){let c=n[l],u=pe(c,{revisionView:r}),f=St(c),m=gr(c),d=H(u),p=Object.freeze({paragraph:c,index:l+1,paragraphId:f,text:u,normalizedText:d,revisionView:r,fingerprint:Tt(c,{text:u,index:l+1,paragraphId:f,inTable:m,revisionView:r}),inTable:m});o.push(p),i.set(c,p),f&&!a.has(f)&&a.set(f,p),d&&(s.has(d)||s.set(d,[]),s.get(d).push(p))}for(let[l,c]of s)s.set(l,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:i,byId:a,byNormalizedText:s})}function H(e){return String(e||"").replace(/\s+/g," ").trim()}function go(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
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 Xc(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function Dc(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:Se(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:Se(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:Se(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 v=H(g).toLowerCase().split(/\s+/).filter(T=>T.length>2).filter(T=>p.has(T)).length/Math.max(p.size,1);v>m&&v>.5&&(m=v,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]||Sa(e,{revisionView:a}):u||(u=Sa(e,{revisionView:a})),i?.paragraphId){let m=Wc(e,i.paragraphId,u);if(!m)throw Te("TARGET_NOT_FOUND",`Target paragraphId not found: "${i.paragraphId}".`);let d=u?.byParagraph?.get(m)||null,p=d?.index??Se(e).indexOf(m)+1,h=d?.fingerprint||Tt(m,{revisionView:a}),w=d?.inTable??gr(m),b=d?.normalizedText||H(pe(m,{revisionView:a}));if(l!=null&&l!==p)throw Te("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=Tt(m,{revisionView:g}),N=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 Te("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches its source fingerprint.${N}`,d?[We(d)]:null)}if(typeof i.inTable=="boolean"&&i.inTable!==w)throw Te("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",N=H(pe(m,{revisionView:g}))===H(s)?` The supplied text matches the ${g} view; set target.revisionView to "${g}".`:"";throw Te("TARGET_TEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches the supplied text.${N}`,d?[We(d)]:null)}if(i.occurrence!=null){let x=an(e,s||b,u),N=x.findIndex(v=>v.paragraph===m)+1;if(N===0||N!==i.occurrence)throw Te("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${i.paragraphId}" matches occurrence ${N}, 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?Te("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",m.map(We)):Te("TARGET_NOT_FOUND",`Target fingerprint not found: "${i.fingerprint}".`)}let f=[];if(s){let m=an(e,s,u);if(f=zc(m,i),i?.fingerprint&&m.length>0&&f.length===0)throw Te("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 Te("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 Te("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 Te("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 Te("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 Te("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`);if(typeof i?.inTable=="boolean"&&i.inTable!==d?.inTable)throw Te("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||pe(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=Se(e),s=[];for(let l=0;l<a.length;l++){let c=a[l],u=pe(c,{revisionView:i}).trim();u&&H(u)===n&&s.push({paragraph:c,index:l+1,inTable:gr(c),paragraphId:St(c),fingerprint:Tt(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 zc(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 Wc(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:Se(e).find(n=>St(n)===t)||null:null}function Uc(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 jc(e,t=null){let r=t?.entries||null,n=r?null:Se(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=Uc(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 Hc(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 Vc(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 Gc(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 Kc(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 Yc(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
+ `)||!tt(e))return null;let s=Oa(e);if(!s||s.length===0)return null;let l=Ca(i);if(!l.hasListMarkers||l.items.length<2)return null;let c=H(r.currentParagraphText||ue(e)),f=l.items.filter(y=>y.kind==="list")[0]?.markerType||"bullet",m=s.map(y=>({paragraph:y,list:tt(y),text:String(ue(y)||"").trim()})),d=s.indexOf(e);if(d<0)return null;let p=Math.min(...m.map(y=>y.list?.ilvl??0)),h=m.map(y=>Pa((y.list?.ilvl??0)-p,f,y.text)),w=null,b=l.items[0],g=l.items.slice(1).filter(y=>y.kind==="list");if(b?.kind==="text"&&hr(b.text,c)&&g.length>0){let y=Math.max(0,(m[d].list?.ilvl??0)-p),S=g[0].level;w=[{level:y,markerType:f,text:m[d].text},...g.map(I=>({level:ln(I,y,S),markerType:I.markerType||f,text:I.text}))]}else if(l.items.every(y=>y.kind==="list")){let y=Math.max(0,(m[d].list?.ilvl??0)-p),S=l.items[0].level;w=l.items.map(I=>({level:ln(I,y,S),markerType:I.markerType||f,text:I.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let x=w.map(y=>Pa(y.level,y.markerType,y.text)),N=h.slice(0,d).concat(x).concat(h.slice(d+1)),v=h.join(`
166
+ `),T=N.join(`
167
+ `);return T===v?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:s,originalText:v,modifiedText:T})}function Jc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
168
+ `))return null;let a=tt(e);if(!a)return null;let s=Ca(i);if(!s.hasListMarkers||s.items.length<2)return null;let l=H(r.currentParagraphText||ue(e)),u=s.items.filter(d=>d.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,a.ilvl),m=Kc(s.items,l,f,u);return!m||m.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(Vc(s.items,l,f)&&(m=Gc(m,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:a.numId,entries:m})}function wr(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
169
+ `),n=[];for(let a of r){if(!a.trim())continue;let s=er(a,{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:a.trim()})}if(n.length===0)return null;let o=n.some(a=>a.type==="numbered"),i=n.some(a=>a.type==="bullet");return{type:o?"numbered":i?"bullet":"text",items:n}}function wo(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function qc(e,t,r){let n=new Map,o=[];for(let i of e){let a=Math.max(0,Number(i?.level)||0);for(let u of Array.from(n.keys()))u>a&&n.delete(u);let s=(n.get(a)||0)+1;n.set(a,s);let l=Qc(s,t,r),c=" ".repeat(a*4);o.push(`${c}${l} ${i.text||""}`.trimEnd())}return o.join(`
170
+ `)}function Zc(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let o=String(n??""),i=o.match(/^(\s*)/),a=i?i[1].length:0,s=Math.floor(a/r),l=o.trim(),c=null,u=Fe(l,{allowZeroSpaceAfterMarker:!0});return u&&(c=u[2].trim()||null,l=je(l,{allowZeroSpaceAfterMarker:!0})),{text:l.trim(),level:s,removedMarker:c}})}function Qc(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${ka(e,!1)}.`;case"upperAlpha":return`${ka(e,!0)}.`;case"lowerRoman":return`${Ma(e,!1)}.`;case"upperRoman":return`${Ma(e,!0)}.`;default:return`${e}.`}}function ka(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 Ma(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[i,a]of n)for(;r>=i;)o+=a,r-=i;return t?o:o.toLowerCase()}function cn(e){let t=String(e||"");if(!t.trim()||t.includes(`
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:tu(o,i),contentText:String(n.text||"").trim(),normalizedContent:H(String(n.text||""))}}function eu(e){let t=cn(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function tu(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 ru(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 nu(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 ou(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 iu(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=C(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=C(c,"w:numPr"),u.appendChild(f));let m=zt(f,"ilvl");m||(m=C(c,"w:ilvl"),f.appendChild(m)),m.setAttribute("w:val",String(n));let d=zt(f,"numId");d||(d=C(c,"w:numId"),f.appendChild(d)),d.setAttribute("w:val",String(r)),s++}return s}function au(e){let t=j(e,"application/xml").doc;return!t||ne(t)?null:Se(t)[0]||null}function su(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function lu(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=lu(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 cu(e){let t=j(e,"application/xml").doc;if(!t||ne(t))return null;let o=Se(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 uu(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,i=me(),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=C(a,"w:lvlOverride"),m.setAttribute("w:ilvl","0"),c.appendChild(m));let d=Array.from(m.getElementsByTagNameNS("*","startOverride"))[0]||null;if(d||(d=C(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=C(a,"w:lvl"),w.setAttribute("w:ilvl","0"),h.appendChild(w));let b=Array.from(w.getElementsByTagNameNS("*","start"))[0]||null;b||(b=C(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=au(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=su(i),s=cu(a),l=uu(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 fu=new Set(["ins","del","rPrChange","pPrChange"]),mu=/^\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 du(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function pu(e){return ut(e.parentNode)==="rPr"}function gu(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 hu(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}:gu(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"),mu.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(!fu.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)&&du(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(pu(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 wu(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function bu(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 xu(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=>wu(l)).join(" | ")} |`;return[a(n),a(o),...i.map(a)].join(`
173
+ `)}function Nu(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>H(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function La(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 vu(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:ue;if(!e||!e.parentNode)return null;let o=[e],i=e.nextSibling,a=0;for(;i&&a<r;){a+=1;let s=i.nextSibling;if(i.nodeType!==1||i.namespaceURI!==Oe||i.localName!=="p"){i=s;continue}let l=String(n(i)||"").trim();if(!l){if(o.length>1)break;i=s;continue}if(!La(l))break;o.push(i),i=s}return o.length>1?o:null}function yu(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
174
+ `)||go(i))return null;let a=i.split(/\r?\n/g).map(N=>N.trim()).filter(Boolean);if(a.length<2)return null;let s=r.tableElement||Dt(e,"tbl"),l=Dt(e,"tr"),c=Dt(e,"tc");if(!s||!l||!c)return null;let u=H(r.currentParagraphText||ue(e)),f=H(a[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:m,rowElements:d,columnCount:p}=bu(s);if(m.length===0||p===0)return null;let h=d.indexOf(l),b=fn(l,"tc").indexOf(c);if(h<0||b<0||b>=p)return null;m[h][b]=a[0];let g=Nu(m[h]);g&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let N=1;N<a.length;N++){let v=h+N,T=a[N];if(v<m.length&&!H(m[v][b]))if(g)for(let y=0;y<p;y++)H(m[v][y])||(m[v][y]=T);else m[v][b]=T;else{let y=new Array(p).fill("");if(g)for(let S=0;S<p;S++)y[S]=T;else y[b]=T;m.splice(Math.min(v,m.length),0,y)}}let x=xu(m,p);return x?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),x):null}function Ut(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 jt(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 i=1;i<=r;i+=1)if(!o.has(i))return i}return n}function Tu(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,i=new Set;if(String(e||"").trim())try{let u=et(e),f=Array.from(u.getElementsByTagNameNS("*","abstractNum")),m=Array.from(u.getElementsByTagNameNS("*","num"));for(let d of f){let p=Ut(d,["w:abstractNumId","abstractNumId"]);p!=null&&i.add(p)}for(let d of m){let p=Ut(d,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let a=o.size>0?Math.max(...o):0,s=i.size>0?Math.max(...i):0,l=Math.max(r,a+1),c=Math.max(r,s+1);return{nextNumId:jt(l,o,n),nextAbstractNumId:jt(c,i,n),usedNumIds:o,usedAbstractNumIds:i,minId:r,maxPreferred:n}}function Su(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=jt(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=jt(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function xr(e,t="num"){let r=Su(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=jt(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=jt(o+1,r.usedNumIds,r.maxPreferred)),o)}function Eu(e){let t=xr(e,"num"),r=xr(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function xo(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function mn(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Oe&&e.localName===t)}function Ba(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(i=>i&&i.nodeType===1&&i.namespaceURI===Oe),o=null;r==="abstract"?o=n.find(i=>i.localName==="num"||i.localName==="numIdMacAtCleanup")||null:o=n.find(i=>i.localName==="numIdMacAtCleanup")||null,o?e.insertBefore(t,o):e.appendChild(t)}function Au(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function br(e,t){let r=Au(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Fa(e,t,r){e?.setAttribute?.(t,String(r))}function No(e,t){e?.setAttribute?.("w:val",String(t))}function Iu(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)No(o,t)}}function Pu(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let o=br(n,["w:val","val"]);if(o!=null)return String(o)}}return null}function Ru(e,t,r){let n=String(e),o=String(t),i=Number.isInteger(r)&&r>0?r:1,a=Array.from({length:9},(s,l)=>{let c=Array.from({length:l+1},(f,m)=>`%${m+1}`).join(".")+".",u=720*(l+1);return`
175
175
  <w:lvl w:ilvl="${l}">
176
176
  <w:start w:val="1"/>
177
177
  <w:numFmt w:val="decimal"/>
@@ -190,25 +190,25 @@ var ds=Object.create;var _o=Object.defineProperty;var ps=Object.getOwnPropertyDe
190
190
  <w:startOverride w:val="${i}"/>
191
191
  </w:lvlOverride>
192
192
  </w:num>
193
- </w:numbering>`.trim()}function yu(e,t,r){let n=tt(e);if(ho(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let o=new Map,i=new Map,a=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of a){let u=wr(c,["w:abstractNumId","abstractNumId"]);if(u==null)continue;let f=br(r,"abstract");f!=null&&(o.set(u,f),Ma(c,"w:abstractNumId",f))}let s=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of s){let u=wr(c,["w:numId","numId"]);if(u==null)continue;let f=br(r,"num");if(f==null)continue;i.set(u,f),Ma(c,"w:numId",f);let m=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(m){let d=wr(m,["w:val","val"]);d!=null&&o.has(d)&&wo(m,o.get(d))}}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 m=wr(f,["w:val","val"]);m!=null&&i.has(m)&&wo(f,i.get(m))}}return{numberingXml:vt(n),replacementNodes:l}}function Tu(e,t){let r=String(e||""),n=String(t||"");if(!n.trim())return r;if(!r.trim())return n;try{let o=tt(r),i=tt(n);if(ho(o)||ho(i))return r;let a=o.documentElement,s=i.documentElement;if(!a||!s)return r;let l=new Set(Array.from(a.childNodes||[]).filter(u=>ln(u,"abstractNum")).map(u=>zt(u,["w:abstractNumId","abstractNumId"])).filter(u=>u!=null)),c=new Set(Array.from(a.childNodes||[]).filter(u=>ln(u,"num")).map(u=>zt(u,["w:numId","numId"])).filter(u=>u!=null));for(let u of Array.from(s.childNodes||[])){if(!ln(u,"abstractNum"))continue;let f=zt(u,["w:abstractNumId","abstractNumId"]);f==null||l.has(f)||(ka(a,o.importNode(u,!0),"abstract"),l.add(f))}for(let u of Array.from(s.childNodes||[])){if(!ln(u,"num"))continue;let f=zt(u,["w:numId","numId"]);f==null||c.has(f)||(ka(a,o.importNode(u,!0),"num"),c.add(f))}return vt(o)}catch{return r}}function Su(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!re(e)}function _a(e){let t=j(e,"application/xml");return t.error||Su(t.doc)?{...t,doc:null}:t}function La(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(E,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function bo(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===E&&n.localName===t)return n;return null}function mt(e,t){return Array.from(e?.getElementsByTagNameNS?.(E,t)||[])}function xr(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function Eu(e){let t=bo(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=mt(t,"rStyle")[0]||null,n=xr(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),i=n.includes("italic")||n.includes("emphasis");return{bold:mt(t,"b").length>0||o,italic:mt(t,"i").length>0||i}}function Ba(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(E,"r")||[]);for(let n of r){if(!bt(n,e,"accepted"))continue;let o=xt(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...Eu(n)})}return t}function xo(e){return String(e||"").replace(/\r/g,"").split(`
193
+ </w:numbering>`.trim()}function Cu(e,t,r){let n=et(e);if(xo(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let o=new Map,i=new Map,a=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of a){let u=br(c,["w:abstractNumId","abstractNumId"]);if(u==null)continue;let f=xr(r,"abstract");f!=null&&(o.set(u,f),Fa(c,"w:abstractNumId",f))}let s=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of s){let u=br(c,["w:numId","numId"]);if(u==null)continue;let f=xr(r,"num");if(f==null)continue;i.set(u,f),Fa(c,"w:numId",f);let m=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(m){let d=br(m,["w:val","val"]);d!=null&&o.has(d)&&No(m,o.get(d))}}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 m=br(f,["w:val","val"]);m!=null&&i.has(m)&&No(f,i.get(m))}}return{numberingXml:yt(n),replacementNodes:l}}function Ou(e,t){let r=String(e||""),n=String(t||"");if(!n.trim())return r;if(!r.trim())return n;try{let o=et(r),i=et(n);if(xo(o)||xo(i))return r;let a=o.documentElement,s=i.documentElement;if(!a||!s)return r;let l=new Set(Array.from(a.childNodes||[]).filter(u=>mn(u,"abstractNum")).map(u=>Ut(u,["w:abstractNumId","abstractNumId"])).filter(u=>u!=null)),c=new Set(Array.from(a.childNodes||[]).filter(u=>mn(u,"num")).map(u=>Ut(u,["w:numId","numId"])).filter(u=>u!=null));for(let u of Array.from(s.childNodes||[])){if(!mn(u,"abstractNum"))continue;let f=Ut(u,["w:abstractNumId","abstractNumId"]);f==null||l.has(f)||(Ba(a,o.importNode(u,!0),"abstract"),l.add(f))}for(let u of Array.from(s.childNodes||[])){if(!mn(u,"num"))continue;let f=Ut(u,["w:numId","numId"]);f==null||c.has(f)||(Ba(a,o.importNode(u,!0),"num"),c.add(f))}return yt(o)}catch{return r}}function ku(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!ne(e)}function $a(e){let t=j(e,"application/xml");return t.error||ku(t.doc)?{...t,doc:null}:t}function Xa(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(E,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function vo(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===E&&n.localName===t)return n;return null}function ft(e,t){return Array.from(e?.getElementsByTagNameNS?.(E,t)||[])}function Nr(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function Mu(e){let t=vo(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=ft(t,"rStyle")[0]||null,n=Nr(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),i=n.includes("italic")||n.includes("emphasis");return{bold:ft(t,"b").length>0||o,italic:ft(t,"i").length>0||i}}function Da(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(E,"r")||[]);for(let n of r){if(!bt(n,e,"accepted"))continue;let o=xt(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...Mu(n)})}return t}function yo(e){return String(e||"").replace(/\r/g,"").split(`
194
194
  `).map(r=>r.replace(/[ \t]+/g," ").trim()).join(`
195
- `).trim()}function Au(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]||"",i=n[2]||"",a=n[3]||"";if(!i.trim())return r;let s=i;return t.bold&&t.italic?s=`***${i}***`:t.bold?s=`**${i}**`:t.italic&&(s=`*${i}*`),`${o}${s}${a}`}function Iu(e){let t=bo(e,"pPr");if(!t)return null;let r=mt(t,"pStyle")[0]||null,n=xr(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=mt(t,"outlineLvl")[0]||null,i=xr(o,["w:val","val"]),a=Number.parseInt(i,10);return Number.isInteger(a)&&a>=0?Math.min(a+1,6):null}function Pu(e){let t=bo(e,"pPr");if(!t)return null;let r=mt(t,"numPr")[0]||null;if(!r)return null;let n=mt(r,"ilvl")[0]||null,o=mt(r,"numId")[0]||null,i=Number.parseInt(xr(n,["w:val","val"]),10),a=xr(o,["w:val","val"]);return{level:Number.isInteger(i)&&i>=0?i:0,marker:a==="1"?"-":"1."}}function Ru(e){let t=Ba(e).map(r=>r.text).join("");return xo(t)}function Cu(e){let r=Ba(e).map(a=>Au(a.text,a)).join(""),n=xo(r);if(!n)return"";let o=Iu(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let i=Pu(e);return i?`${" ".repeat(i.level)}${i.marker} ${n}`:n}function Ou(e){return Fa(e).text}function Fa(e){let t=_a(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=La(r);return n.length===0?{text:xo(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(Ru).join(`
195
+ `).trim()}function _u(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]||"",i=n[2]||"",a=n[3]||"";if(!i.trim())return r;let s=i;return t.bold&&t.italic?s=`***${i}***`:t.bold?s=`**${i}**`:t.italic&&(s=`*${i}*`),`${o}${s}${a}`}function Lu(e){let t=vo(e,"pPr");if(!t)return null;let r=ft(t,"pStyle")[0]||null,n=Nr(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=ft(t,"outlineLvl")[0]||null,i=Nr(o,["w:val","val"]),a=Number.parseInt(i,10);return Number.isInteger(a)&&a>=0?Math.min(a+1,6):null}function Bu(e){let t=vo(e,"pPr");if(!t)return null;let r=ft(t,"numPr")[0]||null;if(!r)return null;let n=ft(r,"ilvl")[0]||null,o=ft(r,"numId")[0]||null,i=Number.parseInt(Nr(n,["w:val","val"]),10),a=Nr(o,["w:val","val"]);return{level:Number.isInteger(i)&&i>=0?i:0,marker:a==="1"?"-":"1."}}function Fu(e){let t=Da(e).map(r=>r.text).join("");return yo(t)}function $u(e){let r=Da(e).map(a=>_u(a.text,a)).join(""),n=yo(r);if(!n)return"";let o=Lu(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let i=Bu(e);return i?`${" ".repeat(i.level)}${i.marker} ${n}`:n}function Xu(e){return za(e).text}function za(e){let t=$a(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Xa(r);return n.length===0?{text:yo(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(Fu).join(`
196
196
 
197
- `).trim(),status:"ok",warnings:t.warnings}}function ku(e){return $a(e).text}function $a(e){let t=_a(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=La(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(Cu).join(`
197
+ `).trim(),status:"ok",warnings:t.warnings}}function Du(e){return Wa(e).text}function Wa(e){let t=$a(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Xa(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map($u).join(`
198
198
 
199
- `).trim(),status:"ok",warnings:t.warnings}}var Ut=new TextEncoder;function Xa(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 No({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=Ut.encode("docx-redline-revision-token\0"),n=1,o=Ut.encode(e),i=[],a=new Set,s=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let m of s){if(!m)continue;let d=Array.isArray(m)?m[0]:m.name,p=Array.isArray(m)?m[1]:m.payload??m.bytes;if(d==null)continue;let b=Xa(String(d));if(a.has(b))throw new Error(`Duplicate normalized entry path detected: "${b}"`);a.add(b);let h;typeof p=="string"?h=Ut.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),i.push({name:b,nameBytes:Ut.encode(b),payloadBytes:h})}i.sort((m,d)=>m.name<d.name?-1:m.name>d.name?1:0);let l=r.length+4+4+o.length+4;for(let m of i)l+=4+m.nameBytes.length+4+m.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,i.length,!1),f+=4;for(let m of i)u.setUint32(f,m.nameBytes.length,!1),f+=4,c.set(m.nameBytes,f),f+=m.nameBytes.length,u.setUint32(f,m.payloadBytes.length,!1),f+=4,c.set(m.payloadBytes,f),f+=m.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:i.map(m=>m.name)}}async function Da({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:i}=No({scope:e,entries:t}),a="";if(typeof r=="function")a=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);a=Array.from(l).map(c=>c.toString(16).padStart(2,"0")).join("")}else throw new Error("No crypto provider available for SHA-256 revision token computation.");return{algorithm:"sha256",version:i,scope:e,value:a,coveredParts:o}}function vo({scope:e,entries:t=[],digestFn:r}){if(typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn.");let{framing:n,coveredParts:o,version:i}=No({scope:e,entries:t}),a=r(n);return{algorithm:"sha256",version:i,scope:e,value:a,coveredParts:o}}function cn(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 Mu(e,t={}){let r=cn(e);return Da({scope:"document-parts",entries:r,digestFn:t.digestFn})}function _u(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 Lu(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=Ut.encode(r),i=Ut.encode(n),a=0;for(let s=0;s<o.length;s++)a|=o[s]^i[s];return a===0}var q=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",je=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(E,t)||[]),pe=(e,t)=>je(e,t)[0]||null;function Bu(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===E))return!0;r=r.parentNode}return!1}function un(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=j(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function Fu(e){let t=pe(pe(e,"pPr"),"numPr");if(!t)return null;let r=q(pe(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(q(pe(t,"ilvl"),"val")||"0",10)||0}}function $u(e){let t=new Map;for(let n of je(e,"abstractNum")){let o=new Map;for(let i of je(n,"lvl")){let a=Number.parseInt(q(i,"ilvl")||"0",10)||0;o.set(a,{start:Number.parseInt(q(pe(i,"start"),"val")||"1",10)||1,format:q(pe(i,"numFmt"),"val")||"decimal",text:q(pe(i,"lvlText"),"val")||`%${a+1}.`})}t.set(q(n,"abstractNumId"),o)}let r=new Map;for(let n of je(e,"num")){let o=q(pe(n,"abstractNumId"),"val"),i=new Map(t.get(o)||[]);for(let a of je(n,"lvlOverride")){let s=Number.parseInt(q(a,"ilvl")||"0",10)||0,l=pe(a,"lvl"),c={...i.get(s)||{start:1,format:"decimal",text:`%${s+1}.`}};l&&(c.start=Number.parseInt(q(pe(l,"start"),"val")||String(c.start),10)||c.start,c.format=q(pe(l,"numFmt"),"val")||c.format,c.text=q(pe(l,"lvlText"),"val")||c.text);let u=pe(a,"startOverride");u&&(c.start=Number.parseInt(q(u,"val")||String(c.start),10)||c.start),i.set(s,c)}r.set(q(n,"numId"),i)}return r}function za(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 Wa(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,i]of t)for(;r>=o;)n+=i,r-=o;return n}function Xu(e,t){return t==="lowerLetter"?za(e,!1):t==="upperLetter"?za(e,!0):t==="lowerRoman"?Wa(e).toLowerCase():t==="upperRoman"?Wa(e):String(e)}function Du(e){let t=e?$u(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 i=r.get(n.numId)||[],a=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};i[n.level]=i[n.level]==null?a.start:i[n.level]+1,i.length=n.level+1,r.set(n.numId,i);let s=a.text.replace(/%([1-9])/g,(l,c)=>{let u=Number(c)-1,f=o.get(u)||a;return Xu(i[u]??f.start,f.format)});return{...n,label:s,format:a.format}}}function zu(e){let t=pe(e,"pPr"),n=q(pe(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(q(pe(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function Wu(e,t){let r=[];for(let[s,l]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of je(e,s))r.push({type:l,id:q(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 i=o?.parentNode;for(;i&&i.localName!=="tbl";)i=i.parentNode;let a=e.ownerDocument;return{references:r,table:i?{tableIndex:Array.from(a.getElementsByTagNameNS(E,"tbl")).indexOf(i)+1,rowIndex:Array.from(i.getElementsByTagNameNS(E,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(E,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Uu(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of je(e,r))q(n,"author")&&t.add(q(n,"author"));return[...t].sort()}function ju(e){let t=new Map;for(let r of je(e,"comment")){let n=je(r,"p");t.set(q(r,"id"),{id:q(r,"id"),author:q(r,"author")||null,date:q(r,"date")||null,text:n.map(o=>be(o)).join(`
200
- `),paraId:n[0]?.getAttribute?.("w14:paraId")||n[0]?.getAttribute?.("paraId")||null})}return t}function Hu(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")||"",i=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",a=r.get(o.toUpperCase());a&&(a.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",i&&(a.parentParaId=i,a.parentCommentId=r.get(i.toUpperCase())?.id||null))}}function Vu(e,t){let r=new Map,n=new Map,o=null,i=s=>{for(let l of r.values())l.text+=s},a=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(q(l,"id"),{text:""});else if(c==="commentRangeEnd"){let u=q(l,"id");r.has(u)&&(n.set(u,r.get(u).text),r.delete(u))}else c==="r"?i(xt(l,{revisionView:t,boundary:o})):a(l)}};return e.forEach((s,l)=>{o=s,a(s),l<e.length-1&&r.size&&i(`
201
- `)}),n}function Gu(e,t={}){let r=un(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=un(e?.commentsXml,"word/comments.xml"),o=un(e?.commentsExtendedXml,"word/commentsExtended.xml"),i=un(e?.numberingXml,"word/numbering.xml"),a=[...r.warnings||[]];n.error&&a.push(n.error.message),o.error&&a.push(o.error.message),i.error&&a.push(i.error.message);let s=ju(n.doc);Hu(s,o.doc);let l=Du(i.doc),c=null,u=Ee(r.doc),f=Vu(u,t.revisionView||"accepted"),m=u.map((g,w)=>{let x=be(g,{revisionView:t.revisionView||"accepted"}),y=zu(g);y&&(c={level:y,text:x});let N=[...new Set([...je(g,"commentRangeStart"),...je(g,"commentReference")].map(U=>q(U,"id")).filter(Boolean))],T=Uu(g),v=l(Fu(g)),S=q(pe(pe(g,"pPr"),"pStyle"),"val")||null,I=Wu(g,x),_=w+1,L=v?.label&&v.format!=="bullet"?v.label:null,F=c?.text||null,X=[L,F,x.slice(0,t.excerptLength||120)].filter(Boolean).join(" \u2014 "),C=jr(g);return{index:_,ref:`P${_}`,paragraphId:yt(g),fingerprint:Ft(g),text:x,exactText:x,excerpt:x.slice(0,t.excerptLength||120),humanReference:X,inTable:Bu(g,"tc"),table:I.table,styleId:S,headingLevel:y,nearestHeading:c,list:v,structuralReferences:I.references,hasRevisions:T.length>0,revisionAuthors:T,commentIds:N,segments:C}});for(let g of m)for(let w of g.commentIds){let x=s.get(w)||{id:w,author:null,date:null,text:""};x.paragraphIndex??(x.paragraphIndex=g.index),x.targetRef??(x.targetRef=g.ref),x.anchoredText??(x.anchoredText=f.get(w)||g.text),s.set(w,x)}if(t.revisedOnly&&(m=m.filter(g=>g.hasRevisions)),t.inTable!=null&&(m=m.filter(g=>g.inTable===!!t.inTable)),t.skipEmpty&&(m=m.filter(g=>g.text.length>0)),t.search){let g=String(t.search).toLowerCase();m=m.filter(w=>w.text.toLowerCase().includes(g))}if(Array.isArray(t.indexes)){let g=new Set(t.indexes);m=m.filter(w=>g.has(w.index))}if(t.range){let g=Number(t.range.start??t.range[0]),w=Number(t.range.end??t.range[1]);m=m.filter(x=>x.index>=g&&x.index<=w)}let d=[...new Set(m.flatMap(g=>g.revisionAuthors))].sort(),p=cn(e),b=p.map(g=>g.name).sort(),h=null;return typeof t.digestFn=="function"&&(h=vo({scope:"document-parts",entries:p,digestFn:t.digestFn})),{status:"ok",revisionToken:h,coveredParts:b,paragraphs:m,comments:[...s.values()],revisionAuthors:d,commentAuthors:[...new Set([...s.values()].map(g=>g.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:s.size,revisedParagraphs:m.filter(g=>g.hasRevisions).length},warnings:a}}var fn="http://schemas.microsoft.com/office/word/2010/wordml",nt="http://schemas.microsoft.com/office/word/2012/wordml";function yo(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 Nr(e,t,r,n,o=yo(e)){let i=t.split(" ").map(l=>l[0]).join("").toUpperCase()||"AI",a=Ne(r),s=Ne(t);return`<w:comment w:id="${e}" w:author="${s}" w:date="${n}" w:initials="${i}">
202
- <w:p w14:paraId="${Ne(o)}" xmlns:w14="${fn}">
199
+ `).trim(),status:"ok",warnings:t.warnings}}var Ht=new TextEncoder;function Ua(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 To({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=Ht.encode("docx-redline-revision-token\0"),n=1,o=Ht.encode(e),i=[],a=new Set,s=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let m of s){if(!m)continue;let d=Array.isArray(m)?m[0]:m.name,p=Array.isArray(m)?m[1]:m.payload??m.bytes;if(d==null)continue;let h=Ua(String(d));if(a.has(h))throw new Error(`Duplicate normalized entry path detected: "${h}"`);a.add(h);let w;typeof p=="string"?w=Ht.encode(p):p instanceof Uint8Array?w=p:p&&typeof p.length=="number"?w=new Uint8Array(p):w=new Uint8Array(0),i.push({name:h,nameBytes:Ht.encode(h),payloadBytes:w})}i.sort((m,d)=>m.name<d.name?-1:m.name>d.name?1:0);let l=r.length+4+4+o.length+4;for(let m of i)l+=4+m.nameBytes.length+4+m.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,i.length,!1),f+=4;for(let m of i)u.setUint32(f,m.nameBytes.length,!1),f+=4,c.set(m.nameBytes,f),f+=m.nameBytes.length,u.setUint32(f,m.payloadBytes.length,!1),f+=4,c.set(m.payloadBytes,f),f+=m.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:i.map(m=>m.name)}}async function ja({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:i}=To({scope:e,entries:t}),a="";if(typeof r=="function")a=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);a=Array.from(l).map(c=>c.toString(16).padStart(2,"0")).join("")}else throw new Error("No crypto provider available for SHA-256 revision token computation.");return{algorithm:"sha256",version:i,scope:e,value:a,coveredParts:o}}function So({scope:e,entries:t=[],digestFn:r}){if(typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn.");let{framing:n,coveredParts:o,version:i}=To({scope:e,entries:t}),a=r(n);return{algorithm:"sha256",version:i,scope:e,value:a,coveredParts:o}}function dn(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 zu(e,t={}){let r=dn(e);return ja({scope:"document-parts",entries:r,digestFn:t.digestFn})}function Wu(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 Uu(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=Ht.encode(r),i=Ht.encode(n),a=0;for(let s=0;s<o.length;s++)a|=o[s]^i[s];return a===0}var q=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",Ue=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(E,t)||[]),ge=(e,t)=>Ue(e,t)[0]||null;function ju(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===E))return!0;r=r.parentNode}return!1}function pn(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=j(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function Hu(e){let t=ge(ge(e,"pPr"),"numPr");if(!t)return null;let r=q(ge(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(q(ge(t,"ilvl"),"val")||"0",10)||0}}function Vu(e){let t=new Map;for(let n of Ue(e,"abstractNum")){let o=new Map;for(let i of Ue(n,"lvl")){let a=Number.parseInt(q(i,"ilvl")||"0",10)||0;o.set(a,{start:Number.parseInt(q(ge(i,"start"),"val")||"1",10)||1,format:q(ge(i,"numFmt"),"val")||"decimal",text:q(ge(i,"lvlText"),"val")||`%${a+1}.`})}t.set(q(n,"abstractNumId"),o)}let r=new Map;for(let n of Ue(e,"num")){let o=q(ge(n,"abstractNumId"),"val"),i=new Map(t.get(o)||[]);for(let a of Ue(n,"lvlOverride")){let s=Number.parseInt(q(a,"ilvl")||"0",10)||0,l=ge(a,"lvl"),c={...i.get(s)||{start:1,format:"decimal",text:`%${s+1}.`}};l&&(c.start=Number.parseInt(q(ge(l,"start"),"val")||String(c.start),10)||c.start,c.format=q(ge(l,"numFmt"),"val")||c.format,c.text=q(ge(l,"lvlText"),"val")||c.text);let u=ge(a,"startOverride");u&&(c.start=Number.parseInt(q(u,"val")||String(c.start),10)||c.start),i.set(s,c)}r.set(q(n,"numId"),i)}return r}function Ha(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 Va(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,i]of t)for(;r>=o;)n+=i,r-=o;return n}function Gu(e,t){return t==="lowerLetter"?Ha(e,!1):t==="upperLetter"?Ha(e,!0):t==="lowerRoman"?Va(e).toLowerCase():t==="upperRoman"?Va(e):String(e)}function Ku(e){let t=e?Vu(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 i=r.get(n.numId)||[],a=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};i[n.level]=i[n.level]==null?a.start:i[n.level]+1,i.length=n.level+1,r.set(n.numId,i);let s=a.text.replace(/%([1-9])/g,(l,c)=>{let u=Number(c)-1,f=o.get(u)||a;return Gu(i[u]??f.start,f.format)});return{...n,label:s,format:a.format}}}function Yu(e){let t=ge(e,"pPr"),n=q(ge(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(q(ge(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function Ju(e,t){let r=[];for(let[s,l]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of Ue(e,s))r.push({type:l,id:q(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 i=o?.parentNode;for(;i&&i.localName!=="tbl";)i=i.parentNode;let a=e.ownerDocument;return{references:r,table:i?{tableIndex:Array.from(a.getElementsByTagNameNS(E,"tbl")).indexOf(i)+1,rowIndex:Array.from(i.getElementsByTagNameNS(E,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(E,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function qu(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of Ue(e,r))q(n,"author")&&t.add(q(n,"author"));return[...t].sort()}function Zu(e){let t=new Map;for(let r of Ue(e,"comment")){let n=Ue(r,"p");t.set(q(r,"id"),{id:q(r,"id"),author:q(r,"author")||null,date:q(r,"date")||null,text:n.map(o=>pe(o)).join(`
200
+ `),paraId:n[0]?.getAttribute?.("w14:paraId")||n[0]?.getAttribute?.("paraId")||null})}return t}function Qu(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")||"",i=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",a=r.get(o.toUpperCase());a&&(a.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",i&&(a.parentParaId=i,a.parentCommentId=r.get(i.toUpperCase())?.id||null))}}function ef(e,t){let r=new Map,n=new Map,o=null,i=s=>{for(let l of r.values())l.text+=s},a=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(q(l,"id"),{text:""});else if(c==="commentRangeEnd"){let u=q(l,"id");r.has(u)&&(n.set(u,r.get(u).text),r.delete(u))}else c==="r"?i(xt(l,{revisionView:t,boundary:o})):a(l)}};return e.forEach((s,l)=>{o=s,a(s),l<e.length-1&&r.size&&i(`
201
+ `)}),n}function tf(e,t={}){let r=pn(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=pn(e?.commentsXml,"word/comments.xml"),o=pn(e?.commentsExtendedXml,"word/commentsExtended.xml"),i=pn(e?.numberingXml,"word/numbering.xml"),a=[...r.warnings||[]];n.error&&a.push(n.error.message),o.error&&a.push(o.error.message),i.error&&a.push(i.error.message);let s=Zu(n.doc);Qu(s,o.doc);let l=Ku(i.doc),c=null,u=Se(r.doc),f=t.revisionView==="rejected"?"rejected":"accepted",m=ef(u,f),d=u.map((g,x)=>{let N=pe(g,{revisionView:f}),v=Yu(g);v&&(c={level:v,text:N});let T=[...new Set([...Ue(g,"commentRangeStart"),...Ue(g,"commentReference")].map(R=>q(R,"id")).filter(Boolean))],y=qu(g),S=l(Hu(g)),I=q(ge(ge(g,"pPr"),"pStyle"),"val")||null,L=Ju(g,N),_=x+1,F=S?.label&&S.format!=="bullet"?S.label:null,D=c?.text||null,O=[F,D,N.slice(0,t.excerptLength||120)].filter(Boolean).join(" \u2014 "),U=Kr(g);return{index:_,ref:`P${_}`,paragraphId:St(g),fingerprint:Tt(g,{text:N,index:_,revisionView:f}),revisionView:f,text:N,exactText:N,excerpt:N.slice(0,t.excerptLength||120),humanReference:O,inTable:ju(g,"tc"),table:L.table,styleId:I,headingLevel:v,nearestHeading:c,list:S,structuralReferences:L.references,hasRevisions:y.length>0,revisionAuthors:y,commentIds:T,segments:U}});for(let g of d)for(let x of g.commentIds){let N=s.get(x)||{id:x,author:null,date:null,text:""};N.paragraphIndex??(N.paragraphIndex=g.index),N.targetRef??(N.targetRef=g.ref),N.anchoredText??(N.anchoredText=m.get(x)||g.text),s.set(x,N)}if(t.revisedOnly&&(d=d.filter(g=>g.hasRevisions)),t.inTable!=null&&(d=d.filter(g=>g.inTable===!!t.inTable)),t.skipEmpty&&(d=d.filter(g=>g.text.length>0)),t.search){let g=String(t.search).toLowerCase();d=d.filter(x=>x.text.toLowerCase().includes(g))}if(Array.isArray(t.indexes)){let g=new Set(t.indexes);d=d.filter(x=>g.has(x.index))}if(t.range){let g=Number(t.range.start??t.range[0]),x=Number(t.range.end??t.range[1]);d=d.filter(N=>N.index>=g&&N.index<=x)}let p=[...new Set(d.flatMap(g=>g.revisionAuthors))].sort(),h=dn(e),w=h.map(g=>g.name).sort(),b=null;return typeof t.digestFn=="function"&&(b=So({scope:"document-parts",entries:h,digestFn:t.digestFn})),{status:"ok",revisionToken:b,coveredParts:w,paragraphs:d,comments:[...s.values()],revisionAuthors:p,commentAuthors:[...new Set([...s.values()].map(g=>g.author).filter(Boolean))].sort(),counts:{paragraphs:d.length,comments:s.size,revisedParagraphs:d.filter(g=>g.hasRevisions).length},warnings:a}}var gn="http://schemas.microsoft.com/office/word/2010/wordml",rt="http://schemas.microsoft.com/office/word/2012/wordml";function Eo(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 vr(e,t,r,n,o=Eo(e)){let i=t.split(" ").map(l=>l[0]).join("").toUpperCase()||"AI",a=Ne(r),s=Ne(t);return`<w:comment w:id="${e}" w:author="${s}" w:date="${n}" w:initials="${i}">
202
+ <w:p w14:paraId="${Ne(o)}" xmlns:w14="${gn}">
203
203
  <w:r><w:t>${a}</w:t></w:r>
204
204
  </w:p>
205
- </w:comment>`}function To(e){if(!e||e.length===0)return`<w:comments xmlns:w="${E}"></w:comments>`;let t=e.map(r=>Nr(r.id,r.author,r.content,r.date,r.paraId)).join(`
205
+ </w:comment>`}function Ao(e){if(!e||e.length===0)return`<w:comments xmlns:w="${E}"></w:comments>`;let t=e.map(r=>vr(r.id,r.author,r.content,r.date,r.paraId)).join(`
206
206
  `);return`<w:comments xmlns:w="${E}">
207
207
  ${t}
208
- </w:comments>`}function Ua(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="${nt}">${t}</w15:commentsEx>`}function mn(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=rr(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 Ha(e){return String(e).replace(/[ \u00a0]/g," ")}function yr(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Va(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 Ga(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 Ka(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(Ga(n,["del"]))return{found:!1,error:yr("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(Ga(n,["moveFrom","moveTo"]))return{found:!1,error:yr("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function So(e,t){let r=String(t??""),n=ja(e.fullText,r);if(n.length>1)return{found:!1,error:yr("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=Va(e,n[0],"exact_anchor");if(s)return Ka(e,s)}let o=Ha(r),i=Ha(e.fullText),a=ja(i,o);if(a.length>1)return{found:!1,error:yr("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${a.length} locations in the target paragraph.`,a)};if(a.length===1){let s=Va(e,a[0],"space_equivalent_anchor");if(s)return Ka(e,s)}return{found:!1,error:yr("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function vr(e,t,r,n,o=!1){let i=O(e,"w:r");if(t){let s=t.cloneNode(!0);o||ct(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 Ya(e,t,r,n,o=null,i=null,a=null){let s=o||mn(t),l=a||So(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 h=l.startRun,g=ie(h,"w:t");if(!g)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=g.textContent||"",x=w.substring(0,l.startOffset),y=w.substring(l.startOffset,l.endOffset),N=w.substring(l.endOffset),T=ie(h,"w:rPr"),v=h.parentNode;return x&&(v.insertBefore(vr(e,T,x,i,!0),h),ct(T,i)),v.insertBefore(c,h),g.textContent=y,h.nextSibling?v.insertBefore(u,h.nextSibling):v.appendChild(u),v.insertBefore(f,u.nextSibling||null),N&&v.insertBefore(vr(e,T,N,i),f.nextSibling||null),!0}let d=ie(l.startRun,"w:t");if(d&&l.startOffset>0){let h=d.textContent||"",g=h.substring(0,l.startOffset),w=h.substring(l.startOffset);if(g){let x=ie(l.startRun,"w:rPr");l.startRun.parentNode.insertBefore(vr(e,x,g,i,!0),l.startRun),ct(x,i)}d.textContent=w}l.startRun.parentNode.insertBefore(c,l.startRun);let p=l.endRun||l.startRun,b=ie(p,"w:t");if(b&&l.endOffset<(b.textContent||"").length){let h=b.textContent||"",g=h.substring(0,l.endOffset),w=h.substring(l.endOffset);if(b.textContent=g,w){let x=ie(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(vr(e,x,w,i),p.nextSibling):p.parentNode.appendChild(vr(e,x,w,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 jt="http://schemas.microsoft.com/office/2006/xmlPackage",Tr="http://schemas.openxmlformats.org/package/2006/relationships";function Ja(e,t){let r=me(),n=j(e,"text/xml"),o=n.doc,i=o?re(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(jt,"pkg:part");s.setAttribute("pkg:name","/word/comments.xml"),s.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let l=o.createElementNS(jt,"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,jt,"part").find(m=>m.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let m=ce(f,jt,"xmlData");if(m.length>0){let d=ce(m[0],Tr,"Relationships");if(d.length>0){let p=d[0],b=ce(p,Tr,"Relationship");if(!b.some(g=>g.getAttribute("Type")?.includes("comments"))){let g=0;b.forEach(x=>{let y=x.getAttribute("Id"),N=parseInt(y?.replace("rId","")||"0",10);N>g&&(g=N)});let w=o.createElementNS(Tr,"Relationship");w.setAttribute("Id",`rId${g+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let m=o.createElementNS(jt,"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(jt,"pkg:xmlData"),p=o.createElementNS(Tr,"Relationships"),b=o.createElementNS(Tr,"Relationship");b.setAttribute("Id","rId1"),b.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),b.setAttribute("Target","comments.xml"),p.appendChild(b),d.appendChild(p),m.appendChild(d),a.appendChild(m)}return r.serializeToString(o)}function Ku(e,t){let r=j(e,"text/xml"),n=r.doc?re(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 Yu(e,t,r={}){let n=r?.author||de(),o=Or(),i=[],a=[],s=[],l=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=me(),u=Ku(e,h=>`Failed to parse OXML: ${h}`);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=ot(f),d=rr(f,"w:p");k(`[CommentEngine] Found ${d.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let g=h.paragraphIndex-1;if(g<0||g>=d.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${d.length})`;i.push(w),l.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(g,(p.get(g)||0)+1)}let b=new Map;for(let[h,g]of t.entries()){let w=g.paragraphIndex-1;if(w<0||w>=d.length)continue;let x=d[w],y=b.get(w);y||(y=mn(x),b.set(w,y));let N=String(g.textToFind??""),T=So(y,N),v=(p.get(w)||1)-1;if(p.set(w,v),!T.found){let _={...T.error,requestIndex:h+1,paragraphIndex:g.paragraphIndex};l.push(_),i.push(_.message),v===0&&b.delete(w);continue}let S=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():Go();if(!Ya(f,x,N,S,y,m,T)){let _={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${g.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:g.paragraphIndex};l.push(_),i.push(_.message),v===0&&b.delete(w);continue}a.push({id:S,content:g.commentContent,author:n,date:o}),s.push({requestIndex:h+1,paragraphIndex:g.paragraphIndex,text:N,resolvedBy:T.resolvedBy,start:T.start,end:T.end}),v>0?b.set(w,mn(x)):b.delete(w)}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:To(a),commentsApplied:a.length,placedComments:a,warnings:i,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}}function Ju(e,t){return Ja(e,t)}var qa="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Sr(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function dn(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 qu(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=Sr(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=Sr(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function Za(e,t){let r=yo(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 Zu({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=dn(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let l=s.doc,c=Array.from(l.getElementsByTagNameNS("*","comment")).find(y=>Sr(y,"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 y=dn(t,"word/commentsExtended.xml");if(y.error)return{status:"error",error:y.error};u=y.doc}let f=qu(l,u),m=Array.from(c.getElementsByTagNameNS(qa,"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=Sr(m,"w14:paraId","paraId");d?d=d.toUpperCase():(d=Za(r,f),m.setAttributeNS(fn,"w14:paraId",d));let p=Za(n,f),b=dn(`<w:comments xmlns:w="${qa}" xmlns:w14="${fn}">${Nr(n,i,o,a,p)}</w:comments>`,"reply comment");l.documentElement.appendChild(l.importNode(b.doc.documentElement.firstChild,!0)),u||(u=dn(Ua([]),"word/commentsExtended.xml").doc);let h=u.documentElement;if(!Array.from(h.getElementsByTagNameNS("*","commentEx")).some(y=>Sr(y,"w15:paraId","paraId").toUpperCase()===d)){let y=u.createElementNS(nt,"w15:commentEx");y.setAttributeNS(nt,"w15:paraId",d),y.setAttributeNS(nt,"w15:done","0"),h.appendChild(y)}let w=u.createElementNS(nt,"w15:commentEx");w.setAttributeNS(nt,"w15:paraId",p),w.setAttributeNS(nt,"w15:paraIdParent",d),w.setAttributeNS(nt,"w15:done","0"),h.appendChild(w);let x=me();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 Ht(e){e?.parentNode&&e.parentNode.removeChild(e)}function Qa(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(Ht)});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(Ht)})}return r.children.length>0?r:null}function Qu(e,t,r){if(!t||!e)return e;let n=tt(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=Qa(m,r);d?m.parentNode&&m.parentNode.replaceChild(d,m):Ht(m)}}}return vt(n)}var ef={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 tf(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=ef[r.toLowerCase()]||"yellow",a=n?.generateRedlines??!1,s=n?.author||de(),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(Ht);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=oe(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(Ht),l.appendChild(m)}return l}function rf(e,t,r="yellow",n={}){if(!t||!e)return e;let o=tt(e);if(!o)return e;let i;n?._revisionIdAllocator instanceof he?(i=n._revisionIdAllocator,At(o,i)):i=ot(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)?ct(p,i):c.add(f);let b=p.getElementsByTagNameNS(a,"t");Array.from(b).forEach(Ht);let h=O(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=m,p.appendChild(h),d){let g=p.getElementsByTagNameNS(a,"rPr"),w=g.length>0?g[0]:null,x=tf(o,w,r,n);w?p.replaceChild(x,w):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 w=m.indexOf(t,p);if(w===-1)break;d.push(w),p=w+t.length}if(d.length===0)continue;let b=f.parentNode;if(!b){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),g=0;for(let w of d)w>g&&h.appendChild(u(f,m.slice(g,w),!1)),h.appendChild(u(f,m.slice(w,w+t.length),!0)),g=w+t.length;g<m.length&&h.appendChild(u(f,m.slice(g),!1)),b.replaceChild(h,f)}return vt(o)}var Ae="http://schemas.openxmlformats.org/wordprocessingml/2006/main",nf="http://schemas.openxmlformats.org/package/2006/content-types",of="http://schemas.openxmlformats.org/package/2006/relationships",ts="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",rs="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",ns="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",os="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",is="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",as="application/vnd.ms-word.commentsExtended+xml",es="word/document.xml",pn="word/numbering.xml",Er="word/comments.xml",Eo="word/commentsExtended.xml",_e="[Content_Types].xml",Le="word/_rels/document.xml.rels";function ge(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 gn(e){return!!e&&e.nodeType===1&&e.namespaceURI===Ae&&e.localName==="sectPr"}function Io(e){return e.getElementsByTagNameNS("*","body")[0]||null}function ss(e){for(let t of Array.from(e.childNodes||[]))if(gn(t))return t;return null}function af(e,t){let r=ss(e);r?e.insertBefore(t,r):e.appendChild(t)}function ls(e){let t=Io(e);if(!t)return;let r=ss(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function sf(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(Ae,"tc"),o=0;for(let i of Array.from(n)){let a=Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===Ae&&s.localName==="p");for(let s of a){let l=Array.from(s.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===Ae&&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 Ao(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function lf(e){let t=me(),r=ge(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(f=>Ao(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&&!gn(f)):[a],c=n.find(f=>Ao(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 cf(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 lf(e);if(e.includes("<w:document")){let o=ge(e,"document OOXML"),i=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:i?Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&!gn(s)):Array.from(o.childNodes||[]).filter(s=>s.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${Ae}">${e}</root>`,r=ge(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 Po(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(nf,"Override");return i.setAttribute("PartName",t),i.setAttribute("ContentType",r),e.documentElement.appendChild(i),!0}function Ro(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(of,"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 Pe(e,t){let r=e.file(t);return r?r.async("string"):null}async function uf(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:Fe,a=(Array.isArray(t)?t:[t]).filter(Boolean);if(a.length===0)return;let s=await Pe(e,pn);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(pn,l);let c=me(),u=await Pe(e,_e);if(u){let m=ge(u,_e);Po(m,"/word/numbering.xml",rs)&&e.file(_e,c.serializeToString(m))}let f=await Pe(e,Le);if(f){let m=ge(f,Le);Ro(m,ts,"numbering.xml",r)&&e.file(Le,c.serializeToString(m))}}async function ff(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=me(),i=await Pe(e,Er);if(!i||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(Er,t);else{let l=ge(i,"word/comments.xml (existing)"),c=ge(t,"word/comments.xml (incoming)"),u=l.documentElement,f=new Set(Array.from(u.getElementsByTagNameNS(Ae,"comment")).map(m=>m.getAttribute("w:id")||m.getAttribute("id")).filter(Boolean));for(let m of Array.from(c.documentElement.getElementsByTagNameNS(Ae,"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(Er,o.serializeToString(l))}let a=await Pe(e,_e);if(a){let l=ge(a,_e);Po(l,"/word/comments.xml",os)&&e.file(_e,o.serializeToString(l))}let s=await Pe(e,Le);if(s){let l=ge(s,Le);Ro(l,ns,"comments.xml",r)&&e.file(Le,o.serializeToString(l))}}async function mf(e,t,r={}){if(!t)return;ge(t,"word/commentsExtended.xml"),e.file(Eo,t);let n=me(),o=await Pe(e,_e);if(o){let a=ge(o,_e);Po(a,"/word/commentsExtended.xml",as)&&e.file(_e,n.serializeToString(a))}let i=await Pe(e,Le);if(i){let a=ge(i,Le);Ro(a,is,"commentsExtended.xml",r)&&e.file(Le,n.serializeToString(a))}}async function df(e){let t=await Pe(e,es);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=ge(t,es);ls(r);let n=Io(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),i=o.map((h,g)=>({node:h,index:g})).filter(h=>gn(h.node)).map(h=>h.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(Ae,"tc");for(let h of Array.from(a))for(let g of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(g.namespaceURI===Ae&&g.localName==="p"&&Array.from(g.childNodes||[]).some(x=>x.nodeType===1&&x.namespaceURI===Ae&&x.localName==="p"))throw new Error("Validation failed: nested w:p");let s=r.getElementsByTagNameNS(Ae,"numPr").length>0,l=r.getElementsByTagNameNS(Ae,"commentRangeStart").length>0||r.getElementsByTagNameNS(Ae,"commentRangeEnd").length>0||r.getElementsByTagNameNS(Ae,"commentReference").length>0,c=await Pe(e,pn),u=await Pe(e,Er),f=await Pe(e,Eo);if(f&&!u)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)ge(c,pn);else if(s)throw new Error("Validation failed: numbering used but part missing");if(u){let h=ge(u,Er),g=(R,B)=>Array.from(R.getElementsByTagNameNS(Ae,B)).map($=>$.getAttribute("w:id")||$.getAttribute("id")).filter($=>$!==""),w=new Set(g(r,"commentRangeStart")),x=new Set(g(r,"commentRangeEnd")),y=new Set(g(r,"commentReference")),N=g(h,"comment"),T=new Set(N),v=R=>Array.from(R).sort((B,$)=>Number(B)-Number($)||B.localeCompare($)),S=(R,B)=>v(new Set(Array.from(R).filter($=>!B.has($)))),I=v(new Set(N.filter((R,B)=>N.indexOf(R)!==B)));if(I.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${I.join(", ")}`);let _=S(w,x),L=S(x,w);if(_.length>0||L.length>0){let R=[];throw _.length>0&&R.push(`start without end: ${_.join(", ")}`),L.length>0&&R.push(`end without start: ${L.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${R.join("; ")})`)}let F=S(new Set([...w,...x]),y);if(F.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${F.join(", ")}`);let X=S(new Set([...w,...x,...y]),T);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=ge(f,Eo),B=new Map;for(let V of Array.from(h.getElementsByTagNameNS("*","comment"))){let K=V.getAttribute("w:id")||V.getAttribute("id"),se=Array.from(V.getElementsByTagNameNS("*","p"))[0],Be=se?.getAttribute("w14:paraId")||se?.getAttribute("paraId");Be&&B.set(Be.toUpperCase(),K)}let $=new Set(B.keys()),Y=new Set;for(let V of Array.from(R.getElementsByTagNameNS("*","commentEx"))){let K=V.getAttribute("w15:paraId")||V.getAttribute("paraId"),se=V.getAttribute("w15:paraIdParent")||V.getAttribute("paraIdParent");if(!K||!$.has(K.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${K||"(missing)"}`);if(Y.has(K.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${K}`);if(Y.add(K.toUpperCase()),se){if(!$.has(se.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${se}`);C.add(B.get(K.toUpperCase()))}}}let U=S(new Set([...T].filter(R=>!C.has(R))),y);if(U.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${U.join(", ")}`)}else if(l)throw new Error("Validation failed: comments used but part missing");let m=await Pe(e,_e);if(!m)throw new Error(`Validation failed: missing ${_e}`);let d=ge(m,_e),p=await Pe(e,Le);if(!p)throw new Error(`Validation failed: missing ${Le}`);let b=ge(p,Le);if(c){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===rs),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===ts);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!g)throw new Error("Validation failed: numbering rel missing")}if(u){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===os),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===ns);if(!h)throw new Error("Validation failed: comments CT override missing");if(!g)throw new Error("Validation failed: comments rel missing")}if(f){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml"&&(w.getAttribute("ContentType")||"")===as),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===is);if(!h)throw new Error("Validation failed: commentsExtended CT override missing");if(!g)throw new Error("Validation failed: commentsExtended rel missing")}}var Vt=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 us(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
209
- `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function pf(e={}){let t=e.originalText||"",r=us(e.newContent||""),n=hr(r)||{type:"text",items:[]};return r.includes(`
210
- `)&&n.type!=="text"?{kind:Vt.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:cs(t),hasInlineFormatting:hn(r),hasBlockElements:wn(r),hasMarkdownTable:Ar(r)}}:cs(t)?hn(r)?{kind:Vt.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:wn(r),hasMarkdownTable:Ar(r)}}:{kind:Vt.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:wn(r),hasMarkdownTable:Ar(r)}}:wn(r)?{kind:Vt.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:hn(r),hasBlockElements:!0,hasMarkdownTable:Ar(r)}}:{kind:Vt.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:hn(r),hasBlockElements:!1,hasMarkdownTable:Ar(r)}}}function cs(e){return!e||e.trim().length===0}function Ar(e){if(!e||!e.includes("|"))return!1;let t=De(e);return t.rows.length>0||t.headers.length>0}function hn(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function wn(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(`
208
+ </w:comments>`}function Ga(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 Ka(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 Ya(e){return String(e).replace(/[ \u00a0]/g," ")}function Tr(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Ja(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 Za(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:Tr("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(qa(n,["moveFrom","moveTo"]))return{found:!1,error:Tr("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=Ka(e.fullText,r);if(n.length>1)return{found:!1,error:Tr("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=Ja(e,n[0],"exact_anchor");if(s)return Za(e,s)}let o=Ya(r),i=Ya(e.fullText),a=Ka(i,o);if(a.length>1)return{found:!1,error:Tr("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${a.length} locations in the target paragraph.`,a)};if(a.length===1){let s=Ja(e,a[0],"space_equivalent_anchor");if(s)return Za(e,s)}return{found:!1,error:Tr("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function yr(e,t,r,n,o=!1){let i=C(e,"w:r");if(t){let s=t.cloneNode(!0);o||at(s,n),i.appendChild(s)}let a=C(e,"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=r,i.appendChild(a),i}function Qa(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=C(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let u=C(e,"w:commentRangeEnd");u.setAttribute("w:id",String(n));let f=C(e,"w:r"),m=C(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),N=g.substring(l.startOffset,l.endOffset),v=g.substring(l.endOffset),T=ae(w,"w:rPr"),y=w.parentNode;return x&&(y.insertBefore(yr(e,T,x,i,!0),w),at(T,i)),y.insertBefore(c,w),b.textContent=N,w.nextSibling?y.insertBefore(u,w.nextSibling):y.appendChild(u),y.insertBefore(f,u.nextSibling||null),v&&y.insertBefore(yr(e,T,v,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",Sr="http://schemas.openxmlformats.org/package/2006/relationships";function es(e,t){let r=me(),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],Sr,"Relationships");if(d.length>0){let p=d[0],h=ce(p,Sr,"Relationship");if(!h.some(b=>b.getAttribute("Type")?.includes("comments"))){let b=0;h.forEach(x=>{let N=x.getAttribute("Id"),v=parseInt(N?.replace("rId","")||"0",10);v>b&&(b=v)});let g=o.createElementNS(Sr,"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(Sr,"Relationships"),h=o.createElementNS(Sr,"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 rf(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 nf(e,t,r={}){let n=r?.author||de(),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=me(),u=rf(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");M(`[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],N=h.get(g);N||(N=hn(x),h.set(g,N));let v=String(b.textToFind??""),T=Io(N,v),y=(p.get(g)||1)-1;if(p.set(g,y),!T.found){let L={...T.error,requestIndex:w+1,paragraphIndex:b.paragraphIndex};l.push(L),i.push(L.message),y===0&&h.delete(g);continue}let S=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():qo();if(!Qa(f,x,v,S,N,m,T)){let L={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${b.paragraphIndex}.`,requestIndex:w+1,paragraphIndex:b.paragraphIndex};l.push(L),i.push(L.message),y===0&&h.delete(g);continue}a.push({id:S,content:b.commentContent,author:n,date:o}),s.push({requestIndex:w+1,paragraphIndex:b.paragraphIndex,text:v,resolvedBy:T.resolvedBy,start:T.start,end:T.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 of(e,t){return es(e,t)}var ts="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 af(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 rs(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 sf({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(N=>Er(N,"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 N=wn(t,"word/commentsExtended.xml");if(N.error)return{status:"error",error:N.error};u=N.doc}let f=af(l,u),m=Array.from(c.getElementsByTagNameNS(ts,"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=rs(r,f),m.setAttributeNS(gn,"w14:paraId",d));let p=rs(n,f),h=wn(`<w:comments xmlns:w="${ts}" 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(Ga([]),"word/commentsExtended.xml").doc);let w=u.documentElement;if(!Array.from(w.getElementsByTagNameNS("*","commentEx")).some(N=>Er(N,"w15:paraId","paraId").toUpperCase()===d)){let N=u.createElementNS(rt,"w15:commentEx");N.setAttributeNS(rt,"w15:paraId",d),N.setAttributeNS(rt,"w15:done","0"),w.appendChild(N)}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=me();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 ns(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 lf(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=ns(m,r);d?m.parentNode&&m.parentNode.replaceChild(d,m):Gt(m)}}}return yt(n)}var cf={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 uf(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=cf[r.toLowerCase()]||"yellow",a=n?.generateRedlines??!1,s=n?.author||de(),l=t;l?l=t.cloneNode(!0):l=C(e,"w:rPr");let c=null;a&&(c=C(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=C(e,"w:highlight");if(f.setAttributeNS(o,"w:val",i),l.appendChild(f),a&&c){let m=C(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 ff(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=C(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=uf(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",mf="http://schemas.openxmlformats.org/package/2006/content-types",df="http://schemas.openxmlformats.org/package/2006/relationships",is="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",as="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",ss="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",ls="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",cs="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",us="application/vnd.ms-word.commentsExtended+xml",os="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 fs(e){for(let t of Array.from(e.childNodes||[]))if(xn(t))return t;return null}function pf(e,t){let r=fs(e);r?e.insertBefore(t,r):e.appendChild(t)}function ms(e){let t=Co(e);if(!t)return;let r=fs(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function gf(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 hf(e){let t=me(),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 wf(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 hf(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(mf,"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(df,"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 bf(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=me(),u=await Re(e,_e);if(u){let m=he(u,_e);Oo(m,"/word/numbering.xml",as)&&e.file(_e,c.serializeToString(m))}let f=await Re(e,Le);if(f){let m=he(f,Le);ko(m,is,"numbering.xml",r)&&e.file(Le,c.serializeToString(m))}}async function xf(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=me(),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",ls)&&e.file(_e,o.serializeToString(l))}let s=await Re(e,Le);if(s){let l=he(s,Le);ko(l,ss,"comments.xml",r)&&e.file(Le,o.serializeToString(l))}}async function Nf(e,t,r={}){if(!t)return;he(t,"word/commentsExtended.xml"),e.file(Po,t);let n=me(),o=await Re(e,_e);if(o){let a=he(o,_e);Oo(a,"/word/commentsExtended.xml",us)&&e.file(_e,n.serializeToString(a))}let i=await Re(e,Le);if(i){let a=he(i,Le);ko(a,cs,"commentsExtended.xml",r)&&e.file(Le,n.serializeToString(a))}}async function vf(e){let t=await Re(e,os);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=he(t,os);ms(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")),N=new Set(b(r,"commentReference")),v=b(w,"comment"),T=new Set(v),y=R=>Array.from(R).sort((B,$)=>Number(B)-Number($)||B.localeCompare($)),S=(R,B)=>y(new Set(Array.from(R).filter($=>!B.has($)))),I=y(new Set(v.filter((R,B)=>v.indexOf(R)!==B)));if(I.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${I.join(", ")}`);let L=S(g,x),_=S(x,g);if(L.length>0||_.length>0){let R=[];throw L.length>0&&R.push(`start without end: ${L.join(", ")}`),_.length>0&&R.push(`end without start: ${_.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${R.join("; ")})`)}let F=S(new Set([...g,...x]),N);if(F.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${F.join(", ")}`);let D=S(new Set([...g,...x,...N]),T);if(D.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${D.join(", ")}`);let O=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}`);O.add(B.get(Y.toUpperCase()))}}}let U=S(new Set([...T].filter(R=>!O.has(R))),N);if(U.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${U.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")||"")===as),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===is);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")||"")===ls),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===ss);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")||"")===us),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===cs);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 ps(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
209
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function yf(e={}){let t=e.originalText||"",r=ps(e.newContent||""),n=wr(r)||{type:"text",items:[]};return r.includes(`
210
+ `)&&n.type!=="text"?{kind:Kt.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:ds(t),hasInlineFormatting:Nn(r),hasBlockElements:vn(r),hasMarkdownTable:Ir(r)}}:ds(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 ds(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(`
211
211
 
212
- `);return t||r||n||o||i||a||s||l||c}function gf(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 Co=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(i=>i.id===o&&i.kind===r&&i.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 hf(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 wf(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 i=new Set,a=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
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 fs(e,t,r,n={}){let o=await so(e,t,r,n);if(o?.useNativeApi&&typeof o?.oxml!="string"){let i=Array.isArray(o?.warnings)?o.warnings:[];return ae({...o,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return o}async function aw(e,t,r,n={}){let o=typeof e=="string"?e:"",i=typeof r=="string"?r:String(r||""),a;try{a=De(i)}catch{a={headers:[],rows:[]}}return(a?.headers?.length||0)>0||(a?.rows?.length||0)>0?{...await fs(o,t||"",i,n),isMarkdownTable:!0,tableData:a}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function sw(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,i=n.sanitizeInput===!0?lo(r):r,a=i!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],s=go({oxml:e,originalText:t,modifiedText:i,allowExistingList:o}),l=n.preferListStructuralFallback!==!1,c=[];if(s&&l){let b=await an(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(b?.hasChanges&&b?.oxml){let h=at(b.oxml,{includeNumbering:b.includeNumbering??!0,numberingXml:b.numberingXml}),g=Array.isArray(b?.warnings)?b.warnings:[];return ae({oxml:h,hasChanges:!0,warnings:[...a,...g],listStructuralFallbackApplied:!0,listStructuralFallbackKey:b.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:b.numberingXml||null})}c=Array.isArray(b?.warnings)?b.warnings:[]}let u=await fs(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 an(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let b=Array.isArray(u?.warnings)?u.warnings:[],h=Array.isArray(f?.warnings)?f.warnings:[];return{...u,warnings:[...b,...h],listStructuralFallbackApplied:!1}}let m=at(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),d=Array.isArray(u?.warnings)?u.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return ae({...u,oxml:m,hasChanges:!0,warnings:[...d,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{Et as ContainerKind,Ho as ContentType,ke as DiffOp,E as NS_W,qe as NumberingService,Co as ReceiptCollector,ir as ReconciliationPipeline,Vt as RoutePlanKind,D as RunKind,Oe as WORD_MAIN_NS,to as acceptTrackedChangesInOoxml,Xr as analyzeStructuredContent,Zu as applyCommentReplyToParts,Qu as applyFormattingRemovalToOoxml,rf as applyHighlightToOoxml,fs as applyRedlineToOxml,sw as applyRedlineToOxmlWithListFallback,Lu as areRevisionTokensEqual,Nr as buildCommentElement,To as buildCommentsPartXml,vu as buildExplicitDecimalMultilevelNumberingXml,Uc as buildListMarkdown,pf as buildReconciliationPlan,No as buildRevisionTokenFraming,go as buildSingleLineListStructuralFallbackPlan,Bc as buildTargetReferenceSnapshot,Jc as clearSingleLineListFallbackExplicitSequence,Ia as collectContiguousListParagraphBlock,Mu as computeDocumentPartsRevisionToken,Da as computeRevisionToken,vo as computeRevisionTokenSync,ys as configureLogger,Ts as configureXmlProvider,$r as containsTrackedChanges,gu as createDynamicNumberingIdState,hf as createEmptyReceipt,Ft as createParagraphFingerprint,Ec as deleteCommentsByAuthorInOoxml,qc as enforceListBindingOnParagraphNodes,ff as ensureCommentsArtifactsInZip,mf as ensureCommentsExtendedArtifactsInZip,uf as ensureNumberingArtifactsInZip,Ne as escapeXml,an as executeSingleLineListStructuralFallback,be as extractCanonicalParagraphText,cn as extractDocumentPartsEntries,Nu as extractFirstParagraphNumId,gf as extractParagraphIdFromOoxml,jr as extractParagraphRevisionSegments,cf as extractReplacementNodesFromOoxml,$t as findContainingWordElement,co as findParagraphByBestTextMatch,va as findParagraphByReference,en as findParagraphByStrictText,tn as findStrictTargetCandidates,ht as generateTableOoxml,Io as getBodyElementFromDocument,de as getDefaultAuthor,Ee as getDocumentParagraphNodes,Ao as getPackagePartName,yt as getParagraphId,rt as getParagraphListInfo,ue as getParagraphText,yn as getPlatform,Fn as getTrackedChangeAuthors,po as hasListItems,Zt as inferNumberingStyleFromMarker,du as inferTableReplacementParagraphBlock,Rt as ingestOoxml,ku as ingestWordOoxmlToMarkdown,$a as ingestWordOoxmlToMarkdownResult,Ou as ingestWordOoxmlToPlainText,Fa as ingestWordOoxmlToPlainTextResult,Yu as injectCommentsIntoOoxml,Ju as injectCommentsIntoPackage,af as insertBodyElementBeforeSectPr,Gu as inspectDocumentParts,Oa as isLikelyStructuredTableSourceParagraph,fo as isMarkdownTableText,bt as isNodeVisibleInRevisionView,Tu as mergeNumberingXmlBySchemaOrder,ls as normalizeBodySectionOrderStandalone,us as normalizeContentEscapesForRouting,jc as normalizeListItemsWithLevels,Xa as normalizeOpcEntryName,H as normalizeWhitespaceForTargeting,xu as overwriteParagraphNumIds,hr as parseMarkdownListContent,tt as parseOoxml,j as parseOoxmlSafe,mo as parseParagraphReference,Wc as planListInsertionOnlyEdit,Cl as planStructuredReplacement,Ie as preprocessMarkdown,xt as readCanonicalRunText,aw as reconcileMarkdownTableOoxml,wf as reconcileReceiptsAgainstOutput,Yc as recordSingleLineListFallbackExplicitSequence,ro as rejectTrackedChangesInOoxml,yu as remapNumberingPayloadForDocument,Qa as removeFormattingFromRPr,br as reserveNextNumberingId,wu as reserveNextNumberingIdPair,Fc as resolveParagraphRangeByRefs,Kc as resolveSingleLineListFallbackNumberingAction,ya as resolveTargetParagraph,uo as resolveTargetParagraphWithSnapshot,lo as sanitizeAiResponse,sf as sanitizeNestedParagraphsInTables,vt as serializeOoxml,Xe as serializeToOoxml,As as setDefaultAuthor,Is as setPlatform,kc as splitLeadingParagraphMarker,Oc as stripLeadingParagraphMarker,Ea as stripRedundantLeadingListMarkers,Vc as stripSingleLineListMarkerPrefix,zc as synthesizeExpandedListScopeEdit,pu as synthesizeTableMarkdownFromMultilineCellEdit,df as validateDocxPackage,lu as validateRedlineOoxml,_u as validateRevisionToken,at as wrapInDocumentFragment};
212
+ `);return t||r||n||o||i||a||s||l||c}function Tf(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 Mo=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(i=>i.id===o&&i.kind===r&&i.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 Sf(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 Ef(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 i=new Set,a=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
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 gs(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 hw(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 gs(o,t||"",i,n),isMarkdownTable:!0,tableData:a}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function ww(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 gs(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,X as RunKind,Oe as WORD_MAIN_NS,oo as acceptTrackedChangesInOoxml,Wr as analyzeStructuredContent,sf as applyCommentReplyToParts,lf as applyFormattingRemovalToOoxml,ff as applyHighlightToOoxml,gs as applyRedlineToOxml,ww as applyRedlineToOxmlWithListFallback,Uu as areRevisionTokensEqual,vr as buildCommentElement,Ao as buildCommentsPartXml,Ru as buildExplicitDecimalMultilevelNumberingXml,qc as buildListMarkdown,yf as buildReconciliationPlan,To as buildRevisionTokenFraming,bo as buildSingleLineListStructuralFallbackPlan,jc as buildTargetReferenceSnapshot,ou as clearSingleLineListFallbackExplicitSequence,Oa as collectContiguousListParagraphBlock,zu as computeDocumentPartsRevisionToken,ja as computeRevisionToken,So as computeRevisionTokenSync,As as configureLogger,Is as configureXmlProvider,zr as containsTrackedChanges,Tu as createDynamicNumberingIdState,Sf as createEmptyReceipt,Tt as createParagraphFingerprint,Cc as deleteCommentsByAuthorInOoxml,iu as enforceListBindingOnParagraphNodes,xf as ensureCommentsArtifactsInZip,Nf as ensureCommentsExtendedArtifactsInZip,bf as ensureNumberingArtifactsInZip,Ne as escapeXml,un as executeSingleLineListStructuralFallback,pe as extractCanonicalParagraphText,dn as extractDocumentPartsEntries,Pu as extractFirstParagraphNumId,Tf as extractParagraphIdFromOoxml,Kr as extractParagraphRevisionSegments,wf as extractReplacementNodesFromOoxml,Dt as findContainingWordElement,mo as findParagraphByBestTextMatch,Ea as findParagraphByReference,on as findParagraphByStrictText,an as findStrictTargetCandidates,ht as generateTableOoxml,Co as getBodyElementFromDocument,de as getDefaultAuthor,Se as getDocumentParagraphNodes,Ro as getPackagePartName,St as getParagraphId,tt as getParagraphListInfo,ue as getParagraphText,En as getPlatform,Dn as getTrackedChangeAuthors,wo as hasListItems,Qt as inferNumberingStyleFromMarker,vu as inferTableReplacementParagraphBlock,kt as ingestOoxml,Du as ingestWordOoxmlToMarkdown,Wa as ingestWordOoxmlToMarkdownResult,Xu as ingestWordOoxmlToPlainText,za as ingestWordOoxmlToPlainTextResult,nf as injectCommentsIntoOoxml,of as injectCommentsIntoPackage,pf as insertBodyElementBeforeSectPr,tf as inspectDocumentParts,La as isLikelyStructuredTableSourceParagraph,go as isMarkdownTableText,bt as isNodeVisibleInRevisionView,Ou as mergeNumberingXmlBySchemaOrder,ms as normalizeBodySectionOrderStandalone,ps as normalizeContentEscapesForRouting,Zc as normalizeListItemsWithLevels,Ua as normalizeOpcEntryName,H as normalizeWhitespaceForTargeting,Iu as overwriteParagraphNumIds,wr as parseMarkdownListContent,et as parseOoxml,j as parseOoxmlSafe,ho as parseParagraphReference,Jc as planListInsertionOnlyEdit,_l as planStructuredReplacement,Ie as preprocessMarkdown,xt as readCanonicalRunText,hw as reconcileMarkdownTableOoxml,Ef as reconcileReceiptsAgainstOutput,nu as recordSingleLineListFallbackExplicitSequence,io as rejectTrackedChangesInOoxml,Cu as remapNumberingPayloadForDocument,ns as removeFormattingFromRPr,xr as reserveNextNumberingId,Eu as reserveNextNumberingIdPair,Hc as resolveParagraphRangeByRefs,ru as resolveSingleLineListFallbackNumberingAction,Aa as resolveTargetParagraph,po as resolveTargetParagraphWithSnapshot,fo as sanitizeAiResponse,gf as sanitizeNestedParagraphsInTables,yt as serializeOoxml,$e as serializeToOoxml,Cs as setDefaultAuthor,Os as setPlatform,Dc as splitLeadingParagraphMarker,Xc as stripLeadingParagraphMarker,Ra as stripRedundantLeadingListMarkers,eu as stripSingleLineListMarkerPrefix,Yc as synthesizeExpandedListScopeEdit,yu as synthesizeTableMarkdownFromMultilineCellEdit,vf as validateDocxPackage,hu as validateRedlineOoxml,Wu as validateRevisionToken,it as wrapInDocumentFragment};
214
214
  //# sourceMappingURL=docx-redline-js.esm.min.js.map