@ansonlai/docx-redline-js 0.8.4 → 0.10.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 (72) hide show
  1. package/ARCHITECTURE.md +679 -460
  2. package/CHANGELOG.md +208 -1
  3. package/README.md +152 -16
  4. package/core/current-properties.js +136 -0
  5. package/core/paragraph-text.js +211 -209
  6. package/core/types.js +9 -3
  7. package/core/word-revision-semantics.js +256 -0
  8. package/core/word-xml.js +160 -118
  9. package/dist/docx-redline-js.esm.js +4338 -796
  10. package/dist/docx-redline-js.esm.js.map +4 -4
  11. package/dist/docx-redline-js.esm.min.js +111 -108
  12. package/dist/docx-redline-js.esm.min.js.map +4 -4
  13. package/dist/docx-redline.bundle.cjs +4463 -921
  14. package/dist/docx-redline.bundle.cjs.map +4 -4
  15. package/dist/docx-redline.bundle.js +4463 -921
  16. package/dist/docx-redline.bundle.js.map +4 -4
  17. package/docs/AGENT_FAST_START.md +2 -0
  18. package/docs/AGENT_KNOWLEDGE_BASE.md +49 -7
  19. package/docs/SKILL_AUTHORING.md +169 -150
  20. package/docs/TESTING.md +1146 -1059
  21. package/docs/schemas/document-operations.schema.json +55 -2
  22. package/document/docx-document.js +1022 -1010
  23. package/engine/oxml-engine.js +21 -22
  24. package/engine/paragraph-mark-revisions.js +292 -0
  25. package/engine/reconstruction-mapper.js +312 -311
  26. package/engine/reconstruction-writer.js +67 -10
  27. package/engine/rpr-helpers.js +42 -0
  28. package/engine/run-builders.js +0 -73
  29. package/engine/surgical-diff-application.js +604 -605
  30. package/engine/table-mode.js +63 -63
  31. package/index.d.ts +53 -2
  32. package/index.js +13 -2
  33. package/node/cli-help.js +1 -0
  34. package/node/cli.js +21 -3
  35. package/orchestration/list-structural-fallback.js +67 -9
  36. package/package.json +1 -1
  37. package/pipeline/diff-engine.js +130 -1
  38. package/pipeline/ingestion-export.js +227 -243
  39. package/pipeline/ingestion-paragraph.js +93 -98
  40. package/pipeline/list-generation.js +415 -419
  41. package/pipeline/markdown-processor.js +5 -2
  42. package/pipeline/pipeline.js +206 -204
  43. package/scripts/export-validation-fixtures.mjs +19 -6
  44. package/scripts/generate-word-revision-semantics-matrix.mjs +134 -0
  45. package/scripts/lib/word-coverage-catalogue.mjs +7 -2
  46. package/scripts/render-multilevel-bullet-visual.ps1 +2 -2
  47. package/scripts/word-com-corpus-visual-suite.ps1 +2 -2
  48. package/scripts/word-com-differential.ps1 +443 -335
  49. package/scripts/word-com-visual-suite.ps1 +2 -2
  50. package/scripts/word-revision-semantics-matrix.ps1 +108 -0
  51. package/services/batch-operation-orchestrator.js +23 -3
  52. package/services/capture-engine.js +228 -226
  53. package/services/comment-replies.js +1 -1
  54. package/services/document-operation-applier.js +214 -0
  55. package/services/document-operation-contract.js +76 -0
  56. package/services/document-operation-mutations.js +688 -51
  57. package/services/error-recovery.js +17 -0
  58. package/services/inspection-comparison.js +82 -0
  59. package/services/list-conversion-diagnostics.js +296 -0
  60. package/services/list-format-change.js +586 -0
  61. package/services/list-format-mutation.js +416 -0
  62. package/services/list-format.js +305 -0
  63. package/services/numbering-allocation.js +642 -0
  64. package/services/numbering-helpers.js +354 -524
  65. package/services/operation-batch-compiler.js +183 -11
  66. package/services/operation-preflight.js +43 -33
  67. package/services/receipt-collector.js +288 -288
  68. package/services/revision-comment-management.js +38 -5
  69. package/services/revision-fidelity-verifier.js +484 -0
  70. package/services/standalone-docx-plumbing.js +627 -631
  71. package/services/standalone-operation-runner.d.ts +182 -5
  72. package/services/table-reconciliation.js +59 -7
@@ -1,16 +1,16 @@
1
- var Af=Object.create;var _s=Object.defineProperty;var Ef=Object.getOwnPropertyDescriptor;var Rf=Object.getOwnPropertyNames;var Pf=Object.getPrototypeOf,Cf=Object.prototype.hasOwnProperty;var Of=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var _f=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rf(t))!Cf.call(e,o)&&o!==r&&_s(e,o,{get:()=>t[o],enumerable:!(n=Ef(t,o))||n.enumerable});return e};var ks=(e,t,r)=>(r=e!=null?Af(Pf(e)):{},_f(t||!e||!e.__esModule?_s(r,"default",{value:e,enumerable:!0}):r,e));var ti=Of((mw,an)=>{var $=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},ge=-1,ye=1,Q=0;$.Diff=function(e,t){return[e,t]};$.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 $.Diff(Q,e)]:[];typeof r>"u"&&(r=!0);var a=r,i=this.diff_commonPrefix(e,t),s=e.substring(0,i);e=e.substring(i),t=t.substring(i),i=this.diff_commonSuffix(e,t);var l=e.substring(e.length-i);e=e.substring(0,e.length-i),t=t.substring(0,t.length-i);var c=this.diff_compute_(e,t,a,o);return s&&c.unshift(new $.Diff(Q,s)),l&&c.push(new $.Diff(Q,l)),this.diff_cleanupMerge(c),c};$.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new $.Diff(ye,t)];if(!t)return[new $.Diff(ge,e)];var a=e.length>t.length?e:t,i=e.length>t.length?t:e,s=a.indexOf(i);if(s!=-1)return o=[new $.Diff(ye,a.substring(0,s)),new $.Diff(Q,i),new $.Diff(ye,a.substring(s+i.length))],e.length>t.length&&(o[0][0]=o[2][0]=ge),o;if(i.length==1)return[new $.Diff(ge,e),new $.Diff(ye,t)];var l=this.diff_halfMatch_(e,t);if(l){var c=l[0],u=l[1],f=l[2],d=l[3],m=l[4],p=this.diff_main(c,f,r,n),g=this.diff_main(u,d,r,n);return p.concat([new $.Diff(Q,m)],g)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};$.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var o=n.lineArray,a=this.diff_main(e,t,!1,r);this.diff_charsToLines_(a,o),this.diff_cleanupSemantic(a),a.push(new $.Diff(Q,""));for(var i=0,s=0,l=0,c="",u="";i<a.length;){switch(a[i][0]){case ye:l++,u+=a[i][1];break;case ge:s++,c+=a[i][1];break;case Q:if(s>=1&&l>=1){a.splice(i-s-l,s+l),i=i-s-l;for(var f=this.diff_main(c,u,!1,r),d=f.length-1;d>=0;d--)a.splice(i,0,f[d]);i=i+f.length}l=0,s=0,c="",u="";break}i++}return a.pop(),a};$.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,o=t.length,a=Math.ceil((n+o)/2),i=a,s=2*a,l=new Array(s),c=new Array(s),u=0;u<s;u++)l[u]=-1,c[u]=-1;l[i+1]=0,c[i+1]=0;for(var f=n-o,d=f%2!=0,m=0,p=0,g=0,h=0,y=0;y<a&&!(new Date().getTime()>r);y++){for(var w=-y+m;w<=y-p;w+=2){var v=i+w,b;w==-y||w!=y&&l[v-1]<l[v+1]?b=l[v+1]:b=l[v-1]+1;for(var x=b-w;b<n&&x<o&&e.charAt(b)==t.charAt(x);)b++,x++;if(l[v]=b,b>n)p+=2;else if(x>o)m+=2;else if(d){var T=i+f-w;if(T>=0&&T<s&&c[T]!=-1){var I=n-c[T];if(b>=I)return this.diff_bisectSplit_(e,t,b,x,r)}}}for(var N=-y+g;N<=y-h;N+=2){var T=i+N,I;N==-y||N!=y&&c[T-1]<c[T+1]?I=c[T+1]:I=c[T-1]+1;for(var A=I-N;I<n&&A<o&&e.charAt(n-I-1)==t.charAt(o-A-1);)I++,A++;if(c[T]=I,I>n)h+=2;else if(A>o)g+=2;else if(!d){var v=i+f-N;if(v>=0&&v<s&&l[v]!=-1){var b=l[v],x=i+b-v;if(I=n-I,b>=I)return this.diff_bisectSplit_(e,t,b,x,r)}}}}return[new $.Diff(ge,e),new $.Diff(ye,t)]};$.prototype.diff_bisectSplit_=function(e,t,r,n,o){var a=e.substring(0,r),i=t.substring(0,n),s=e.substring(r),l=t.substring(n),c=this.diff_main(a,i,!1,o),u=this.diff_main(s,l,!1,o);return c.concat(u)};$.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(l){for(var c="",u=0,f=-1,d=r.length;f<l.length-1;){f=l.indexOf(`
2
- `,u),f==-1&&(f=l.length-1);var m=l.substring(u,f+1);(n.hasOwnProperty?n.hasOwnProperty(m):n[m]!==void 0)?c+=String.fromCharCode(n[m]):(d==a&&(m=l.substring(u),f=l.length),c+=String.fromCharCode(d),n[m]=d,r[d++]=m),u=f+1}return c}var a=4e4,i=o(e);a=65535;var s=o(t);return{chars1:i,chars2:s,lineArray:r}};$.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],o=[],a=0;a<n.length;a++)o[a]=t[n.charCodeAt(a)];e[r][1]=o.join("")}};$.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(a,o)==t.substring(a,o)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};$.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(e.length-o,e.length-a)==t.substring(t.length-o,t.length-a)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};$.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var o=Math.min(r,n);if(e==t)return o;for(var a=0,i=1;;){var s=e.substring(o-i),l=t.indexOf(s);if(l==-1)return a;i+=l,(l==0||e.substring(o-i)==t.substring(0,i))&&(a=i,i++)}};$.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var o=this;function a(p,g,h){for(var y=p.substring(h,h+Math.floor(p.length/4)),w=-1,v="",b,x,T,I;(w=g.indexOf(y,w+1))!=-1;){var N=o.diff_commonPrefix(p.substring(h),g.substring(w)),A=o.diff_commonSuffix(p.substring(0,h),g.substring(0,w));v.length<A+N&&(v=g.substring(w-A,w)+g.substring(w,w+N),b=p.substring(0,h-A),x=p.substring(h+N),T=g.substring(0,w-A),I=g.substring(w+N))}return v.length*2>=p.length?[b,x,T,I,v]:null}var i=a(r,n,Math.ceil(r.length/4)),s=a(r,n,Math.ceil(r.length/2)),l;if(!i&&!s)return null;s?i?l=i[4].length>s[4].length?i:s:l=s:l=i;var c,u,f,d;e.length>t.length?(c=l[0],u=l[1],f=l[2],d=l[3]):(f=l[0],d=l[1],c=l[2],u=l[3]);var m=l[4];return[c,u,f,d,m]};$.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=0,s=0,l=0,c=0;a<e.length;)e[a][0]==Q?(r[n++]=a,i=l,s=c,l=0,c=0,o=e[a][1]):(e[a][0]==ye?l+=e[a][1].length:c+=e[a][1].length,o&&o.length<=Math.max(i,s)&&o.length<=Math.max(l,c)&&(e.splice(r[n-1],0,new $.Diff(ge,o)),e[r[n-1]+1][0]=ye,n--,n--,a=n>0?r[n-1]:-1,i=0,s=0,l=0,c=0,o=null,t=!0)),a++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),a=1;a<e.length;){if(e[a-1][0]==ge&&e[a][0]==ye){var u=e[a-1][1],f=e[a][1],d=this.diff_commonOverlap_(u,f),m=this.diff_commonOverlap_(f,u);d>=m?(d>=u.length/2||d>=f.length/2)&&(e.splice(a,0,new $.Diff(Q,f.substring(0,d))),e[a-1][1]=u.substring(0,u.length-d),e[a+1][1]=f.substring(d),a++):(m>=u.length/2||m>=f.length/2)&&(e.splice(a,0,new $.Diff(Q,u.substring(0,m))),e[a-1][0]=ye,e[a-1][1]=f.substring(0,f.length-m),e[a+1][0]=ge,e[a+1][1]=u.substring(m),a++),a++}a++}};$.prototype.diff_cleanupSemanticLossless=function(e){function t(m,p){if(!m||!p)return 6;var g=m.charAt(m.length-1),h=p.charAt(0),y=g.match($.nonAlphaNumericRegex_),w=h.match($.nonAlphaNumericRegex_),v=y&&g.match($.whitespaceRegex_),b=w&&h.match($.whitespaceRegex_),x=v&&g.match($.linebreakRegex_),T=b&&h.match($.linebreakRegex_),I=x&&m.match($.blanklineEndRegex_),N=T&&p.match($.blanklineStartRegex_);return I||N?5:x||T?4:y&&!v&&b?3:v||b?2:y||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==Q&&e[r+1][0]==Q){var n=e[r-1][1],o=e[r][1],a=e[r+1][1],i=this.diff_commonSuffix(n,o);if(i){var s=o.substring(o.length-i);n=n.substring(0,n.length-i),o=s+o.substring(0,o.length-i),a=s+a}for(var l=n,c=o,u=a,f=t(n,o)+t(o,a);o.charAt(0)===a.charAt(0);){n+=o.charAt(0),o=o.substring(1)+a.charAt(0),a=a.substring(1);var d=t(n,o)+t(o,a);d>=f&&(f=d,l=n,c=o,u=a)}e[r-1][1]!=l&&(l?e[r-1][1]=l:(e.splice(r-1,1),r--),e[r][1]=c,u?e[r+1][1]=u:(e.splice(r+1,1),r--))}r++}};$.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;$.whitespaceRegex_=/\s/;$.linebreakRegex_=/[\r\n]/;$.blanklineEndRegex_=/\n\r?\n$/;$.blanklineStartRegex_=/^\r?\n\r?\n/;$.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=!1,s=!1,l=!1,c=!1;a<e.length;)e[a][0]==Q?(e[a][1].length<this.Diff_EditCost&&(l||c)?(r[n++]=a,i=l,s=c,o=e[a][1]):(n=0,o=null),l=c=!1):(e[a][0]==ge?c=!0:l=!0,o&&(i&&s&&l&&c||o.length<this.Diff_EditCost/2&&i+s+l+c==3)&&(e.splice(r[n-1],0,new $.Diff(ge,o)),e[r[n-1]+1][0]=ye,n--,o=null,i&&s?(l=c=!0,n=0):(n--,a=n>0?r[n-1]:-1,l=c=!1),t=!0)),a++;t&&this.diff_cleanupMerge(e)};$.prototype.diff_cleanupMerge=function(e){e.push(new $.Diff(Q,""));for(var t=0,r=0,n=0,o="",a="",i;t<e.length;)switch(e[t][0]){case ye:n++,a+=e[t][1],t++;break;case ge:r++,o+=e[t][1],t++;break;case Q:r+n>1?(r!==0&&n!==0&&(i=this.diff_commonPrefix(a,o),i!==0&&(t-r-n>0&&e[t-r-n-1][0]==Q?e[t-r-n-1][1]+=a.substring(0,i):(e.splice(0,0,new $.Diff(Q,a.substring(0,i))),t++),a=a.substring(i),o=o.substring(i)),i=this.diff_commonSuffix(a,o),i!==0&&(e[t][1]=a.substring(a.length-i)+e[t][1],a=a.substring(0,a.length-i),o=o.substring(0,o.length-i))),t-=r+n,e.splice(t,r+n),o.length&&(e.splice(t,0,new $.Diff(ge,o)),t++),a.length&&(e.splice(t,0,new $.Diff(ye,a)),t++),t++):t!==0&&e[t-1][0]==Q?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,o="",a="";break}e[e.length-1][1]===""&&e.pop();var s=!1;for(t=1;t<e.length-1;)e[t-1][0]==Q&&e[t+1][0]==Q&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),s=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),s=!0)),t++;s&&this.diff_cleanupMerge(e)};$.prototype.diff_xIndex=function(e,t){var r=0,n=0,o=0,a=0,i;for(i=0;i<e.length&&(e[i][0]!==ye&&(r+=e[i][1].length),e[i][0]!==ge&&(n+=e[i][1].length),!(r>t));i++)o=r,a=n;return e.length!=i&&e[i][0]===ge?a:a+(t-o)};$.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,o=/>/g,a=/\n/g,i=0;i<e.length;i++){var s=e[i][0],l=e[i][1],c=l.replace(r,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(a,"&para;<br>");switch(s){case ye:t[i]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case ge:t[i]='<del style="background:#ffe6e6;">'+c+"</del>";break;case Q:t[i]="<span>"+c+"</span>";break}}return t.join("")};$.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==ye&&(t[r]=e[r][1]);return t.join("")};$.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==ge&&(t[r]=e[r][1]);return t.join("")};$.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,o=0;o<e.length;o++){var a=e[o][0],i=e[o][1];switch(a){case ye:r+=i.length;break;case ge:n+=i.length;break;case Q:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};$.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case ye:t[r]="+"+encodeURI(e[r][1]);break;case ge:t[r]="-"+e[r][1].length;break;case Q:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};$.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,o=0,a=t.split(/\t/g),i=0;i<a.length;i++){var s=a[i].substring(1);switch(a[i].charAt(0)){case"+":try{r[n++]=new $.Diff(ye,decodeURI(s))}catch{throw new Error("Illegal escape in diff_fromDelta: "+s)}break;case"-":case"=":var l=parseInt(s,10);if(isNaN(l)||l<0)throw new Error("Invalid number in diff_fromDelta: "+s);var c=e.substring(o,o+=l);a[i].charAt(0)=="="?r[n++]=new $.Diff(Q,c):r[n++]=new $.Diff(ge,c);break;default:if(a[i])throw new Error("Invalid diff operation in diff_fromDelta: "+a[i])}}if(o!=e.length)throw new Error("Delta length ("+o+") does not equal source text length ("+e.length+").");return r};$.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};$.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),o=this;function a(b,x){var T=b/t.length,I=Math.abs(r-x);return o.Match_Distance?T+I/o.Match_Distance:I?1:T}var i=this.Match_Threshold,s=e.indexOf(t,r);s!=-1&&(i=Math.min(a(0,s),i),s=e.lastIndexOf(t,r+t.length),s!=-1&&(i=Math.min(a(0,s),i)));var l=1<<t.length-1;s=-1;for(var c,u,f=t.length+e.length,d,m=0;m<t.length;m++){for(c=0,u=f;c<u;)a(m,r+u)<=i?c=u:f=u,u=Math.floor((f-c)/2+c);f=u;var p=Math.max(1,r-u+1),g=Math.min(r+u,e.length)+t.length,h=Array(g+2);h[g+1]=(1<<m)-1;for(var y=g;y>=p;y--){var w=n[e.charAt(y-1)];if(m===0?h[y]=(h[y+1]<<1|1)&w:h[y]=(h[y+1]<<1|1)&w|((d[y+1]|d[y])<<1|1)|d[y+1],h[y]&l){var v=a(m,y-1);if(v<=i)if(i=v,s=y-1,s>r)p=Math.max(1,2*r-s);else break}}if(a(m+1,r)>i)break;d=h}return s};$.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};$.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 $.Diff(Q,o));var a=t.substring(e.start2+e.length1,e.start2+e.length1+n);a&&e.diffs.push(new $.Diff(Q,a)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+a.length,e.length2+=o.length+a.length}};$.prototype.patch_make=function(e,t,r){var n,o;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,o=this.diff_main(n,t,!0),o.length>2&&(this.diff_cleanupSemantic(o),this.diff_cleanupEfficiency(o));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")o=e,n=this.diff_text1(o);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,o=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,o=r;else throw new Error("Unknown call format to patch_make.");if(o.length===0)return[];for(var a=[],i=new $.patch_obj,s=0,l=0,c=0,u=n,f=n,d=0;d<o.length;d++){var m=o[d][0],p=o[d][1];switch(!s&&m!==Q&&(i.start1=l,i.start2=c),m){case ye:i.diffs[s++]=o[d],i.length2+=p.length,f=f.substring(0,c)+p+f.substring(c);break;case ge:i.length1+=p.length,i.diffs[s++]=o[d],f=f.substring(0,c)+f.substring(c+p.length);break;case Q:p.length<=2*this.Patch_Margin&&s&&o.length!=d+1?(i.diffs[s++]=o[d],i.length1+=p.length,i.length2+=p.length):p.length>=2*this.Patch_Margin&&s&&(this.patch_addContext_(i,u),a.push(i),i=new $.patch_obj,s=0,u=f,l=c);break}m!==ye&&(l+=p.length),m!==ge&&(c+=p.length)}return s&&(this.patch_addContext_(i,u),a.push(i)),a};$.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new $.patch_obj;o.diffs=[];for(var a=0;a<n.diffs.length;a++)o.diffs[a]=new $.Diff(n.diffs[a][0],n.diffs[a][1]);o.start1=n.start1,o.start2=n.start2,o.length1=n.length1,o.length2=n.length2,t[r]=o}return t};$.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,o=[],a=0;a<e.length;a++){var i=e[a].start2+n,s=this.diff_text1(e[a].diffs),l,c=-1;if(s.length>this.Match_MaxBits?(l=this.match_main(t,s.substring(0,this.Match_MaxBits),i),l!=-1&&(c=this.match_main(t,s.substring(s.length-this.Match_MaxBits),i+s.length-this.Match_MaxBits),(c==-1||l>=c)&&(l=-1))):l=this.match_main(t,s,i),l==-1)o[a]=!1,n-=e[a].length2-e[a].length1;else{o[a]=!0,n=l-i;var u;if(c==-1?u=t.substring(l,l+s.length):u=t.substring(l,c+this.Match_MaxBits),s==u)t=t.substring(0,l)+this.diff_text2(e[a].diffs)+t.substring(l+s.length);else{var f=this.diff_main(s,u,!1);if(s.length>this.Match_MaxBits&&this.diff_levenshtein(f)/s.length>this.Patch_DeleteThreshold)o[a]=!1;else{this.diff_cleanupSemanticLossless(f);for(var d=0,m,p=0;p<e[a].diffs.length;p++){var g=e[a].diffs[p];g[0]!==Q&&(m=this.diff_xIndex(f,d)),g[0]===ye?t=t.substring(0,l+m)+g[1]+t.substring(l+m):g[0]===ge&&(t=t.substring(0,l+m)+t.substring(l+this.diff_xIndex(f,d+g[1].length))),g[0]!==ge&&(d+=g[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};$.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var o=e[0],a=o.diffs;if(a.length==0||a[0][0]!=Q)a.unshift(new $.Diff(Q,r)),o.start1-=t,o.start2-=t,o.length1+=t,o.length2+=t;else if(t>a[0][1].length){var i=t-a[0][1].length;a[0][1]=r.substring(a[0][1].length)+a[0][1],o.start1-=i,o.start2-=i,o.length1+=i,o.length2+=i}if(o=e[e.length-1],a=o.diffs,a.length==0||a[a.length-1][0]!=Q)a.push(new $.Diff(Q,r)),o.length1+=t,o.length2+=t;else if(t>a[a.length-1][1].length){var i=t-a[a.length-1][1].length;a[a.length-1][1]+=r.substring(0,i),o.length1+=i,o.length2+=i}return r};$.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var o=n.start1,a=n.start2,i="";n.diffs.length!==0;){var s=new $.patch_obj,l=!0;for(s.start1=o-i.length,s.start2=a-i.length,i!==""&&(s.length1=s.length2=i.length,s.diffs.push(new $.Diff(Q,i)));n.diffs.length!==0&&s.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],u=n.diffs[0][1];c===ye?(s.length2+=u.length,a+=u.length,s.diffs.push(n.diffs.shift()),l=!1):c===ge&&s.diffs.length==1&&s.diffs[0][0]==Q&&u.length>2*t?(s.length1+=u.length,o+=u.length,l=!1,s.diffs.push(new $.Diff(c,u)),n.diffs.shift()):(u=u.substring(0,t-s.length1-this.Patch_Margin),s.length1+=u.length,o+=u.length,c===Q?(s.length2+=u.length,a+=u.length):l=!1,s.diffs.push(new $.Diff(c,u)),u==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(u.length))}i=this.diff_text2(s.diffs),i=i.substring(i.length-this.Patch_Margin);var f=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);f!==""&&(s.length1+=f.length,s.length2+=f.length,s.diffs.length!==0&&s.diffs[s.diffs.length-1][0]===Q?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new $.Diff(Q,f))),l||e.splice(++r,0,s)}}};$.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};$.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
3
- `),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var a=r[n].match(o);if(!a)throw new Error("Invalid patch string: "+r[n]);var i=new $.patch_obj;for(t.push(i),i.start1=parseInt(a[1],10),a[2]===""?(i.start1--,i.length1=1):a[2]=="0"?i.length1=0:(i.start1--,i.length1=parseInt(a[2],10)),i.start2=parseInt(a[3],10),a[4]===""?(i.start2--,i.length2=1):a[4]=="0"?i.length2=0:(i.start2--,i.length2=parseInt(a[4],10)),n++;n<r.length;){var s=r[n].charAt(0);try{var l=decodeURI(r[n].substring(1))}catch{throw new Error("Illegal escape in patch_fromText: "+l)}if(s=="-")i.diffs.push(new $.Diff(ge,l));else if(s=="+")i.diffs.push(new $.Diff(ye,l));else if(s==" ")i.diffs.push(new $.Diff(Q,l));else{if(s=="@")break;if(s!=="")throw new Error('Invalid patch mode "'+s+'" in: '+l)}n++}}return t};$.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};$.patch_obj.prototype.toString=function(){var e,t;this.length1===0?e=this.start1+",0":this.length1==1?e=this.start1+1:e=this.start1+1+","+this.length1,this.length2===0?t=this.start2+",0":this.length2==1?t=this.start2+1:t=this.start2+1+","+this.length2;for(var r=["@@ -"+e+" +"+t+` @@
4
- `],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case ye:n="+";break;case ge:n="-";break;case Q:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
5
- `}return r.join("").replace(/%20/g," ")};an.exports=$;an.exports.diff_match_patch=$;an.exports.DIFF_DELETE=ge;an.exports.DIFF_INSERT=ye;an.exports.DIFF_EQUAL=Q});import{DOMParser as Bf,XMLSerializer as Df}from"@xmldom/xmldom";var Ao=console,Xa=Object.freeze({silent:0,error:1,warn:2,info:3}),kf=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",Va=kf;function Mf(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(Xa,t)?t:Va}function Wa(e){return Xa[Va]>=Xa[e]}function Lf(e,t={}){Ao=e||console,t.level&&(Va=Mf(t.level))}function V(...e){Wa("info")&&(Ao.log||(()=>{}))(...e)}function St(...e){Wa("warn")&&(Ao.warn||(()=>{}))(...e)}function Te(...e){Wa("error")&&(Ao.error||(()=>{}))(...e)}var Ms=null,Ls=null;function Ff(e={}){"DOMParser"in e&&(Ms=e.DOMParser),"XMLSerializer"in e&&(Ls=e.XMLSerializer)}function $f(){return Ms||globalThis.DOMParser||Bf}function Uf(){return Ls||globalThis.XMLSerializer||Df}function zf(e={}){let t=$f();if(!t)throw new Error("DOMParser is not configured and no fallback XML parser is available.");return new t(e)}function oe(){let e=Uf();if(!e)throw new Error("XMLSerializer is not configured and no fallback XML serializer is available.");return new e}function Bs(e,t="text/xml"){let r=W(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function Xf(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function W(e,t="application/xml"){let r=[];if(typeof e!="string"||e.trim()==="")return{doc:null,error:{code:"PARSE_ERROR",message:"Input is not a non-empty XML string."},warnings:r};let n=(o,a)=>{let i=String(a||"XML parser diagnostic.");o==="fatalError"?Te("[XmlAdapter] XML fatal parse error:",i):(r.push(i),St(`[XmlAdapter] XML ${o||"warning"}:`,i))};try{let a=zf({onError:n}).parseFromString(e,t),i=Xf(a);if(!a?.documentElement||i){let s=i?.textContent||"Could not parse XML input.";return Te("[XmlAdapter] XML parse error:",s),{doc:null,error:{code:"PARSE_ERROR",message:s},warnings:r}}return{doc:a,error:null,warnings:r}}catch(o){let a=o?.message||String(o||"Could not parse XML input.");return Te("[XmlAdapter] XML parse error:",a),{doc:null,error:{code:"PARSE_ERROR",message:a},warnings:r}}}function Se(e){return oe().serializeToString(e)}var Ds=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",Fs=Ds(),$s="Unknown";function Vf(e){Fs=typeof e=="string"&&e.trim()?e.trim():Ds()}function re(){return Fs}function Wf(e){$s=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function ja(){return $s}var jf=[{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 We(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let s of jf){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?Kf(l[1]):l[1],format:s.format}),l.index===f.lastIndex&&f.lastIndex++}n.sort((s,l)=>s.start-l.start||l.end-s.end);let o=[],a=0;for(let s of n)s.start>=a&&(o.push(s),a=s.end);let i=0;for(let s of o){r+=e.slice(i,s.start);let l=We(s.innerText),c=r.length;r+=l.cleanText;let u=r.length;t.push({start:c,end:u,format:s.format});for(let f of l.formatHints)t.push({start:c+f.start,end:c+f.end,format:f.format});i=s.end}return r+=e.slice(i),{cleanText:r,formatHints:t}}function Xt(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function Ka(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function Kf(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var Eo=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,Us=new RegExp(`^(\\s*)((?:${Eo})\\s+)`),zs=new RegExp(`^(\\s*)((?:${Eo})\\s*)`),Hf=new RegExp(`^(\\s*)((?:${Eo})\\s+)`,"m"),Gf=new RegExp(`^(\\s*)((?:${Eo})\\s*)`,"m");function Ha(e){return typeof e!="string"?!1:e.includes(`
6
- `)&&Hf.test(e)}function en(e){return typeof e!="string"?!1:e.includes(`
7
- `)&&Gf.test(e.trim())}function At(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?zs:Us;return e.match(n)}function _t(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?zs:Us;return e.replace(n,"")}function Xs(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function kn(e){let t=String(e||"").trim();return Xs(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 qf(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function Mn(e,t={}){let r=At(String(e||""),t);if(!r)return null;let n=r[2].trim(),o=(r[1]||"").length,a=Math.max(1,Number(t.indentSpaces)||2),i=Xs(n);return{line:String(e||""),text:_t(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/a)),markerType:i,listType:i,numberingStyle:kn(n),outlineLevel:i==="numbered"?qf(n):null}}var B="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var ht=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),Z=Object.freeze({TEXT:"run",DELETION:"deletion",INSERTION:"insertion",HYPERLINK:"hyperlink",BOOKMARK:"bookmark",FIELD:"field",CONTAINER_START:"container_start",CONTAINER_END:"container_end",PARAGRAPH_START:"paragraph_start"}),tn=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),js=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),de=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),Fe=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function je(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var Ga=1e3,Vs=2147483647,Ws=1e4,Yf=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Ks=new WeakMap;function Zf(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return Yf.has(t)?!e.namespaceURI||e.namespaceURI===B||String(e.nodeName||"").startsWith("w:"):!1}function Jf(e){let t=e?.getAttributeNS?.(B,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var Pe=class{constructor(t=Ga){this.startValue=Number.isInteger(t)&&t>=0?t:Ga,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(Zf(o)){let i=Jf(o);i!=null&&(this.occupiedIds.add(i),r=Math.max(r,i))}if(o.firstChild){o=o.firstChild;continue}for(;o&&o!==n&&!o.nextSibling;)o=o.parentNode;o=o&&o!==n?o.nextSibling:null}let a=Vs-Ws;return this.nextId=r>=a?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=Vs-Ws;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}},Ln=new Pe;function cr(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof Pe&&Ks.set(r,t),t}function Vt(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Ks.get(t)||null}function ur(e,t=Ga){let r=new Pe(t);return r.seed(e),cr(e,r),r}function Hs(){return Ln.next()}function Ro(e=new Date){return e.toISOString()}function ie(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():re(),o=t instanceof Pe?t:Vt(t)||Ln,a=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(a,r||"structural"),{id:a,author:n,date:Ro()}}function Bn(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():re(),n=t instanceof Pe?t:Vt(t)||Ln,o=Ro(),a=n.next(),i=n.next();return n._receiptCollector&&(n._receiptCollector.recordRevision(a,"del"),n._receiptCollector.recordRevision(i,"ins")),{deletionId:a,insertionId:i,author:r,date:o}}function Wt(e,t=Ln){let r=t instanceof Pe?t:Ln,n=r.seed(e);return cr(e,r),n}function Gs(e,t){return e<t-1}function rn(e,t,r){return Gs(t,r)?e+`
8
- `:e}function Ar(e,t,r){return Gs(t,r)?e+1:e}function Dn(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function Ce(e,t){if(!e||typeof e.getElementsByTagName!="function")return null;let r=e.getElementsByTagName(t);return r.length>0?r[0]:null}function _e(e,t,r){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(t,r))}function Ae(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 $e(e,t,r,n=`w:${r}`){let o=_e(e,t,r);return o.length>0?o:Dn(e,n)}function Ke(e,t,r,n=`w:${r}`){let o=Ae(e,t,r);return o||Ce(e,n)}function Ee(e){return Ce(e,"parsererror")}function qa(e){return Array.from(e?.childNodes||[])}function qs(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Ya(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var Za=0;function on(e,t={}){let r=[],n="",o=t.xmlDoc||null;if(!e&&!o)return{runModel:r,acceptedText:n,pPr:null};try{let a=o?{doc:o,error:null}:W(e,"application/xml"),i=a.doc;if(a.error||!i)return Te("OOXML parse error:",a.error?.message),{runModel:r,acceptedText:n,pPr:null,error:a.error};let s=Ee(i);if(s)return Te("OOXML parse error:",s.textContent),{runModel:r,acceptedText:n,pPr:null};let l=_e(i,B,"p");return l.length===0?(St("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):Zs(l,{includeParagraphBoundaries:!0})}catch(a){return Te("Error ingesting OOXML:",a),{runModel:r,acceptedText:n,pPr:null}}}function Ja(e){return e?Zs([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function Fn(e){let t=Ae(e,B,"pPr");if(!t)return null;let r=Ae(t,B,"numPr");if(!r)return null;let n=Ae(r,B,"numId"),o=Ae(r,B,"ilvl");if(!n)return null;let a=n.getAttribute("w:val");if(!/^\d+$/.test(a)||Number.parseInt(a,10)===0)return null;let i=a==="1"?"bullet":a==="2"?"numbered":"unknown";return{numId:a,ilvl:parseInt(o?.getAttribute("w:val")||"0",10),type:i}}function Zs(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],o="",a=0,i=null;for(let s=0;s<e.length;s++){let l=e[s],c=Ae(l,B,"pPr");s===0&&(i=c),n.push({kind:Z.PARAGRAPH_START,pPrElement:c||null,startOffset:a,endOffset:a,text:""});let u=nn(l,a,n);o+=u.text,a=o.length,r&&(o=rn(o,s,e.length),a=Ar(a,s,e.length))}return{runModel:n,acceptedText:o,pPr:i}}function nn(e,t,r){let n=t,o="",a=Qf(r);for(let i of qa(e)){if(Ya(i,B,"pPr")||Ya(i,B,"proofErr"))continue;let s=a.get(i.localName);if(!s)continue;let l=s(i,n);n=l.offset,o+=l.text}return{offset:n,text:o}}function Qf(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${Za++}`,a=Ae(r,B,"sdtPr"),i=Ae(r,B,"sdtContent");e.push({kind:Z.CONTAINER_START,containerKind:tn.SDT,containerId:o,propertiesXml:a?Se(a):"",startOffset:n,endOffset:n,text:""});let s=i?nn(i,n,e):{offset:n,text:""};return e.push({kind:Z.CONTAINER_END,containerKind:tn.SDT,containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("smartTag",(r,n)=>{let o=`smartTag_${Za++}`;e.push({kind:Z.CONTAINER_START,containerKind:tn.SMART_TAG,containerId:o,propertiesXml:qs(r),startOffset:n,endOffset:n,text:""});let a=nn(r,n,e);return e.push({kind:Z.CONTAINER_END,containerKind:tn.SMART_TAG,containerId:o,startOffset:a.offset,endOffset:a.offset,text:""}),a}),t.set("del",(r,n)=>{let o=Ys(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=Ys(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>nn(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:Z.BOOKMARK,nodeXml:Se(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:Z.BOOKMARK,nodeXml:Se(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:Z.BOOKMARK,nodeXml:Se(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>nn(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${Za++}`,a=r.getAttribute("r:id")||"",i=r.getAttribute("w:anchor")||"";e.push({kind:Z.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:a,anchor:i}),startOffset:n,endOffset:n,text:""});let s=nn(r,n,e);return e.push({kind:Z.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("r",(r,n)=>{let o=ed(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function ed(e,t){let r=Ke(e,B,"rPr"),n=r?Se(r):"",o="";for(let a of qa(e)){let i=a.nodeName;i.endsWith(":t")||i==="t"?o+=a.textContent||"":i.endsWith(":br")||i==="br"||i.endsWith(":cr")||i==="cr"?o+=`
9
- `:i.endsWith(":tab")||i==="tab"?o+=" ":i.endsWith(":noBreakHyphen")||i==="noBreakHyphen"?o+="\u2011":(i.endsWith(":softHyphen")||i==="softHyphen")&&(o+="\xAD")}return o?{kind:Z.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function Ys(e,t){let r=e.getAttribute("w:author")||"",n="",o=_e(e,B,"delText");for(let i of o)n+=i.textContent||"";let a=_e(e,B,"r");for(let i of a){let s=_e(i,B,"delText");for(let l of s)n+=l.textContent||""}return n?{kind:Z.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:Se(e)}:null}function ei(e){let t=Ae(e,B,"tblGrid"),r=t?_e(t,B,"gridCol"):[],n=$e(e,B,"tr"),o=n.length,a=n.reduce((u,f)=>{let d=$e(f,B,"tc");return Math.max(u,d.length)},0),i=r.length||a,s=Array.from({length:o},()=>Array.from({length:i},()=>null)),l=new Map,c=new Map;for(let u=0;u<n.length;u++){let f=n[u],d=$e(f,B,"tc"),m=0;for(let p=0;p<d.length;p++){let g=d[p],h=Ae(g,B,"tcPr");for(;m<i&&s[u][m]!==null;)m++;if(m>=i)break;let y=h?Ae(h,B,"gridSpan")||Ce(h,"w:gridSpan"):null,w=parseInt(y?.getAttribute("w:val")||"1",10),v=h?Ae(h,B,"vMerge")||Ce(h,"w:vMerge"):null,b=v?.getAttribute("w:val"),x=v!==null,T;if(x&&b!=="restart"){let I=c.get(m);I?(I.cell.rowSpan++,T={gridRow:u,gridCol:m,rowSpan:0,colSpan:w,tcNode:g,blocks:[],tcPrXml:Qa(h),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:I.cell}):T=td(u,m,w,g,h)}else{let I=Js(g);if(T={gridRow:u,gridCol:m,rowSpan:1,colSpan:w,tcNode:g,blocks:I,tcPrXml:Qa(h),isMergeOrigin:x&&b==="restart",isMergeContinuation:!1,getText:()=>I.map(N=>N.acceptedText).join(`
10
- `)},x&&b==="restart")for(let N=0;N<w;N++)c.set(m+N,{originRow:u,cell:T});else for(let N=0;N<w;N++)c.delete(m+N)}for(let I=0;I<w;I++){let N=m+I;N<i&&(s[u][N]=T,l.set(`${u},${N}`,T))}m+=w}}return{rowCount:o,colCount:i,grid:s,cellMap:l,tblPrXml:rd(e),tblGridXml:nd(e),trPrList:Array.from(n).map(u=>od(u))}}function td(e,t,r,n,o){let a=Js(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:a,tcPrXml:Qa(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>a.map(i=>i.acceptedText).join(`
11
- `)}}function Js(e){return $e(e,B,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:a}=Ja(r);return{runModel:n,acceptedText:o,pPr:a}})}function Qa(e){return e?Se(e):"<w:tcPr/>"}function rd(e){let t=Ae(e,B,"tblPr");return t?Se(t):"<w:tblPr/>"}function nd(e){let t=Ae(e,B,"tblGrid");return t?Se(t):"<w:tblGrid/>"}function od(e){let t=Ae(e,B,"trPr");return t?Se(t):"<w:trPr/>"}var tl=ks(ti(),1);var ad=65536,Po=262144,Co=1,Oo=55296-Co,id=8192,sd=Oo+id,ri=class extends Error{constructor(t=Po){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function rl(e){return e?.code==="DIFF_TOKEN_LIMIT"}function ni(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 tl.diff_match_patch;return r.Diff_Timeout=t,r}function Qs(e,t=null){let r=[],n=s=>{if(!t||t.size===0){r.push(s);return}let l=0;for(let c=0;c<s.length;c++)t.has(s[c])&&(c>l&&r.push(s.slice(l,c)),r.push(s[c]),l=c+1);l<s.length&&r.push(s.slice(l))},o=e.match(/^\s+/);o&&r.push(o[0]);let a=/(\S+)(\s*)/g;a.lastIndex=o?.[0].length||0;let i;for(;(i=a.exec(e))!==null;)i[1]&&n(i[1]),i[2]&&r.push(i[2]);return r}function ld(e,t,r={}){let n=[],o=new Map,a=r.maxTokens??Po;if(!Number.isInteger(a)||a<1||a>Po)throw new RangeError(`maxTokens must be an integer from 1 to ${Po}.`);function i(f){let d="",m=[];for(let p of f){let g=o.get(p);if(g===void 0){if(n.length>=a)throw new ri(a);g=n.length,n.push(p),o.set(p,g)}m.push(g),d+=String.fromCodePoint(ad+g)}return{chars:d,tokenIds:m}}let s=Qs(e,r.atomicChars),l=Qs(t,r.atomicChars),c=i(s),u=i(l);return{chars1:c.chars,chars2:u.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:u.tokenIds}}function cd(e){let t=e<Oo?Co+e:57344+(e-Oo);return String.fromCharCode(t)}function ud(e){if(e>=Co&&e<55296)return e-Co;if(e>=57344&&e<=65535)return Oo+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function el(e){let t="";for(let r of e)t+=cd(r);return t}function fd(e,t){return e.map(([r,n])=>{let o=[];for(let a=0;a<n.length;a++){let i=ud(n.charCodeAt(a));if(i>=t.length)throw new RangeError(`BMP diff token ${i} has no mapping.`);o.push(t[i])}return[r,o.join("")]})}function dd(e,t,r){let n=0,o=Math.min(e.length,t.length);for(;n<o&&e[n]===t[n];)n++;let a=0;for(;a<o-n&&e[e.length-1-a]===t[t.length-1-a];)a++;let i=u=>u.map(f=>r[f]).join(""),s=[];n&&s.push([0,i(e.slice(0,n))]);let l=e.slice(n,e.length-a),c=t.slice(n,t.length-a);return l.length&&s.push([-1,i(l)]),c.length&&s.push([1,i(c)]),a&&s.push([0,i(e.slice(e.length-a))]),s}function $n(e,t,r={}){if(e===t)return[[0,e]];if(!e)return[[1,t]];if(!t)return[[-1,e]];let{cleanupSemantic:n=!0}=r,{wordArray:o,tokenIds1:a,tokenIds2:i}=ld(e,t,r);if(o.length>sd)return dd(a,i,o);let s=ni(r),l=s.diff_main(el(a),el(i));return n&&s.diff_cleanupSemantic(l),fd(l,o)}function nl(e,t,r={}){return e===t?[[0,e]]:ni(r).diff_main(e,t)}function ol(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=ni().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function _o(e,t,r={}){if(e===t)return[{type:ht.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:ht.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:ht.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=$n(e,t,r),o=[],a=0;for(let[i,s]of n)i===0?(o.push({type:ht.EQUAL,startOffset:a,endOffset:a+s.length,text:s}),a+=s.length):i===-1?(o.push({type:ht.DELETE,startOffset:a,endOffset:a+s.length,text:s}),a+=s.length):i===1&&o.push({type:ht.INSERT,startOffset:a,endOffset:a,text:s});return o}var md=/\s+xmlns:[^=]+="[^"]*"/g;function ko(e,t){let r=vd(t),n=[],o=0;for(let a of e){if(a.kind!==Z.TEXT&&a.kind!==Z.HYPERLINK){n.push(a);continue}for(;o<r.length&&r[o]<=a.startOffset;)o++;let i=o,s=a.startOffset,l=!1;for(;i<r.length;){let c=r[i];if(c>=a.endOffset)break;c>s&&(l=!0,n.push({...a,text:a.text.slice(s-a.startOffset,c-a.startOffset),startOffset:s,endOffset:c}),s=c),i++}if(o=i,!l){n.push(a);continue}n.push({...a,text:a.text.slice(s-a.startOffset),startOffset:s,endOffset:a.endOffset})}return n}function Mo(e,t,r){let{generateRedlines:n,author:o}=r,a=[],i=new Set,s=xd(t),l=wd(e),c=yd(s.nonInsertOps),u={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let d of e){if(d.kind===Z.CONTAINER_START){u.containerStack.push(d.containerId),a.push({...d});continue}if(d.kind===Z.CONTAINER_END){u.containerStack.pop(),a.push({...d});continue}if(d.kind===Z.PARAGRAPH_START){u.currentParagraphPPrXml=typeof d.pPrXml=="string"?d.pPrXml:"",u.currentParagraphPPrElement=d.pPrElement||null,a.push({...d}),u.lastParagraphStartIndex=a.length-1;continue}if(d.kind===Z.BOOKMARK||d.kind===Z.DELETION){a.push({...d});continue}let m=c(d.startOffset,d.endOffset),p=s.insertOpsByStartOffset.get(d.startOffset)||[];for(let g of p)i.has(g)||(i.add(g),pd({insertOp:g,splitModel:e,styleLookup:l,patchedModel:a,state:u,options:r,generateRedlines:n,author:o}));if(!m||m.type===ht.EQUAL){a.push({...d,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null});continue}m.type===ht.DELETE&&n&&a.push({...d,kind:Z.DELETION,author:o,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null})}let f=e.length>0?Math.max(...e.map(d=>d.endOffset)):0;for(let d of s.sortedInsertOps){if(d.startOffset<f||i.has(d))continue;let m=e[e.length-1];a.push({kind:n?Z.INSERTION:Z.TEXT,text:d.text,rPrXml:m?.rPrXml||"",startOffset:d.startOffset,endOffset:d.startOffset+d.text.length,author:n?o:void 0})}return a}function pd(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:a,generateRedlines:i,author:s}=e,l=t.text.split(`
12
- `),c=hd(r,t.startOffset,t.text);for(let u=0;u<l.length;u++){let f=gd(l[u],a.numberingService,o),d=f.lineText;if(u>0){let m=al(o);f.isListLine&&f.numId&&(m=a.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:Z.PARAGRAPH_START,pPrXml:m,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,o.lastParagraphStartIndex=n.length-1}else if(f.isListLine&&f.numId&&o.lastParagraphStartIndex>=0){let m=a.numberingService.buildListPPr(f.numId,f.ilvl);n[o.lastParagraphStartIndex].pPrXml=m,n[o.lastParagraphStartIndex].pPrElement=null,o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,V(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(d.length>0||u>0)&&n.push({kind:i?Z.INSERTION:Z.TEXT,text:d,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+d.length,author:i?s:void 0,containerContext:o.containerStack.length>0?o.containerStack[o.containerStack.length-1]:null})}}function gd(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=At(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let o=n[2].trim(),a=t.detectNumberingFormat(o),i=e.match(/^(\s*)/),s=i?i[1].length:0,l=s>=4?4:2,c=Math.floor(s/l),u=al(r),f=_t(e,{allowZeroSpaceAfterMarker:!0}),d=u.match(/w:numId w:val="(\d+)"/),m=u.match(/w:ilvl w:val="(\d+)"/),p=d?d[1]:null,g=m?parseInt(m[1],10):0,h=t.getOrCreateNumId({type:a.format},{numId:p,type:"unknown"}),y=a.format==="outline"?Math.min(8,a.depth):Math.min(8,c+g);return{lineText:f,isListLine:!0,numId:h,ilvl:y}}function al(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=Se(e.currentParagraphPPrElement).replace(md,""),e.currentParagraphPPrXml):""}function hd(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 wd(e){let t=e.filter(o=>o.kind===Z.TEXT),r=t.map(o=>o.startOffset),n=t.map(o=>o.endOffset);return{findRunBefore(o){let a=0,i=n.length-1,s=-1;for(;a<=i;){let l=a+i>>1;n[l]<=o?(s=l,a=l+1):i=l-1}return s>=0?t[s]:null},findRunAfter(o){let a=0,i=r.length-1,s=-1;for(;a<=i;){let l=a+i>>1;r[l]>=o?(s=l,i=l-1):a=l+1}return s>=0?t[s]:null}}}function yd(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 vd(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 xd(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===ht.INSERT){t.has(o.startOffset)||t.set(o.startOffset,[]),t.get(o.startOffset).push(o),n.push(o);continue}r.push(o)}return r.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),n.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var cl="http://schemas.openxmlformats.org/wordprocessingml/2006/main",bd="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Nd="http://schemas.microsoft.com/office/2006/xmlPackage",il="http://schemas.openxmlformats.org/package/2006/relationships",Id='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',sl='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var Td=`
13
- <w:numbering xmlns:w="${cl}">
1
+ var bp=Object.create;var pc=Object.defineProperty;var xp=Object.getOwnPropertyDescriptor;var Ip=Object.getOwnPropertyNames;var Np=Object.getPrototypeOf,Tp=Object.prototype.hasOwnProperty;var Sp=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Ap=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ip(t))!Tp.call(e,o)&&o!==r&&pc(e,o,{get:()=>t[o],enumerable:!(n=xp(t,o))||n.enumerable});return e};var gc=(e,t,r)=>(r=e!=null?bp(Np(e)):{},Ap(t||!e||!e.__esModule?pc(r,"default",{value:e,enumerable:!0}):r,e));var ns=Sp((Lx,Un)=>{var U=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},xe=-1,Ee=1,oe=0;U.Diff=function(e,t){return[e,t]};U.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 U.Diff(oe,e)]:[];typeof r>"u"&&(r=!0);var a=r,i=this.diff_commonPrefix(e,t),l=e.substring(0,i);e=e.substring(i),t=t.substring(i),i=this.diff_commonSuffix(e,t);var s=e.substring(e.length-i);e=e.substring(0,e.length-i),t=t.substring(0,t.length-i);var c=this.diff_compute_(e,t,a,o);return l&&c.unshift(new U.Diff(oe,l)),s&&c.push(new U.Diff(oe,s)),this.diff_cleanupMerge(c),c};U.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new U.Diff(Ee,t)];if(!t)return[new U.Diff(xe,e)];var a=e.length>t.length?e:t,i=e.length>t.length?t:e,l=a.indexOf(i);if(l!=-1)return o=[new U.Diff(Ee,a.substring(0,l)),new U.Diff(oe,i),new U.Diff(Ee,a.substring(l+i.length))],e.length>t.length&&(o[0][0]=o[2][0]=xe),o;if(i.length==1)return[new U.Diff(xe,e),new U.Diff(Ee,t)];var s=this.diff_halfMatch_(e,t);if(s){var c=s[0],f=s[1],u=s[2],d=s[3],m=s[4],p=this.diff_main(c,u,r,n),g=this.diff_main(f,d,r,n);return p.concat([new U.Diff(oe,m)],g)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};U.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var o=n.lineArray,a=this.diff_main(e,t,!1,r);this.diff_charsToLines_(a,o),this.diff_cleanupSemantic(a),a.push(new U.Diff(oe,""));for(var i=0,l=0,s=0,c="",f="";i<a.length;){switch(a[i][0]){case Ee:s++,f+=a[i][1];break;case xe:l++,c+=a[i][1];break;case oe:if(l>=1&&s>=1){a.splice(i-l-s,l+s),i=i-l-s;for(var u=this.diff_main(c,f,!1,r),d=u.length-1;d>=0;d--)a.splice(i,0,u[d]);i=i+u.length}s=0,l=0,c="",f="";break}i++}return a.pop(),a};U.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,o=t.length,a=Math.ceil((n+o)/2),i=a,l=2*a,s=new Array(l),c=new Array(l),f=0;f<l;f++)s[f]=-1,c[f]=-1;s[i+1]=0,c[i+1]=0;for(var u=n-o,d=u%2!=0,m=0,p=0,g=0,h=0,v=0;v<a&&!(new Date().getTime()>r);v++){for(var w=-v+m;w<=v-p;w+=2){var y=i+w,b;w==-v||w!=v&&s[y-1]<s[y+1]?b=s[y+1]:b=s[y-1]+1;for(var x=b-w;b<n&&x<o&&e.charAt(b)==t.charAt(x);)b++,x++;if(s[y]=b,b>n)p+=2;else if(x>o)m+=2;else if(d){var S=i+u-w;if(S>=0&&S<l&&c[S]!=-1){var A=n-c[S];if(b>=A)return this.diff_bisectSplit_(e,t,b,x,r)}}}for(var E=-v+g;E<=v-h;E+=2){var S=i+E,A;E==-v||E!=v&&c[S-1]<c[S+1]?A=c[S+1]:A=c[S-1]+1;for(var I=A-E;A<n&&I<o&&e.charAt(n-A-1)==t.charAt(o-I-1);)A++,I++;if(c[S]=A,A>n)h+=2;else if(I>o)g+=2;else if(!d){var y=i+u-E;if(y>=0&&y<l&&s[y]!=-1){var b=s[y],x=i+b-y;if(A=n-A,b>=A)return this.diff_bisectSplit_(e,t,b,x,r)}}}}return[new U.Diff(xe,e),new U.Diff(Ee,t)]};U.prototype.diff_bisectSplit_=function(e,t,r,n,o){var a=e.substring(0,r),i=t.substring(0,n),l=e.substring(r),s=t.substring(n),c=this.diff_main(a,i,!1,o),f=this.diff_main(l,s,!1,o);return c.concat(f)};U.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(s){for(var c="",f=0,u=-1,d=r.length;u<s.length-1;){u=s.indexOf(`
2
+ `,f),u==-1&&(u=s.length-1);var m=s.substring(f,u+1);(n.hasOwnProperty?n.hasOwnProperty(m):n[m]!==void 0)?c+=String.fromCharCode(n[m]):(d==a&&(m=s.substring(f),u=s.length),c+=String.fromCharCode(d),n[m]=d,r[d++]=m),f=u+1}return c}var a=4e4,i=o(e);a=65535;var l=o(t);return{chars1:i,chars2:l,lineArray:r}};U.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],o=[],a=0;a<n.length;a++)o[a]=t[n.charCodeAt(a)];e[r][1]=o.join("")}};U.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(a,o)==t.substring(a,o)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};U.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(e.length-o,e.length-a)==t.substring(t.length-o,t.length-a)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};U.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var o=Math.min(r,n);if(e==t)return o;for(var a=0,i=1;;){var l=e.substring(o-i),s=t.indexOf(l);if(s==-1)return a;i+=s,(s==0||e.substring(o-i)==t.substring(0,i))&&(a=i,i++)}};U.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var o=this;function a(p,g,h){for(var v=p.substring(h,h+Math.floor(p.length/4)),w=-1,y="",b,x,S,A;(w=g.indexOf(v,w+1))!=-1;){var E=o.diff_commonPrefix(p.substring(h),g.substring(w)),I=o.diff_commonSuffix(p.substring(0,h),g.substring(0,w));y.length<I+E&&(y=g.substring(w-I,w)+g.substring(w,w+E),b=p.substring(0,h-I),x=p.substring(h+E),S=g.substring(0,w-I),A=g.substring(w+E))}return y.length*2>=p.length?[b,x,S,A,y]:null}var i=a(r,n,Math.ceil(r.length/4)),l=a(r,n,Math.ceil(r.length/2)),s;if(!i&&!l)return null;l?i?s=i[4].length>l[4].length?i:l:s=l:s=i;var c,f,u,d;e.length>t.length?(c=s[0],f=s[1],u=s[2],d=s[3]):(u=s[0],d=s[1],c=s[2],f=s[3]);var m=s[4];return[c,f,u,d,m]};U.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=0,l=0,s=0,c=0;a<e.length;)e[a][0]==oe?(r[n++]=a,i=s,l=c,s=0,c=0,o=e[a][1]):(e[a][0]==Ee?s+=e[a][1].length:c+=e[a][1].length,o&&o.length<=Math.max(i,l)&&o.length<=Math.max(s,c)&&(e.splice(r[n-1],0,new U.Diff(xe,o)),e[r[n-1]+1][0]=Ee,n--,n--,a=n>0?r[n-1]:-1,i=0,l=0,s=0,c=0,o=null,t=!0)),a++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),a=1;a<e.length;){if(e[a-1][0]==xe&&e[a][0]==Ee){var f=e[a-1][1],u=e[a][1],d=this.diff_commonOverlap_(f,u),m=this.diff_commonOverlap_(u,f);d>=m?(d>=f.length/2||d>=u.length/2)&&(e.splice(a,0,new U.Diff(oe,u.substring(0,d))),e[a-1][1]=f.substring(0,f.length-d),e[a+1][1]=u.substring(d),a++):(m>=f.length/2||m>=u.length/2)&&(e.splice(a,0,new U.Diff(oe,f.substring(0,m))),e[a-1][0]=Ee,e[a-1][1]=u.substring(0,u.length-m),e[a+1][0]=xe,e[a+1][1]=f.substring(m),a++),a++}a++}};U.prototype.diff_cleanupSemanticLossless=function(e){function t(m,p){if(!m||!p)return 6;var g=m.charAt(m.length-1),h=p.charAt(0),v=g.match(U.nonAlphaNumericRegex_),w=h.match(U.nonAlphaNumericRegex_),y=v&&g.match(U.whitespaceRegex_),b=w&&h.match(U.whitespaceRegex_),x=y&&g.match(U.linebreakRegex_),S=b&&h.match(U.linebreakRegex_),A=x&&m.match(U.blanklineEndRegex_),E=S&&p.match(U.blanklineStartRegex_);return A||E?5:x||S?4:v&&!y&&b?3:y||b?2:v||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==oe&&e[r+1][0]==oe){var n=e[r-1][1],o=e[r][1],a=e[r+1][1],i=this.diff_commonSuffix(n,o);if(i){var l=o.substring(o.length-i);n=n.substring(0,n.length-i),o=l+o.substring(0,o.length-i),a=l+a}for(var s=n,c=o,f=a,u=t(n,o)+t(o,a);o.charAt(0)===a.charAt(0);){n+=o.charAt(0),o=o.substring(1)+a.charAt(0),a=a.substring(1);var d=t(n,o)+t(o,a);d>=u&&(u=d,s=n,c=o,f=a)}e[r-1][1]!=s&&(s?e[r-1][1]=s:(e.splice(r-1,1),r--),e[r][1]=c,f?e[r+1][1]=f:(e.splice(r+1,1),r--))}r++}};U.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;U.whitespaceRegex_=/\s/;U.linebreakRegex_=/[\r\n]/;U.blanklineEndRegex_=/\n\r?\n$/;U.blanklineStartRegex_=/^\r?\n\r?\n/;U.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=!1,l=!1,s=!1,c=!1;a<e.length;)e[a][0]==oe?(e[a][1].length<this.Diff_EditCost&&(s||c)?(r[n++]=a,i=s,l=c,o=e[a][1]):(n=0,o=null),s=c=!1):(e[a][0]==xe?c=!0:s=!0,o&&(i&&l&&s&&c||o.length<this.Diff_EditCost/2&&i+l+s+c==3)&&(e.splice(r[n-1],0,new U.Diff(xe,o)),e[r[n-1]+1][0]=Ee,n--,o=null,i&&l?(s=c=!0,n=0):(n--,a=n>0?r[n-1]:-1,s=c=!1),t=!0)),a++;t&&this.diff_cleanupMerge(e)};U.prototype.diff_cleanupMerge=function(e){e.push(new U.Diff(oe,""));for(var t=0,r=0,n=0,o="",a="",i;t<e.length;)switch(e[t][0]){case Ee:n++,a+=e[t][1],t++;break;case xe:r++,o+=e[t][1],t++;break;case oe:r+n>1?(r!==0&&n!==0&&(i=this.diff_commonPrefix(a,o),i!==0&&(t-r-n>0&&e[t-r-n-1][0]==oe?e[t-r-n-1][1]+=a.substring(0,i):(e.splice(0,0,new U.Diff(oe,a.substring(0,i))),t++),a=a.substring(i),o=o.substring(i)),i=this.diff_commonSuffix(a,o),i!==0&&(e[t][1]=a.substring(a.length-i)+e[t][1],a=a.substring(0,a.length-i),o=o.substring(0,o.length-i))),t-=r+n,e.splice(t,r+n),o.length&&(e.splice(t,0,new U.Diff(xe,o)),t++),a.length&&(e.splice(t,0,new U.Diff(Ee,a)),t++),t++):t!==0&&e[t-1][0]==oe?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,o="",a="";break}e[e.length-1][1]===""&&e.pop();var l=!1;for(t=1;t<e.length-1;)e[t-1][0]==oe&&e[t+1][0]==oe&&(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),l=!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),l=!0)),t++;l&&this.diff_cleanupMerge(e)};U.prototype.diff_xIndex=function(e,t){var r=0,n=0,o=0,a=0,i;for(i=0;i<e.length&&(e[i][0]!==Ee&&(r+=e[i][1].length),e[i][0]!==xe&&(n+=e[i][1].length),!(r>t));i++)o=r,a=n;return e.length!=i&&e[i][0]===xe?a:a+(t-o)};U.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,o=/>/g,a=/\n/g,i=0;i<e.length;i++){var l=e[i][0],s=e[i][1],c=s.replace(r,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(a,"&para;<br>");switch(l){case Ee:t[i]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case xe:t[i]='<del style="background:#ffe6e6;">'+c+"</del>";break;case oe:t[i]="<span>"+c+"</span>";break}}return t.join("")};U.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==Ee&&(t[r]=e[r][1]);return t.join("")};U.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==xe&&(t[r]=e[r][1]);return t.join("")};U.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,o=0;o<e.length;o++){var a=e[o][0],i=e[o][1];switch(a){case Ee:r+=i.length;break;case xe:n+=i.length;break;case oe:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};U.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case Ee:t[r]="+"+encodeURI(e[r][1]);break;case xe:t[r]="-"+e[r][1].length;break;case oe:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};U.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,o=0,a=t.split(/\t/g),i=0;i<a.length;i++){var l=a[i].substring(1);switch(a[i].charAt(0)){case"+":try{r[n++]=new U.Diff(Ee,decodeURI(l))}catch{throw new Error("Illegal escape in diff_fromDelta: "+l)}break;case"-":case"=":var s=parseInt(l,10);if(isNaN(s)||s<0)throw new Error("Invalid number in diff_fromDelta: "+l);var c=e.substring(o,o+=s);a[i].charAt(0)=="="?r[n++]=new U.Diff(oe,c):r[n++]=new U.Diff(xe,c);break;default:if(a[i])throw new Error("Invalid diff operation in diff_fromDelta: "+a[i])}}if(o!=e.length)throw new Error("Delta length ("+o+") does not equal source text length ("+e.length+").");return r};U.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};U.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),o=this;function a(b,x){var S=b/t.length,A=Math.abs(r-x);return o.Match_Distance?S+A/o.Match_Distance:A?1:S}var i=this.Match_Threshold,l=e.indexOf(t,r);l!=-1&&(i=Math.min(a(0,l),i),l=e.lastIndexOf(t,r+t.length),l!=-1&&(i=Math.min(a(0,l),i)));var s=1<<t.length-1;l=-1;for(var c,f,u=t.length+e.length,d,m=0;m<t.length;m++){for(c=0,f=u;c<f;)a(m,r+f)<=i?c=f:u=f,f=Math.floor((u-c)/2+c);u=f;var p=Math.max(1,r-f+1),g=Math.min(r+f,e.length)+t.length,h=Array(g+2);h[g+1]=(1<<m)-1;for(var v=g;v>=p;v--){var w=n[e.charAt(v-1)];if(m===0?h[v]=(h[v+1]<<1|1)&w:h[v]=(h[v+1]<<1|1)&w|((d[v+1]|d[v])<<1|1)|d[v+1],h[v]&s){var y=a(m,v-1);if(y<=i)if(i=y,l=v-1,l>r)p=Math.max(1,2*r-l);else break}}if(a(m+1,r)>i)break;d=h}return l};U.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};U.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 U.Diff(oe,o));var a=t.substring(e.start2+e.length1,e.start2+e.length1+n);a&&e.diffs.push(new U.Diff(oe,a)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+a.length,e.length2+=o.length+a.length}};U.prototype.patch_make=function(e,t,r){var n,o;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,o=this.diff_main(n,t,!0),o.length>2&&(this.diff_cleanupSemantic(o),this.diff_cleanupEfficiency(o));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")o=e,n=this.diff_text1(o);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,o=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,o=r;else throw new Error("Unknown call format to patch_make.");if(o.length===0)return[];for(var a=[],i=new U.patch_obj,l=0,s=0,c=0,f=n,u=n,d=0;d<o.length;d++){var m=o[d][0],p=o[d][1];switch(!l&&m!==oe&&(i.start1=s,i.start2=c),m){case Ee:i.diffs[l++]=o[d],i.length2+=p.length,u=u.substring(0,c)+p+u.substring(c);break;case xe:i.length1+=p.length,i.diffs[l++]=o[d],u=u.substring(0,c)+u.substring(c+p.length);break;case oe:p.length<=2*this.Patch_Margin&&l&&o.length!=d+1?(i.diffs[l++]=o[d],i.length1+=p.length,i.length2+=p.length):p.length>=2*this.Patch_Margin&&l&&(this.patch_addContext_(i,f),a.push(i),i=new U.patch_obj,l=0,f=u,s=c);break}m!==Ee&&(s+=p.length),m!==xe&&(c+=p.length)}return l&&(this.patch_addContext_(i,f),a.push(i)),a};U.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new U.patch_obj;o.diffs=[];for(var a=0;a<n.diffs.length;a++)o.diffs[a]=new U.Diff(n.diffs[a][0],n.diffs[a][1]);o.start1=n.start1,o.start2=n.start2,o.length1=n.length1,o.length2=n.length2,t[r]=o}return t};U.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,o=[],a=0;a<e.length;a++){var i=e[a].start2+n,l=this.diff_text1(e[a].diffs),s,c=-1;if(l.length>this.Match_MaxBits?(s=this.match_main(t,l.substring(0,this.Match_MaxBits),i),s!=-1&&(c=this.match_main(t,l.substring(l.length-this.Match_MaxBits),i+l.length-this.Match_MaxBits),(c==-1||s>=c)&&(s=-1))):s=this.match_main(t,l,i),s==-1)o[a]=!1,n-=e[a].length2-e[a].length1;else{o[a]=!0,n=s-i;var f;if(c==-1?f=t.substring(s,s+l.length):f=t.substring(s,c+this.Match_MaxBits),l==f)t=t.substring(0,s)+this.diff_text2(e[a].diffs)+t.substring(s+l.length);else{var u=this.diff_main(l,f,!1);if(l.length>this.Match_MaxBits&&this.diff_levenshtein(u)/l.length>this.Patch_DeleteThreshold)o[a]=!1;else{this.diff_cleanupSemanticLossless(u);for(var d=0,m,p=0;p<e[a].diffs.length;p++){var g=e[a].diffs[p];g[0]!==oe&&(m=this.diff_xIndex(u,d)),g[0]===Ee?t=t.substring(0,s+m)+g[1]+t.substring(s+m):g[0]===xe&&(t=t.substring(0,s+m)+t.substring(s+this.diff_xIndex(u,d+g[1].length))),g[0]!==xe&&(d+=g[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};U.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var o=e[0],a=o.diffs;if(a.length==0||a[0][0]!=oe)a.unshift(new U.Diff(oe,r)),o.start1-=t,o.start2-=t,o.length1+=t,o.length2+=t;else if(t>a[0][1].length){var i=t-a[0][1].length;a[0][1]=r.substring(a[0][1].length)+a[0][1],o.start1-=i,o.start2-=i,o.length1+=i,o.length2+=i}if(o=e[e.length-1],a=o.diffs,a.length==0||a[a.length-1][0]!=oe)a.push(new U.Diff(oe,r)),o.length1+=t,o.length2+=t;else if(t>a[a.length-1][1].length){var i=t-a[a.length-1][1].length;a[a.length-1][1]+=r.substring(0,i),o.length1+=i,o.length2+=i}return r};U.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var o=n.start1,a=n.start2,i="";n.diffs.length!==0;){var l=new U.patch_obj,s=!0;for(l.start1=o-i.length,l.start2=a-i.length,i!==""&&(l.length1=l.length2=i.length,l.diffs.push(new U.Diff(oe,i)));n.diffs.length!==0&&l.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],f=n.diffs[0][1];c===Ee?(l.length2+=f.length,a+=f.length,l.diffs.push(n.diffs.shift()),s=!1):c===xe&&l.diffs.length==1&&l.diffs[0][0]==oe&&f.length>2*t?(l.length1+=f.length,o+=f.length,s=!1,l.diffs.push(new U.Diff(c,f)),n.diffs.shift()):(f=f.substring(0,t-l.length1-this.Patch_Margin),l.length1+=f.length,o+=f.length,c===oe?(l.length2+=f.length,a+=f.length):s=!1,l.diffs.push(new U.Diff(c,f)),f==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(f.length))}i=this.diff_text2(l.diffs),i=i.substring(i.length-this.Patch_Margin);var u=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);u!==""&&(l.length1+=u.length,l.length2+=u.length,l.diffs.length!==0&&l.diffs[l.diffs.length-1][0]===oe?l.diffs[l.diffs.length-1][1]+=u:l.diffs.push(new U.Diff(oe,u))),s||e.splice(++r,0,l)}}};U.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};U.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
3
+ `),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var a=r[n].match(o);if(!a)throw new Error("Invalid patch string: "+r[n]);var i=new U.patch_obj;for(t.push(i),i.start1=parseInt(a[1],10),a[2]===""?(i.start1--,i.length1=1):a[2]=="0"?i.length1=0:(i.start1--,i.length1=parseInt(a[2],10)),i.start2=parseInt(a[3],10),a[4]===""?(i.start2--,i.length2=1):a[4]=="0"?i.length2=0:(i.start2--,i.length2=parseInt(a[4],10)),n++;n<r.length;){var l=r[n].charAt(0);try{var s=decodeURI(r[n].substring(1))}catch{throw new Error("Illegal escape in patch_fromText: "+s)}if(l=="-")i.diffs.push(new U.Diff(xe,s));else if(l=="+")i.diffs.push(new U.Diff(Ee,s));else if(l==" ")i.diffs.push(new U.Diff(oe,s));else{if(l=="@")break;if(l!=="")throw new Error('Invalid patch mode "'+l+'" in: '+s)}n++}}return t};U.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};U.patch_obj.prototype.toString=function(){var e,t;this.length1===0?e=this.start1+",0":this.length1==1?e=this.start1+1:e=this.start1+1+","+this.length1,this.length2===0?t=this.start2+",0":this.length2==1?t=this.start2+1:t=this.start2+1+","+this.length2;for(var r=["@@ -"+e+" +"+t+` @@
4
+ `],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case Ee:n="+";break;case xe:n="-";break;case oe:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
5
+ `}return r.join("").replace(/%20/g," ")};Un.exports=U;Un.exports.diff_match_patch=U;Un.exports.DIFF_DELETE=xe;Un.exports.DIFF_INSERT=Ee;Un.exports.DIFF_EQUAL=oe});import{DOMParser as Cp,XMLSerializer as _p}from"@xmldom/xmldom";var ba=console,Xi=Object.freeze({silent:0,error:1,warn:2,info:3}),Ep=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",Vi=Ep;function Rp(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(Xi,t)?t:Vi}function ji(e){return Xi[Vi]>=Xi[e]}function Pp(e,t={}){ba=e||console,t.level&&(Vi=Rp(t.level))}function W(...e){ji("info")&&(ba.log||(()=>{}))(...e)}function ir(...e){ji("warn")&&(ba.warn||(()=>{}))(...e)}function Le(...e){ji("error")&&(ba.error||(()=>{}))(...e)}var hc=null,wc=null;function Op(e={}){"DOMParser"in e&&(hc=e.DOMParser),"XMLSerializer"in e&&(wc=e.XMLSerializer)}function kp(){return hc||globalThis.DOMParser||Cp}function Mp(){return wc||globalThis.XMLSerializer||_p}function Lp(e={}){let t=kp();if(!t)throw new Error("DOMParser is not configured and no fallback XML parser is available.");return new t(e)}function le(){let e=Mp();if(!e)throw new Error("XMLSerializer is not configured and no fallback XML serializer is available.");return new e}function vc(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 Bp(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,a)=>{let i=String(a||"XML parser diagnostic.");o==="fatalError"?Le("[XmlAdapter] XML fatal parse error:",i):(r.push(i),ir(`[XmlAdapter] XML ${o||"warning"}:`,i))};try{let a=Lp({onError:n}).parseFromString(e,t),i=Bp(a);if(!a?.documentElement||i){let l=i?.textContent||"Could not parse XML input.";return Le("[XmlAdapter] XML parse error:",l),{doc:null,error:{code:"PARSE_ERROR",message:l},warnings:r}}return{doc:a,error:null,warnings:r}}catch(o){let a=o?.message||String(o||"Could not parse XML input.");return Le("[XmlAdapter] XML parse error:",a),{doc:null,error:{code:"PARSE_ERROR",message:a},warnings:r}}}function Be(e){return le().serializeToString(e)}var yc=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",bc=yc(),xc="Unknown";function Fp(e){bc=typeof e=="string"&&e.trim()?e.trim():yc()}function ae(){return bc}function $p(e){xc=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function Wi(){return xc}var Dp=[{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:/(?<![A-Za-z0-9_])__(?=[^_\s])(.+?)(?<=[^_\s])__(?![A-Za-z0-9_])/,format:{bold:!0}},{regex:/\+\+(.+?)\+\+/,format:{underline:!0}},{regex:/~~(.+?)~~/,format:{strikethrough:!0}},{regex:/~(.+?)~/,format:{strikethrough:!0}},{regex:/\*(?!\*)(.+?)\*(?!\*)/,format:{italic:!0}},{regex:/(?<![A-Za-z0-9_])_(?=[^_\s])(.+?)(?<=[^_\s])_(?![A-Za-z0-9_])/,format:{italic:!0}}];function qe(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let l of Dp){let s,c=l.regex.source||l.regex.toString().replace(/^\/|\/[gimuy]*$/g,""),f="g"+(l.regex.ignoreCase?"i":""),u=new RegExp(c,f);for(;(s=u.exec(e))!==null;)n.push({start:s.index,end:s.index+s[0].length,fullMatch:s[0],innerText:l.isEscaped?Up(s[1]):s[1],format:l.format}),s.index===u.lastIndex&&u.lastIndex++}n.sort((l,s)=>l.start-s.start||s.end-l.end);let o=[],a=0;for(let l of n)l.start>=a&&(o.push(l),a=l.end);let i=0;for(let l of o){r+=e.slice(i,l.start);let s=qe(l.innerText),c=r.length;r+=s.cleanText;let f=r.length;t.push({start:c,end:f,format:l.format});for(let u of s.formatHints)t.push({start:c+u.start,end:c+u.end,format:u.format});i=l.end}return r+=e.slice(i),{cleanText:r,formatHints:t}}function sr(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function Ki(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function Up(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var xa=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,Ic=new RegExp(`^(\\s*)((?:${xa})\\s+)`),Nc=new RegExp(`^(\\s*)((?:${xa})\\s*)`),zp=new RegExp(`^(\\s*)((?:${xa})\\s+)`,"m"),Xp=new RegExp(`^(\\s*)((?:${xa})\\s*)`,"m");function Gi(e){return typeof e!="string"?!1:e.includes(`
6
+ `)&&zp.test(e)}function Mn(e){return typeof e!="string"?!1:e.includes(`
7
+ `)&&Xp.test(e.trim())}function Xt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Nc:Ic;return e.match(n)}function Zt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Nc:Ic;return e.replace(n,"")}function Tc(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function So(e){let t=String(e||"").trim();return Tc(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 Vp(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function qr(e,t={}){let r=Xt(String(e||""),t);if(!r)return null;let n=r[2].trim(),o=(r[1]||"").length,a=Math.max(1,Number(t.indentSpaces)||2),i=Tc(n);return{line:String(e||""),text:Zt(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/a)),markerType:i,listType:i,numberingStyle:So(n),outlineLevel:i==="numbered"?Vp(n):null}}var B="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var Bt=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),H=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"}),Ln=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),Ec=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),ve=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),Ze=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function Qe(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var Hi=1e3,Sc=2147483647,Ac=1e4,jp=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Rc=new WeakMap;function Wp(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return jp.has(t)?!e.namespaceURI||e.namespaceURI===B||String(e.nodeName||"").startsWith("w:"):!1}function Kp(e){let t=e?.getAttributeNS?.(B,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var De=class{constructor(t=Hi){this.startValue=Number.isInteger(t)&&t>=0?t:Hi,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(Wp(o)){let i=Kp(o);i!=null&&(this.occupiedIds.add(i),r=Math.max(r,i))}if(o.firstChild){o=o.firstChild;continue}for(;o&&o!==n&&!o.nextSibling;)o=o.parentNode;o=o&&o!==n?o.nextSibling:null}let a=Sc-Ac;return this.nextId=r>=a?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=Sc-Ac;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}},Ao=new De;function Cr(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof De&&Rc.set(r,t),t}function lr(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Rc.get(t)||null}function _r(e,t=Hi){let r=new De(t);return r.seed(e),Cr(e,r),r}function Pc(){return Ao.next()}function Ia(e=new Date){return e.toISOString()}function ue(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():ae(),o=t instanceof De?t:lr(t)||Ao,a=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(a,r||"structural"),{id:a,author:n,date:Ia()}}function Eo(e,t=null,{deferReceipt:r=!1}={}){let n=typeof e=="string"&&e.trim()?e.trim():ae(),o=t instanceof De?t:lr(t)||Ao,a=Ia(),i=o.next(),l=o.next();return o._receiptCollector&&!r&&(o._receiptCollector.recordRevision(i,"del"),o._receiptCollector.recordRevision(l,"ins")),{deletionId:i,insertionId:l,author:n,date:a,recordUsed:r?s=>o._receiptCollector?.recordRevision(s==="del"?i:l,s):null}}function cr(e,t=Ao){let r=t instanceof De?t:Ao,n=r.seed(e);return Cr(e,r),n}function qi(e,t){if(!e||e.nodeType!==1)return!1;let r=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return t!=null&&r!==t?!1:!e.namespaceURI||e.namespaceURI===B}function me(e,t){if(!e)return null;for(let r of Array.from(e.childNodes||[]))if(qi(r,t))return r;return null}function Yi(e,t){return e?Array.from(e.childNodes||[]).filter(r=>qi(r,t)):[]}function et(e,t){return me(e,t)}function Na(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"&&e.getAttributeNS(B,"val")||e.getAttribute?.("w:val")||e.getAttribute?.("val")||null;return t===""?null:t}function Gp(e){let t=me(e,"numPr");return t?{element:t,numId:Na(me(t,"numId")),ilvl:Na(me(t,"ilvl")),numIdElement:me(t,"numId"),ilvlElement:me(t,"ilvl")}:null}function Cc(e){let t=me(e,"pStyle"),r=me(e,"outlineLvl");return{pPr:e||null,numPr:Gp(e),pStyle:Na(t),pStyleElement:t,outlineLvl:Na(r),outlineLvlElement:r}}function it(e){return Cc(me(e,"pPr"))}function _c(e){return me(e,"rPr")}function Oc(e){let t=me(me(e,"pPr"),"pPrChange"),r=me(t,"pPr");return r?Cc(r):null}function Hp(e){if(!e||e.nodeType!==1)return[];let t=qi(e,"p")?[e]:[];return typeof e.getElementsByTagNameNS=="function"&&t.push(...Array.from(e.getElementsByTagNameNS(B,"p"))),t}function Vt(e){let t=[];for(let r of Hp(e)){let n=it(r).numPr?.numIdElement;n&&t.push(n)}return t}function Bn(e){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(B,"numId"))}function kc(e,t){return e<t-1}function Fn(e,t,r){return kc(t,r)?e+`
8
+ `:e}function Yr(e,t,r){return kc(t,r)?e+1:e}function Ro(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function Ue(e,t){if(!e||typeof e.getElementsByTagName!="function")return null;let r=e.getElementsByTagName(t);return r.length>0?r[0]:null}function We(e,t,r){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(t,r))}function Ge(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 st(e,t,r,n=`w:${r}`){let o=We(e,t,r);return o.length>0?o:Ro(e,n)}function lt(e,t,r,n=`w:${r}`){let o=Ge(e,t,r);return o||Ue(e,n)}function Fe(e){return Ue(e,"parsererror")}function Ji(e){return Array.from(e?.childNodes||[])}function Mc(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Zi(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var Qi=0;function Dn(e,t={}){let r=[],n="",o=t.xmlDoc||null;if(!e&&!o)return{runModel:r,acceptedText:n,pPr:null};try{let a=o?{doc:o,error:null}:j(e,"application/xml"),i=a.doc;if(a.error||!i)return Le("OOXML parse error:",a.error?.message),{runModel:r,acceptedText:n,pPr:null,error:a.error};let l=Fe(i);if(l)return Le("OOXML parse error:",l.textContent),{runModel:r,acceptedText:n,pPr:null};let s=We(i,B,"p");return s.length===0?(ir("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):Bc(s,{includeParagraphBoundaries:!0})}catch(a){return Le("Error ingesting OOXML:",a),{runModel:r,acceptedText:n,pPr:null}}}function es(e){return e?Bc([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function Po(e){let{numPr:t}=it(e);if(!t||!t.numIdElement)return null;let r=t.numId;if(!/^\d+$/.test(r)||Number.parseInt(r,10)===0)return null;let n=r==="1"?"bullet":r==="2"?"numbered":"unknown";return{numId:r,ilvl:parseInt(t.ilvl||"0",10),type:n}}function Bc(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],o="",a=0,i=null;for(let l=0;l<e.length;l++){let s=e[l],c=Ge(s,B,"pPr");l===0&&(i=c),n.push({kind:H.PARAGRAPH_START,pPrElement:c||null,startOffset:a,endOffset:a,text:""});let f=$n(s,a,n);o+=f.text,a=o.length,r&&(o=Fn(o,l,e.length),a=Yr(a,l,e.length))}return{runModel:n,acceptedText:o,pPr:i}}function $n(e,t,r){let n=t,o="",a=qp(r);for(let i of Ji(e)){if(Zi(i,B,"pPr")||Zi(i,B,"proofErr"))continue;let l=a.get(i.localName);if(!l)continue;let s=l(i,n);n=s.offset,o+=s.text}return{offset:n,text:o}}function qp(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${Qi++}`,a=Ge(r,B,"sdtPr"),i=Ge(r,B,"sdtContent");e.push({kind:H.CONTAINER_START,containerKind:Ln.SDT,containerId:o,propertiesXml:a?Be(a):"",startOffset:n,endOffset:n,text:""});let l=i?$n(i,n,e):{offset:n,text:""};return e.push({kind:H.CONTAINER_END,containerKind:Ln.SDT,containerId:o,startOffset:l.offset,endOffset:l.offset,text:""}),l}),t.set("smartTag",(r,n)=>{let o=`smartTag_${Qi++}`;e.push({kind:H.CONTAINER_START,containerKind:Ln.SMART_TAG,containerId:o,propertiesXml:Mc(r),startOffset:n,endOffset:n,text:""});let a=$n(r,n,e);return e.push({kind:H.CONTAINER_END,containerKind:Ln.SMART_TAG,containerId:o,startOffset:a.offset,endOffset:a.offset,text:""}),a}),t.set("del",(r,n)=>{let o=Lc(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=Lc(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>$n(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:H.BOOKMARK,nodeXml:Be(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:H.BOOKMARK,nodeXml:Be(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:H.BOOKMARK,nodeXml:Be(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>$n(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${Qi++}`,a=r.getAttribute("r:id")||"",i=r.getAttribute("w:anchor")||"";e.push({kind:H.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:a,anchor:i}),startOffset:n,endOffset:n,text:""});let l=$n(r,n,e);return e.push({kind:H.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:l.offset,endOffset:l.offset,text:""}),l}),t.set("r",(r,n)=>{let o=Yp(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function Yp(e,t){let r=lt(e,B,"rPr"),n=r?Be(r):"",o="";for(let a of Ji(e)){let i=a.nodeName;i.endsWith(":t")||i==="t"?o+=a.textContent||"":i.endsWith(":br")||i==="br"||i.endsWith(":cr")||i==="cr"?o+=`
9
+ `:i.endsWith(":tab")||i==="tab"?o+=" ":i.endsWith(":noBreakHyphen")||i==="noBreakHyphen"?o+="\u2011":(i.endsWith(":softHyphen")||i==="softHyphen")&&(o+="\xAD")}return o?{kind:H.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function Lc(e,t){let r=e.getAttribute("w:author")||"",n="",o=We(e,B,"delText");for(let i of o)n+=i.textContent||"";let a=We(e,B,"r");for(let i of a){let l=We(i,B,"delText");for(let s of l)n+=s.textContent||""}return n?{kind:H.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:Be(e)}:null}function rs(e){let t=Ge(e,B,"tblGrid"),r=t?We(t,B,"gridCol"):[],n=st(e,B,"tr"),o=n.length,a=n.reduce((f,u)=>{let d=st(u,B,"tc");return Math.max(f,d.length)},0),i=r.length||a,l=Array.from({length:o},()=>Array.from({length:i},()=>null)),s=new Map,c=new Map;for(let f=0;f<n.length;f++){let u=n[f],d=st(u,B,"tc"),m=0;for(let p=0;p<d.length;p++){let g=d[p],h=Ge(g,B,"tcPr");for(;m<i&&l[f][m]!==null;)m++;if(m>=i)break;let v=h?Ge(h,B,"gridSpan")||Ue(h,"w:gridSpan"):null,w=parseInt(v?.getAttribute("w:val")||"1",10),y=h?Ge(h,B,"vMerge")||Ue(h,"w:vMerge"):null,b=y?.getAttribute("w:val"),x=y!==null,S;if(x&&b!=="restart"){let A=c.get(m);A?(A.cell.rowSpan++,S={gridRow:f,gridCol:m,rowSpan:0,colSpan:w,tcNode:g,blocks:[],tcPrXml:ts(h),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:A.cell}):S=Jp(f,m,w,g,h)}else{let A=Fc(g);if(S={gridRow:f,gridCol:m,rowSpan:1,colSpan:w,tcNode:g,blocks:A,tcPrXml:ts(h),isMergeOrigin:x&&b==="restart",isMergeContinuation:!1,getText:()=>A.map(E=>E.acceptedText).join(`
10
+ `)},x&&b==="restart")for(let E=0;E<w;E++)c.set(m+E,{originRow:f,cell:S});else for(let E=0;E<w;E++)c.delete(m+E)}for(let A=0;A<w;A++){let E=m+A;E<i&&(l[f][E]=S,s.set(`${f},${E}`,S))}m+=w}}return{rowCount:o,colCount:i,grid:l,cellMap:s,tblPrXml:Zp(e),tblGridXml:Qp(e),trPrList:Array.from(n).map(f=>eg(f))}}function Jp(e,t,r,n,o){let a=Fc(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:a,tcPrXml:ts(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>a.map(i=>i.acceptedText).join(`
11
+ `)}}function Fc(e){return st(e,B,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:a}=es(r);return{runModel:n,acceptedText:o,pPr:a}})}function ts(e){return e?Be(e):"<w:tcPr/>"}function Zp(e){let t=Ge(e,B,"tblPr");return t?Be(t):"<w:tblPr/>"}function Qp(e){let t=Ge(e,B,"tblGrid");return t?Be(t):"<w:tblGrid/>"}function eg(e){let t=Ge(e,B,"trPr");return t?Be(t):"<w:trPr/>"}var zc=gc(ns(),1);var tg=65536,Ta=262144,Sa=1,Aa=55296-Sa,rg=8192,ng=Aa+rg,os=class extends Error{constructor(t=Ta){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function Xc(e){return e?.code==="DIFF_TOKEN_LIMIT"}function as(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 zc.diff_match_patch;return r.Diff_Timeout=t,r}var og=/^[("'\[{“‘]+/u,ag=/[)"'\]}”’,.;:!?]+$/u;function $c(e,t=null){let r=[],n=s=>{if(!t||t.size===0){r.push(s);return}let c=0;for(let f=0;f<s.length;f++)t.has(s[f])&&(f>c&&r.push(s.slice(c,f)),r.push(s[f]),c=f+1);c<s.length&&r.push(s.slice(c))},o=s=>{let c=s.match(og)?.[0]||"",f=s.slice(c.length),u=f.match(ag)?.[0]||"",d=f.slice(0,f.length-u.length);if(!d){n(s);return}for(let m of c)n(m);n(d);for(let m of u)n(m)},a=e.match(/^\s+/);a&&r.push(a[0]);let i=/(\S+)(\s*)/g;i.lastIndex=a?.[0].length||0;let l;for(;(l=i.exec(e))!==null;)l[1]&&o(l[1]),l[2]&&r.push(l[2]);return r}function ig(e,t,r={}){let n=[],o=new Map,a=r.maxTokens??Ta;if(!Number.isInteger(a)||a<1||a>Ta)throw new RangeError(`maxTokens must be an integer from 1 to ${Ta}.`);function i(u){let d="",m=[];for(let p of u){let g=o.get(p);if(g===void 0){if(n.length>=a)throw new os(a);g=n.length,n.push(p),o.set(p,g)}m.push(g),d+=String.fromCodePoint(tg+g)}return{chars:d,tokenIds:m}}let l=$c(e,r.atomicChars),s=$c(t,r.atomicChars),c=i(l),f=i(s);return{chars1:c.chars,chars2:f.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:f.tokenIds}}function sg(e){let t=e<Aa?Sa+e:57344+(e-Aa);return String.fromCharCode(t)}function is(e){if(e>=Sa&&e<55296)return e-Sa;if(e>=57344&&e<=65535)return Aa+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function Dc(e){let t="";for(let r of e)t+=sg(r);return t}function lg(e,t){return e.map(([r,n])=>{let o=[];for(let a=0;a<n.length;a++){let i=is(n.charCodeAt(a));if(i>=t.length)throw new RangeError(`BMP diff token ${i} has no mapping.`);o.push(t[i])}return[r,o.join("")]})}function cg(e,t,r){let n=0,o=Math.min(e.length,t.length);for(;n<o&&e[n]===t[n];)n++;let a=0;for(;a<o-n&&e[e.length-1-a]===t[t.length-1-a];)a++;let i=f=>f.map(u=>r[u]).join(""),l=[];n&&l.push([0,i(e.slice(0,n))]);let s=e.slice(n,e.length-a),c=t.slice(n,t.length-a);return s.length&&l.push([-1,i(s)]),c.length&&l.push([1,i(c)]),a&&l.push([0,i(e.slice(e.length-a))]),l}function Co(e,t,r={}){if(e===t)return[[0,e]];if(!e)return[[1,t]];if(!t)return[[-1,e]];let{cleanupSemantic:n=!0}=r,{wordArray:o,tokenIds1:a,tokenIds2:i}=ig(e,t,r);if(o.length>ng)return cg(a,i,o);let l=as(r),s=l.diff_main(Dc(a),Dc(i));return n&&(l.diff_cleanupSemantic(s),dg(l,s,o)),lg(s,o)}var Vc=/^[\p{L}\p{N}][\p{L}\p{N}'’-]{3,}$/u;function Uc(e,t){for(let r=0;r<e.length;r++)if(Vc.test(t[is(e.charCodeAt(r))]))return!0;return!1}var ug=25e4;function fg(e,t,r){let n=e.length,o=t.length;if(!n||!o||(n+1)*(o+1)>ug)return null;let a=d=>{let m=r[is(d.charCodeAt(0))];return Vc.test(m)?m.length*100:m.length},i=o+1,l=new Float64Array((n+1)*i);for(let d=n-1;d>=0;d--)for(let m=o-1;m>=0;m--){let p=Math.max(l[(d+1)*i+m],l[d*i+m+1]);l[d*i+m]=e[d]===t[m]?Math.max(p,a(e[d])+l[(d+1)*i+m+1]):p}let s=[],c=(d,m)=>{let p=s[s.length-1];p?.[0]===d?p[1]+=m:s.push([d,m])},f=0,u=0;for(;f<n&&u<o;){let d=l[f*i+u];e[f]===t[u]&&d===a(e[f])+l[(f+1)*i+u+1]?(c(0,e[f]),f++,u++):l[(f+1)*i+u]>=l[f*i+u+1]?c(-1,e[f++]):c(1,t[u++])}for(;f<n;)c(-1,e[f++]);for(;u<o;)c(1,t[u++]);return s}function dg(e,t,r){for(let n=0;n<t.length;n++){let o=-1,a=-1;if(t[n][0]===-1&&t[n+1]?.[0]===1)o=n,a=n+1;else if(t[n][0]===1&&t[n+1]?.[0]===-1)a=n,o=n+1;else continue;let i=fg(t[o][1],t[a][1],r);if(!i?.some(([s,c])=>s===0&&Uc(c,r)))continue;let l=[];for(let[s,c]of i)s===0&&!Uc(c,r)?l.push([-1,c],[1,c]):l.push([s,c]);e.diff_cleanupMerge(l),t.splice(n,2,...l),n+=l.length-1}}function jc(e,t,r={}){return e===t?[[0,e]]:as(r).diff_main(e,t)}function Wc(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=as().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function zn(e,t,r={}){if(e===t)return[{type:Bt.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:Bt.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:Bt.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=Co(e,t,r),o=[],a=0;for(let[i,l]of n)i===0?(o.push({type:Bt.EQUAL,startOffset:a,endOffset:a+l.length,text:l}),a+=l.length):i===-1?(o.push({type:Bt.DELETE,startOffset:a,endOffset:a+l.length,text:l}),a+=l.length):i===1&&o.push({type:Bt.INSERT,startOffset:a,endOffset:a,text:l});return o}var mg=/\s+xmlns:[^=]+="[^"]*"/g;function Xn(e,t){let r=yg(t),n=[],o=0;for(let a of e){if(a.kind!==H.TEXT&&a.kind!==H.HYPERLINK){n.push(a);continue}for(;o<r.length&&r[o]<=a.startOffset;)o++;let i=o,l=a.startOffset,s=!1;for(;i<r.length;){let c=r[i];if(c>=a.endOffset)break;c>l&&(s=!0,n.push({...a,text:a.text.slice(l-a.startOffset,c-a.startOffset),startOffset:l,endOffset:c}),l=c),i++}if(o=i,!s){n.push(a);continue}n.push({...a,text:a.text.slice(l-a.startOffset),startOffset:l,endOffset:a.endOffset})}return n}function Vn(e,t,r){let{generateRedlines:n,author:o}=r,a=[],i=new Set,l=bg(t),s=wg(e),c=vg(l.nonInsertOps),f={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let d of e){if(d.kind===H.CONTAINER_START){f.containerStack.push(d.containerId),a.push({...d});continue}if(d.kind===H.CONTAINER_END){f.containerStack.pop(),a.push({...d});continue}if(d.kind===H.PARAGRAPH_START){f.currentParagraphPPrXml=typeof d.pPrXml=="string"?d.pPrXml:"",f.currentParagraphPPrElement=d.pPrElement||null,a.push({...d}),f.lastParagraphStartIndex=a.length-1;continue}if(d.kind===H.BOOKMARK||d.kind===H.DELETION){a.push({...d});continue}let m=c(d.startOffset,d.endOffset),p=l.insertOpsByStartOffset.get(d.startOffset)||[];for(let g of p)i.has(g)||(i.add(g),pg({insertOp:g,splitModel:e,styleLookup:s,patchedModel:a,state:f,options:r,generateRedlines:n,author:o}));if(!m||m.type===Bt.EQUAL){a.push({...d,containerContext:f.containerStack.length>0?f.containerStack[f.containerStack.length-1]:null});continue}m.type===Bt.DELETE&&n&&a.push({...d,kind:H.DELETION,author:o,containerContext:f.containerStack.length>0?f.containerStack[f.containerStack.length-1]:null})}let u=e.length>0?Math.max(...e.map(d=>d.endOffset)):0;for(let d of l.sortedInsertOps){if(d.startOffset<u||i.has(d))continue;let m=e[e.length-1];a.push({kind:n?H.INSERTION:H.TEXT,text:d.text,rPrXml:m?.rPrXml||"",startOffset:d.startOffset,endOffset:d.startOffset+d.text.length,author:n?o:void 0})}return a}function pg(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:a,generateRedlines:i,author:l}=e,s=t.text.split(`
12
+ `),c=hg(r,t.startOffset,t.text);for(let f=0;f<s.length;f++){let u=gg(s[f],a.numberingService,o),d=u.lineText;if(f>0){let m=Kc(o);u.isListLine&&u.numId&&(m=a.numberingService.buildListPPr(u.numId,u.ilvl)),n.push({kind:H.PARAGRAPH_START,pPrXml:m,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,o.lastParagraphStartIndex=n.length-1}else if(u.isListLine&&u.numId&&o.lastParagraphStartIndex>=0){let m=a.numberingService.buildListPPr(u.numId,u.ilvl);n[o.lastParagraphStartIndex].pPrXml=m,n[o.lastParagraphStartIndex].pPrElement=null,o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,W(`[Patching] Converted current paragraph to list item: numId=${u.numId}, ilvl=${u.ilvl}`)}(d.length>0||f>0)&&n.push({kind:i?H.INSERTION:H.TEXT,text:d,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+d.length,author:i?l:void 0,containerContext:o.containerStack.length>0?o.containerStack[o.containerStack.length-1]:null})}}function gg(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=Xt(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let o=n[2].trim(),a=t.detectNumberingFormat(o),i=e.match(/^(\s*)/),l=i?i[1].length:0,s=l>=4?4:2,c=Math.floor(l/s),f=Kc(r),u=Zt(e,{allowZeroSpaceAfterMarker:!0}),d=f.match(/w:numId w:val="(\d+)"/),m=f.match(/w:ilvl w:val="(\d+)"/),p=d?d[1]:null,g=m?parseInt(m[1],10):0,h=t.getOrCreateNumId({type:a.format},{numId:p,type:"unknown"}),v=a.format==="outline"?Math.min(8,a.depth):Math.min(8,c+g);return{lineText:u,isListLine:!0,numId:h,ilvl:v}}function Kc(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=Be(e.currentParagraphPPrElement).replace(mg,""),e.currentParagraphPPrXml):""}function hg(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 wg(e){let t=e.filter(o=>o.kind===H.TEXT),r=t.map(o=>o.startOffset),n=t.map(o=>o.endOffset);return{findRunBefore(o){let a=0,i=n.length-1,l=-1;for(;a<=i;){let s=a+i>>1;n[s]<=o?(l=s,a=s+1):i=s-1}return l>=0?t[l]:null},findRunAfter(o){let a=0,i=r.length-1,l=-1;for(;a<=i;){let s=a+i>>1;r[s]>=o?(l=s,i=s-1):a=s+1}return l>=0?t[l]:null}}}function vg(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 yg(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 bg(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===Bt.INSERT){t.has(o.startOffset)||t.set(o.startOffset,[]),t.get(o.startOffset).push(o),n.push(o);continue}r.push(o)}return r.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),n.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var Yc="http://schemas.openxmlformats.org/wordprocessingml/2006/main",xg="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Ig="http://schemas.microsoft.com/office/2006/xmlPackage",Gc="http://schemas.openxmlformats.org/package/2006/relationships",Ng='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',Hc='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var Tg=`
13
+ <w:numbering xmlns:w="${Yc}">
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 Af=Object.create;var _s=Object.defineProperty;var Ef=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 Sd(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function ul(e,t=!0){let r=t?` xmlns:r="${bd}"`:"";return`<w:document xmlns:w="${cl}"${r}><w:body>${e}</w:body></w:document>`}function ll(e){return`
22
+ </w:numbering>`.trim();function Sg(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function Jc(e,t=!0){let r=t?` xmlns:r="${xg}"`:"";return`<w:document xmlns:w="${Yc}"${r}><w:body>${e}</w:body></w:document>`}function qc(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
- ${Sd(e)}
25
+ ${Sg(e)}
26
26
  </pkg:xmlData>
27
- </pkg:part>`}function fl(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
- <pkg:package xmlns:pkg="${Nd}">
27
+ </pkg:part>`}function Zc(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
+ <pkg:package xmlns:pkg="${Ig}">
29
29
  <pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
30
30
  <pkg:xmlData>
31
- <Relationships xmlns="${il}">
32
- ${Id}
31
+ <Relationships xmlns="${Gc}">
32
+ ${Ng}
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="${il}">
38
+ <Relationships xmlns="${Gc}">
39
39
  ${t}
40
40
  </Relationships>
41
41
  </pkg:xmlData>
@@ -45,9 +45,9 @@ var Af=Object.create;var _s=Object.defineProperty;var Ef=Object.getOwnPropertyDe
45
45
  ${e}
46
46
  </pkg:xmlData>
47
47
  </pkg:part>
48
- </pkg:package>`}function dl(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:o=!0}=t,a=o?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,i=ul(a,!0),s="",l="";return n?(s=sl,l+=ll(n)):r&&(s=sl,l+=ll(Td)),fl(i,s,l)}function ml(e){let t=ul(e,!0);return fl(t)}var Ad=/\s+xmlns:[^=]+="[^"]*"/g;function wt(e,t,r=[],n={}){let o=Ed(n),{generateRedlines:a}=o,i=[],s="",l=null,c=[];function u(){if(c.length>0||i.length===0){let f="";s?f=Er(s):l?(s=Er(Se(l)),f=s):t&&(typeof t=="string"?f=t:f=Se(t),f=Er(f)),i.push(`<w:p>${f}${c.join("")}</w:p>`),c=[]}}for(let f of e)switch(f.kind){case Z.PARAGRAPH_START:(c.length>0||i.length>0)&&u(),s=f.pPrXml||"",l=f.pPrElement||null;break;case Z.TEXT:c.push(pl(f,r,o));break;case Z.DELETION:a&&c.push(Rd(f,o));break;case Z.INSERTION:a?c.push(Pd(f,r,o)):c.push(pl(f,r,o));break;case Z.BOOKMARK:case Z.HYPERLINK:f.nodeXml&&c.push(Er(f.nodeXml));break;case Z.CONTAINER_START:if(f.containerKind==="sdt")c.push(`<w:sdt>${f.propertiesXml}<w:sdtContent>`);else if(f.containerKind==="smartTag")c.push(`<w:smartTag ${f.propertiesXml}>`);else if(f.containerKind==="hyperlink"){let d=JSON.parse(f.propertiesXml),m=d.rId?` r:id="${d.rId}"`:"",p=d.anchor?` w:anchor="${d.anchor}"`:"";c.push(`<w:hyperlink${m}${p}>`)}break;case Z.CONTAINER_END:f.containerKind==="sdt"?c.push("</w:sdtContent></w:sdt>"):f.containerKind==="smartTag"?c.push("</w:smartTag>"):f.containerKind==="hyperlink"&&c.push("</w:hyperlink>");break;default:St("Unknown run kind:",f.kind)}return u(),i.join("")}function Ed(e){if(typeof e=="string")return{author:re(),generateRedlines:!0,font:e,revisionIdAllocator:null};let t=e&&typeof e=="object"?e:{};return{author:typeof t.author=="string"&&t.author.trim()?t.author.trim():re(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function pl(e,t,r={}){let n=Xt(t,e.startOffset,e.endOffset),o=r?.font??null,a=e.rPrXml?Er(e.rPrXml):"";if(o&&(a=oi(a,o)),n.length===0)return fr(e.text,a);let i=[],s=0,l=e.text,c=e.startOffset;for(let u of n){let f=Math.max(0,u.start-c),d=Math.min(l.length,u.end-c);f>s&&i.push(fr(l.slice(s,f),a));let m=hl(a,u.format);i.push(fr(l.slice(f,d),m)),s=d}return s<l.length&&i.push(fr(l.slice(s),a)),i.join("")}function fr(e,t){return e?`<w:r>${t||""}${gl(e,"w:t")}</w:r>`:""}function gl(e,t){return String(e).split(/(\r\n|[\n\r\v\t])/).map(r=>r===" "?"<w:tab/>":r===`
48
+ </pkg:package>`}function Qc(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:o=!0}=t,a=o?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,i=Jc(a,!0),l="",s="";return n?(l=Hc,s+=qc(n)):r&&(l=Hc,s+=qc(Tg)),Zc(i,l,s)}function eu(e){let t=Jc(e,!0);return Zc(t)}var Ag=/\s+xmlns:[^=]+="[^"]*"/g;function ct(e,t,r=[],n={}){let o=Eg(n),{generateRedlines:a}=o,i=[],l="",s=null,c=[];function f(){if(c.length>0||i.length===0){let u="";l?u=Jr(l):s?(l=Jr(Be(s)),u=l):t&&(typeof t=="string"?u=t:u=Be(t),u=Jr(u)),i.push(`<w:p>${u}${c.join("")}</w:p>`),c=[]}}for(let u of e)switch(u.kind){case H.PARAGRAPH_START:(c.length>0||i.length>0)&&f(),l=u.pPrXml||"",s=u.pPrElement||null;break;case H.TEXT:c.push(tu(u,r,o));break;case H.DELETION:a&&c.push(Rg(u,o));break;case H.INSERTION:a?c.push(Pg(u,r,o)):c.push(tu(u,r,o));break;case H.BOOKMARK:case H.HYPERLINK:u.nodeXml&&c.push(Jr(u.nodeXml));break;case H.CONTAINER_START:if(u.containerKind==="sdt")c.push(`<w:sdt>${u.propertiesXml}<w:sdtContent>`);else if(u.containerKind==="smartTag")c.push(`<w:smartTag ${u.propertiesXml}>`);else if(u.containerKind==="hyperlink"){let d=JSON.parse(u.propertiesXml),m=d.rId?` r:id="${d.rId}"`:"",p=d.anchor?` w:anchor="${d.anchor}"`:"";c.push(`<w:hyperlink${m}${p}>`)}break;case H.CONTAINER_END:u.containerKind==="sdt"?c.push("</w:sdtContent></w:sdt>"):u.containerKind==="smartTag"?c.push("</w:smartTag>"):u.containerKind==="hyperlink"&&c.push("</w:hyperlink>");break;default:ir("Unknown run kind:",u.kind)}return f(),i.join("")}function Eg(e){if(typeof e=="string")return{author:ae(),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():ae(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function tu(e,t,r={}){let n=sr(t,e.startOffset,e.endOffset),o=r?.font??null,a=e.rPrXml?Jr(e.rPrXml):"";if(o&&(a=ss(a,o)),n.length===0)return Or(e.text,a);let i=[],l=0,s=e.text,c=e.startOffset;for(let f of n){let u=Math.max(0,f.start-c),d=Math.min(s.length,f.end-c);u>l&&i.push(Or(s.slice(l,u),a));let m=nu(a,f.format);i.push(Or(s.slice(u,d),m)),l=d}return l<s.length&&i.push(Or(s.slice(l),a)),i.join("")}function Or(e,t){return e?`<w:r>${t||""}${ru(e,"w:t")}</w:r>`:""}function ru(e,t){return String(e).split(/(\r\n|[\n\r\v\t])/).map(r=>r===" "?"<w:tab/>":r===`
49
49
  `||r==="\r"||r===`\r
50
- `||r==="\v"?"<w:br/>":r?`<${t} xml:space="preserve">${je(r)}</${t}>`:"").join("")}function Rd(e,t={}){let r=ie(t.author??re(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?Er(e.rPrXml):"";return n&&(o=oi(o,n)),`<w:del w:id="${r.id}" w:author="${je(r.author)}" w:date="${r.date}"><w:r>${o}${gl(e.text,"w:delText")}</w:r></w:del>`}function Pd(e,t,r={}){let n=ie(r.author??re(),r.revisionIdAllocator,"ins"),o=r.font??null,a=Xt(t,e.startOffset,e.endOffset),i="",s=e.rPrXml?Er(e.rPrXml):"";if(o&&(s=oi(s,o)),a.length===0)i=fr(e.text,s);else{let l=0,c=e.text,u=e.startOffset;for(let f of a){let d=Math.max(0,f.start-u),m=Math.min(c.length,f.end-u);d>l&&(i+=fr(c.slice(l,d),s));let p=hl(s,f.format);i+=fr(c.slice(d,m),p),l=m}l<c.length&&(i+=fr(c.slice(l),s))}return`<w:ins w:id="${n.id}" w:author="${je(n.author)}" w:date="${n.date}">`+i+"</w:ins>"}function oi(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 hl(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 dr(e,t={}){let r=Cd(t);return dl(e,r)}function Cd(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function Er(e){return e?e.replace(Ad,""):""}function ai(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var jt=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){ai(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||de.BULLET;if(r&&ai(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let a=this.contextMap.get(n);if(ai(a))return a;this.contextMap.delete(n)}if(n===de.OUTLINE)return"3";if(n===de.DECIMAL)return"2";if(n===de.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==de.DECIMAL&&n!==de.BULLET){let a=`custom_${n}`;if(this.contextMap.has(a))return this.contextMap.get(a);let i=String(this.nextNumId++);return this.customConfigs.push({numId:i,levels:[{format:n,suffix:t.suffix||Fe.PERIOD}]}),this.contextMap.set(a,i),i}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:de.BULLET,suffix:Fe.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:de.BULLET,suffix:Fe.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:de.OUTLINE,suffix:Fe.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:de.LOWER_ALPHA,suffix:Fe.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?de.LOWER_ROMAN:de.UPPER_ROMAN,suffix:Fe.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:de.DECIMAL,suffix:Fe.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:de.DECIMAL,suffix:Fe.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:de.LOWER_ALPHA,suffix:Fe.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:de.UPPER_ALPHA,suffix:Fe.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?de.LOWER_ROMAN:de.UPPER_ROMAN,suffix:Fe.PERIOD,depth:0}:/^\d+/.test(r)?{format:de.DECIMAL,suffix:Fe.PERIOD,depth:0}:{format:de.BULLET,suffix:Fe.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[de.DECIMAL]:"decimal",[de.LOWER_ALPHA]:"lowerLetter",[de.UPPER_ALPHA]:"upperLetter",[de.LOWER_ROMAN]:"lowerRoman",[de.UPPER_ROMAN]:"upperRoman",[de.BULLET]:"bullet",[de.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===de.BULLET)return"\u2022";let o=`%${n+1}`;if(t===de.OUTLINE)return Array(n+1).fill(0).map((a,i)=>`%${i+1}`).join(".")+".";switch(r){case Fe.PERIOD:return`${o}.`;case Fe.PAREN_RIGHT:return`${o})`;case Fe.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
50
+ `||r==="\v"?"<w:br/>":r?`<${t} xml:space="preserve">${Qe(r)}</${t}>`:"").join("")}function Rg(e,t={}){let r=ue(t.author??ae(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?Jr(e.rPrXml):"";return n&&(o=ss(o,n)),`<w:del w:id="${r.id}" w:author="${Qe(r.author)}" w:date="${r.date}"><w:r>${o}${ru(e.text,"w:delText")}</w:r></w:del>`}function Pg(e,t,r={}){let n=ue(r.author??ae(),r.revisionIdAllocator,"ins"),o=r.font??null,a=sr(t,e.startOffset,e.endOffset),i="",l=e.rPrXml?Jr(e.rPrXml):"";if(o&&(l=ss(l,o)),a.length===0)i=Or(e.text,l);else{let s=0,c=e.text,f=e.startOffset;for(let u of a){let d=Math.max(0,u.start-f),m=Math.min(c.length,u.end-f);d>s&&(i+=Or(c.slice(s,d),l));let p=nu(l,u.format);i+=Or(c.slice(d,m),p),s=m}s<c.length&&(i+=Or(c.slice(s),l))}return`<w:ins w:id="${n.id}" w:author="${Qe(n.author)}" w:date="${n.date}">`+i+"</w:ins>"}function ss(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 nu(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 kr(e,t={}){let r=Cg(t);return Qc(e,r)}function Cg(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function Jr(e){return e?e.replace(Ag,""):""}function ls(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var ur=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){ls(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||ve.BULLET;if(r&&ls(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let a=this.contextMap.get(n);if(ls(a))return a;this.contextMap.delete(n)}if(n===ve.OUTLINE)return"3";if(n===ve.DECIMAL)return"2";if(n===ve.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==ve.DECIMAL&&n!==ve.BULLET){let a=`custom_${n}`;if(this.contextMap.has(a))return this.contextMap.get(a);let i=String(this.nextNumId++);return this.customConfigs.push({numId:i,levels:[{format:n,suffix:t.suffix||Ze.PERIOD}]}),this.contextMap.set(a,i),i}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:ve.BULLET,suffix:Ze.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:ve.BULLET,suffix:Ze.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:ve.OUTLINE,suffix:Ze.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:ve.LOWER_ALPHA,suffix:Ze.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?ve.LOWER_ROMAN:ve.UPPER_ROMAN,suffix:Ze.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:ve.DECIMAL,suffix:Ze.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:ve.DECIMAL,suffix:Ze.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:ve.LOWER_ALPHA,suffix:Ze.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:ve.UPPER_ALPHA,suffix:Ze.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?ve.LOWER_ROMAN:ve.UPPER_ROMAN,suffix:Ze.PERIOD,depth:0}:/^\d+/.test(r)?{format:ve.DECIMAL,suffix:Ze.PERIOD,depth:0}:{format:ve.BULLET,suffix:Ze.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[ve.DECIMAL]:"decimal",[ve.LOWER_ALPHA]:"lowerLetter",[ve.UPPER_ALPHA]:"upperLetter",[ve.LOWER_ROMAN]:"lowerRoman",[ve.UPPER_ROMAN]:"upperRoman",[ve.BULLET]:"bullet",[ve.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===ve.BULLET)return"\u2022";let o=`%${n+1}`;if(t===ve.OUTLINE)return Array(n+1).fill(0).map((a,i)=>`%${i+1}`).join(".")+".";switch(r){case Ze.PERIOD:return`${o}.`;case Ze.PAREN_RIGHT:return`${o})`;case Ze.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
51
51
  <w:pPr>${n.includeListParagraphStyle===!0?`
52
52
  <w:pStyle w:val="ListParagraph"/>`:""}
53
53
  <w:numPr>
@@ -58,13 +58,13 @@ var Af=Object.create;var _s=Object.defineProperty;var Ef=Object.getOwnPropertyDe
58
58
  `}generateNumberingXml(t=[]){let r=[...this.customConfigs,...t],n=`
59
59
  <w:abstractNum w:abstractNumId="0">
60
60
  <w:multiLevelType w:val="hybridMultilevel"/>
61
- ${[0,1,2,3,4,5,6,7,8].map(l=>`
62
- <w:lvl w:ilvl="${l}">
61
+ ${[0,1,2,3,4,5,6,7,8].map(s=>`
62
+ <w:lvl w:ilvl="${s}">
63
63
  <w:start w:val="1"/>
64
- <w:numFmt w:val="${l%3===0?"bullet":l%3===1?"circle":"square"}"/>
65
- <w:lvlText w:val="${l%3===0?"\u2022":l%3===1?"\u25CB":"\u25A0"}"/>
64
+ <w:numFmt w:val="${s%3===0?"bullet":s%3===1?"circle":"square"}"/>
65
+ <w:lvlText w:val="${s%3===0?"\u2022":s%3===1?"\u25CB":"\u25A0"}"/>
66
66
  <w:lvlJc w:val="left"/>
67
- <w:pPr><w:ind w:left="${720*(l+1)}" w:hanging="360"/></w:pPr>
67
+ <w:pPr><w:ind w:left="${720*(s+1)}" w:hanging="360"/></w:pPr>
68
68
  </w:lvl>`).join("")}
69
69
  </w:abstractNum>`,o=`
70
70
  <w:abstractNum w:abstractNumId="1">
@@ -82,20 +82,20 @@ var Af=Object.create;var _s=Object.defineProperty;var Ef=Object.getOwnPropertyDe
82
82
  <w:lvl w:ilvl="2"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2160" w:hanging="360"/></w:pPr></w:lvl>
83
83
  <w:lvl w:ilvl="3"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3.%4"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2880" w:hanging="360"/></w:pPr></w:lvl>
84
84
  <w:lvl w:ilvl="4"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3.%4.%5"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="3600" w:hanging="360"/></w:pPr></w:lvl>
85
- </w:abstractNum>`,i="",s="";return r.forEach((l,c)=>{let u=10+c;i+=`
86
- <w:abstractNum w:abstractNumId="${u}">
85
+ </w:abstractNum>`,i="",l="";return r.forEach((s,c)=>{let f=10+c;i+=`
86
+ <w:abstractNum w:abstractNumId="${f}">
87
87
  <w:multiLevelType w:val="multilevel"/>
88
- ${l.levels.map((f,d)=>`
88
+ ${s.levels.map((u,d)=>`
89
89
  <w:lvl w:ilvl="${d}">
90
90
  <w:start w:val="1"/>
91
- <w:numFmt w:val="${this.formatToOoxmlNumFmt(f.format)}"/>
92
- <w:lvlText w:val="${this.suffixToOoxmlLevelText(f.format,f.suffix,d)}"/>
91
+ <w:numFmt w:val="${this.formatToOoxmlNumFmt(u.format)}"/>
92
+ <w:lvlText w:val="${this.suffixToOoxmlLevelText(u.format,u.suffix,d)}"/>
93
93
  <w:lvlJc w:val="left"/>
94
94
  <w:pPr><w:ind w:left="${720*(d+1)}" w:hanging="360"/></w:pPr>
95
95
  </w:lvl>`).join("")}
96
- </w:abstractNum>`,s+=`
97
- <w:num w:numId="${l.numId}">
98
- <w:abstractNumId w:val="${u}"/>
96
+ </w:abstractNum>`,l+=`
97
+ <w:num w:numId="${s.numId}">
98
+ <w:abstractNumId w:val="${f}"/>
99
99
  </w:num>`}),`
100
100
  <w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
101
101
  ${n}
@@ -111,8 +111,8 @@ var Af=Object.create;var _s=Object.defineProperty;var Ef=Object.getOwnPropertyDe
111
111
  <w:num w:numId="3">
112
112
  <w:abstractNumId w:val="2"/>
113
113
  </w:num>
114
- ${s}
115
- </w:numbering>`}};function Kt(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:o=null,trackAsBlock:a=!1}=t,i=r&&a,s=e.headers?.length||e.rows?.[0]?.length||1,l=`
114
+ ${l}
115
+ </w:numbering>`}};function $(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===B&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function F(e,t){return typeof e.createElementNS=="function"?e.createElementNS(B,t):e.createElement(t)}function cs(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(B,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>$(n,t))}var us=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function fr(e){return us.some(t=>cs(e,t).length>0)}function Mr(e){if(!e)return[];let t=new Set;for(let r of us)for(let n of cs(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(B,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function _g(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 Ce(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:_g(e.oxml)}}function dr(e){if(!e)return!1;for(let t of us)for(let r of cs(e,t)){let n=r.getAttribute?.("w:author")||r.getAttribute?.("author")||(typeof r.getAttributeNS=="function"?r.getAttributeNS(B,"author"):null);if(!n||!String(n).trim())return!0}return!1}function Lr(e,t,r){if(e!=="auto")return e;let n=(Array.isArray(t)?t:[t]).filter(Boolean),o=String(r||"").trim().toLowerCase();return n.some(i=>fr(i)&&(dr(i)||Mr(i).some(l=>l.trim().toLowerCase()!==o)))?"slice-cross-author":"merge-same-author"}function ou(e){return!e||e.nodeType!==1?"":e.localName||String(e.nodeName||"").replace(/^.*:/,"")}function jn(e,t){for(let r of Array.from(e?.childNodes||[]))if(r.nodeType===1&&ou(r)===t)return r;return null}function au(e){if(e==="ins"||e==="del")return e;throw new Error(`Unsupported paragraph-mark revision kind: ${e}`)}function iu(e,t,r){let n=t||{};if(n.metadata)return n.metadata;let o=n.revisionIdAllocator||(r?.nodeType===9?r:r?.ownerDocument)||null,a=ue(n.author,o,e);return n.date&&(a.date=n.date),a}function Og(e,t,r){let n=F(e,t==="ins"?"w:ins":"w:del");return n.setAttribute("w:id",String(r.id)),n.setAttribute("w:author",r.author),n.setAttribute("w:date",r.date),n}function kg(e){for(let t of Array.from(e.childNodes||[])){let r=ou(t);(r==="ins"||r==="del")&&e.removeChild(t)}}function su(e,t){let r=jn(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=F(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function Mg(e,t){let r=jn(t,"rPr");if(!r){r=F(e,"w:rPr");let n=jn(t,"sectPr")||jn(t,"pPrChange");t.insertBefore(r,n||null)}return r}function fs(e,t,r={}){let n=au(t),o=e.ownerDocument,a=iu(n,r,e),i=Mg(o,e);kg(i);let l=Og(o,n,a);return i.appendChild(l),l}function lu(e,t,r){let n=e.ownerDocument,o=su(n,e);return fs(o,t,{...r,revisionIdAllocator:r?.revisionIdAllocator||n})}function Zr(e,t={}){return lu(e,"ins",t)}function Qr(e,t={}){return lu(e,"del",t)}function cu(e,t){let r=e.ownerDocument,n=su(r,e),o=jn(n,"rPr")||(()=>{let i=F(r,"w:rPr");return n.appendChild(i),i})();if(jn(o,"ins"))return null;let a=F(r,"w:ins");return t.id&&a.setAttribute("w:id",String(t.id)),a.setAttribute("w:author",t.author),t.date&&a.setAttribute("w:date",t.date),o.appendChild(a),a}function Lg(e,t={}){let r=au(e),n=iu(r,t,null);return`<w:${r} w:id="${n.id}" w:author="${Qe(n.author)}" w:date="${n.date}"/>`}function ds(e,t={}){return`<w:pPr><w:rPr>${Lg(e,t)}</w:rPr></w:pPr>`}function mr(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:o=null,trackAsBlock:a=!1}=t,i=r&&a,l=e.headers?.length||e.rows?.[0]?.length||1,s=`
116
116
  <w:tblPr>
117
117
  <w:tblW w:w="5000" w:type="pct"/>
118
118
  <w:tblBorders>
@@ -125,61 +125,62 @@ var Af=Object.create;var _s=Object.defineProperty;var Ef=Object.getOwnPropertyDe
125
125
  </w:tblBorders>
126
126
  <w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
127
127
  </w:tblPr>
128
- `.trim(),u=`<w:tblGrid>${Array(s).fill("<w:gridCol/>").join("")}</w:tblGrid>`,f=e.hasHeader?[e.headers,...e.rows]:e.rows,d="";for(let m=0;m<f.length;m++){let p=e.hasHeader&&m===0,g=f[m]||[],h="";for(let b=0;b<s;b++){let x=g[b]||"",{cleanText:T,formatHints:I}=We(x),N=[{kind:r?Z.INSERTION:Z.TEXT,text:T,rPrXml:p?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:T.length}],A=i?ie(n,o):null,S=A?`<w:pPr><w:rPr><w:ins w:id="${A.id}" w:author="${je(A.author)}" w:date="${A.date}"/></w:rPr></w:pPr>`:null,O=wt(N,S,I,{author:n,generateRedlines:r,revisionIdAllocator:o});h+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${O}</w:tc>`}let y=p?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>",w=i?ie(n,o):null,v=w?y.replace("</w:trPr>",`<w:ins w:id="${w.id}" w:author="${je(w.author)}" w:date="${w.date}"/></w:trPr>`):y;d+=`<w:tr>${v}${h}</w:tr>`}return`<w:tbl>${l}${u}${d}</w:tbl>`}function wl(e,t){let r=[],{headers:n,rows:o,hasHeader:a}=t,i=a?[n,...o]:o,s=Math.max(e.rowCount,i.length);for(let l=0;l<s;l++){if(l>=e.rowCount&&i[l]){r.push({type:"row_insert",gridRow:l,cells:i[l]});continue}if(l<e.rowCount&&!i[l]){r.push({type:"row_delete",gridRow:l});continue}let c=i[l];for(let u=0;u<e.colCount;u++){let f=e.grid[l]?.[u],d=c?.[u];f&&(f.isMergeContinuation||u>f.gridCol||d!==void 0&&f.getText()!==d&&r.push({type:"cell_modify",gridRow:l,gridCol:u,originalCell:f,newText:d}))}}return r}function yl(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,i=Od(t),s="";for(let c=0;c<e.rowCount;c++){let u=i.rowDeleteByRow.get(c)||null;if(u&&!n)continue;let f="",d=0;for(;d<e.colCount;){let p=e.grid[c][d];if(!p){d++;continue}if(p.isMergeContinuation){d++;continue}let g=i.cellModifyByCoordinate.get(`${c}:${d}`)||null,h;g?h=_d(p,g.newText,r):h=kd(p.blocks),f+=Md(p,h,r),d+=p.colSpan}let m=e.trPrList[c]||"<w:trPr/>";if(u&&n){let p=ie(o,a),g=`<w:del w:id="${p.id}" w:author="${je(p.author)}" w:date="${p.date}"/>`;m.includes("</w:trPr>")?m=m.replace("</w:trPr>",`${g}</w:trPr>`):m=`<w:trPr>${g}</w:trPr>`}s+=`<w:tr>${m}${f}</w:tr>`}let l=i.rowInsertOperations;for(let c of l){let u="",f=n?ie(o,a):null;for(let m of c.cells){let{cleanText:p,formatHints:g}=We(m),h=[{kind:n?Z.INSERTION:Z.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],y=wt(h,null,g,{author:o,generateRedlines:n,revisionIdAllocator:a});u+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${y}</w:tc>`}let d="<w:trPr/>";n&&(d=`<w:trPr><w:ins w:id="${f.id}" w:author="${je(f.author)}" w:date="${f.date}"/></w:trPr>`),s+=`<w:tr>${d}${u}</w:tr>`}return`
128
+ `.trim(),f=`<w:tblGrid>${Array(l).fill("<w:gridCol/>").join("")}</w:tblGrid>`,u=e.hasHeader?[e.headers,...e.rows]:e.rows,d="";for(let m=0;m<u.length;m++){let p=e.hasHeader&&m===0,g=u[m]||[],h="";for(let b=0;b<l;b++){let x=g[b]||"",{cleanText:S,formatHints:A}=qe(x),E=[{kind:r?H.INSERTION:H.TEXT,text:S,rPrXml:p?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:S.length}],I=i?ds("ins",{author:n,revisionIdAllocator:o}):null,R=ct(E,I,A,{author:n,generateRedlines:r,revisionIdAllocator:o});h+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${R}</w:tc>`}let v=p?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>",w=i?ue(n,o):null,y=w?v.replace("</w:trPr>",`<w:ins w:id="${w.id}" w:author="${Qe(w.author)}" w:date="${w.date}"/></w:trPr>`):v;d+=`<w:tr>${y}${h}</w:tr>`}return`<w:tbl>${s}${f}${d}</w:tbl>`}function fu(e,t){let r=[],{headers:n,rows:o,hasHeader:a}=t,i=a?[n,...o]:o,l=Math.max(e.rowCount,i.length);for(let s=0;s<l;s++){if(s>=e.rowCount&&i[s]){r.push({type:"row_insert",gridRow:s,cells:i[s]});continue}if(s<e.rowCount&&!i[s]){r.push({type:"row_delete",gridRow:s});continue}let c=i[s];for(let f=0;f<e.colCount;f++){let u=e.grid[s]?.[f],d=c?.[f];u&&(u.isMergeContinuation||f>u.gridCol||d!==void 0&&uu(u.getText())!==uu(d)&&r.push({type:"cell_modify",gridRow:s,gridCol:f,originalCell:u,newText:d}))}}return r}function du(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,i=Bg(t),l="";for(let c=0;c<e.rowCount;c++){let f=i.rowDeleteByRow.get(c)||null;if(f&&!n)continue;let u="",d=0;for(;d<e.colCount;){let p=e.grid[c][d];if(!p){d++;continue}if(p.isMergeContinuation){d++;continue}let g=i.cellModifyByCoordinate.get(`${c}:${d}`)||null,h;g?h=$g(p,g.newText,r):h=Dg(p.blocks),u+=Ug(p,h,r),d+=p.colSpan}let m=e.trPrList[c]||"<w:trPr/>";if(f&&n){let p=ue(o,a),g=`<w:del w:id="${p.id}" w:author="${Qe(p.author)}" w:date="${p.date}"/>`;m.includes("</w:trPr>")?m=m.replace("</w:trPr>",`${g}</w:trPr>`):m=`<w:trPr>${g}</w:trPr>`}l+=`<w:tr>${m}${u}</w:tr>`}let s=i.rowInsertOperations;for(let c of s){let f="",u=n?ue(o,a):null;for(let m of c.cells){let{cleanText:p,formatHints:g}=qe(m),h=[{kind:n?H.INSERTION:H.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],v=ct(h,null,g,{author:o,generateRedlines:n,revisionIdAllocator:a});f+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${v}</w:tc>`}let d="<w:trPr/>";n&&(d=`<w:trPr><w:ins w:id="${u.id}" w:author="${Qe(u.author)}" w:date="${u.date}"/></w:trPr>`),l+=`<w:tr>${d}${f}</w:tr>`}return`
129
129
  <w:tbl>
130
130
  ${e.tblPrXml}
131
131
  ${e.tblGridXml}
132
- ${s}
132
+ ${l}
133
133
  </w:tbl>
134
- `}function Od(e){let t=new Map,r=new Map,n=[];for(let o of e)o.type==="row_delete"?t.set(o.gridRow,o):o.type==="cell_modify"?r.set(`${o.gridRow}:${o.gridCol}`,o):o.type==="row_insert"&&n.push(o);return n.sort((o,a)=>o.gridRow-a.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function _d(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,{cleanText:i,formatHints:s}=We(t),l=e.getText(),c=_o(l,i),u=e.blocks[0]||{runModel:[],pPr:null},f=ko(u.runModel,c),d=Mo(f,c,{generateRedlines:n,author:o,formatHints:s});return wt(d,u.pPr,s,{author:o,generateRedlines:n,revisionIdAllocator:a})}function kd(e){return e.map(t=>wt(t.runModel,t.pPr,[],{})).join("")}function Md(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 rt(e){let t=e.split(`
135
- `).map(i=>i.trim()).filter(i=>i.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=i=>{let s=i.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(s)},n=t.some(r),a=t.filter(i=>!r(i)).map(i=>i.split("|").slice(1,-1).map(s=>s.trim()));return n?{headers:a[0]||[],rows:a.slice(1),hasHeader:!0}:{headers:[],rows:a,hasHeader:!1}}function F(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===B&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function D(e,t){return typeof e.createElementNS=="function"?e.createElementNS(B,t):e.createElement(t)}function vl(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(B,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>F(n,t))}var xl=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function mr(e){return xl.some(t=>vl(e,t).length>0)}function Rr(e){if(!e)return[];let t=new Set;for(let r of xl)for(let n of vl(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(B,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function Ld(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 Ne(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:Ld(e.oxml)}}async function sn(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:a=!0,author:i="AI",font:s=null,revisionIdAllocator:l=null,numberingService:c}=e,u=Dd(t),f=Bd(u),d=f.map(N=>N.raw),m=[],p=Ud(n),g=bl(n,p),h=bl(n,p,["rFonts","kern","position","rtl","cs","lang"]),y=[];if(a){if(n&&n.length>0)y=n.filter(N=>N.kind==="text"||N.kind==="run").map(N=>({...N,kind:"deletion",author:i}));else if(o&&o.trim().length>0){let N=o.trim();y=[{kind:"deletion",text:N,author:i,startOffset:0,endOffset:N.length}]}}let w=(n||[]).filter(N=>N.kind===Z.PARAGRAPH_START).length;if(a&&w>0&&(w>1||y.length===0)){let N=null,A=()=>{N&&(m.push(wt(N,null,[],{author:i,generateRedlines:a,revisionIdAllocator:l})),N=null)};for(let S of n)S.kind===Z.PARAGRAPH_START?(A(),N=[{...S,pPrElement:null,pPrXml:ii(S.pPrElement||S.pPrXml||null,"del",i,l)}]):N&&(S.kind==="text"||S.kind==="run")&&N.push({...S,kind:"deletion",author:i});A()}else if(a&&y.length>0){let N=ii(p,"del",i,l),A=wt(y,N,[],{author:i,generateRedlines:a,revisionIdAllocator:l});m.push(A)}let v=si(d);V(`[ListGen] Detected indentation step: ${v} spaces/chars`);let b=f.find(N=>N.marker)?.marker||"",{format:x}=c.detectNumberingFormat(b);V(`[ListGen] Detected primary marker: "${b}", format: ${x}`);for(let N=0;N<f.length;N++){let A=Fd(f,N);if(A){let E=rt(A.tableText);if(E.headers.length>0||E.rows.length>0){m.push(Kt(E,{generateRedlines:a,author:i,revisionIdAllocator:l,trackAsBlock:!0})),N=A.endIndex;continue}}let S=f[N],O=$d(S,v,r,c,a,i,s,l,g,h);m.push(O.ooxml)}let T=c.generateNumberingXml(),I=m.join("");return V(`[ListGen] \u2705 Generated OOXML for ${m.length} paragraphs, total length: ${I.length}`),V(`[ListGen] First 200 chars: ${I.substring(0,200)}...`),{ooxml:I,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:T}}function si(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 Bd(e){return e.split(`
136
- `).filter(t=>t.trim().length>0).map(t=>{let r=At(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 Dd(e){let t=String(e||"").split(`
137
- `),r=t.map((i,s)=>({line:i,index:s})).filter(i=>i.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:i,index:s}of r){let l=At(i);if(!l)return e;let c=_t(i),u=At(c);if(!u)return e;let f=(l[2]||"").trim(),d=(u[2]||"").trim();if(!f||!d||f===d)return e;let p=`${l[1]||""}${c.trimStart()}`;n.push({index:s,rewritten:p}),o++}if(o<2)return e;let a=t.slice();for(let i of n)a[i.index]=i.rewritten;return V(`[ListGen] Normalized ${o} composite list markers (e.g., "- A." -> "A.").`),a.join(`
138
- `)}function Fd(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let o=[],a=t;for(;a<e.length&&e[a].isTableLine;)o.push(e[a].raw),a++;return{tableText:o.join(`
139
- `),endIndex:a-1}}function $d(e,t,r,n,o,a,i,s,l,c){let u="",f="",d=l;if(e.headerMatch){let h=Math.min(e.headerMatch[1].length,9),y=Math.min(h-1,8),w=[32,28,26,24,22,20,20,20,20],v=w[h-1]||w[w.length-1];f=e.headerMatch[2].trim(),u=`<w:pPr><w:pStyle w:val="Heading${h}"/><w:outlineLvl w:val="${y}"/><w:rPr><w:b/><w:sz w:val="${v}"/><w:szCs w:val="${v}"/></w:rPr></w:pPr>`,d=zd(c,`<w:rPr><w:b/><w:sz w:val="${v}"/><w:szCs w:val="${v}"/></w:rPr>`)}else if(e.marker){let h=n.detectNumberingFormat(e.marker),y=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,v=h.format==="outline"?Math.min(8,h.depth):Math.min(8,y+w);f=_t(e.raw);let b=n.getOrCreateNumId({type:h.format},r);u=n.buildListPPr(b,v)}else f=e.raw;o&&(u=ii(u||"<w:pPr/>","ins",a,s));let{cleanText:m,formatHints:p}=We(f),g=[];return g.push({kind:o?"insertion":"run",text:m,rPrXml:d,author:a,startOffset:0,endOffset:m.length}),{ooxml:wt(g,u,p,{author:a,generateRedlines:o,font:i,revisionIdAllocator:s})}}function Ud(e){let t=(e||[]).find(r=>r.kind===Z.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function bl(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(a=>(a.kind===Z.TEXT||a.kind==="text")&&a.rPrXml).map(a=>a.rPrXml);t&&n.push(typeof t=="string"?t:Se(t));let o=[];for(let a of r){let i=null;for(let s of n)if(i=String(s||"").match(new RegExp(`<w:${a}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${a}>)`)),i)break;i&&o.push(i[0])}return o.length>0?`<w:rPr>${o.join("")}</w:rPr>`:""}function zd(...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 ii(e,t,r,n){let o=ie(r,n),a,i;if(e?.nodeType===1)a=e.cloneNode(!0),i=a.ownerDocument;else{let c=typeof e=="string"&&e.trim()?e:"<w:pPr/>",u=W(`<w:root xmlns:w="${B}">${c}</w:root>`);if(!u.doc)throw new Error(u.error?.message||"Could not parse paragraph properties for list revision");i=u.doc,a=Array.from(i.documentElement.childNodes||[]).find(f=>f.nodeType===1&&f.localName==="pPr")}if(!a||!i)throw new Error("List paragraph properties are unavailable");let s=Array.from(a.childNodes||[]).find(c=>c.nodeType===1&&c.localName==="rPr");s||(s=D(i,"w:rPr"),a.appendChild(s));let l=D(i,t==="del"?"w:del":"w:ins");return l.setAttribute("w:id",String(o.id)),l.setAttribute("w:author",o.author),l.setAttribute("w:date",o.date),s.appendChild(l),Se(a)}var Xd=new Set(["officeonline","officeweb","web"]);function Vd(e){return e?Xd.has(String(e).toLowerCase()):!1}function Wd(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function jd(){return new Promise(e=>setTimeout(e,0))}var Un=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 jt,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??ja(),this.isWebPlatform=t.isWebPlatform??Vd(this.platform),this.enableEventLoopYielding=t.enableEventLoopYielding??this.isWebPlatform,this.yieldRunThreshold=t.yieldRunThreshold??50,this.yieldCharThreshold=t.yieldCharThreshold??5e3,this.disableSemanticCleanupOverChars=t.disableSemanticCleanupOverChars??(this.isWebPlatform?8e3:Number.POSITIVE_INFINITY)}async execute(t,r,n={}){let o=[];try{let a=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:W(t,"application/xml");if(a.error||!a.doc)return{ooxml:t,isValid:!1,status:"error",error:a.error,warnings:a.warnings||[]};o.push(...a.warnings||[]);let i=a.doc,s=Ae(i,"*","p"),{runModel:l,acceptedText:c,pPr:u}=on(t,{xmlDoc:i}),f=s?Fn(s):null;V(`[Reconcile] Ingested ${l.length} runs, ${c.length} chars, numbering:`,f),await this.maybeYield(l.length,Math.max(c.length,r?.length||0));let{cleanText:d,formatHints:m}=We(r);V(`[Reconcile] Preprocessed: ${m.length} format hints`),await this.maybeYield(l.length,Math.max(c.length,d.length));let p=Ha(d),g=en(d),h=p||g;if(!p&&g&&V("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===d&&m.length===0&&!h)return V("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let y=Math.max(c.length,d.length)<this.disableSemanticCleanupOverChars,w=_o(c,d,{cleanupSemantic:y});y||V("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(l.length,Math.max(c.length,d.length));let v=l.filter(A=>A.kind===Z.PARAGRAPH_START).length,b=Ha(c)||en(c),x=h&&b&&v>1&&c!==d;if(V(`[Reconcile] isTargetList: ${h}, paragraphCount: ${v}`),x)V("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(h)return V("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),V(`[Reconcile] cleanText preview: ${d.substring(0,100)}...`),V(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(d,f,l);V(`[Reconcile] Computed ${w.length} diff operations`);let T=ko(l,w);V(`[Reconcile] Split into ${T.length} runs`);let I=Mo(T,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:m,numberingService:this.numberingService});V(`[Reconcile] Patched model has ${I.length} runs`),await this.maybeYield(I.length,Math.max(c.length,d.length));let N=wt(I,u,m,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let A=this.validateBasic(N);A.isValid||o.push(...A.errors)}return{ooxml:N,isValid:o.length===0,warnings:o}}catch(a){return Te("[Reconcile] Pipeline error:",a),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${a.message}`],error:a?.code?{code:a.code,message:a.message}:void 0}}}validateBasic(t){let r=[];try{let n=`<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${t}</root>`,o=W(n,"application/xml"),a=o.doc;if(o.error||!a)return r.push("Generated OOXML is not well-formed XML: "+(o.error?.message||"parse error")),{isValid:!1,errors:r};let i=Ee(a);i&&r.push("Generated OOXML is not well-formed XML: "+i.textContent.substring(0,100)),t.includes("<w:p")||r.push("Generated OOXML missing paragraph element")}catch(n){r.push(`Validation error: ${n.message}`)}return{isValid:r.length===0,errors:r}}shouldRunValidation(){return this.validateOutput?this.validationMode==="always"?!0:this.validationMode==="never"?!1:!(this.isWebPlatform&&Wd()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await jd())}wrapForInsertion(t,r={}){return dr(t,r)}async executeListGeneration(t,r,n,o=""){return sn({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 si(t)}executeTableGeneration(t){let r=rt(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:Kt(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var Nl=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function Il(e){return!e||e.trim().length===0}function Tl(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function Kd(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function li(e){return Il(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":Tl(e)?"table":At(e)?"list":"paragraph"}function Lo(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
134
+ `}function Bg(e){let t=new Map,r=new Map,n=[];for(let o of e)o.type==="row_delete"?t.set(o.gridRow,o):o.type==="cell_modify"?r.set(`${o.gridRow}:${o.gridCol}`,o):o.type==="row_insert"&&n.push(o);return n.sort((o,a)=>o.gridRow-a.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function uu(e){return typeof e=="string"?e.replace(/\n+$/,""):e}function Fg(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,i=String(t??"").split(`
135
+ `);for(;i.length>e.blocks.length&&i[i.length-1]==="";)i.pop();let l="";e.blocks.forEach((s,c)=>{let f=i[c];if(f===void 0||f===s.acceptedText){if(f===void 0&&s.acceptedText!==""){let g=zn(s.acceptedText,""),h=Vn(Xn(s.runModel,g),g,{generateRedlines:n,author:o,formatHints:[]});l+=ct(h,s.pPr,[],{author:o,generateRedlines:n,revisionIdAllocator:a})}else l+=ct(s.runModel,s.pPr,[],{});return}let{cleanText:u,formatHints:d}=qe(f),m=zn(s.acceptedText,u),p=Vn(Xn(s.runModel,m),m,{generateRedlines:n,author:o,formatHints:d});l+=ct(p,s.pPr,d,{author:o,generateRedlines:n,revisionIdAllocator:a})});for(let s=e.blocks.length;s<i.length;s++){let{cleanText:c,formatHints:f}=qe(i[s]),u=[{kind:n?H.INSERTION:H.TEXT,text:c,rPrXml:"",author:o,startOffset:0,endOffset:c.length}],d=n?ds("ins",{author:o,revisionIdAllocator:a}):null;l+=ct(u,d,f,{author:o,generateRedlines:n,revisionIdAllocator:a})}return l}function $g(e,t,r){if(e.blocks.length>1)return Fg(e,t,r);let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,{cleanText:i,formatHints:l}=qe(t),s=e.getText(),c=zn(s,i),f=e.blocks[0]||{runModel:[],pPr:null},u=Xn(f.runModel,c),d=Vn(u,c,{generateRedlines:n,author:o,formatHints:l});return ct(d,f.pPr,l,{author:o,generateRedlines:n,revisionIdAllocator:a})}function Dg(e){return e.map(t=>ct(t.runModel,t.pPr,[],{})).join("")}function Ug(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 bt(e){let t=e.split(`
136
+ `).map(i=>i.trim()).filter(i=>i.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=i=>{let l=i.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(l)},n=t.some(r),a=t.filter(i=>!r(i)).map(i=>i.split("|").slice(1,-1).map(l=>l.trim()));return n?{headers:a[0]||[],rows:a.slice(1),hasHeader:!0}:{headers:[],rows:a,hasHeader:!1}}async function Wn(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:a=!0,author:i="AI",font:l=null,revisionIdAllocator:s=null,numberingService:c}=e,f=Xg(t),u=zg(f),d=u.map(E=>E.raw),m=[],p=Wg(n),g=mu(n,p),h=mu(n,p,["rFonts","kern","position","rtl","cs","lang"]),v=[];if(a){if(n&&n.length>0)v=n.filter(E=>E.kind==="text"||E.kind==="run"||E.kind===H.CONTAINER_START||E.kind===H.CONTAINER_END).map(E=>E.kind===H.CONTAINER_START||E.kind===H.CONTAINER_END?E:{...E,kind:"deletion",author:i});else if(o&&o.trim().length>0){let E=o.trim();v=[{kind:"deletion",text:E,author:i,startOffset:0,endOffset:E.length}]}}let w=(n||[]).filter(E=>E.kind===H.PARAGRAPH_START).length;if(a&&w>0&&(w>1||v.length===0)){let E=null,I=()=>{E&&(m.push(ct(E,null,[],{author:i,generateRedlines:a,revisionIdAllocator:s})),E=null)};for(let R of n)R.kind===H.PARAGRAPH_START?(I(),E=[{...R,pPrElement:null,pPrXml:ms(R.pPrElement||R.pPrXml||null,"del",i,s)}]):E&&(R.kind==="text"||R.kind==="run")?E.push({...R,kind:"deletion",author:i}):E&&(R.kind===H.CONTAINER_START||R.kind===H.CONTAINER_END)&&E.push(R);I()}else if(a&&v.length>0){let E=ms(p,"del",i,s),I=ct(v,E,[],{author:i,generateRedlines:a,revisionIdAllocator:s});m.push(I)}let y=ps(d);W(`[ListGen] Detected indentation step: ${y} spaces/chars`);let b=u.find(E=>E.marker)?.marker||"",{format:x}=c.detectNumberingFormat(b);W(`[ListGen] Detected primary marker: "${b}", format: ${x}`);for(let E=0;E<u.length;E++){let I=Vg(u,E);if(I){let N=bt(I.tableText);if(N.headers.length>0||N.rows.length>0){m.push(mr(N,{generateRedlines:a,author:i,revisionIdAllocator:s,trackAsBlock:!0})),E=I.endIndex;continue}}let R=u[E],T=jg(R,y,r,c,a,i,l,s,g,h);m.push(T.ooxml)}let S=c.generateNumberingXml(),A=m.join("");return W(`[ListGen] \u2705 Generated OOXML for ${m.length} paragraphs, total length: ${A.length}`),W(`[ListGen] First 200 chars: ${A.substring(0,200)}...`),{ooxml:A,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:S}}function ps(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 zg(e){return e.split(`
137
+ `).filter(t=>t.trim().length>0).map(t=>{let r=Xt(t),n=t.match(/^\s*(#{1,9})\s+(.*)/);return{raw:t,marker:r?r[2].trim():"",headerMatch:n,indentSize:t.match(/^(\s*)/)?.[1].length||0,isTableLine:/^\s*\|/.test(t),isTableSeparator:/^\s*\|?[\s:-]*-[-\s|:]*\|?\s*$/.test(t)}})}function Xg(e){let t=String(e||"").split(`
138
+ `),r=t.map((i,l)=>({line:i,index:l})).filter(i=>i.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:i,index:l}of r){let s=Xt(i);if(!s)return e;let c=Zt(i),f=Xt(c);if(!f)return e;let u=(s[2]||"").trim(),d=(f[2]||"").trim();if(!u||!d||u===d)return e;let p=`${s[1]||""}${c.trimStart()}`;n.push({index:l,rewritten:p}),o++}if(o<2)return e;let a=t.slice();for(let i of n)a[i.index]=i.rewritten;return W(`[ListGen] Normalized ${o} composite list markers (e.g., "- A." -> "A.").`),a.join(`
139
+ `)}function Vg(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let o=[],a=t;for(;a<e.length&&e[a].isTableLine;)o.push(e[a].raw),a++;return{tableText:o.join(`
140
+ `),endIndex:a-1}}function jg(e,t,r,n,o,a,i,l,s,c){let f="",u="",d=s;if(e.headerMatch){let h=Math.min(e.headerMatch[1].length,9),v=Math.min(h-1,8),w=[32,28,26,24,22,20,20,20,20],y=w[h-1]||w[w.length-1];u=e.headerMatch[2].trim(),f=`<w:pPr><w:pStyle w:val="Heading${h}"/><w:outlineLvl w:val="${v}"/><w:rPr><w:b/><w:sz w:val="${y}"/><w:szCs w:val="${y}"/></w:rPr></w:pPr>`,d=Kg(c,`<w:rPr><w:b/><w:sz w:val="${y}"/><w:szCs w:val="${y}"/></w:rPr>`)}else if(e.marker){let h=n.detectNumberingFormat(e.marker),v=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,y=h.format==="outline"?Math.min(8,h.depth):Math.min(8,v+w);u=Zt(e.raw);let b=n.getOrCreateNumId({type:h.format},r);f=n.buildListPPr(b,y)}else u=e.raw;o&&(f=ms(f||"<w:pPr/>","ins",a,l));let{cleanText:m,formatHints:p}=qe(u),g=[];return g.push({kind:o?"insertion":"run",text:m,rPrXml:d,author:a,startOffset:0,endOffset:m.length}),{ooxml:ct(g,f,p,{author:a,generateRedlines:o,font:i,revisionIdAllocator:l})}}function Wg(e){let t=(e||[]).find(r=>r.kind===H.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function mu(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(a=>(a.kind===H.TEXT||a.kind==="text")&&a.rPrXml).map(a=>a.rPrXml);t&&n.push(typeof t=="string"?t:Be(t));let o=[];for(let a of r){let i=null;for(let l of n)if(i=String(l||"").match(new RegExp(`<w:${a}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${a}>)`)),i)break;i&&o.push(i[0])}return o.length>0?`<w:rPr>${o.join("")}</w:rPr>`:""}function Kg(...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 ms(e,t,r,n){let o,a;if(e?.nodeType===1)o=e.cloneNode(!0),a=o.ownerDocument;else{let i=typeof e=="string"&&e.trim()?e:"<w:pPr/>",l=j(`<w:root xmlns:w="${B}">${i}</w:root>`);if(!l.doc)throw new Error(l.error?.message||"Could not parse paragraph properties for list revision");a=l.doc,o=Array.from(a.documentElement.childNodes||[]).find(s=>s.nodeType===1&&s.localName==="pPr")}if(!o||!a)throw new Error("List paragraph properties are unavailable");return fs(o,t==="del"?"del":"ins",{author:r,revisionIdAllocator:n}),Be(o)}var Gg=new Set(["officeonline","officeweb","web"]);function Hg(e){return e?Gg.has(String(e).toLowerCase()):!1}function qg(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function Yg(){return new Promise(e=>setTimeout(e,0))}var _o=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 ur,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??Wi(),this.isWebPlatform=t.isWebPlatform??Hg(this.platform),this.enableEventLoopYielding=t.enableEventLoopYielding??this.isWebPlatform,this.yieldRunThreshold=t.yieldRunThreshold??50,this.yieldCharThreshold=t.yieldCharThreshold??5e3,this.disableSemanticCleanupOverChars=t.disableSemanticCleanupOverChars??(this.isWebPlatform?8e3:Number.POSITIVE_INFINITY)}async execute(t,r,n={}){let o=[];try{let a=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:j(t,"application/xml");if(a.error||!a.doc)return{ooxml:t,isValid:!1,status:"error",error:a.error,warnings:a.warnings||[]};o.push(...a.warnings||[]);let i=a.doc,l=Ge(i,"*","p"),{runModel:s,acceptedText:c,pPr:f}=Dn(t,{xmlDoc:i}),u=l?Po(l):null;W(`[Reconcile] Ingested ${s.length} runs, ${c.length} chars, numbering:`,u),await this.maybeYield(s.length,Math.max(c.length,r?.length||0));let{cleanText:d,formatHints:m}=qe(r);W(`[Reconcile] Preprocessed: ${m.length} format hints`),await this.maybeYield(s.length,Math.max(c.length,d.length));let p=Gi(d),g=Mn(d),h=p||g;if(!p&&g&&W("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===d&&m.length===0&&!h)return W("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let v=Math.max(c.length,d.length)<this.disableSemanticCleanupOverChars,w=zn(c,d,{cleanupSemantic:v});v||W("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(s.length,Math.max(c.length,d.length));let y=s.filter(I=>I.kind===H.PARAGRAPH_START).length,b=Gi(c)||Mn(c),x=h&&b&&y>1&&c!==d;if(W(`[Reconcile] isTargetList: ${h}, paragraphCount: ${y}`),x)W("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(h)return W("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),W(`[Reconcile] cleanText preview: ${d.substring(0,100)}...`),W(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(d,u,s);W(`[Reconcile] Computed ${w.length} diff operations`);let S=Xn(s,w);W(`[Reconcile] Split into ${S.length} runs`);let A=Vn(S,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:m,numberingService:this.numberingService});W(`[Reconcile] Patched model has ${A.length} runs`),await this.maybeYield(A.length,Math.max(c.length,d.length));let E=ct(A,f,m,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let I=this.validateBasic(E);I.isValid||o.push(...I.errors)}return{ooxml:E,isValid:o.length===0,warnings:o}}catch(a){return Le("[Reconcile] Pipeline error:",a),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${a.message}`],error:a?.code?{code:a.code,message:a.message}:void 0}}}validateBasic(t){let r=[];try{let n=`<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${t}</root>`,o=j(n,"application/xml"),a=o.doc;if(o.error||!a)return r.push("Generated OOXML is not well-formed XML: "+(o.error?.message||"parse error")),{isValid:!1,errors:r};let i=Fe(a);i&&r.push("Generated OOXML is not well-formed XML: "+i.textContent.substring(0,100)),t.includes("<w:p")||r.push("Generated OOXML missing paragraph element")}catch(n){r.push(`Validation error: ${n.message}`)}return{isValid:r.length===0,errors:r}}shouldRunValidation(){return this.validateOutput?this.validationMode==="always"?!0:this.validationMode==="never"?!1:!(this.isWebPlatform&&qg()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await Yg())}wrapForInsertion(t,r={}){return kr(t,r)}async executeListGeneration(t,r,n,o=""){return Wn({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 ps(t)}executeTableGeneration(t){let r=bt(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:mr(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator,trackAsBlock:!0}),isValid:!0,warnings:[],includeNumbering:!1}}};var pu=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function gu(e){return!e||e.trim().length===0}function hu(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function Jg(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function gs(e){return gu(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":hu(e)?"table":Xt(e)?"list":"paragraph"}function Ea(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
140
141
  `):String(e??"")).split(`
141
- `),n=[],o=[],a=0;for(;a<r.length;){if(Il(r[a])){a++;continue}let l=li(r[a]),c=a+1;if(l==="heading"){let d=r[a].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:d[1].length,text:d[2],markdown:r[a].trim()}),a++;continue}if(l==="table"){let d=[];for(;a<r.length&&Tl(r[a]);)d.push(r[a].trim()),a++;let m=d.length>1&&Nl.test(d[1]),p=d.filter(g=>!Nl.test(g)).map(g=>Kd(g).length);m||o.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:c,message:"Markdown tables require a separator row immediately after the header (for example | --- | --- |)."}),p.length<2?o.push({severity:"error",code:"TABLE_DATA_ROW_REQUIRED",line:c,message:"Markdown tables require a header and at least one data row."}):new Set(p).size>1&&o.push({severity:"error",code:"TABLE_COLUMN_COUNT_MISMATCH",line:c,message:`Markdown table rows have inconsistent column counts: ${p.join(", ")}.`}),n.push({type:"table",columns:p[0]||0,rows:Math.max(0,p.length-1),hasHeader:m,markdown:d.join(`
142
- `)});continue}if(l==="list"){let d=[];for(;a<r.length&&li(r[a])==="list";)d.push(r[a].trimEnd()),a++;n.push({type:"list",items:d.length,markdown:d.join(`
143
- `)});continue}let u=[];for(;a<r.length&&li(r[a])==="paragraph";)u.push(r[a].trim()),a++;let f=u.join(" ").trim();n.push({type:"paragraph",text:f,markdown:f})}let i={heading:0,paragraph:0,list:0,table:0};for(let l of n)i[l.type]=(i[l.type]||0)+1;let s=n.map(l=>l.markdown).join(`
142
+ `),n=[],o=[],a=0;for(;a<r.length;){if(gu(r[a])){a++;continue}let s=gs(r[a]),c=a+1;if(s==="heading"){let d=r[a].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:d[1].length,text:d[2],markdown:r[a].trim()}),a++;continue}if(s==="table"){let d=[];for(;a<r.length&&hu(r[a]);)d.push(r[a].trim()),a++;let m=d.length>1&&pu.test(d[1]),p=d.filter(g=>!pu.test(g)).map(g=>Jg(g).length);m||o.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:c,message:"Markdown tables require a separator row immediately after the header (for example | --- | --- |)."}),p.length<2?o.push({severity:"error",code:"TABLE_DATA_ROW_REQUIRED",line:c,message:"Markdown tables require a header and at least one data row."}):new Set(p).size>1&&o.push({severity:"error",code:"TABLE_COLUMN_COUNT_MISMATCH",line:c,message:`Markdown table rows have inconsistent column counts: ${p.join(", ")}.`}),n.push({type:"table",columns:p[0]||0,rows:Math.max(0,p.length-1),hasHeader:m,markdown:d.join(`
143
+ `)});continue}if(s==="list"){let d=[];for(;a<r.length&&gs(r[a])==="list";)d.push(r[a].trimEnd()),a++;n.push({type:"list",items:d.length,markdown:d.join(`
144
+ `)});continue}let f=[];for(;a<r.length&&gs(r[a])==="paragraph";)f.push(r[a].trim()),a++;let u=f.join(" ").trim();n.push({type:"paragraph",text:u,markdown:u})}let i={heading:0,paragraph:0,list:0,table:0};for(let s of n)i[s.type]=(i[s.type]||0)+1;let l=n.map(s=>s.markdown).join(`
144
145
 
145
- `);return{valid:o.every(l=>l.severity!=="error"),normalizedMarkdown:s,blocks:n,issues:o,counts:i,requiresStructuredContent:n.length>1||n.some(l=>l.type==="heading"||l.type==="table"||l.type==="list"&&l.items>1)}}function Hd(e,t,r={}){let n=Lo(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 zn=["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 Ue(e,t){let r=zn.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=zn.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function Gd(e,t,r,n){if(!t||!r)return;let o=!!r.bold,a=!!r.italic,i=!!r.underline,s=!!r.strikethrough,l=new Set;if(o&&(l.add("w:b"),l.add("w:bCs")),a&&(l.add("w:i"),l.add("w:iCs")),i&&l.add("w:u"),s&&l.add("w:strike"),l.size>0){let c=[];for(let u of Array.from(t.childNodes))l.has(u.nodeName)&&c.push(u);for(let u of c)t.removeChild(u)}if(o){let c=D(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),Ue(t,c);let u=D(e,"w:bCs");u.setAttribute("w:val",n==="add"?"1":"0"),Ue(t,u)}if(a){let c=D(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),Ue(t,c);let u=D(e,"w:iCs");u.setAttribute("w:val",n==="add"?"1":"0"),Ue(t,u)}if(i){let c=D(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),Ue(t,c)}if(s){let c=D(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),Ue(t,c)}}function Al(e,t,r){Gd(e,t,r,"remove")}function kt(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=Pr(r,!1)),r.nodeName==="w:i"&&(t.italic=Pr(r,!1)),r.nodeName==="w:u"&&(t.underline=Pr(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=Pr(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 Pr(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 Sl=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"];function pr(e,t){let r=Sl.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=Sl.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function El(e,t){if(!t)return!1;let r=kt(e);if(t.bold!==void 0&&r.bold!==!!t.bold||t.italic!==void 0&&r.italic!==!!t.italic||t.underline!==void 0&&r.underline!==!!t.underline)return!0;let n=t.strike!==void 0?t.strike:t.strikethrough;if(n!==void 0&&r.strikethrough!==!!n)return!0;if(t.highlight!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:highlight"||s.localName==="highlight")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.highlight&&t.highlight!=="none"?String(t.highlight).toLowerCase():null;if((a||null)!==i)return!0}if(t.color!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:color"||s.localName==="color")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.color&&t.color!=="auto"?String(t.color).replace(/^#/,"").toUpperCase():null;if((a?.toUpperCase()||null)!==i)return!0}if(t.fontSize!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:sz"||s.localName==="sz")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.fontSize!==null&&t.fontSize!==""?String(t.fontSize):null;if(a!==i)return!0}if(t.fontFamily!==void 0){let o=Array.from(e?.childNodes||[]).find(s=>s.nodeType===1&&(s.nodeName==="w:rFonts"||s.localName==="rFonts")),a=o?o.getAttribute("w:ascii")||o.getAttribute("ascii"):null,i=t.fontFamily||null;if(a!==i)return!0}return!1}function Rl(e,t,r){if(!t||!r)return;let n=a=>{let i=[];for(let s of Array.from(t.childNodes))s.nodeType===1&&a.includes(s.nodeName)&&i.push(s);for(let s of i)t.removeChild(s)};if(r.bold!==void 0){n(["w:b","w:bCs"]);let a=D(e,"w:b");a.setAttribute("w:val",r.bold?"1":"0"),Ue(t,a);let i=D(e,"w:bCs");i.setAttribute("w:val",r.bold?"1":"0"),Ue(t,i)}if(r.italic!==void 0){n(["w:i","w:iCs"]);let a=D(e,"w:i");a.setAttribute("w:val",r.italic?"1":"0"),Ue(t,a);let i=D(e,"w:iCs");i.setAttribute("w:val",r.italic?"1":"0"),Ue(t,i)}if(r.underline!==void 0){n(["w:u"]);let a=D(e,"w:u");a.setAttribute("w:val",r.underline?"single":"none"),Ue(t,a)}let o=r.strike!==void 0?r.strike:r.strikethrough;if(o!==void 0){n(["w:strike","w:dstrike"]);let a=D(e,"w:strike");a.setAttribute("w:val",o?"1":"0"),Ue(t,a)}if(r.highlight!==void 0&&(n(["w:highlight"]),r.highlight&&r.highlight!=="none")){let a=D(e,"w:highlight");a.setAttribute("w:val",String(r.highlight).toLowerCase()),Ue(t,a)}if(r.color!==void 0&&(n(["w:color"]),r.color&&r.color!=="auto")){let a=D(e,"w:color");a.setAttribute("w:val",String(r.color).replace(/^#/,"")),Ue(t,a)}if(r.fontSize!==void 0&&(n(["w:sz","w:szCs"]),r.fontSize!==null&&r.fontSize!=="")){let a=String(r.fontSize),i=D(e,"w:sz");i.setAttribute("w:val",a),Ue(t,i);let s=D(e,"w:szCs");s.setAttribute("w:val",a),Ue(t,s)}if(r.fontFamily!==void 0&&(n(["w:rFonts"]),r.fontFamily)){let a=D(e,"w:rFonts");a.setAttribute("w:ascii",r.fontFamily),a.setAttribute("w:hAnsi",r.fontFamily),a.setAttribute("w:cs",r.fontFamily),Ue(t,a)}}function Pl(e,t){if(!t)return!1;if(t.alignment!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:jc"||o.localName==="jc"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.alignment)return!0}if(t.keepNext!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepNext"||o.localName==="keepNext"));if((r?Pr(r,!1):!1)!==!!t.keepNext)return!0}if(t.keepLines!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepLines"||o.localName==="keepLines"));if((r?Pr(r,!1):!1)!==!!t.keepLines)return!0}if(t.pageBreakBefore!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pageBreakBefore"||o.localName==="pageBreakBefore"));if((r?Pr(r,!1):!1)!==!!t.pageBreakBefore)return!0}if(t.style!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pStyle"||o.localName==="pStyle"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.style)return!0}return!1}function Cl(e,t,r){if(!t||!r)return;let n=o=>{let a=[];for(let i of Array.from(t.childNodes))i.nodeType===1&&o.includes(i.nodeName)&&a.push(i);for(let i of a)t.removeChild(i)};if(r.alignment!==void 0&&(n(["w:jc"]),r.alignment)){let o=D(e,"w:jc");o.setAttribute("w:val",r.alignment),pr(t,o)}if(r.keepNext!==void 0){n(["w:keepNext"]);let o=D(e,"w:keepNext");r.keepNext||o.setAttribute("w:val","0"),pr(t,o)}if(r.keepLines!==void 0){n(["w:keepLines"]);let o=D(e,"w:keepLines");r.keepLines||o.setAttribute("w:val","0"),pr(t,o)}if(r.pageBreakBefore!==void 0){n(["w:pageBreakBefore"]);let o=D(e,"w:pageBreakBefore");r.pageBreakBefore||o.setAttribute("w:val","0"),pr(t,o)}if(r.style!==void 0&&(n(["w:pStyle"]),r.style)){let o=D(e,"w:pStyle");o.setAttribute("w:val",r.style),pr(t,o)}}var Ol="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Mt(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Ol&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function qd(e){return!e||e.nodeType!==1||e.namespaceURI!==Ol?!1:e.localName==="del"||e.localName==="moveFrom"}function _l(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||qd(n))continue;if(Mt(n,"r")){t.push(n);continue}let o=Array.from(n.childNodes||[]);for(let a=o.length-1;a>=0;a-=1)r.push(o[a])}return t}function nt(e){let t=new Set(["comment","footnote","endnote"]);return _e(e,"*","p").filter(n=>{let o=n.parentNode;for(;o&&o.nodeName;){let a=String(o.localName||"").toLowerCase();if(t.has(a))return!1;o=o.parentNode}return!0})}function Bo(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],a=_l(o);for(let i of a){let s=Ce(i,"w:rPr");Array.from(i.childNodes||[]).forEach(l=>{if(Mt(l,"t")){let c=l.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:l,runElement:i,paragraph:o,container:i.parentNode,rPr:s}),r+=c.length)}else(Mt(l,"br")||Mt(l,"cr")||Mt(l,"tab")||Mt(l,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:l,runElement:i,paragraph:o,container:i.parentNode,rPr:s}),r+=1)})}r=Ar(r,n,e.length)}return{textSpans:t,charOffset:r}}function Yd(e,t,r,n,o,a=null){let i=null;for(let c of Array.from(e.childNodes))if(Mt(c,"rPr")){i=c;break}let s=kt(i);a&&(a.bold&&!s.bold&&(s.bold=!0),a.italic&&!s.italic&&(s.italic=!0),a.underline&&!s.underline&&(s.underline=!0),a.strikethrough&&!s.strikethrough&&(s.strikethrough=!0)),s.hasFormatting=s.bold||s.italic||s.underline||s.strikethrough;let l=r;for(let c of Array.from(e.childNodes))if(Mt(c,"t")){let u=c.textContent||"";if(u.length>0){let f=l,d=l+u.length;n.push({charStart:f,charEnd:d,textElement:c,runElement:e,paragraph:t,rPr:i,format:{...s}}),s.hasFormatting&&o.push({start:f,end:d,format:{...s},run:e,rPr:i}),l=d}}return l}function kl(e){let t=[],r=[],n=0,o=nt(e);for(let a=0;a<o.length;a++){let i=o[a],s=null;for(let u of Array.from(i.childNodes))if(Mt(u,"pPr")){for(let f of Array.from(u.childNodes))if(Mt(f,"rPr")){s=f;break}break}let l=kt(s);l.hasFormatting&&V(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let c=_l(i);for(let u of c)n=Yd(u,i,n,r,t,l);n=Ar(n,a,o.length)}return V(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var Zd=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function ct(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())Zd.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function Lt(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof Pe?t:Vt(r)||ur(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let a of o){if(!F(a,"rPrChange"))continue;let i=String(n.next());typeof a.setAttributeNS=="function"?a.setAttributeNS(B,"w:id",i):a.setAttribute("w:id",i),n._receiptCollector?.recordRevision(Number(i),"rPrChange")}return e}function Cr(e,t,r,n,o=null){let a=D(e,t==="ins"?"w:ins":"w:del"),i=o||ie(n,e,t==="ins"?"ins":"del");return a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",i.date),r&&a.appendChild(r),a}function Ml(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function Jd(e,t){let r=Ml(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=D(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function Qd(e,t){let r=Ml(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=D(e,"w:rPr"),t.appendChild(r)),r}function Ll(e,t,r,n,o=null){let a=Jd(e,t),i=Qd(e,a);for(let c of Array.from(i.childNodes||[]))c.nodeType===1&&(c.localName==="ins"||c.localName==="del"||c.nodeName==="w:ins"||c.nodeName==="w:del")&&i.removeChild(c);let s=D(e,n==="ins"?"w:ins":"w:del"),l=o||ie(r,e,n==="ins"?"ins":"del");return s.setAttribute("w:id",String(l.id)),s.setAttribute("w:author",l.author),s.setAttribute("w:date",l.date),i.appendChild(s),s}function Or(e,t,r,n=null){return Ll(e,t,r,"ins",n)}function _r(e,t,r,n=null){return Ll(e,t,r,"del",n)}function gr(e,t,r,n){let o=D(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Bl(e,o,t),o;let a=D(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Do(e,t,r,n,o,a,i){if(!t)return[];let s=new Set([0,t.length]);for(let u of n){let f=Math.max(0,u.start-o),d=Math.min(t.length,u.end-o);f>=0&&f<t.length&&s.add(f),d>0&&d<=t.length&&s.add(d)}let l=Array.from(s).sort((u,f)=>u-f),c=[];for(let u=0;u<l.length-1;u++){let f=l[u],d=l[u+1],m=t.slice(f,d);if(!m)continue;let p=o+f,g=o+d,h=n.filter(v=>v.start<=p&&v.end>=g),y={...kt(r)};h.forEach(v=>{v.format&&Object.assign(y,v.format)});let w=h.length>0?ln(e,r,y,a,i):r?.cloneNode(!0)||null;c.push(ci(e,m,w,!1))}return c}function ci(e,t,r,n){let o=D(e,"w:r");if(r&&o.appendChild(r),!n)return Bl(e,o,t),o;let a=D(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Bl(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let a of o){if(!a)continue;if(a===" "){t.appendChild(D(e,"w:tab"));continue}if(a===`
146
- `){t.appendChild(D(e,"w:br"));continue}if(a==="\u2011"){t.appendChild(D(e,"w:noBreakHyphen"));continue}let i=D(e,"w:t");/^\s|\s$/.test(a)&&i.setAttribute("xml:space","preserve"),i.textContent=a,t.appendChild(i)}}function ln(e,t,r,n,o){let a=D(e,"w:rPr");t&&Array.from(t.childNodes).forEach(l=>{["w:b","w:bCs","w:i","w:iCs","w:u","w:strike","w:rPrChange"].includes(l.nodeName)||a.appendChild(l.cloneNode(!0))});let i=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&o&&em(e,a,n,t);let s=(l,c,u=null,f="0")=>{let d=D(e,l);c?u&&d.setAttribute("w:val",u):f&&d.setAttribute("w:val",f);let m=zn.indexOf(l),p=m===-1?999:m,g=!1;for(let h of Array.from(a.childNodes)){if(h.nodeType!==1)continue;let y=zn.indexOf(h.nodeName);if((y===-1?999:y)>p){a.insertBefore(d,h),g=!0;break}}g||a.appendChild(d)};return s("w:b",!!i.bold,"1","0"),s("w:bCs",!!i.bold,"1","0"),s("w:i",!!i.italic,"1","0"),s("w:iCs",!!i.italic,"1","0"),s("w:u",!!i.underline,"single","none"),s("w:strike",!!i.strikethrough,"1","0"),a}function Xn(e,t,r,n,o){let a=D(e,"w:rPrChange"),i=ie(r,e,"rPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let l=ct(o||t)||D(e,"w:rPr");a.appendChild(l);let c=Ce(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(a),a}function em(e,t,r,n){Xn(e,t,r,null,n||t)}function Dl(e,t,r,n,o){let a=D(e,"w:pPrChange"),i=ie(r,e,"pPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let l=ct(o||t)||D(e,"w:pPr");a.appendChild(l);let c=Array.from(t.childNodes).find(u=>u.nodeType===1&&(u.nodeName==="w:pPrChange"||u.localName==="pPrChange"));return c&&t.removeChild(c),t.appendChild(a),a}var tm="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function cn(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===tm&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Fo(e,t,r){let n=new Map;for(let i of r)!i||!i.paragraph||(n.has(i.paragraph)||n.set(i.paragraph,[]),n.get(i.paragraph).push(i));let o=[],a=0;return t.forEach((i,s)=>{let l=(n.get(i)||[]).slice().sort((d,m)=>d.charStart-m.charStart),c=rm(l),u=ui(c),f=u.trim();o.push({paragraph:i,spans:l,text:c,normalizedText:u,normalizedTrim:f,startOffset:a}),a+=u.length,a=Ar(a,s,t.length)}),o}function Fl(e,t){if(!t)return null;let r=ui(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 $l(e,t){let r=ui(t),n=r.trim(),o=null,a=0;for(let i of e)if(i.normalizedText===r)return o=i,{targetInfo:o,matchOffset:a};if(n.length>0){for(let i of e)if(i.normalizedTrim===n)return o=i,{targetInfo:o,matchOffset:a}}if(n.length>0){let s=e.map(l=>l.normalizedText).join(`
147
- `).indexOf(n);if(s!==-1)for(let l of e){let c=l.startOffset,u=l.normalizedText.length;if(s>=c&&s<=c+u){o=l,a=s-c;break}}}if(!o&&e.length===1&&r.length>0){let i=e[0],s=i.normalizedTrim||"";if(s.length>0){let l=r.indexOf(s);l>=0&&(o=i,a=-l)}}return{targetInfo:o,matchOffset:a}}function Ul(e){let t=e;for(;t;){if(cn(t,"p"))return t;t=t.parentNode}return null}function rm(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;cn(n,"t")?t+=r.textElement.textContent||"":cn(n,"tab")?t+=" ":cn(n,"br")||cn(n,"cr")?t+=`
148
- `:cn(n,"noBreakHyphen")&&(t+="\u2011")}return t}function ui(e){return e?e.replace(/\r/g,`
149
- `).replace(/\u00a0/g," "):""}function zl(e,t,r){let n=Array.from(new Set(r)).sort((s,l)=>s-l);if(n.length===0||t.length===0)return[...t];let o=[...t].sort((s,l)=>s.charStart-l.charStart||s.charEnd-l.charEnd),a=[],i=0;for(let s of o){for(;i<n.length&&n[i]<=s.charStart;)i++;let l=s;for(;i<n.length&&n[i]<l.charEnd;){let c=n[i],u=nm(e,l,c);if(!u){i++;continue}a.push(u[0]),l=u[1],i++}a.push(l)}return a}function nm(e,t,r){let n=t.runElement,o=n.parentNode;if(!o)return null;let a=t.textElement.textContent||"",i=r-t.charStart,s=a.substring(0,i),l=a.substring(i);if(s.length===0||l.length===0)return null;let c=gr(e,s,t.rPr,!1),u=gr(e,l,t.rPr,!1);o.insertBefore(c,n),o.insertBefore(u,n),o.removeChild(n);let f=c.getElementsByTagName("w:t")[0],d=u.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:c},{...t,charStart:r,textElement:d,runElement:u}]}var om="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function am(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===om&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function im(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 Xl(e,t,r,n,o,a=!0){let i=!1,s=new Set;V(`[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;V("[OxmlEngine] Processing run for surgical format removal, format:",l.format);let u=Ce(c,"w:rPr");u||(u=D(e,"w:rPr"),c.insertBefore(u,c.firstChild)),a&&Xn(e,u,o||re()),Al(e,u,l.format),i=!0}return i?(V("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(V("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function sm(e,t,r,n,o,a=!0){let i=!1,s=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let l=[];for(let d of r)l.push(d.start,d.end);let u=zl(e,t,l).slice().sort((d,m)=>d.charStart-m.charStart||d.charEnd-m.charEnd),f=lm(r);for(let d of u){if(!d||!d.textElement||!am(d.textElement,"t"))continue;let m=f(d.charStart,d.charEnd);if(m.length===0)continue;let p=Ka(...m.map(S=>S.format)),g={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},h=d.format||kt(d.rPr),y={bold:!!h.bold,italic:!!h.italic,underline:!!h.underline,strikethrough:!!h.strikethrough};if(!["bold","italic","underline","strikethrough"].some(S=>g[S]!==y[S])||s.has(d.runElement)||(s.add(d.runElement),!(d.textElement.textContent||""))||!d.runElement.parentNode)continue;let T=d.runElement,I=Ce(T,"w:rPr"),N=ln(e,I,g,o||re(),a),A=I;if(!A)T.insertBefore(N,T.firstChild);else{for(;A.firstChild;)A.removeChild(A.firstChild);Array.from(N.childNodes).forEach(S=>A.appendChild(S))}i=!0}return{oxml:n.serializeToString(e),hasChanges:i}}function Vl(e,t,r,n,o,a=!0,i=null){let s=im(i),l=s.paragraphs||nt(e),c=s.textSpans||[];if(s.textSpans||({textSpans:c}=Bo(l)),!c||c.length===0)return St("[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||Fo(e,l,c),{targetInfo:f,matchOffset:d}=$l(u,t);if(!f||!f.spans||f.spans.length===0)return St("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let m=f.spans[0].charStart,p=f.spans.map(h=>({...h,charStart:h.charStart-m,charEnd:h.charEnd-m})),g=r.map(h=>({...h,start:h.start+d,end:h.end+d}));return sm(e,p,g,n,o,a)}function lm(e){let t=(e||[]).slice().sort((o,a)=>o.start-a.start||o.end-a.end),r=[],n=0;return(o,a)=>{for(;n<t.length&&t[n].start<a;)r.push(t[n]),n++;for(let i=r.length-1;i>=0;i--)r[i].end<=o&&r.splice(i,1);return r.filter(i=>i.start<a&&i.end>o)}}function $o(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function kr(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let a=$o(o);if(n==="accepted"&&(a==="del"||a==="moveFrom")||n==="rejected"&&(a==="ins"||a==="moveTo"))return!1;o=o.parentNode}return!0}function Mr(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!kr(e,n,r))return"";let o="",a=i=>{for(let s of Array.from(i?.childNodes||[])){if(s?.nodeType!==1||s.namespaceURI&&s.namespaceURI!==B||!kr(s,n,r))continue;let l=$o(s);l==="t"||l==="delText"&&r==="rejected"?o+=s.textContent||"":l==="tab"?o+=" ":l==="br"||l==="cr"?o+=`
150
- `:l==="noBreakHyphen"?o+="\u2011":l==="softHyphen"?o+="\xAD":a(s)}};return a(e),o}var hr=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Uo(e,t={}){if(!e)return[];let r=[];function n(f,d,m){for(let p of Array.from(f?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==B)continue;let g=$o(p);if(g==="pPr"||g==="rPr")continue;let h=d;g==="ins"?h={kind:"insertion",author:hr(p,"author")||void 0,revisionId:hr(p,"id")||void 0}:g==="del"?h={kind:"deletion",author:hr(p,"author")||void 0,revisionId:hr(p,"id")||void 0}:g==="moveFrom"?h={kind:"move_from",author:hr(p,"author")||void 0,revisionId:hr(p,"id")||void 0}:g==="moveTo"&&(h={kind:"move_to",author:hr(p,"author")||void 0,revisionId:hr(p,"id")||void 0});let y=m;g==="r"&&(y=p);let w=null,v=h?h.kind:"baseline",b=h?.author,x=h?.revisionId;g==="t"?w=p.textContent||"":g==="delText"?(w=p.textContent||"",h||(v="deletion")):g==="tab"?w=" ":g==="br"||g==="cr"?w=`
151
- `:g==="noBreakHyphen"?w="\u2011":g==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:v,author:b,revisionId:x,carrier:y||p,carrierContainer:(y||p)?.parentNode||null}):n(p,h,y)}}let o=$o(e)==="r"?e:null;if(n(e,null,o),r.length===0)return[];let a=t.mergeRuns!==!1,i=[],s=null;for(let f of r){if(!s){s={...f};continue}let d=s.kind===f.kind,m=s.author===f.author,p=s.revisionId===f.revisionId,g=s.carrier===f.carrier,h=a&&s.carrierContainer===f.carrierContainer;d&&m&&p&&(g||h)?s.text+=f.text:(i.push(s),s={...f})}s&&i.push(s);let l=0,c=0,u=[];for(let f of i){let d=f.kind!=="deletion"&&f.kind!=="move_from",m=f.kind!=="insertion"&&f.kind!=="move_to",p=d?l:null,g=m?c:null;d&&(l+=f.text.length),m&&(c+=f.text.length);let h={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:g};f.author!==void 0&&(h.author=f.author),f.revisionId!==void 0&&(h.revisionId=f.revisionId),u.push(h)}return u}function te(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Uo(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 cm="http://schemas.microsoft.com/office/word/2010/wordml";function Wl(e,t,r={}){let{targetParagraphId:n=null}=r,o=$e(e,B,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let i=nt(e).filter(l=>{let c=l.parentNode;for(;c;){if(F(c,"tc"))return!0;c=c.parentNode}return!1});V(`[OxmlEngine] Table wrapper detected: ${o.length} tables, ${i.length} paragraphs in cells`);let s=null;if(n){let l=String(n).toUpperCase();s=i.find(c=>{let u=fm(c);return u&&u.toUpperCase()===l})||null,s?V(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):V(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let l=t.trim();if(!s){for(let c of i)if(te(c).trim()===l){s=c,V(`[OxmlEngine] Found target paragraph by text match: "${l.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:i.length>0,targetParagraph:s,paragraphs:i,paragraph:s||i[0]||null,tableElement:o[0]}}function Vn(e,t,r){let n=Array.isArray(t)?t:[t],o="";for(let a of n){if(!a)continue;let i=r.serializeToString(a);i=i.replace(/\s+xmlns:w="[^"]*"/g,""),i=i.replace(/\s+xmlns:r="[^"]*"/g,""),i=i.replace(/\s+xmlns:wp="[^"]*"/g,""),o+=i}return V(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),V(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),um(o)}function um(e){return ml(e)}function fm(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(cm,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function fi(e){return F(e,"t")||F(e,"delText")?e.textContent||"":F(e,"br")||F(e,"cr")?`
152
- `:F(e,"tab")?" ":F(e,"noBreakHyphen")?"\u2011":F(e,"softHyphen")?"\xAD":""}function di(e){return F(e,"t")||F(e,"delText")||F(e,"br")||F(e,"cr")||F(e,"tab")||F(e,"noBreakHyphen")||F(e,"softHyphen")}function zo(e){let t="",r=[];return e.forEach((n,o)=>{let a=n.parentNode;for(let i=n.firstChild;i;i=i.nextSibling)if(F(i,"r"))t+=Wn(i,n,a,t.length,r).text;else if(F(i,"hyperlink"))for(let s=i.firstChild;s;s=s.nextSibling)F(s,"r")&&(t+=Wn(s,n,a,t.length,r).text);else if(F(i,"ins"))for(let s=i.firstChild;s;s=s.nextSibling)F(s,"r")&&(t+=Wn(s,n,a,t.length,r).text);else if(F(i,"sdt")){let s=Array.from(i.childNodes||[]).find(l=>F(l,"sdtContent"));if(s)for(let l=s.firstChild;l;l=l.nextSibling)F(l,"r")&&(t+=Wn(l,n,a,t.length,r).text)}else if(F(i,"smartTag"))for(let s=i.firstChild;s;s=s.nextSibling)F(s,"r")&&(t+=Wn(s,n,a,t.length,r).text);t=rn(t,o,e.length)}),{fullText:t,textSpans:r}}function Wn(e,t,r,n,o){let a=Ce(e,"w:rPr"),i=n,s=[];for(let l=e.firstChild;l;l=l.nextSibling)if(F(l,"t")){let c=l.textContent||"";if(c.length===0)continue;o.push({charStart:i,charEnd:i+c.length,textElement:l,runElement:e,paragraph:t,container:r,rPr:a}),i+=c.length,s.push(c)}else if(di(l)){let c=fi(l);o.push({charStart:i,charEnd:i+1,textElement:l,runElement:e,paragraph:t,container:r,rPr:a}),i+=1,s.push(c)}return{text:s.join("")}}function Xo(e){let t=e.slice().sort((o,a)=>o.charStart-a.charStart||o.charEnd-a.charEnd),r=t.map(o=>o.charStart),n=t.map(o=>o.charEnd);return{spans:t,starts:r,ends:n}}function jn(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=hi(e.ends,t);for(;o<e.spans.length;){let a=e.spans[o];if(a.charStart>=r)break;n(a),o++}}function mi(e,t){if(e.spans.length===0)return null;let r=hi(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function pi(e,t){let r=dm(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function gi(e,t){let r=hi(e.ends,t)-1;return r>=0?e.spans[r]:null}function hi(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 dm(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 jl(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=mi(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,a=pi(e,t)||(t>0?gi(e,t):null),i=e.spans.find(s=>s.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:a,rightSpan:i,containingSpan:n,isInterior:o,fallbackParagraph:r}}var mm=new Set(["ins","del"]);function Ht(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(F(n,"rPr")||!di(n))continue;let o=fi(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function yt(e){return e.length===0?0:e[e.length-1].end}function Bt(e,t,r,n,o){let a=[];return n<=r||t.forEach(i=>{let s=Math.max(r,i.start),l=Math.min(n,i.end);if(l<=s)return;let c=s-i.start,u=l-i.start,f=i.text.slice(c,u);a.push(wm(e,i.node,f,o))}),a}function Kn(e,t,r){let n=D(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function Lr(e,t,r,n,o){if(n.length===0)return null;let a=Kn(e,n,o);return t.insertBefore(a,r),a}function Vo(e,t,r,n=null){let o=hm(t);if(!mm.has(o))throw new TypeError("splitTrackChangeCarrier requires a w:ins or w:del carrier.");if(!Number.isInteger(r)||r<0)throw new RangeError("splitOffset must be a non-negative integer.");let a=Array.from(t.childNodes||[]),i=a.reduce((d,m)=>d+(F(m,"r")?yt(Ht(m)):0),0);if(r>i)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${i}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===i)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let s=t.cloneNode(!1),l=t.cloneNode(!1),c=0;for(let d of a){if(!F(d,"r")){(c<=r?s:l).appendChild(d.cloneNode(!0));continue}let m=Ht(d),p=yt(m),g=c+p;if(g<=r)s.appendChild(d.cloneNode(!0));else if(c>=r)l.appendChild(d.cloneNode(!0));else{let h=r-c,y=Array.from(d.childNodes||[]).find(T=>F(T,"rPr"))||null,w=o==="del",v=Bt(e,m,0,h,w),b=Bt(e,m,h,p,w);s.appendChild(Kn(e,v,y));let x=Kn(e,b,y);l.appendChild(x)}c=g}let u=pm(e,n);Lt(l,u);let f=u.next();return gm(l,"id",String(f)),u._receiptCollector?.recordRevision(f,o),{leftCarrier:s,rightCarrier:l}}function pm(e,t){return t instanceof Pe?t:Vt(e)||ur(e)}function gm(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(B,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function hm(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function wm(e,t,r,n){if(n&&(F(t,"delText")||F(t,"t"))){let a=D(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}if(F(t,"t")){let a=t.cloneNode(!1);return a.textContent=r,/^\s|\s$/.test(r)&&a.setAttribute("xml:space","preserve"),a}if(r===`
153
- `&&(F(t,"br")||F(t,"cr"))||r===" "&&F(t,"tab")||r==="\u2011"&&F(t,"noBreakHyphen")||r==="\xAD"&&F(t,"softHyphen"))return t.cloneNode(!0);if(n){let a=D(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}let o=D(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function Gl(e,t,r,n,o,a,i){if(o.length===0)return!1;let s=t.rPr,l=kt(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 d=t.runElement.parentNode;if(!d)return!1;let m=t.textElement.textContent||"",p=t.charStart,g=r-p,h=n-p,y=m.substring(0,g),w=m.substring(g,h),v=m.substring(h);if(y.length>0){let T=gr(e,y,s,!1);d.insertBefore(T,t.runElement)}let b=ln(e,s,c,a,i),x=ci(e,w,b,!1);if(d.insertBefore(x,t.runElement),v.length>0){let T=gr(e,v,s,!1);d.insertBefore(T,t.runElement)}return d.removeChild(t.runElement),!0}function vi(e,t,r,n,o,a,i=null){let s=[];if(jn(t,r,n,m=>{s.push(m)}),s.length===0)return!1;let l=new Map;s.forEach(m=>{m.runElement?.parentNode&&(l.has(m.runElement)||l.set(m.runElement,[]),l.get(m.runElement).push(m))});let c=[];l.forEach((m,p)=>{let g=p.parentNode;if(!g)return;let h=Ht(p);if(h.length===0)return;let y=1/0,w=-1/0;m.forEach(v=>{let b=h.find(I=>I.node===v.textElement);if(!b)return;let x=Math.max(0,r-v.charStart),T=Math.min(v.charEnd-v.charStart,n-v.charStart);T<=x||(y=Math.min(y,b.start+x),w=Math.max(w,b.start+T))}),!(!Number.isFinite(y)||w<=y)&&c.push({runElement:p,parent:g,rPr:m[0].rPr,beforePieces:Bt(e,h,0,y,!1),deletedPieces:Bt(e,h,y,w,!0),afterPieces:Bt(e,h,w,yt(h),!1),globalStart:Math.max(r,Math.min(...m.map(v=>v.charStart))),globalEnd:Math.min(n,Math.max(...m.map(v=>v.charEnd))),carrierGlobalStart:F(g,"ins")?ql(t,g):null})});let u=[];for(let m of c){let p=u[u.length-1],g=p?.[p.length-1];g&&g.parent===m.parent&&xm(g.runElement)===m.runElement?p.push(m):u.push([m])}let f=!1,d=!1;for(let m of u){let p=m[0],g=null;if(a&&m.some(w=>w.deletedPieces.length>0)){let w=i?d?{...i,id:ie(o,e,"del").id}:i:null;d=!0,g=Cr(e,"del",null,o,w)}for(let w of m){let{parent:v,runElement:b}=w;Lr(e,v,b,w.beforePieces,w.rPr),g&&w===p&&v.insertBefore(g,b),g&&w.deletedPieces.length>0&&g.appendChild(Kn(e,w.deletedPieces,w.rPr));let x=Lr(e,v,b,w.afterPieces,w.rPr);w.globalEnd===n&&!F(v,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:v,referenceNode:x||b.nextSibling,rPr:w.rPr})),v.removeChild(b),f=!0}let h=F(p.parent,"ins")?p.parent:null,y=Math.max(...m.map(w=>w.globalEnd));if(h&&y===n){let w=p.carrierGlobalStart,v=m.filter(x=>x.globalStart<n).reduce((x,T)=>x+T.deletedPieces.reduce((I,N)=>I+(N.textContent||"").length,0),0),b=Math.max(0,n-w-v);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:b,rPr:p.rPr})}}return f}function un(e,t,r,n,o,a=[],i=0,s=!0,l=null,c=null,u=null,f="merge-same-author"){let d=t.revisionInsertionAnchors?.get(r)||null;if(d&&f==="slice-cross-author"&&Hl(d.carrier)&&yi(d.carrier,o))return t.revisionInsertionAnchors.delete(r),wi(e,d.carrier,d.splitOffset,n,d.rPr,o,a,i,s,c);let m=t.replacementInsertionAnchors?.get(r)||null;if(m&&!u&&Hl(m.parent)&&(!m.referenceNode||m.referenceNode.parentNode===m.parent))return t.replacementInsertionAnchors.delete(r),wr(e,m.parent,m.referenceNode,n,m.rPr,o,a,i,s,c),!0;if(!u){let x=mi(t,r);if(!x&&r>0&&(x=pi(t,r)),!x&&r>0&&(x=gi(t,r)),!x&&t.spans.length>0&&(x=t.spans[t.spans.length-1]),!x)return l?(wr(e,l,null,n,null,o,a,i,s,c),!0):!1;let T=x.runElement.parentNode;if(!T)return l?(wr(e,l,null,n,x.rPr,o,a,i,s,c),!0):!1;let I=!(s&&f==="slice-cross-author"&&vm(T,o));if(s&&f==="slice-cross-author"&&yi(T,o))return wi(e,T,Kl(t,T,r),n,x.rPr,o,a,i,s,c);let N=Ht(x.runElement),A=N.find(E=>E.node===x.textElement),S=A?A.start+Math.max(0,Math.min(r-x.charStart,x.charEnd-x.charStart)):r<=x.charStart?0:yt(N);if(S>0&&S<yt(N)){let E=Bt(e,N,0,S,!1),k=Bt(e,N,S,yt(N),!1);return Lr(e,T,x.runElement,E,x.rPr),wr(e,T,x.runElement,n,x.rPr,o,a,i,I,c),Lr(e,T,x.runElement,k,x.rPr),T.removeChild(x.runElement),!0}let O=r<=x.charStart?x.runElement:x.runElement.nextSibling;return wr(e,T,O,n,x.rPr,o,a,i,I,c),!0}let p=jl(t,r,l),g=p.leftSpan&&F(p.leftSpan.runElement?.parentNode,"hyperlink"),h=p.rightSpan&&F(p.rightSpan.runElement?.parentNode,"hyperlink"),y=p.containingSpan&&F(p.containingSpan.runElement?.parentNode,"hyperlink");if(u.hyperlink==="outside"){if(p.isInterior&&y)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(u.hyperlink==="inside"&&!g&&!h&&!y)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let w=null;if(u.formatting==="none"?w=null:u.formatting==="right"?w=p.rightSpan?.rPr||null:u.formatting==="left"?w=p.leftSpan?.rPr||null:w=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let x=p.containingSpan,T=x.runElement.parentNode||l;if(!T)return!1;let I=Ht(x.runElement),N=I.find(S=>S.node===x.textElement),A=N?N.start+Math.max(0,Math.min(r-x.charStart,x.charEnd-x.charStart)):r<=x.charStart?0:yt(I);if(A>0&&A<yt(I)){let S=Bt(e,I,0,A,!1),O=Bt(e,I,A,yt(I),!1);return Lr(e,T,x.runElement,S,x.rPr),wr(e,T,x.runElement,n,w,o,a,i,s,c),Lr(e,T,x.runElement,O,x.rPr),T.removeChild(x.runElement),!0}}let v=null,b=null;if(u.hyperlink==="outside"){if(h){let x=p.rightSpan.runElement.parentNode;v=x.parentNode||l,b=x}else if(g){let x=p.leftSpan.runElement.parentNode;v=x.parentNode||l,b=x.nextSibling}}else u.hyperlink==="inside"&&(h?(v=p.rightSpan.runElement.parentNode,b=p.rightSpan.runElement):g&&(v=p.leftSpan.runElement.parentNode,b=p.leftSpan.runElement.nextSibling));if(v||(p.rightSpan?(v=p.rightSpan.runElement.parentNode||l,b=p.rightSpan.runElement):p.leftSpan?(v=p.leftSpan.runElement.parentNode||l,b=p.leftSpan.runElement.nextSibling):(v=l,b=null)),u.bookmark&&v&&(u.bookmark==="outside"?(b&&F(b.previousSibling,"bookmarkStart")&&(b=b.previousSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling.nextSibling)):u.bookmark==="inside"&&(b&&F(b,"bookmarkStart")&&(b=b.nextSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling))),u.comment&&v)if(u.comment==="outside"){if(b&&F(b.previousSibling,"commentRangeStart")&&(b=b.previousSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let x=p.leftSpan.runElement.nextSibling.nextSibling;x&&(F(x,"commentReference")||F(x,"r"))&&Array.from(x.childNodes||[]).some(I=>F(I,"commentReference"))&&(x=x.nextSibling),b=x}}else u.comment==="inside"&&(b&&F(b,"commentRangeStart")&&(b=b.nextSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(b=p.leftSpan.runElement.nextSibling));if(s&&u.revision==="coalesce_same_author"){let x=null,T=null;if(p.leftSpan&&F(p.leftSpan.runElement.parentNode,"ins")){let I=p.leftSpan.runElement.parentNode;(I.getAttribute("w:author")||I.getAttributeNS(B,"author"))===o&&(x=I,T=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&F(p.rightSpan.runElement.parentNode,"ins")){let I=p.rightSpan.runElement.parentNode;(I.getAttribute("w:author")||I.getAttributeNS(B,"author"))===o&&(x=I,T=p.rightSpan.runElement)}if(x){let I=gr(e,n,w,!1);return x.insertBefore(I,T),!0}}return s&&f==="slice-cross-author"&&yi(v,o)?wi(e,v,Kl(t,v,r),n,w,o,a,i,s,c):(wr(e,v,b,n,w,o,a,i,s,c),!0)}function wi(e,t,r,n,o,a,i,s,l,c){let u=t.parentNode;if(!u)return!1;let{leftCarrier:f,rightCarrier:d}=Vo(e,t,r);return f&&u.insertBefore(f,t),wr(e,u,t,n,ym(o),a,i,s,l,c),d&&u.insertBefore(d,t),u.removeChild(t),!0}function ym(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>F(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Kl(e,t,r){let n=ql(e,t),o=e.spans.filter(a=>a.runElement?.parentNode===t).reduce((a,i)=>a+(i.charEnd-i.charStart),0);return Math.max(0,Math.min(r-n,o))}function ql(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 yi(e,t){return F(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function vm(e,t){return F(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function xm(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Hl(e){return!!e?.parentNode}function wr(e,t,r,n,o,a,i,s,l,c=null){let u=Xt(i,s,s+n.length);if(u.length===0){let d=gr(e,n,o,!1);if(l){let m=Cr(e,"ins",d,a,c);t.insertBefore(m,r)}else t.insertBefore(d,r);return}let f=Do(e,n,o,u,s,a,l);if(l){let d=Cr(e,"ins",null,a,c);f.forEach(m=>d.appendChild(m)),t.insertBefore(d,r)}else f.forEach(d=>t.insertBefore(d,r))}function Yl(e,t,r,n=!1){let o=[];if(jn(e,t,r,m=>o.push(m)),o.length===0)return{safe:!1};let a=o[0].runElement,i=a?.parentNode;if(!i)return{safe:!1};if(!o.every(m=>m.runElement?.parentNode===i))return{safe:!1,structuralBoundary:!0};let l=i.localName||i.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(l)||l==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let m of o){let p=m.runElement;for(let g of Array.from(p.childNodes||[]))if(g.nodeType===1){let h=g.localName||g.nodeName.replace(/^.*:/,"");if(c.has(h)||h==="fldChar")return{safe:!1,structuralBoundary:!0}}}let u=o[o.length-1].runElement,f=a;for(;f&&f!==u;){if(f!==a){let m=f.localName||f.nodeName.replace(/^.*:/,"");if(c.has(m))return{safe:!1,structuralBoundary:!0}}f=f.nextSibling}function d(m){if(!m||m.nodeType!==1)return!1;let p=m.localName||m.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let g of Array.from(m.childNodes||[]))if(g.nodeType===1&&d(g))return!0;return!1}return d(a.previousSibling)||d(u.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function Ql(e,t,r,n,o,a,i=!0,s=null,l={},c={}){let u=s?[s]:nt(e),{fullText:f,textSpans:d}=zo(u),m=c.existingRevisions==="slice-cross-author"?ol(f,r):null,p=m||Nm($n(f,r,l),l),g=Xo(d),h=c.pairReplacements===!0,y=[],w=0,v=0,b=!1,x=m?Tm(m):[];if(x.length>1&&a.length===0)for(let N of x.slice().reverse()){let A=zo(u).textSpans,S=Xo(A),O=N.text.replace(/\n/g," ");if(O.length===0)continue;let E=un(e,S,N.originalPos,O,o,a,N.newPos,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(E&&typeof E=="object"&&E.error)return Ne({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:E.error});E===!0&&(b=!0)}else if(a.length===0){let N=Im(p);for(let A of N.reverse()){let S=Xo(zo(u).textSpans);if(A.type==="insert"){let k=un(e,S,A.start,A.text.replace(/\n/g," "),o,a,A.newPos,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(k&&typeof k=="object"&&k.error)return Ne({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:k.error});k===!0&&(b=!0);continue}let O=null,E=null;if(A.type==="replace"&&h&&i&&A.text.replace(/\n/g," ")){let k=Yl(S,A.start,A.end,c?.existingRevisions==="slice-cross-author");if(k.safe){let C=Bn(o,e);O={id:C.deletionId,author:C.author,date:C.date},E={id:C.insertionId,author:C.author,date:C.date}}else k.structuralBoundary&&y.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(vi(e,S,A.start,A.end,o,i,O)&&(b=!0),A.type==="replace"){let k=un(e,S,A.end,A.text.replace(/\n/g," "),o,a,A.newPos,i,u[0]||null,E,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(k&&typeof k=="object"&&k.error)return Ne({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:k.error});k===!0&&(b=!0)}}}else for(let N=0;N<p.length;N++){let[A,S]=p[N];if(A===0){let O=S.length,E=w,k=w+O;jn(g,E,k,C=>{let P=Math.max(C.charStart,E),_=Math.min(C.charEnd,k),R=_-P,M=P-E,U=v+M,X=U+R,z=Xt(a,U,X);Gl(e,C,P,_,z,o,i)&&(b=!0)}),w+=O,v+=O}else if(A===-1){let O=N+1<p.length&&p[N+1][0]===1,E=!1,k=null,C=null;if(h&&i&&O&&p[N+1][1].replace(/\n/g," ").length>0){let R=Yl(g,w,w+S.length,c?.existingRevisions==="slice-cross-author");if(R.safe){let M=Bn(o,e);k={id:M.deletionId,author:M.author,date:M.date},C={id:M.insertionId,author:M.author,date:M.date},E=!0}else R.structuralBoundary&&y.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(vi(e,g,w,w+S.length,o,i,k)&&(b=!0),w+=S.length,E){N++;let[,P]=p[N],_=P.replace(/\n/g," ");if(_.length>0){let R=un(e,g,w,_,o,a,v,i,u[0]||null,C,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(R&&typeof R=="object"&&R.error)return Ne({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:R.error});R===!0&&(b=!0)}v+=P.length}}else if(A===1){let O=S.replace(/\n/g," ");if(O.length>0){let E=un(e,g,w,O,o,a,v,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(E&&typeof E=="object"&&E.error)return Ne({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:E.error});E===!0&&(b=!0)}v+=S.length}}let T=u.map(N=>te(N)).join(`
154
- `),I=String(r).replace(/\r\n/g,`
155
- `);if(c.existingRevisions==="slice-cross-author"&&T!==I){let N=bm(I,T);return Ne({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:N,expectedExcerpt:Zl(I,N),actualExcerpt:Zl(T,N),expectedCodePoint:Jl(I,N),actualCodePoint:Jl(T,N)},...y.length>0?{warnings:[...new Set(y)]}:{}})}return Ne({oxml:n.serializeToString(e),hasChanges:b,...y.length>0?{warnings:[...new Set(y)]}:{}})}function bm(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 Zl(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}function Jl(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function Nm(e,t){let r=[];for(let n=0;n<e.length;n++){let[o,a]=e[n],i=e[n+1];if(o===-1&&i?.[0]===1&&a!==i[1]&&a.length===i[1].length&&a.replace(/\u00a0/g," ")===i[1].replace(/\u00a0/g," ")){r.push(...nl(a,i[1],t)),n++;continue}r.push([o,a])}return r}function Im(e){let t=[],r=0,n=0;for(let o=0;o<e.length;o++){let[a,i]=e[o];if(a===0){r+=i.length,n+=i.length;continue}if(a===-1){let s=e[o+1];s?.[0]===1?(t.push({type:"replace",start:r,end:r+i.length,newPos:n,text:s[1]}),r+=i.length,n+=s[1].length,o++):(t.push({type:"delete",start:r,end:r+i.length,newPos:n,text:""}),r+=i.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:i}),n+=i.length}return t}function Tm(e){let t=[],r=0,n=0;for(let[o,a]of e)o===0?(r+=a.length,n+=a.length):o===-1?r+=a.length:o===1&&(t.push({originalPos:r,newPos:n,text:a}),n+=a.length);return t}var tc=ks(ti(),1);var rc=new tc.diff_match_patch;function nc(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Sm(e,t){return e?.getAttributeNS?.(B,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function ec(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let o=0,a=t-1;for(;o<=a;){let i=Math.floor((o+a)/2);e[i].end<=r?o=i+1:a=i-1}t=o}for(;t<e.length&&e[t].end<=r;)t++;let n=e[t];return n&&n.start<=r&&r<n.end?n:null}}}function Am(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 oc(e,t,r=null){let n=e.documentElement,o=F(n,"body")||nc(n)==="package",a=r||nt(e),i=Ke(e,B,"body");!i&&o&&(i=n);let s="",l=[],c=[],u=[],f=new Map,d=new Map,m=new Set,p={nextCharCode:57344},g=new Set;a.forEach((O,E)=>{let k=s.length;Array.from(O.childNodes).forEach(R=>{s=Om(R,s,l,u,f,d,p,m)}),s=rn(s,E,a.length);let C=s.length,P=Ke(O,B,"pPr"),_=O.parentNode;_&&g.add(_),c.push({start:k,end:C,pPr:P,container:_||i})});let h="";for(let O=0;O<s.length;O++){let E=s[O];h+=m.has(E)?`
156
- `:E}let y=Pm(h,t,u);y=Rm(h,s,y,m),d.forEach((O,E)=>{let k=E.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");y=y.replace(new RegExp(k,"g"),O)}),y=Cm(s,y,f);let w=new Map;g.forEach(O=>{w.set(O,e.createDocumentFragment())}),i&&!w.has(i)&&w.set(i,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let v=new Map,b=new Set(c.map(O=>O.start)),x=ec(c),T=ec(l),I=Am(u);return{paragraphs:a,body:i||e,paragraphMap:c,paragraphStarts:b,propertyMap:l,sentinelMap:u,sentinelMapByStart:I,referenceMap:f,tokenToCharMap:d,containerFragments:w,replacementContainers:v,originalFullText:s,processedModifiedText:y,getParagraphInfo:O=>{let E=x.at(O);return E||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:i||e})},getRunProperties:O=>{let E=T.at(O);return E?{rPr:E.rPr,wrapper:E.wrapper}:{rPr:null}},getPropertySpanLength:(O,E)=>{let k=T.at(O);return k?Math.min(k.end-O,E):1},isParagraphStart:O=>b.has(O)}}function Wo(e,t){let r=nt(e);if(r.length===0)return[];let n=ac(t),o=r.map(Em);if(!n){let i=o.findIndex(s=>s==="");return i>=0?[r[i]]:null}if(r.length===1&&o[0]==="")return r;let a=[i=>i,i=>i.trim(),i=>i.replace(/\s+/g," ").trim()];for(let i of a){let s=i(n);for(let l=0;l<r.length;l++){let c="";for(let u=l;u<r.length;u++)if(c+=(u===l?"":`
157
- `)+o[u],i(c)===s)return r.slice(l,u+1)}}return null}function ac(e){return String(e??"").replace(/\r\n?/g,`
158
- `).replace(/\u00a0/g," ")}function Em(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&(F(o,"pPr")||F(o,"del")||F(o,"moveFrom")||(F(o,"t")?t+=o.textContent||"":F(o,"tab")?t+=" ":F(o,"br")||F(o,"cr")?t+=`
159
- `:F(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),ac(t)}function Rm(e,t,r,n){if(n.size===0)return r;let o=rc.diff_main(e,r),a=0,i="";for(let[s,l]of o)if(s===0){for(let c=0;c<l.length;c++){let u=t[a+c];i+=n.has(u)?u:l[c]}a+=l.length}else s===-1?a+=l.length:i+=l;return i}function Pm(e,t,r){let n=new Map;if(r.forEach(f=>{f.zeroWidth&&n.set(f.start,f)}),n.size===0)return t;let o="",a=0,i=new Map;for(let f=0;f<e.length;f++){let d=n.get(f);if(d){i.has(a)||i.set(a,[]),i.get(a).push({char:e[f],affinity:d.affinity||"right",emitted:!1});continue}o+=e[f],a++}let s=rc.diff_main(o,t),l=0,c="",u=(f,d)=>{let m=i.get(f)||[];for(let p of m)p.emitted||d&&p.affinity!==d||(c+=p.char,p.emitted=!0)};for(let[f,d]of s){if(f===1){u(l,"left"),c+=d;continue}for(let m=0;m<d.length;m++)u(l),f===0&&(c+=d[m]),l++}return u(l),c}function Cm(e,t,r){let n=t;for(let o of r.keys()){if(n.includes(o))continue;let a=e.indexOf(o);if(a<0)continue;let i=e.slice(0,a),s=e.slice(a+o.length);if(i&&n.startsWith(i)){n=`${n.slice(0,i.length)}${o}${n.slice(i.length)}`;continue}if(s&&n.endsWith(s)){let l=n.length-s.length;n=`${n.slice(0,l)}${o}${n.slice(l)}`}}return n}function Om(e,t,r,n,o,a,i,s){return F(e,"r")?_m(e,t,r,n,o,a,i,s):F(e,"hyperlink")?km(e,t,r):F(e,"sdt")||F(e,"oMath")||nc(e)==="oMath"||F(e,"bookmarkStart")||F(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((F(e,"commentRangeStart")||F(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function _m(e,t,r,n,o,a,i,s){let l=t,c=Ke(e,B,"rPr");return Array.from(e.childNodes).forEach(u=>{if(F(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(F(u,"br")||F(u,"cr")){let f=String.fromCharCode(i.nextCharCode++);o.set(f,u),s.add(f),l+=f,r.push({start:l.length-1,end:l.length,rPr:c})}else if(F(u,"tab"))l+=" ",r.push({start:l.length-1,end:l.length,rPr:c});else if(F(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=>F(u,f))){let f=Ke(u,B,"txbxContent"),d=F(u,"pict")&&!!f,m=F(u,"fldChar")||F(u,"instrText"),p=F(u,"fldChar")?u.getAttributeNS?.(B,"fldCharType")||u.getAttribute("w:fldCharType")||u.getAttribute("fldCharType"):null;n.push({start:l.length,node:u,wrapInRun:!0,rPr:c,zeroWidth:m,affinity:p==="end"?"left":"right",isTextBox:d,originalContainer:d?f:void 0}),l+="\uFFFC",r.push({start:l.length-1,end:l.length,rPr:c})}else if(F(u,"footnoteReference")||F(u,"endnoteReference")){let f=Sm(u,"id");if(f){let m=`{{__${F(u,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(i.nextCharCode++);o.set(p,u),a.set(m,p),l+=p,r.push({start:l.length-1,end:l.length,rPr:c})}}else F(u,"commentReference")&&n.push({start:l.length,node:u,isCommentMarker:!0})}),l}function km(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!F(o,"r"))return;let a=Ke(o,B,"rPr");$e(o,B,"t").forEach(s=>{let l=s.textContent||"";l.length!==0&&(r.push({start:n.length,end:n.length+l.length,rPr:a,wrapper:e}),n+=l)})}),n}function sc(e,t,r,n,o,a,i=!0,s={}){let{paragraphs:l,containerFragments:c,sentinelMapByStart:u,referenceMap:f,replacementContainers:d,getParagraphInfo:m,getRunProperties:p,getPropertySpanLength:g,isParagraphStart:h}=r,y=_=>{let R=D(e,"w:p");if(_){let M=_.cloneNode(!0),U=Ke(M,B,"sectPr");U&&M.removeChild(U),R.appendChild(M)}return R},w=m(0),v=y(w.pPr),b=c.get(w.container);b&&b.appendChild(v);let x=0,T=0,I=s?.pairReplacements===!0,N=null,A=null,S=new WeakSet;for(let _=0;_<t.length;_++){let[R,M]=t[_];if(R===0||R===-1){let U=R===0?"equal":"delete";if(R===0)N=null,A=null;else if(N===null){N=x;let z=!1;for(let H=_+1;H<t.length;H++){if(t[H][0]===1){z=!0;break}if(t[H][0]===0)break}I&&i&&z&&(A=Bn(o,e))}let X=0;for(;X<M.length;){let z=x+X,H=p(z),se=g(z,M.length-X),ue=M.substring(X,X+se);v=ic(e,ue,U,H.rPr,H.wrapper,z,v,c,u,f,d,m,y,o,a,T,i,S,A).currentParagraph,R===0&&(T+=se),X+=se}x+=M.length;continue}if(R===1){let U=N!==null?N:x>0&&!h(x)?x-1:x,X=p(U);v=ic(e,M,"insert",X.rPr,X.wrapper,x,v,c,u,f,d,m,y,o,a,T,i,S,A,N!==null).currentParagraph,T+=M.length,N=null,A=null}}for(let _ of Array.from(u.keys()).sort((R,M)=>R-M))for(let R of u.get(_))if(!(!R.isCommentMarker||S.has(R.node)))if(S.add(R.node),F(R.node,"commentReference")){let M=D(e,"w:r");M.appendChild(R.node.cloneNode(!0)),v.appendChild(M)}else v.appendChild(R.node.cloneNode(!0));i&&c.forEach(_=>{Array.from(_.childNodes).forEach(R=>{if(F(R,"p")){let M=Array.from(R.getElementsByTagNameNS(B,"t")).length>0,U=Array.from(R.getElementsByTagNameNS(B,"delText")).length>0;l.length===1&&!M&&(U||r.originalFullText.trim()!=="")&&_r(e,R,o)}})}),c.forEach(_=>{let R=Array.from(_.childNodes).filter(M=>F(M,"p"));if(R.length>1){let M=R[0],U=R[R.length-1],X=Ke(M,B,"pPr"),z=X?Ke(X,B,"sectPr"):null;if(z){X.removeChild(z);let H=Ke(U,B,"pPr");H||(H=D(e,"w:pPr"),U.insertBefore(H,U.firstChild||null)),H.appendChild(z)}}});let O=new Set(l),E=new Map;l.forEach(_=>{let R=_.parentNode;if(!R||E.has(R))return;let M=_.nextSibling;for(;M&&O.has(M);)M=M.nextSibling;E.set(R,M)}),l.forEach(_=>{_.parentNode&&_.parentNode.removeChild(_)});let k=!1,C="";return c.forEach((_,R)=>{let M=d.get(R),U=M||R;if(U.nodeType===9){k=!0,_.childNodes.length===1?U.appendChild(_.firstChild):C=Array.from(_.childNodes).map(z=>n.serializeToString(z)).join("");return}let X=M?null:E.get(R);X&&X.parentNode===U?U.insertBefore(_,X):U.appendChild(_)}),{oxml:k&&C?C:n.serializeToString(e),hasChanges:!0}}function ic(e,t,r,n,o,a,i,s,l,c,u,f,d,m,p=[],g=0,h=!0,y=new WeakSet,w=null,v=!1){let b=a,x=g,T=i,I=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(A=>{let S=l.get(b)||[],O=S.filter(C=>C.isCommentMarker&&!y.has(C.node)),E=v?new Set(O.filter(C=>F(C.node,"commentRangeEnd")).map(C=>C.node.getAttributeNS?.(B,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id"))):new Set;if(O.forEach(C=>{y.add(C.node);let P=C.node.getAttributeNS?.(B,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id");if(v&&E.has(P)&&(F(C.node,"commentRangeEnd")||F(C.node,"commentReference"))){I.push(C.node);return}if(F(C.node,"commentReference")){let _=D(e,"w:r");_.appendChild(C.node.cloneNode(!0)),T.appendChild(_)}else T.appendChild(C.node.cloneNode(!0))}),A===`
160
- `){let C=f(b+1),P=d(C.pPr);h&&r==="insert"?Or(e,T,m):h&&r==="delete"&&_r(e,T,m);let _=s.get(C.container);_&&(_.appendChild(P),T=P),b++,r!=="delete"&&x++;return}if(A==="\uFFFC"){let C=S.find(P=>!P.isCommentMarker)||S[0];if(C){let P=C.node.cloneNode(!0);if(C.isTextBox&&C.originalContainer){let _=Ke(P,B,"txbxContent");if(_){for(;_.firstChild;)_.removeChild(_.firstChild);u.set(C.originalContainer,_)}}if(C.wrapInRun){let _=D(e,"w:r");C.rPr&&_.appendChild(C.rPr.cloneNode(!0)),_.appendChild(P),T.appendChild(_)}else T.appendChild(P)}b++,r!=="delete"&&x++;return}if(c.has(A)){if(r!=="delete"){let C=c.get(A);if(C){let P=C.cloneNode(!0),_=D(e,"w:r");n&&_.appendChild(n.cloneNode(!0)),_.appendChild(P),T.appendChild(_)}}b++,r!=="delete"&&x++;return}if(A.length===0)return;let k=T;if(o){let C=o.cloneNode(!1);k=C,T.appendChild(C)}if(r==="delete"){let C=D(e,"w:r");n&&C.appendChild(n.cloneNode(!0));let P=D(e,"w:delText");if(P.setAttribute("xml:space","preserve"),P.textContent=A,C.appendChild(P),h){let _=null;if(w){let M=w.usedDeletionId?ie(m,e,"del").id:w.deletionId;w.usedDeletionId=!0,_={id:M,author:w.author,date:w.date}}let R=Cr(e,"del",C,m,_);k.appendChild(R)}}else{let C=Xt(p,x,x+A.length),P=Do(e,A,n,C,x,m,h);if(r==="insert"&&h){let _=null;if(w){let M=w.usedInsertionId?ie(m,e,"ins").id:w.insertionId;w.usedInsertionId=!0,_={id:M,author:w.author,date:w.date}}let R=Cr(e,"ins",null,m,_);P.forEach(M=>R.appendChild(M)),k.appendChild(R)}else P.forEach(_=>k.appendChild(_))}r!=="delete"&&(x+=A.length),b+=A.length}),I.forEach(A=>{if(F(A,"commentReference")){let S=D(e,"w:r");S.appendChild(A.cloneNode(!0)),T.appendChild(S)}else T.appendChild(A.cloneNode(!0))}),{currentParagraph:T}}function bi(e,t,r,n,o,a,i=!0,s={},l={}){let c=Wo(e,t);if(c===null)return Ne({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=oc(e,r,c);if(u.paragraphs.length===0)return Ne({oxml:n.serializeToString(e),hasChanges:!1});let f=$n(u.originalFullText,u.processedModifiedText,{...s,atomicChars:new Set(u.referenceMap.keys())}),d=Dm(Mm(f,u.referenceMap),u);return Ne(sc(e,d,u,n,o,a,i,l))}function lc(e,t,r){let n=0;for(;n<e.length;){if(e[n][0]===0){t(e[n]),n++;continue}let o=[];for(;n<e.length&&e[n][0]!==0;)o.push(e[n++]);r(o,o.filter(([a])=>a===-1).map(([,a])=>a).join(""),o.filter(([a])=>a===1).map(([,a])=>a).join(""))}}function xi(e,t,r){if(t===r){t&&e.push([0,t]);return}t&&e.push([-1,t]),r&&e.push([1,r])}function Mm(e,t){if(t.size===0)return e;let r=[];return lc(e,n=>r.push(n),(n,o,a)=>{let i=[...o].filter(u=>t.has(u)&&a.includes(u)),s=[...a].filter(u=>i.includes(u));if(i.length===0||i.join("")!==s.join("")){r.push(...n);return}let l=0,c=0;for(let u of i){let f=o.indexOf(u,l),d=a.indexOf(u,c);xi(r,o.slice(l,f),a.slice(c,d)),r.push([0,u]),l=f+1,c=d+1}xi(r,o.slice(l),a.slice(c))}),r}function Lm(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}function Bm(e,t,r){let n=0;for(;n<r&&e[e.length-1-n]===t[t.length-1-n];)n++;return n}function Dm(e,t){let r=a=>t.getRunProperties(a).wrapper||null,n=[],o=0;return lc(e,a=>{n.push(a),o+=a[1].length},(a,i,s)=>{let l=o,c=l+i.length;o=c;let u=m=>m>l&&m<c&&r(m-1)!==r(m),f=0,d=0;if(i&&s){let m=Bm(i,s,Math.min(i.length,s.length));for(let g=m;g>0;g--)if(u(c-g)){d=g;break}let p=Math.min(Lm(i,s),Math.min(i.length,s.length)-d);for(let g=p;g>0;g--)if(u(l+g)){f=g;break}}if(f===0&&d===0){n.push(...a);return}f>0&&n.push([0,i.slice(0,f)]),xi(n,i.slice(f,i.length-d),s.slice(f,s.length-d)),d>0&&n.push([0,i.slice(i.length-d)])}),n}function Et(e,t){return Ne({oxml:e.serializeToString(t),hasChanges:!1})}function cc(e,t,r,n,o,a=!0){let i=$e(e,B,"tbl"),s=rt(t),l=s.rows.length>0||s.headers.length>0;if(i.length===0||!l)return Et(r,e);let c=i[0],u=ei(c),f=wl(u,s);if(f.length===0)return Et(r,e);let d={generateRedlines:a,author:o,revisionIdAllocator:Vt(e)},m=yl(u,f,d),p=`<root xmlns:w="${B}">${m}</root>`,g=W(p,"application/xml").doc;if(!g)return Et(r,e);let h=Ee(g);if(h)return Te("[OxmlEngine] Failed to parse reconciled table OOXML:",h.textContent),Et(r,e);let y=Ke(g,B,"tbl");if(!y)return Te("[OxmlEngine] No table found in reconciled OOXML"),Et(r,e);let w=e.importNode(y,!0);return c.parentNode.replaceChild(w,c),Ne({oxml:r.serializeToString(e),hasChanges:!0})}function uc(e,t,r,n,o,a){let i=Vt(e),s=rt(t);if(!s||s.rows.length===0&&s.headers.length===0)return V("[OxmlEngine] Failed to parse table data from Markdown"),Et(r,e);let l=Kt(s,{generateRedlines:a,author:o,revisionIdAllocator:i}),c=W(`<root xmlns:w="${B}">${l}</root>`,"application/xml").doc;if(!c)return Et(r,e);let u=Ee(c);if(u)return Te("[OxmlEngine] Failed to parse generated table OOXML:",u.textContent),Et(r,e);let f=Ae(c,B,"tbl");if(f||(f=Ae(c,B,"ins")),!f)return Te("[OxmlEngine] No table element found in generated OOXML"),Et(r,e);let d=e,m=_e(d,B,"p");if(m.length===0)return V("[OxmlEngine] No paragraphs found to replace"),Et(r,d);let p=m[0],g=p.parentNode;if(g&&g.nodeType===9){let y=W(`<w:document xmlns:w="${B}"><w:body/></w:document>`,"application/xml").doc;if(!y)return Et(r,d);let w=Ae(y,B,"body");m.forEach(v=>w.appendChild(y.importNode(v,!0))),d=y,cr(d,i),m=_e(d,B,"p"),p=m[0],g=p.parentNode}let h=d.importNode(f,!0);return a?m.forEach(y=>{_r(d,y,o),_e(y,B,"r").forEach(v=>{_e(v,B,"t").forEach(I=>{let N=I.textContent||"";if(N.trim()){let A=D(d,"w:delText");A.textContent=N,I.parentNode.replaceChild(A,I)}});let x=D(d,"w:del"),T=ie(o,d,"del");x.setAttribute("w:id",String(T.id)),x.setAttribute("w:author",T.author),x.setAttribute("w:date",T.date),v.parentNode.insertBefore(x,v),x.appendChild(v)})}):m.slice(1).forEach(y=>y.parentNode.removeChild(y)),g.insertBefore(h,p),a||g.removeChild(p),V("[OxmlEngine] Text-to-table transformation complete"),Ne({oxml:r.serializeToString(d),hasChanges:!0})}function Gt(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 jo(e){return typeof e=="string"?e.trim().toLowerCase():""}function Fm(e){return!!e&&e.nodeType===1}function vt(e,t){return Fm(e)&&e.namespaceURI===B&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function De(e,t){return Array.from(e.getElementsByTagNameNS(B,t))}function Ni(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=jo(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 ut(e,t){if(t.allAuthors)return!0;let r=jo(Gt(e,"author"));return!!r&&r===t.normalizedAuthor}function Ii(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=W(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let i=`<w:body xmlns:w="${B}">${r}</w:body>`,s=W(i,"application/xml");s.error||(o=s,n=!0)}let a=o.doc?Ee(o.doc):null;if(o.error||a){let i=o.error?.message||a?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${i}`,warnings:o.warnings,error:{code:"PARSE_ERROR",message:i}}}return{xmlDoc:o.doc,serializer:oe(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function ke(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Ko(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function fc(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function dc(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(`
161
- `)}function $m(e){let t=0,r=De(e,"ins");for(let n of r){if(!n.parentNode||Go(n))continue;let o=fc(n);for(;vt(o,"ins")&&jo(Gt(o,"author"))===jo(Gt(n,"author"))&&dc(o)===dc(n);){let a=fc(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=a}}return t}function Ho(e){let t=e?.parentNode;return vt(t,"trPr")&&vt(t?.parentNode,"tr")}function Go(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return vt(t,"rPr")&&vt(r,"pPr")&&vt(n,"p")}function gc(e){return Go(e)?e.parentNode.parentNode.parentNode:null}function Um(e){let t=e?.nextSibling||null;for(;t;){if(vt(t,"p"))return t;t=t.nextSibling}return null}function hc(e){if(!e?.parentNode)return!1;let t=Um(e);if(!t)return vt(e.parentNode,"tc")&&De(e.parentNode,"p").length<=1?!1:ke(e);let r=Array.from(e.childNodes||[]).filter(o=>!vt(o,"pPr")),n=t.firstChild||null;vt(n,"pPr")&&(n=n.nextSibling||null);for(let o of r)t.insertBefore(o,n);return ke(e)}function Br(e,t={}){let r=[],n=Ni(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=Ii(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let s=0;for(let u of De(a,"ins"))if(!(!u.parentNode||!ut(u,n))){if(Go(u)){ke(u)&&(s+=1);continue}if(Ho(u)){ke(u)&&(s+=1);continue}Ko(u)&&(s+=1)}for(let u of De(a,"del")){if(!u.parentNode||!ut(u,n))continue;let f=gc(u);if(f){hc(f)&&(s+=1);continue}if(Ho(u)){let d=u.parentNode?.parentNode;ke(d)&&(s+=1);continue}ke(u)&&(s+=1)}for(let u of De(a,"moveFrom"))!u.parentNode||!ut(u,n)||ke(u)&&(s+=1);for(let u of De(a,"moveTo"))!u.parentNode||!ut(u,n)||Ko(u)&&(s+=1);s+=wc(a,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of De(a,u))!f.parentNode||!ut(f,n)||ke(f)&&(s+=1);return{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(a),hasChanges:s>0,acceptedCount:s,warnings:r}}function mc(e,t){for(let r of Array.from(t.getElementsByTagNameNS(B,"delText"))){let n=D(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 zm(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!==B)return ke(e);let o=Array.from(e.childNodes||[]).find(i=>i.nodeType===1&&i.namespaceURI===B&&String(i.localName||"").toLowerCase()===n.toLowerCase());if(!o)return ke(e);let a=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let i of a){let s=Xm(r.ownerDocument,i);r.appendChild(s)}return!0}function Xm(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function pc(e,t,r){let n=new Set;for(let o of De(e,t)){if(!ut(o,r))continue;let a=Gt(o,"id");a&&n.add(a)}return n}function wc(e,t){let r=0,n=pc(e,"moveFromRangeStart",t),o=pc(e,"moveToRangeStart",t),a=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",o,!0],["moveToRangeEnd",o,!1]];for(let[i,s,l]of a)for(let c of De(e,i)){if(!c.parentNode)continue;let u=Gt(c,"id");u&&(t.allAuthors||s.has(u)||l&&ut(c,t))&&ke(c)&&(r+=1)}return r}function yr(e,t={}){let r=[],n=Ni(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=Ii(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let s=0;for(let u of De(a,"ins")){if(!u.parentNode||!ut(u,n))continue;let f=gc(u);if(f){hc(f)&&(s+=1);continue}if(Ho(u)){let d=u.parentNode?.parentNode;ke(d)&&(s+=1);continue}ke(u)&&(s+=1)}for(let u of De(a,"tbl")){if(!u.parentNode)continue;!Array.from(u.childNodes||[]).some(d=>vt(d,"tr"))&&ke(u)&&(s+=1)}for(let u of De(a,"del"))if(!(!u.parentNode||!ut(u,n))){if(Go(u)){ke(u)&&(s+=1);continue}if(Ho(u)){ke(u)&&(s+=1);continue}mc(a,u),Ko(u)&&(s+=1)}for(let u of De(a,"moveFrom"))!u.parentNode||!ut(u,n)||(mc(a,u),Ko(u)&&(s+=1));for(let u of De(a,"moveTo"))!u.parentNode||!ut(u,n)||ke(u)&&(s+=1);s+=wc(a,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of De(a,u))!f.parentNode||!ut(f,n)||zm(f,u)&&(s+=1);return $m(a),{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(a),hasChanges:s>0,rejectedCount:s,warnings:r}}function Vm(e,t){let r=new Set,n=De(e,"comment");for(let o of n){if(!ut(o,t))continue;let a=Gt(o,"id");a&&r.add(a)}return{targetIds:r,commentNodes:n}}function Wm(e,t){let r=0;for(let n of e){let o=Gt(n,"id");!o||!t.has(o)||ke(n)&&(r+=1)}return r}function jm(e){return vt(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!==B)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function Km(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let o of n)for(let a of De(e,o)){if(!a.parentNode)continue;let i=Gt(a,"id");if(!(!i||!t.has(i))){if(o==="commentReference"&&jm(a.parentNode)){ke(a.parentNode)&&(r+=1);continue}ke(a)&&(r+=1)}}return r}function Ti(e,t={}){let r=[],n=Ni(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=Ii(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let{targetIds:s,commentNodes:l}=Vm(a,n);if(n.allAuthors)for(let f of["commentRangeStart","commentRangeEnd","commentReference"])for(let d of De(a,f)){let m=Gt(d,"id");m&&s.add(m)}let c=Wm(l,s),u=Km(a,s);return{oxml:i.serializeToString(a),hasChanges:c>0||u>0,commentsRemoved:c,referencesRemoved:u,warnings:r}}var Hm=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 qt(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:Hm[t]||null,...r}))}var Gm=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function ze(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Hn(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function Dr(e,t){return Hn(e).find(r=>ze(r)===t)||null}function qo(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Yo(e){return String(e||"").trim().toLowerCase()}function qm(e){return ze(e)!=="r"?!1:Hn(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(ze(t)))}function Si(e){return Gm.has(ze(e))||qm(e)}function Ai(e){return ze(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(ze(e))?Hn(e).filter(r=>!Si(r)&&ze(r)!=="sdtPr").every(Ai):!1}function Ym(e){let t=e?.ownerDocument?.documentElement||null;if(!t)return!1;let r=new Set;for(let n of[t,...Array.from(t.getElementsByTagName?.("*")||[])]){if(n===e&&r.size>0)return!0;let o=ze(n),a=qo(n,"id");o==="moveFromRangeStart"&&a!==""&&r.add(a),o==="moveFromRangeEnd"&&a!==""&&r.delete(a)}return!1}function yc(e){let t=Dr(e,"pPr"),r=Dr(t,"rPr");return Dr(r,"del")}function Zm(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=ze(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,o=!1;for(;n&&n!==e;){let a=ze(n);if(a==="del"||a==="moveFrom"){o=!0;break}n=n.parentNode}if(!o&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function vr(e,t){let r=yc(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=qo(r,"author")||null,o=!n||Yo(n)!==Yo(t),i=Hn(e).filter(s=>!Si(s)).every(Ai);return{matches:o&&i,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:i,ownerAuthor:n,markDeletion:r}}function Fr(e,t={}){let r=Dr(e,"pPr");if(Dr(r,"sectPr"))return{code:"SECTION_BREAK_PARAGRAPH",message:"Refusing to restore a deleted paragraph whose paragraph properties contain a section break."};let n=e?.parentNode||null;for(;n;){if(ze(n)==="moveFrom")return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};n=n.parentNode}if(Ym(e)||e?.getElementsByTagName?.("*")&&Array.from(e.getElementsByTagName("*")).some(i=>["moveFrom","moveFromRangeStart","moveFromRangeEnd"].includes(ze(i))))return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};let o=e?.parentNode||null;for(;o&&ze(o)!=="tr";)o=o.parentNode;let a=Dr(o,"trPr");if(a&&Dr(a,"del"))return{code:"UNSAFE_DELETED_TABLE_ROW",message:"Refusing to restore a paragraph inside a table row with a pending row deletion."};if(t.requireFollowingParagraph!==!1){let i=e?.nextSibling||null;for(;i&&(i.nodeType!==1||ze(i)!=="p");)i=i.nextSibling;if(!i)return{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Refusing to restore a deleted paragraph without a following paragraph in the same structural container."}}return null}function vc(e){let t=ze(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>ze(n)==="p"),r=[];for(let n of t){let o=yc(n);if(!o)continue;let a=qo(o,"author")||null,i=Hn(n).filter(c=>!Si(c)),s=i.filter(c=>ze(c)!=="ins"||!Zm(c)?!1:Yo(qo(c,"author"))!==Yo(a)),l=i.every(c=>Ai(c)||s.includes(c));s.length>0&&l&&r.push({paragraph:n,markDeletion:o,ownerAuthor:a,foreignInsertions:s})}return r}function Jm(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of $e(e,B,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 $r(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===B&&r.localName===t)||null}function Qm(e,t){let r=$r($r($r(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(B,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(B,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(B,"date")||""}}function ep(e,t){let r=e.cloneNode(!1),n=$r(e,"pPr");return n&&r.appendChild(ct(n)),t.serializeToString(r)}function tp(e,t){if(!t||typeof e!="string"||!e.trim())return e;let r=W(e,"text/xml");if(!r.doc||r.error)return e;let n=r.doc.documentElement?.localName==="p"?r.doc.documentElement:nt(r.doc)[0];if(!n)return e;let o=$r(n,"pPr");o||(o=D(r.doc,"w:pPr"),n.insertBefore(o,n.firstChild));let a=$r(o,"rPr");if(a||(a=D(r.doc,"w:rPr"),o.appendChild(a)),!$r(a,"ins")){let i=D(r.doc,"w:ins");t.id&&i.setAttribute("w:id",t.id),i.setAttribute("w:author",t.author),t.date&&i.setAttribute("w:date",t.date),a.appendChild(i)}return Se(r.doc)}async function Gn(e,t,r,n={}){let o=e,a=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let i=n.generateRedlines??!0,s=n.author||re(),l=oe(),c=[],u=[],f=!1,d=null,m=n.existingRevisions||"merge-same-author",p=m==="accept-all-first-keep-normalized",g=K=>{let L={...K};f&&L.hasChanges===!1&&L.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(L.oxml=a,L.hasChanges=!0,L.warnings=[...Array.isArray(L.warnings)?L.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(L.oxml=a,L.hasChanges=!0,L.warnings=[...Array.isArray(L.warnings)?L.warnings:[],"Existing revisions were accepted before redlining."]):L.oxml=o);let j=[...c,...u,...Array.isArray(L.warnings)?L.warnings:[]];return j.length>0&&(L.warnings=[...new Set(j)]),L.status||(L.status=L.hasChanges?"ok":"no-op"),d&&L.hasChanges&&typeof L.oxml=="string"&&(L.oxml=tp(L.oxml,d)),Ne(L)},h=()=>g(f&&p?{oxml:a,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),y=W(o,"text/xml");c=y.warnings;let w=y.doc,v=w?Ee(w):null;if(y.error||v){let K=y.error?.message||v?.textContent||"Could not parse OOXML input.";return Te("[OxmlEngine] XML parse error:",K),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:K}})}let b=n?._revisionIdAllocator instanceof Pe?n._revisionIdAllocator:new Pe;Wt(w,b);let x=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:nt(w);if(x.length===1&&r.length>0){let K=vr(x[0],s);if(K.matches){let L=K.ownerAuthor||"unattributed";return g({oxml:o,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${L}). Use explicit paragraph restoration when supported.`,ownerAuthor:L}})}}if(mr(w))if(m==="merge-same-author"||m==="slice-cross-author"){let K=Rr(w),L=String(s||"").trim().toLowerCase();if(K.length>0&&K.every(J=>J.trim().toLowerCase()===L)){let J=Jm(w);if(J.length>0)return g({oxml:o,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:J}});V("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let we=x.length===1?x[0]:null;d=Qm(we,s);let Ze=yr(o,{author:s});if(Ze.status==="error")return g(Ze);a=d&&!String(Ze.oxml||"").trim()?ep(we,l):Ze.oxml,f=!0;let Be=W(a,"text/xml");c.push(...Be.warnings),w=Be.doc;let Ut=w?Ee(w):null;if(Be.error||Ut){let So=Be.error?.message||Ut?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return Te("[OxmlEngine] XML parse error after rejecting same-author revisions:",So),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:So}})}if(mr(w))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});Wt(w,b);let zt=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:nt(w);t=zt.length>0?zt.map(So=>te(So)).join(`
162
- `):""}else{if(m==="merge-same-author")return V("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${K.length?K.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:K,currentPolicy:m}});if(["moveFrom","moveTo"].some(we=>$e(w,B,we).length>0))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});V("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(m==="accept-all-first"||m==="accept-all-first-keep-normalized"){V("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let K=Br(o,{allAuthors:!0});if(K.status==="error")return g(K);a=K.oxml,f=!0;let L=W(a,"text/xml");c.push(...L.warnings),w=L.doc;let j=w?Ee(w):null;if(L.error||j){let J=L.error?.message||j?.textContent||"Could not parse OOXML after accepting existing revisions.";return Te("[OxmlEngine] XML parse error after accepting existing revisions:",J),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:J}})}Wt(w,b)}else return V("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let T=Wl(w,t,n);if(T.hasTableWrapper&&T.targetParagraph&&!n._isolatedTableCell){V("[OxmlEngine] Isolating table-cell paragraph before diff");let K=Vn(w,T.targetParagraph,l),L=await Gn(K,t,r,{...n,_isolatedTableCell:!0});return!L.hasChanges&&L.status==="no-op"?h():L}let I=n.sanitizeInput===!0?Ei(r):r;I!==r&&u.push("Input was sanitized; pass sanitizeInput: false to disable.");let N=null;if(n.structuredContent!==!1&&n.literalTextEdit!==!0)if(N=Lo(I),N.valid)N.requiresStructuredContent&&(I=N.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let K=N.issues.map(L=>`${L.code}: ${L.message}`).join(" ");return g({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:K},warnings:N.issues.map(L=>L.message)})}N=null}let{cleanText:A,formatHints:S}=We(I),{existingFormatHints:O,textSpans:E,paragraphs:k}=kl(w),C=m==="slice-cross-author"?A!==t:A.trim()!==t.trim(),P=!C&&n.explicitStructuredContent===!0&&en(A)&&!rp(k,A),_=C||P,R=S.length>0,M=O.length>0,{textSpans:U}=Bo(k),X=U.map(K=>xc(K)).join(""),z=t.includes(`
163
- `)||t.includes("\r")?t.split(/\r?\n/).map(Zo).filter(Boolean).every(K=>k.some(L=>{let j=U.filter(J=>J.paragraph===L).map(xc).join("");return Zo(j).includes(K)})):X.includes(t.trim())||X.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||Zo(X).includes(Zo(t));if(_&&typeof t=="string"&&t.trim()&&!z)return V("[OxmlEngine] Target text not found in OOXML"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let H=null,se=()=>(H||(H=Fo(w,k,E)),H),ue=(K=null)=>{let L=Vl(w,t,S,l,s,i,K);return L.useNativeApi?(V("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),bi(w,t,A,l,s,S,i)):L};V(`[OxmlEngine] Text changes: ${_}, New format hints: ${S.length}, Existing format hints: ${O.length}`);let Y=n.removeFormatting===!0&&!_&&!R&&M;if(!_&&!R&&!M)return qt(n,"noChange"),V("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),h();if(!_&&!R&&M&&!Y)return V("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),h();if(Y){qt(n,"formatOnly",{removeFormatting:!0}),V("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let K=T,L=K.targetParagraph||null;if(!L){let we=Fl(se(),t);we&&(L=we.paragraph)}let j=O;L&&(j=O.filter(we=>Ul(we.run)===L));let J=Xl(w,E,j,l,s,i);return K.hasTableWrapper&&L?g({oxml:Vn(w,L,l),hasChanges:J.hasChanges}):g(J)}if(!_&&R){qt(n,"formatOnly",{removeFormatting:!1}),V(`[OxmlEngine] Format-only change detected: ${S.length} format hints`);let K=T,L={textSpans:E,paragraphs:k,paragraphInfos:se()};if(K.hasTableWrapper&&K.targetParagraph){V("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let j=ue(L);return V("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),g({oxml:Vn(w,K.targetParagraph,l),hasChanges:j.hasChanges})}return g(ue(L))}let ee=$e(w,B,"tbl").length>0,xe=/^\|.+\|/.test(A.trim())&&A.includes(`
164
- `),me=n.literalTextEdit!==!0&&en(A),pe=n.structuredContent!==!1&&N?.requiresStructuredContent===!0,be=T,Tt=ee||m==="slice-cross-author";V(`[OxmlEngine] Mode: ${Tt?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${S.length}, isMarkdownTable: ${xe}, isTargetList: ${me}, isTableCellParagraph: ${be.isTableCellParagraph}`);try{if(xe&&!ee)return qt(n,"table",{transformation:"text-to-table"}),V("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),g(uc(w,A,l,null,s,i));if(ee&&xe)return qt(n,"table",{transformation:"table-reconciliation"}),g(cc(w,A,l,null,s,i));if(Tt){qt(n,"surgical",{tableScoped:ee});let K=be.hasTableWrapper&&be.targetParagraph?be.targetParagraph:null;K&&V("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let L=Ql(w,t,A,l,s,S,i,K,{},n);return L.status==="error"&&L.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?g({...L,oxml:o,hasChanges:!1}):be.hasTableWrapper&&L.hasChanges&&be.targetParagraph?(V("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),g({oxml:Vn(w,be.targetParagraph,l),hasChanges:!0})):g(L)}if(me||pe){let K=$e(w,B,"p"),L=K.length===1;qt(n,L?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:K.length}),V(`[OxmlEngine] \u{1F3AF} Using ${L?"direct list generation":"compatibility pipeline"} for list reconciliation`);let j;if(L){let J=on(a,{xmlDoc:w}),we=Fn(K[0]);j=await sn({cleanText:A,numberingContext:we,originalRunModel:J.runModel,originalText:J.acceptedText,generateRedlines:i,author:s,font:n.font||null,revisionIdAllocator:b,numberingService:new jt})}else j=await new Un({author:s,generateRedlines:i,revisionIdAllocator:b}).execute(a,I,{xmlDoc:w});if(j.error?.code==="DIFF_TOKEN_LIMIT")return g({oxml:o,hasChanges:!1,status:"error",error:j.error});if(j.isValid&&j.ooxml&&j.ooxml!==a){let J=j.includeNumbering===!0;V(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${J}`);let we=dr(j.ooxml,{includeNumbering:J,numberingXml:j.numberingXml});return V(`[OxmlEngine] \u2705 Wrapped OOXML length: ${we.length}`),g({oxml:we,hasChanges:!0,...Array.isArray(j.warnings)?{warnings:j.warnings}:{}})}return h()}return qt(n,"reconstruction"),g(bi(w,t,A,l,s,S,i,{},n))}catch(K){if(rl(K))return g({oxml:o,hasChanges:!1,status:"error",error:{code:K.code,message:K.message}});throw K}}function rp(e,t){let r=String(t).split(/\r?\n/).filter(n=>n.trim()).length;return e.length===r&&e.every(n=>$e(n,B,"numPr").length>0)}function Zo(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function xc(e){let t=e?.textElement,r=String(t?.localName||t?.nodeName||"").replace(/^.*:/,"");return r==="tab"?" ":r==="br"||r==="cr"?`
165
- `:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function Ei(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 ft(e){return W(e,"application/xml").doc}function Yt(e){return Se(e)}function Jo(e){return Array.from(e||[])}function qn(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function Je(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 bc(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=Jo(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=Jo(e.getElementsByTagName(`w:${t}`));return r.length>0?r:Jo(e.getElementsByTagName(t))}function Ie(e){return e?te(e):""}function le(e){if(!e)return[];let t=bc(e,"body"),r=t.length>0?t[0]:e;return bc(r,"p")}function Xe(e){return e&&Jo(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function dt(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:te(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:le(e.ownerDocument||e).indexOf(e)+1,a=t.paragraphId===void 0?Xe(e):t.paragraphId,i=typeof t.inTable=="boolean"?t.inTable:Zn(e),l=`${a||""}${o}${i?"table":"body"}${r==="rejected"?"rejected":""}${n}`,c=2166136261;for(let u=0;u<l.length;u++)c^=l.charCodeAt(u),c=Math.imul(c,16777619)>>>0;return`fnv1a32:${c.toString(16).padStart(8,"0")}`}function Dt(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=le(e),o=[],a=new Map,i=new Map,s=new Map;for(let l=0;l<n.length;l++){let c=n[l],u=te(c,{revisionView:r}),f=Xe(c),d=Zn(c),m=q(u),p=Object.freeze({paragraph:c,index:l+1,paragraphId:f,text:u,normalizedText:m,revisionView:r,fingerprint:dt(c,{text:u,index:l+1,paragraphId:f,inTable:d,revisionView:r}),inTable:d});o.push(p),a.set(c,p),f&&!i.has(f)&&i.set(f,p),m&&(s.has(m)||s.set(m,[]),s.get(m).push(p))}for(let[l,c]of s)s.set(l,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:a,byId:i,byNormalizedText:s})}function q(e){return String(e||"").replace(/\s+/g," ").trim()}function Ur(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
166
- `)}function Pi(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 np(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function op(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 Nc(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:le(e)[t-1]||null}function He(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 Qo(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,a=o?null:le(e),i=String(t||"").trim();if(!i)return null;let s=o?o.find(c=>c.text.trim()===i)?.paragraph:a.find(c=>Ie(c).trim()===i);if(s)return s;let l=q(i);return n?.byNormalizedText?n.byNormalizedText.get(l)?.[0]?.paragraph||null:a.find(c=>q(Ie(c))===l)||null}function Ri(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,a=o?.entries||null,i=a?null:le(e),s=String(t||"").trim();if(!s)return null;let l=Qo(e,s,{paragraphMetadataIndex:o});if(l)return l;let c=q(s),u=a?a.find(h=>h.normalizedText.length>10&&c.startsWith(h.normalizedText))?.paragraph||null:i.find(h=>{let y=q(Ie(h));return y.length>10&&c.startsWith(y)});if(u)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${Ie(u).trim().slice(0,60)}..."`),u;let f=a?a.find(h=>h.normalizedText.length>15&&c.includes(h.normalizedText))?.paragraph||null:i.find(h=>{let y=q(Ie(h));return y.length>15&&c.includes(y)});if(f)return n(`[Fuzzy] Contains match: "${Ie(f).trim().slice(0,60)}..."`),f;let d=0,m=null,p=new Set(c.toLowerCase().split(/\s+/).filter(h=>h.length>2)),g=a?.length??i.length;for(let h=0;h<g;h++){let y=a?.[h]?.paragraph??i[h],w=(a?.[h]?.text??Ie(y)).trim();if(!w)continue;let x=q(w).toLowerCase().split(/\s+/).filter(T=>T.length>2).filter(T=>p.has(T)).length/Math.max(p.size,1);x>d&&x>.5&&(d=x,m=y)}return m?(n(`[Fuzzy] Best word-overlap match (${(d*100).toFixed(0)}%): "${Ie(m).trim().slice(0,60)}..."`),m):null}function zr(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},o=t.opType||"operation",a=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,i=a?.revisionView==="rejected"?"rejected":"accepted",s=String(a?.exactText??a?.text??t.targetText??"").trim(),l=Pi(a?.index??a?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,u=t.paragraphMetadataIndex||null;if(u&&u.revisionView!==i?u=t.metadataIndices?.[i]||Dt(e,{revisionView:i}):u||(u=Dt(e,{revisionView:i})),a?.paragraphId){let d=ip(e,a.paragraphId,u);if(!d)throw Je("TARGET_NOT_FOUND",`Target paragraphId not found: "${a.paragraphId}".`);let m=u?.byParagraph?.get(d)||null,p=m?.index??le(e).indexOf(d)+1,g=m?.fingerprint||dt(d,{revisionView:i}),h=m?.inTable??Zn(d),y=m?.normalizedText||q(te(d,{revisionView:i}));if(l!=null&&l!==p)throw Je("TARGET_INDEX_MISMATCH",`Target paragraphId "${a.paragraphId}" (index ${p}) does not match requested index ${l}.`,m?[Rt(m)]:null);if(a.fingerprint&&a.fingerprint!==g){let w=i==="rejected"?"accepted":"rejected",v=dt(d,{revisionView:w}),b=a.fingerprint===v?` The supplied fingerprint matches the ${w} view; set target.revisionView to "${w}" or use a fingerprint extracted from the ${i} view.`:"";throw Je("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches its source fingerprint.${b}`,m?[Rt(m)]:null)}if(typeof a.inTable=="boolean"&&a.inTable!==h)throw Je("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" does not match the requested table context.`,m?[Rt(m)]:null);if(s&&y!==q(s)){let w=i==="rejected"?"accepted":"rejected",b=q(te(d,{revisionView:w}))===q(s)?` The supplied text matches the ${w} view; set target.revisionView to "${w}".`:"";throw Je("TARGET_TEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches the supplied text.${b}`,m?[Rt(m)]:null)}if(a.occurrence!=null){let v=ea(e,s||y,u),b=v.findIndex(x=>x.paragraph===d)+1;if(b===0||b!==a.occurrence)throw Je("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${a.paragraphId}" matches occurrence ${b}, not requested occurrence ${a.occurrence}.`,v.map(Rt))}return{paragraph:d,resolvedBy:"paragraph_id"}}if(a?.fingerprint&&!s&&!l){let d=(u?.entries||[]).filter(m=>m.fingerprint===a.fingerprint);if(typeof a.inTable=="boolean"&&(d=d.filter(m=>m.inTable===a.inTable)),d.length===1)return{paragraph:d[0].paragraph,resolvedBy:"fingerprint"};throw d.length>1?Je("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",d.map(Rt)):Je("TARGET_NOT_FOUND",`Target fingerprint not found: "${a.fingerprint}".`)}let f=[];if(s){let d=ea(e,s,u);if(f=ap(d,a),a?.fingerprint&&d.length>0&&f.length===0)throw Je("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",d.map(Rt));if(typeof a?.inTable=="boolean"&&d.length>0&&f.length===0)throw Je("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",d.map(Rt));if(a?.occurrence){let m=f[a.occurrence-1]||null;if(!m)throw Je("TARGET_NOT_FOUND",`Target occurrence ${a.occurrence} was not found.`,f.map(Rt));return{paragraph:m.paragraph,resolvedBy:"occurrence"}}if(c){if(l){let m=f.find(p=>p.index===l)||null;if(m)return{paragraph:m.paragraph,resolvedBy:"ref"};if(a?.fingerprint&&f.length>0)throw Je("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`,f.map(Rt));if(f.length===1)return{paragraph:f[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(f.length>1)throw Je("AMBIGUOUS_TARGET",`Target text matched ${f.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,f.map(Rt));if(f.length===0)throw qn(`Target paragraph not found: "${s}"`)}if(!l&&f.length===1)return{paragraph:f[0].paragraph,resolvedBy:a?.fingerprint?"fingerprint":"strict_text"}}if(l){let d=Nc(e,l,u);if(d){let m=u?.byParagraph?.get(d)||null;if(a?.fingerprint&&a.fingerprint!==m?.fingerprint)throw Je("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`);if(typeof a?.inTable=="boolean"&&a.inTable!==m?.inTable)throw Je("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${l}] does not match requested table context.`);if(s){let p=Qo(e,s,{paragraphMetadataIndex:u}),g=(m?.text||te(d,{revisionView:i})).trim(),h=q(g),y=q(s),w=h!==y;if(w&&p&&p!==d)return r(`[Target] [P${l}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let v=Ri(e,s,{onInfo:r,paragraphMetadataIndex:u});if(v&&v!==d)return r(`[Target] [P${l}] drifted for ${o}; using fuzzy text rematch.`),{paragraph:v,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${l}] fallback for ${o}; target text drifted.`)}else p&&p!==d&&r(`[Target] [P${l}] disambiguated duplicate target text for ${o}.`)}else r(`[Target] Using [P${l}] fallback for ${o}.`);return{paragraph:d,resolvedBy:"ref"}}n(`[WARN] Target reference [P${l}] not found; falling back to text matching for ${o}.`)}if(s&&!c){let d=Qo(e,s,{paragraphMetadataIndex:u});if(d){let p=f.length;if(p>1){let g=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(g),{paragraph:d,resolvedBy:"strict_text",warnings:[g]}}return{paragraph:d,resolvedBy:"strict_text"}}let m=Ri(e,s,{onInfo:r,paragraphMetadataIndex:u});if(m)return{paragraph:m,resolvedBy:"fuzzy_text"}}throw qn(s?`Target paragraph not found: "${s}"`:l?`Target paragraph reference not found: [P${l}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function Zn(e){return!!He(e,"tbl")}function ea(e,t,r=null){let n=q(t);if(!n)return[];let o=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,a=r?.revisionView||o?.revisionView||"accepted";if(o?.byNormalizedText&&o.revisionView===a)return Array.from(o.byNormalizedText.get(n)||[]);let i=le(e),s=[];for(let l=0;l<i.length;l++){let c=i[l],u=te(c,{revisionView:a}).trim();u&&q(u)===n&&s.push({paragraph:c,index:l+1,inTable:Zn(c),paragraphId:Xe(c),fingerprint:dt(c,{text:u,index:l+1,revisionView:a}),text:u,revisionView:a})}return s}function Rt(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function ap(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 ip(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:le(e).find(n=>Xe(n)===t)||null:null}function sp(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let o=n.filter(a=>a.inTable===r);o.length>0&&(n=o)}return Number.isInteger(t)&&t>0&&n.sort((o,a)=>Math.abs(o.index-t)-Math.abs(a.index-t)),n[0]||null}function Ci(e,t=null){let r=t?.entries||null,n=r?null:le(e),o=new Map,a=r?.length??n.length;for(let i=0;i<a;i++){let s=r?.[i]?.paragraph??n[i],l=(r?.[i]?.text??Ie(s)).trim();o.set(i+1,{text:l,normalizedText:r?.[i]?.normalizedText??q(l),inTable:r?.[i]?.inTable??Zn(s)})}return o}function Yn(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=zr(e,t),o=Pi(t.targetRef);if(!o||n?.resolvedBy!=="ref")return n;let a=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(o)||null;if(!a)return n;let i=String(t.targetText||"").trim(),s=i||a.text||"",l=q(s);if(!l||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||q(Ie(n.paragraph)))===l)return n;let u=[];if(i&&u.push(i),a.text){let d=q(a.text);d&&!u.some(m=>q(m)===d)&&u.push(a.text)}let f=null;for(let d of u){let m=ea(e,d,t.paragraphMetadataIndex||null),p=sp(m,o,a.inTable);if(p&&(f||(f=p),p.paragraph!==n.paragraph)){f=p;break}}if(f&&f.paragraph!==n.paragraph){let d=t.opType||"operation";return r(`[Target] [P${o}] appears stale after prior edits; using strict text rematch for ${d}.`),{paragraph:f.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw qn(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function fn(e,t,r,n={}){if(!e||!t||!r)return null;let o=n?.opType||"redline",a=n?.targetRefSnapshot||null,i=typeof n?.onInfo=="function"?n.onInfo:()=>{},s=typeof n?.onWarn=="function"?n.onWarn:()=>{},l=Yn(e,{targetRef:t,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:s})?.paragraph;if(!l)return null;let c=Yn(e,{targetRef:r,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:s})?.paragraph;if(!c)return null;let u=Array.from(e.getElementsByTagNameNS("*","p")),f=u.indexOf(l),d=u.indexOf(c);if(f<0||d<f)return null;let m=u.slice(f,d+1);if(m.length===0)return null;let p=m[0]?.parentNode||null;return!p||!m.every(g=>g&&g.parentNode===p)?null:m}function ta(e,t,r={}){if(!e||!e.parentNode)return{valid:!0};let n=t===""||r.operationKind==="delete",o=typeof t=="string"&&t.includes(`
167
- `),a=r.targetEndParagraph||null,i=He(e,"tc");if(i){if(n&&Array.from(i.childNodes).filter(c=>F(c,"p")).length<=1)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete the sole terminal paragraph of a table cell."};if(a&&He(a,"tc")!==i)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across different table cells."}}else if(a&&He(a,"tc"))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across table boundaries."};if(e.getElementsByTagNameNS(Oe,"sectPr").length>0&&n)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete paragraph containing section properties (w:sectPr)."};if(a){let l=e;for(;l&&l!==a;){if(F(l,"p")&&l.getElementsByTagNameNS(Oe,"sectPr").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across section break."};l=l.nextSibling}}if(o){if(e.getElementsByTagNameNS(Oe,"fldSimple").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph containing a simple field instruction (w:fldSimple)."};let c=Array.from(e.getElementsByTagNameNS(Oe,"fldChar"));if(c.length>0){let p=0;for(let g of c){let h=g.getAttributeNS(Oe,"fldCharType")||g.getAttribute("w:fldCharType");h==="begin"?p++:h==="end"&&(p=Math.max(0,p-1))}if(p>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph across an unclosed field instruction."}}let u=Array.from(e.getElementsByTagNameNS(Oe,"bookmarkStart")),f=Array.from(e.getElementsByTagNameNS(Oe,"bookmarkEnd")),d=new Set(u.map(p=>p.getAttributeNS(Oe,"id")||p.getAttribute("w:id"))),m=new Set(f.map(p=>p.getAttributeNS(Oe,"id")||p.getAttribute("w:id")));for(let p of d)if(p&&!m.has(p))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:`Refusing to split paragraph across open bookmark range (ID: ${p}).`}}return{valid:!0}}function ra(e,t){if(!e)return null;for(let r of Array.from(e.childNodes||[]))if(r?.nodeType===1&&r.localName===t)return r;return null}function Ic(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 Xr(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=_t(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function Sc(e){let t=String(e||"").split(/\r?\n/g),r=[],n=!1;for(let o of t){let a=o.trimEnd();if(!a.trim())continue;let i=Mn(a,{indentSpaces:2});if(i){n=!0,r.push({kind:"list",markerType:i.markerType,level:i.level,marker:i.marker,outlineLevel:i.outlineLevel,text:Xr(i.text)});continue}r.push({kind:"text",text:a.trim()})}return{items:r,hasListMarkers:n}}function Tc(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function Jn(e,t){return q(e)===q(t)}function na(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function lp(e,t,r){if(!Array.isArray(e)||e.length<2||!Number.isInteger(r)||r<0)return!1;let n=e[0],o=e.slice(1).filter(a=>a.kind==="list");if(o.length===0||o.some(a=>a.markerType!=="bullet")||o.some(a=>Number.isInteger(a.outlineLevel)))return!1;if(n?.kind==="text")return Jn(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let a=n.level||0;return o.some(s=>(s.level||0)>a)?!1:Jn(n.text,t)}return!1}function cp(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 up(e,t,r,n){let o=e[0],a=e.slice(1).filter(i=>i.kind==="list");if(o?.kind==="text"&&Jn(o.text,t)&&a.length>0){let i=a[0].level;return a.map(s=>({ilvl:na(s,r,i),markerType:s.markerType||n,text:s.text}))}if(e.every(i=>i.kind==="list")){let i=e[0];if(!i||!Jn(i.text,t))return null;let s=i.level;return e.slice(1).map(l=>({ilvl:na(l,r,s),markerType:l.markerType||n,text:l.text})).filter(l=>l.text)}return null}function mt(e){if(!e)return null;let t=ra(e,"pPr");if(!t)return null;let r=ra(t,"numPr");if(!r)return null;let n=ra(r,"numId");if(!n)return null;let o=Ic(n);if(!o||o==="0")return null;let a=ra(r,"ilvl"),i=Ic(a),s=Number.parseInt(i||"0",10);return{numId:String(o),ilvl:Number.isFinite(s)?s:0}}function Ac(e){let t=mt(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 a=o;for(;a>0;){let s=mt(n[a-1]);if(!s||s.numId!==t.numId)break;a--}let i=o;for(;i<n.length-1;){let s=mt(n[i+1]);if(!s||s.numId!==t.numId)break;i++}return n.slice(a,i+1)}function Oi(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
168
- `)||!mt(e))return null;let s=Ac(e);if(!s||s.length===0)return null;let l=Sc(a);if(!l.hasListMarkers||l.items.length<2)return null;let c=q(r.currentParagraphText||Ie(e)),f=l.items.filter(I=>I.kind==="list")[0]?.markerType||"bullet",d=s.map(I=>({paragraph:I,list:mt(I),text:String(Ie(I)||"").trim()})),m=s.indexOf(e);if(m<0)return null;let p=Math.min(...d.map(I=>I.list?.ilvl??0)),g=d.map(I=>Tc((I.list?.ilvl??0)-p,f,I.text)),h=null,y=l.items[0],w=l.items.slice(1).filter(I=>I.kind==="list");if(y?.kind==="text"&&Jn(y.text,c)&&w.length>0){let I=Math.max(0,(d[m].list?.ilvl??0)-p),N=w[0].level;h=[{level:I,markerType:f,text:d[m].text},...w.map(A=>({level:na(A,I,N),markerType:A.markerType||f,text:A.text}))]}else if(l.items.every(I=>I.kind==="list")){let I=Math.max(0,(d[m].list?.ilvl??0)-p),N=l.items[0].level;h=l.items.map(A=>({level:na(A,I,N),markerType:A.markerType||f,text:A.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let v=h.map(I=>Tc(I.level,I.markerType,I.text)),b=g.slice(0,m).concat(v).concat(g.slice(m+1)),x=g.join(`
169
- `),T=b.join(`
170
- `);return T===x?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:s,originalText:x,modifiedText:T})}function _i(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
171
- `))return null;let i=mt(e);if(!i)return null;let s=Sc(a);if(!s.hasListMarkers||s.items.length<2)return null;let l=q(r.currentParagraphText||Ie(e)),u=s.items.filter(m=>m.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,i.ilvl),d=up(s.items,l,f,u);return!d||d.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(lp(s.items,l,f)&&(d=cp(d,f),n("[List] Promoted bullet insertion to child depth for nested numbered-list intent.")),n("[List] Planned insertion-only list redline entries (no block rewrite)."),{targetParagraph:e,numId:i.numId,entries:d})}function Qn(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
172
- `),n=[];for(let i of r){if(!i.trim())continue;let s=Mn(i,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});if(s){n.push({type:s.markerType,level:s.level,text:s.text.trim(),marker:s.marker});continue}n.push({type:"text",level:0,text:i.trim()})}if(n.length===0)return null;let o=n.some(i=>i.type==="numbered"),a=n.some(i=>i.type==="bullet");return{type:o?"numbered":a?"bullet":"text",items:n}}function ki(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function fp(e,t,r){let n=new Map,o=[];for(let a of e){let i=Math.max(0,Number(a?.level)||0);for(let u of Array.from(n.keys()))u>i&&n.delete(u);let s=(n.get(i)||0)+1;n.set(i,s);let l=mp(s,t,r),c=" ".repeat(i*4);o.push(`${c}${l} ${a.text||""}`.trimEnd())}return o.join(`
173
- `)}function dp(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let o=String(n??""),a=o.match(/^(\s*)/),i=a?a[1].length:0,s=Math.floor(i/r),l=o.trim(),c=null,u=At(l,{allowZeroSpaceAfterMarker:!0});return u&&(c=u[2].trim()||null,l=_t(l,{allowZeroSpaceAfterMarker:!0})),{text:l.trim(),level:s,removedMarker:c}})}function mp(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${Ec(e,!1)}.`;case"upperAlpha":return`${Ec(e,!0)}.`;case"lowerRoman":return`${Rc(e,!1)}.`;case"upperRoman":return`${Rc(e,!0)}.`;default:return`${e}.`}}function Ec(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 Rc(e,t=!1){let r=Math.max(1,Number(e)||1),n=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],o="";for(let[a,i]of n)for(;r>=a;)o+=i,r-=a;return t?o:o.toLowerCase()}function oa(e){let t=String(e||"");if(!t.trim()||t.includes(`
174
- `))return null;let r=Qn(t);if(!r||!ki(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let o=String(n.marker||"").trim(),a=n.type==="numbered"?kn(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:a,startAt:pp(o,a),contentText:String(n.text||"").trim(),normalizedContent:q(String(n.text||""))}}function Mi(e){let t=oa(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function pp(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 aa(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let o=t?.explicitByNumberingKey;if(!(o instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let a=o.get(r)||null;return a&&a.numId!=null&&Number.isInteger(a.nextStartAt)&&a.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(a.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function ia(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 eo(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function dn(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 sa(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,o=t?.clearParagraphPropertyChanges!==!1,a=t?.removeListPropertyNode!==!1,i=(Array.isArray(e)?e:[]).filter(l=>l&&l.nodeType===1&&l.localName==="p"),s=0;for(let l of i){let c=l.ownerDocument;if(!c)continue;let u=dn(l,"pPr");if(u||(u=D(c,"w:pPr"),l.insertBefore(u,l.firstChild)),o){let p=dn(u,"pPrChange");p&&u.removeChild(p)}if(a){let p=dn(u,"listPr");p&&u.removeChild(p)}let f=dn(u,"numPr");f||(f=D(c,"w:numPr"),u.appendChild(f));let d=dn(f,"ilvl");d||(d=D(c,"w:ilvl"),f.appendChild(d)),d.setAttribute("w:val",String(n));let m=dn(f,"numId");m||(m=D(c,"w:numId"),f.appendChild(m)),m.setAttribute("w:val",String(r)),s++}return s}function Cc(e){let t=String(e||""),r=/xmlns:w\s*=/.test(t);return W(r?t:`<w:root xmlns:w="${B}">${t}</w:root>`,"application/xml").doc}function gp(e){let t=Cc(e);return!t||Ee(t)?null:le(t)[0]||null}function hp(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function wp(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function mn(e,t){let r=wp(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Pc(e,t){e.setAttribute("w:val",String(t))}function yp(e){let t=Cc(e);if(!t||Ee(t))return null;let n=le(t);for(let o of n){let a=Array.from(o.getElementsByTagNameNS("*","numId"));for(let i of a){let s=mn(i,["w:val","val"]);if(s!=null)return String(s)}}return null}function vp(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,a=oe(),i=W(e,"application/xml").doc;if(!i||Ee(i))return e;let c=Array.from(i.getElementsByTagNameNS("*","num")).find(p=>{let g=mn(p,["w:numId","numId"]);return g!=null&&String(g)===String(t)});if(!c)return e;let u=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=mn(u,["w:val","val"]),d=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>mn(p,["w:ilvl","ilvl"])===0)||null;d||(d=D(i,"w:lvlOverride"),d.setAttribute("w:ilvl","0"),c.appendChild(d));let m=Array.from(d.getElementsByTagNameNS("*","startOverride"))[0]||null;if(m||(m=D(i,"w:startOverride"),d.appendChild(m)),Pc(m,r),o&&f!=null){let g=Array.from(i.getElementsByTagNameNS("*","abstractNum")).find(h=>{let y=mn(h,["w:abstractNumId","abstractNumId"]);return y!=null&&y===f})||null;if(g){let h=Array.from(g.getElementsByTagNameNS("*","lvl")).find(w=>mn(w,["w:ilvl","ilvl"])===0)||null;h||(h=D(i,"w:lvl"),h.setAttribute("w:ilvl","0"),g.appendChild(h));let y=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;y||(y=D(i,"w:start"),h.insertBefore(y,h.firstChild)),Pc(y,r)}}return a.serializeToString(i)}function pn(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),o=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let a=gp(t);if(!a)return null;let i=mt(a);if(i&&!o)return null;let s=We(n).cleanText||n,l=oa(n)||oa(s);if(!l)return null;let c=oa(r),u=q(r)===q(s),f=!!c&&c.type===l.type&&c.normalizedContent===l.normalizedContent;return!u&&!f?null:{listInput:`${l.marker} ${l.contentText}`.trim(),numberingKey:`${l.type}:${l.numberingStyle}:single`,originalText:r,wasListParagraph:!!i,startAt:l.startAt}}async function gn(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 sn({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new jt}),a=o?.oxml||o?.ooxml||"",i=hp(a),s=yp(i),l=vp(o?.numberingXml||null,s,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=o?.isValid!==!1;return!i||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:i,numberingXml:l,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}function hn(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 wn(e,t,r=null){let n=Number.isInteger(e)&&e>0?e:1,o=t instanceof Set?t:new Set;for(;o.has(n);)n+=1;if(Number.isInteger(r)&&r>0&&n>r){for(let a=1;a<=r;a+=1)if(!o.has(a))return a}return n}function xr(e,t={}){let r=Number.isInteger(t?.minId)&&t.minId>0?t.minId:1,n=Number.isInteger(t?.maxPreferred)&&t.maxPreferred>=r?t.maxPreferred:32767,o=new Set,a=new Set;if(String(e||"").trim())try{let u=ft(e),f=Array.from(u.getElementsByTagNameNS("*","abstractNum")),d=Array.from(u.getElementsByTagNameNS("*","num"));for(let m of f){let p=hn(m,["w:abstractNumId","abstractNumId"]);p!=null&&a.add(p)}for(let m of d){let p=hn(m,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let i=o.size>0?Math.max(...o):0,s=a.size>0?Math.max(...a):0,l=Math.max(r,i+1),c=Math.max(r,s+1);return{sourceNumberingXml:String(e||""),nextNumId:wn(l,o,n),nextAbstractNumId:wn(c,a,n),usedNumIds:o,usedAbstractNumIds:a,minId:r,maxPreferred:n}}function xp(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=wn(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=wn(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function to(e,t="num"){let r=xp(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=wn(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=wn(o+1,r.usedNumIds,r.maxPreferred)),o)}function ca(e){let t=to(e,"num"),r=to(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function ro(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function Vr(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Oe&&e.localName===t)}function Oc(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(a=>a&&a.nodeType===1&&a.namespaceURI===Oe),o=null;r==="abstract"?o=n.find(a=>a.localName==="num"||a.localName==="numIdMacAtCleanup")||null:o=n.find(a=>a.localName==="numIdMacAtCleanup")||null,o?e.insertBefore(t,o):e.appendChild(t)}function bp(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function xt(e,t){let r=bp(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function _c(e,t,r){e?.setAttribute?.(t,String(r))}function la(e,t){e?.setAttribute?.("w:val",String(t))}function ua(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)la(o,t)}}function fa(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let o=xt(n,["w:val","val"]);if(o!=null)return String(o)}}return null}function da(e,t,r){let n=String(e),o=String(t),a=Number.isInteger(r)&&r>0?r:1,i=Array.from({length:9},(s,l)=>{let c=Array.from({length:l+1},(f,d)=>`%${d+1}`).join(".")+".",u=720*(l+1);return`
175
- <w:lvl w:ilvl="${l}">
146
+ `);return{valid:o.every(s=>s.severity!=="error"),normalizedMarkdown:l,blocks:n,issues:o,counts:i,requiresStructuredContent:n.length>1||n.some(s=>s.type==="heading"||s.type==="table"||s.type==="list"&&s.items>1)}}function Zg(e,t,r={}){let n=Ea(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 Oo=["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 tt(e,t){let r=Oo.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=Oo.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function Qg(e,t,r,n){if(!t||!r)return;let o=!!r.bold,a=!!r.italic,i=!!r.underline,l=!!r.strikethrough,s=new Set;if(o&&(s.add("w:b"),s.add("w:bCs")),a&&(s.add("w:i"),s.add("w:iCs")),i&&s.add("w:u"),l&&s.add("w:strike"),s.size>0){let c=[];for(let f of Array.from(t.childNodes))s.has(f.nodeName)&&c.push(f);for(let f of c)t.removeChild(f)}if(o){let c=F(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),tt(t,c);let f=F(e,"w:bCs");f.setAttribute("w:val",n==="add"?"1":"0"),tt(t,f)}if(a){let c=F(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),tt(t,c);let f=F(e,"w:iCs");f.setAttribute("w:val",n==="add"?"1":"0"),tt(t,f)}if(i){let c=F(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),tt(t,c)}if(l){let c=F(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),tt(t,c)}}function vu(e,t,r){Qg(e,t,r,"remove")}function Qt(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=en(r,!1)),r.nodeName==="w:i"&&(t.italic=en(r,!1)),r.nodeName==="w:u"&&(t.underline=en(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=en(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 en(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 wu=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"];function pr(e,t){let r=wu.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=wu.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function yu(e,t){if(!t)return!1;let r=Qt(e);if(t.bold!==void 0&&r.bold!==!!t.bold||t.italic!==void 0&&r.italic!==!!t.italic||t.underline!==void 0&&r.underline!==!!t.underline)return!0;let n=t.strike!==void 0?t.strike:t.strikethrough;if(n!==void 0&&r.strikethrough!==!!n)return!0;if(t.highlight!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:highlight"||l.localName==="highlight")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.highlight&&t.highlight!=="none"?String(t.highlight).toLowerCase():null;if((a||null)!==i)return!0}if(t.color!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:color"||l.localName==="color")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.color&&t.color!=="auto"?String(t.color).replace(/^#/,"").toUpperCase():null;if((a?.toUpperCase()||null)!==i)return!0}if(t.fontSize!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:sz"||l.localName==="sz")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.fontSize!==null&&t.fontSize!==""?String(t.fontSize):null;if(a!==i)return!0}if(t.fontFamily!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:rFonts"||l.localName==="rFonts")),a=o?o.getAttribute("w:ascii")||o.getAttribute("ascii"):null,i=t.fontFamily||null;if(a!==i)return!0}return!1}function bu(e,t,r){if(!t||!r)return;let n=a=>{let i=[];for(let l of Array.from(t.childNodes))l.nodeType===1&&a.includes(l.nodeName)&&i.push(l);for(let l of i)t.removeChild(l)};if(r.bold!==void 0){n(["w:b","w:bCs"]);let a=F(e,"w:b");a.setAttribute("w:val",r.bold?"1":"0"),tt(t,a);let i=F(e,"w:bCs");i.setAttribute("w:val",r.bold?"1":"0"),tt(t,i)}if(r.italic!==void 0){n(["w:i","w:iCs"]);let a=F(e,"w:i");a.setAttribute("w:val",r.italic?"1":"0"),tt(t,a);let i=F(e,"w:iCs");i.setAttribute("w:val",r.italic?"1":"0"),tt(t,i)}if(r.underline!==void 0){n(["w:u"]);let a=F(e,"w:u");a.setAttribute("w:val",r.underline?"single":"none"),tt(t,a)}let o=r.strike!==void 0?r.strike:r.strikethrough;if(o!==void 0){n(["w:strike","w:dstrike"]);let a=F(e,"w:strike");a.setAttribute("w:val",o?"1":"0"),tt(t,a)}if(r.highlight!==void 0&&(n(["w:highlight"]),r.highlight&&r.highlight!=="none")){let a=F(e,"w:highlight");a.setAttribute("w:val",String(r.highlight).toLowerCase()),tt(t,a)}if(r.color!==void 0&&(n(["w:color"]),r.color&&r.color!=="auto")){let a=F(e,"w:color");a.setAttribute("w:val",String(r.color).replace(/^#/,"")),tt(t,a)}if(r.fontSize!==void 0&&(n(["w:sz","w:szCs"]),r.fontSize!==null&&r.fontSize!=="")){let a=String(r.fontSize),i=F(e,"w:sz");i.setAttribute("w:val",a),tt(t,i);let l=F(e,"w:szCs");l.setAttribute("w:val",a),tt(t,l)}if(r.fontFamily!==void 0&&(n(["w:rFonts"]),r.fontFamily)){let a=F(e,"w:rFonts");a.setAttribute("w:ascii",r.fontFamily),a.setAttribute("w:hAnsi",r.fontFamily),a.setAttribute("w:cs",r.fontFamily),tt(t,a)}}function xu(e,t){if(!t)return!1;if(t.alignment!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:jc"||o.localName==="jc"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.alignment)return!0}if(t.keepNext!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepNext"||o.localName==="keepNext"));if((r?en(r,!1):!1)!==!!t.keepNext)return!0}if(t.keepLines!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepLines"||o.localName==="keepLines"));if((r?en(r,!1):!1)!==!!t.keepLines)return!0}if(t.pageBreakBefore!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pageBreakBefore"||o.localName==="pageBreakBefore"));if((r?en(r,!1):!1)!==!!t.pageBreakBefore)return!0}if(t.style!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pStyle"||o.localName==="pStyle"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.style)return!0}if(t.numbering!==void 0){let r=eh(e),n=t.numbering;if(n===null)return r!=null;if(!r||r.numId!==String(Number(n.numId))||r.level!==(Number(n.level)||0))return!0}return!1}function eh(e){let t=et(e,"numPr");if(!t)return null;let r=n=>{let o=et(t,n);return o?o.getAttribute("w:val")??o.getAttribute("val"):null};return{numId:String(Number(r("numId"))),level:Number(r("ilvl"))||0}}function Kn(e,t,r){if(!t||!r)return;let n=o=>{let a=[];for(let i of Array.from(t.childNodes))i.nodeType===1&&o.includes(i.nodeName)&&a.push(i);for(let i of a)t.removeChild(i)};if(r.alignment!==void 0&&(n(["w:jc"]),r.alignment)){let o=F(e,"w:jc");o.setAttribute("w:val",r.alignment),pr(t,o)}if(r.keepNext!==void 0){n(["w:keepNext"]);let o=F(e,"w:keepNext");r.keepNext||o.setAttribute("w:val","0"),pr(t,o)}if(r.keepLines!==void 0){n(["w:keepLines"]);let o=F(e,"w:keepLines");r.keepLines||o.setAttribute("w:val","0"),pr(t,o)}if(r.pageBreakBefore!==void 0){n(["w:pageBreakBefore"]);let o=F(e,"w:pageBreakBefore");r.pageBreakBefore||o.setAttribute("w:val","0"),pr(t,o)}if(r.style!==void 0&&(n(["w:pStyle"]),r.style)){let o=F(e,"w:pStyle");o.setAttribute("w:val",r.style),pr(t,o)}if(r.numbering!==void 0&&(n(["w:numPr"]),r.numbering)){let o=F(e,"w:numPr"),a=F(e,"w:ilvl");a.setAttribute("w:val",String(Number(r.numbering.level)||0));let i=F(e,"w:numId");i.setAttribute("w:val",String(Number(r.numbering.numId))),o.appendChild(a),o.appendChild(i),pr(t,o)}}var Iu="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function er(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Iu&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function th(e){return!e||e.nodeType!==1||e.namespaceURI!==Iu?!1:e.localName==="del"||e.localName==="moveFrom"}function Nu(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||th(n))continue;if(er(n,"r")){t.push(n);continue}let o=Array.from(n.childNodes||[]);for(let a=o.length-1;a>=0;a-=1)r.push(o[a])}return t}function xt(e){let t=new Set(["comment","footnote","endnote"]);return We(e,"*","p").filter(n=>{let o=n.parentNode;for(;o&&o.nodeName;){let a=String(o.localName||"").toLowerCase();if(t.has(a))return!1;o=o.parentNode}return!0})}function Ra(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],a=Nu(o);for(let i of a){let l=Ue(i,"w:rPr");Array.from(i.childNodes||[]).forEach(s=>{if(er(s,"t")){let c=s.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:s,runElement:i,paragraph:o,container:i.parentNode,rPr:l}),r+=c.length)}else(er(s,"br")||er(s,"cr")||er(s,"tab")||er(s,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:s,runElement:i,paragraph:o,container:i.parentNode,rPr:l}),r+=1)})}r=Yr(r,n,e.length)}return{textSpans:t,charOffset:r}}function rh(e,t,r,n,o,a=null){let i=null;for(let c of Array.from(e.childNodes))if(er(c,"rPr")){i=c;break}let l=Qt(i);a&&(a.bold&&!l.bold&&(l.bold=!0),a.italic&&!l.italic&&(l.italic=!0),a.underline&&!l.underline&&(l.underline=!0),a.strikethrough&&!l.strikethrough&&(l.strikethrough=!0)),l.hasFormatting=l.bold||l.italic||l.underline||l.strikethrough;let s=r;for(let c of Array.from(e.childNodes))if(er(c,"t")){let f=c.textContent||"";if(f.length>0){let u=s,d=s+f.length;n.push({charStart:u,charEnd:d,textElement:c,runElement:e,paragraph:t,rPr:i,format:{...l}}),l.hasFormatting&&o.push({start:u,end:d,format:{...l},run:e,rPr:i}),s=d}}return s}function Tu(e){let t=[],r=[],n=0,o=xt(e);for(let a=0;a<o.length;a++){let i=o[a],l=null;for(let f of Array.from(i.childNodes))if(er(f,"pPr")){for(let u of Array.from(f.childNodes))if(er(u,"rPr")){l=u;break}break}let s=Qt(l);s.hasFormatting&&W(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(s)}`);let c=Nu(i);for(let f of c)n=rh(f,i,n,r,t,s);n=Yr(n,a,o.length)}return W(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var nh=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function gt(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())nh.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function Ft(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof De?t:lr(r)||_r(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let a of o){if(!$(a,"rPrChange"))continue;let i=String(n.next());typeof a.setAttributeNS=="function"?a.setAttributeNS(B,"w:id",i):a.setAttribute("w:id",i),n._receiptCollector?.recordRevision(Number(i),"rPrChange")}return e}function tr(e,t,r,n,o=null){let a=F(e,t==="ins"?"w:ins":"w:del"),i=o||ue(n,e,t==="ins"?"ins":"del");return a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",i.date),r&&a.appendChild(r),a}function Br(e,t,r,n){let o=F(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Su(e,o,t),o;let a=F(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Pa(e,t,r,n,o,a,i){if(!t)return[];let l=new Set([0,t.length]);for(let f of n){let u=Math.max(0,f.start-o),d=Math.min(t.length,f.end-o);u>=0&&u<t.length&&l.add(u),d>0&&d<=t.length&&l.add(d)}let s=Array.from(l).sort((f,u)=>f-u),c=[];for(let f=0;f<s.length-1;f++){let u=s[f],d=s[f+1],m=t.slice(u,d);if(!m)continue;let p=o+u,g=o+d,h=n.filter(y=>y.start<=p&&y.end>=g),v={...Qt(r)};h.forEach(y=>{y.format&&Object.assign(v,y.format)});let w=h.length>0?Gn(e,r,v,a,i):r?.cloneNode(!0)||null;c.push(hs(e,m,w,!1))}return c}function hs(e,t,r,n){let o=F(e,"w:r");if(r&&o.appendChild(r),!n)return Su(e,o,t),o;let a=F(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Su(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let a of o){if(!a)continue;if(a===" "){t.appendChild(F(e,"w:tab"));continue}if(a===`
147
+ `){t.appendChild(F(e,"w:br"));continue}if(a==="\u2011"){t.appendChild(F(e,"w:noBreakHyphen"));continue}let i=F(e,"w:t");/^\s|\s$/.test(a)&&i.setAttribute("xml:space","preserve"),i.textContent=a,t.appendChild(i)}}function Gn(e,t,r,n,o){let a=F(e,"w:rPr");t&&Array.from(t.childNodes).forEach(s=>{["w:b","w:bCs","w:i","w:iCs","w:u","w:strike","w:rPrChange"].includes(s.nodeName)||a.appendChild(s.cloneNode(!0))});let i=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&o&&oh(e,a,n,t);let l=(s,c,f=null,u="0")=>{let d=F(e,s);c?f&&d.setAttribute("w:val",f):u&&d.setAttribute("w:val",u);let m=Oo.indexOf(s),p=m===-1?999:m,g=!1;for(let h of Array.from(a.childNodes)){if(h.nodeType!==1)continue;let v=Oo.indexOf(h.nodeName);if((v===-1?999:v)>p){a.insertBefore(d,h),g=!0;break}}g||a.appendChild(d)};return l("w:b",!!i.bold,"1","0"),l("w:bCs",!!i.bold,"1","0"),l("w:i",!!i.italic,"1","0"),l("w:iCs",!!i.italic,"1","0"),l("w:u",!!i.underline,"single","none"),l("w:strike",!!i.strikethrough,"1","0"),a}function ko(e,t,r,n,o){let a=F(e,"w:rPrChange"),i=ue(r,e,"rPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let s=gt(o||t)||F(e,"w:rPr");a.appendChild(s);let c=Ue(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(a),a}function oh(e,t,r,n){ko(e,t,r,null,n||t)}function Hn(e,t,r,n,o){let a=F(e,"w:pPrChange"),i=ue(r,e,"pPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let s=gt(o||t)||F(e,"w:pPr");a.appendChild(s);let c=Array.from(t.childNodes).find(f=>f.nodeType===1&&(f.nodeName==="w:pPrChange"||f.localName==="pPrChange"));return c&&t.removeChild(c),t.appendChild(a),a}var ah="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function qn(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===ah&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Ca(e,t,r){let n=new Map;for(let i of r)!i||!i.paragraph||(n.has(i.paragraph)||n.set(i.paragraph,[]),n.get(i.paragraph).push(i));let o=[],a=0;return t.forEach((i,l)=>{let s=(n.get(i)||[]).slice().sort((d,m)=>d.charStart-m.charStart),c=ih(s),f=ws(c),u=f.trim();o.push({paragraph:i,spans:s,text:c,normalizedText:f,normalizedTrim:u,startOffset:a}),a+=f.length,a=Yr(a,l,t.length)}),o}function Au(e,t){if(!t)return null;let r=ws(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 Eu(e,t){let r=ws(t),n=r.trim(),o=null,a=0;for(let i of e)if(i.normalizedText===r)return o=i,{targetInfo:o,matchOffset:a};if(n.length>0){for(let i of e)if(i.normalizedTrim===n)return o=i,{targetInfo:o,matchOffset:a}}if(n.length>0){let l=e.map(s=>s.normalizedText).join(`
148
+ `).indexOf(n);if(l!==-1)for(let s of e){let c=s.startOffset,f=s.normalizedText.length;if(l>=c&&l<=c+f){o=s,a=l-c;break}}}if(!o&&e.length===1&&r.length>0){let i=e[0],l=i.normalizedTrim||"";if(l.length>0){let s=r.indexOf(l);s>=0&&(o=i,a=-s)}}return{targetInfo:o,matchOffset:a}}function Ru(e){let t=e;for(;t;){if(qn(t,"p"))return t;t=t.parentNode}return null}function ih(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;qn(n,"t")?t+=r.textElement.textContent||"":qn(n,"tab")?t+=" ":qn(n,"br")||qn(n,"cr")?t+=`
149
+ `:qn(n,"noBreakHyphen")&&(t+="\u2011")}return t}function ws(e){return e?e.replace(/\r/g,`
150
+ `).replace(/\u00a0/g," "):""}function Pu(e,t,r){let n=Array.from(new Set(r)).sort((l,s)=>l-s);if(n.length===0||t.length===0)return[...t];let o=[...t].sort((l,s)=>l.charStart-s.charStart||l.charEnd-s.charEnd),a=[],i=0;for(let l of o){for(;i<n.length&&n[i]<=l.charStart;)i++;let s=l;for(;i<n.length&&n[i]<s.charEnd;){let c=n[i],f=sh(e,s,c);if(!f){i++;continue}a.push(f[0]),s=f[1],i++}a.push(s)}return a}function sh(e,t,r){let n=t.runElement,o=n.parentNode;if(!o)return null;let a=t.textElement.textContent||"",i=r-t.charStart,l=a.substring(0,i),s=a.substring(i);if(l.length===0||s.length===0)return null;let c=Br(e,l,t.rPr,!1),f=Br(e,s,t.rPr,!1);o.insertBefore(c,n),o.insertBefore(f,n),o.removeChild(n);let u=c.getElementsByTagName("w:t")[0],d=f.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:u,runElement:c},{...t,charStart:r,textElement:d,runElement:f}]}var lh="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function ch(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===lh&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function uh(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 Cu(e,t,r,n,o,a=!0){let i=!1,l=new Set;W(`[OxmlEngine] Surgical format removal: ${r.length} hints to process (using w:rPrChange)`);for(let s of r){let c=s.run;if(l.has(c)||(l.add(c),!c.parentNode))continue;W("[OxmlEngine] Processing run for surgical format removal, format:",s.format);let f=Ue(c,"w:rPr");f||(f=F(e,"w:rPr"),c.insertBefore(f,c.firstChild)),a&&ko(e,f,o||ae()),vu(e,f,s.format),i=!0}return i?(W("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(W("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function fh(e,t,r,n,o,a=!0){let i=!1,l=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let s=[];for(let d of r)s.push(d.start,d.end);let f=Pu(e,t,s).slice().sort((d,m)=>d.charStart-m.charStart||d.charEnd-m.charEnd),u=dh(r);for(let d of f){if(!d||!d.textElement||!ch(d.textElement,"t"))continue;let m=u(d.charStart,d.charEnd);if(m.length===0)continue;let p=Ki(...m.map(R=>R.format)),g={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},h=d.format||Qt(d.rPr),v={bold:!!h.bold,italic:!!h.italic,underline:!!h.underline,strikethrough:!!h.strikethrough};if(!["bold","italic","underline","strikethrough"].some(R=>g[R]!==v[R])||l.has(d.runElement)||(l.add(d.runElement),!(d.textElement.textContent||""))||!d.runElement.parentNode)continue;let S=d.runElement,A=Ue(S,"w:rPr"),E=Gn(e,A,g,o||ae(),a),I=A;if(!I)S.insertBefore(E,S.firstChild);else{for(;I.firstChild;)I.removeChild(I.firstChild);Array.from(E.childNodes).forEach(R=>I.appendChild(R))}i=!0}return{oxml:n.serializeToString(e),hasChanges:i}}function _u(e,t,r,n,o,a=!0,i=null){let l=uh(i),s=l.paragraphs||xt(e),c=l.textSpans||[];if(l.textSpans||({textSpans:c}=Ra(s)),!c||c.length===0)return ir("[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 f=l.paragraphInfos||Ca(e,s,c),{targetInfo:u,matchOffset:d}=Eu(f,t);if(!u||!u.spans||u.spans.length===0)return ir("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let m=u.spans[0].charStart,p=u.spans.map(h=>({...h,charStart:h.charStart-m,charEnd:h.charEnd-m})),g=r.map(h=>({...h,start:h.start+d,end:h.end+d}));return fh(e,p,g,n,o,a)}function dh(e){let t=(e||[]).slice().sort((o,a)=>o.start-a.start||o.end-a.end),r=[],n=0;return(o,a)=>{for(;n<t.length&&t[n].start<a;)r.push(t[n]),n++;for(let i=r.length-1;i>=0;i--)r[i].end<=o&&r.splice(i,1);return r.filter(i=>i.start<a&&i.end>o)}}function _a(e){let t=e?.localName;return t?t.indexOf(":")<0?t:t.replace(/^.*:/,""):String(e?.nodeName||"").replace(/^.*:/,"")}function tn(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let a=_a(o);if(n==="accepted"&&(a==="del"||a==="moveFrom")||n==="rejected"&&(a==="ins"||a==="moveTo"))return!1;o=o.parentNode}return!0}function gr(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!tn(e,n,r))return"";let o="",a=i=>{for(let l=i?.firstChild;l;l=l.nextSibling){if(l?.nodeType!==1||l.namespaceURI&&l.namespaceURI!==B||!tn(l,n,r))continue;let s=_a(l);s==="t"||s==="delText"&&r==="rejected"?o+=l.textContent||"":s==="tab"?o+=" ":s==="br"||s==="cr"?o+=`
151
+ `:s==="noBreakHyphen"?o+="\u2011":s==="softHyphen"?o+="\xAD":a(l)}};return a(e),o}var Fr=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Oa(e,t={}){if(!e)return[];let r=[];function n(u,d,m){for(let p of Array.from(u?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==B)continue;let g=_a(p);if(g==="pPr"||g==="rPr")continue;let h=d;g==="ins"?h={kind:"insertion",author:Fr(p,"author")||void 0,revisionId:Fr(p,"id")||void 0}:g==="del"?h={kind:"deletion",author:Fr(p,"author")||void 0,revisionId:Fr(p,"id")||void 0}:g==="moveFrom"?h={kind:"move_from",author:Fr(p,"author")||void 0,revisionId:Fr(p,"id")||void 0}:g==="moveTo"&&(h={kind:"move_to",author:Fr(p,"author")||void 0,revisionId:Fr(p,"id")||void 0});let v=m;g==="r"&&(v=p);let w=null,y=h?h.kind:"baseline",b=h?.author,x=h?.revisionId;g==="t"?w=p.textContent||"":g==="delText"?(w=p.textContent||"",h||(y="deletion")):g==="tab"?w=" ":g==="br"||g==="cr"?w=`
152
+ `:g==="noBreakHyphen"?w="\u2011":g==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:y,author:b,revisionId:x,carrier:v||p,carrierContainer:(v||p)?.parentNode||null}):n(p,h,v)}}let o=_a(e)==="r"?e:null;if(n(e,null,o),r.length===0)return[];let a=t.mergeRuns!==!1,i=[],l=null;for(let u of r){if(!l){l={...u};continue}let d=l.kind===u.kind,m=l.author===u.author,p=l.revisionId===u.revisionId,g=l.carrier===u.carrier,h=a&&l.carrierContainer===u.carrierContainer;d&&m&&p&&(g||h)?l.text+=u.text:(i.push(l),l={...u})}l&&i.push(l);let s=0,c=0,f=[];for(let u of i){let d=u.kind!=="deletion"&&u.kind!=="move_from",m=u.kind!=="insertion"&&u.kind!=="move_to",p=d?s:null,g=m?c:null;d&&(s+=u.text.length),m&&(c+=u.text.length);let h={text:u.text,kind:u.kind,acceptedStart:p,rejectedStart:g};u.author!==void 0&&(h.author=u.author),u.revisionId!==void 0&&(h.revisionId=u.revisionId),f.push(h)}return f}function Y(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Oa(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 mh="http://schemas.microsoft.com/office/word/2010/wordml";function Ou(e,t,r={}){let{targetParagraphId:n=null}=r,o=st(e,B,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let i=xt(e).filter(s=>{let c=s.parentNode;for(;c;){if($(c,"tc"))return!0;c=c.parentNode}return!1});W(`[OxmlEngine] Table wrapper detected: ${o.length} tables, ${i.length} paragraphs in cells`);let l=null;if(n){let s=String(n).toUpperCase();l=i.find(c=>{let f=gh(c);return f&&f.toUpperCase()===s})||null,l?W(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):W(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let s=t.trim();if(!l){for(let c of i)if(Y(c).trim()===s){l=c,W(`[OxmlEngine] Found target paragraph by text match: "${s.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:i.length>0,targetParagraph:l,paragraphs:i,paragraph:l||i[0]||null,tableElement:o[0]}}function Mo(e,t,r){let n=Array.isArray(t)?t:[t],o="";for(let a of n){if(!a)continue;let i=r.serializeToString(a);i=i.replace(/\s+xmlns:w="[^"]*"/g,""),i=i.replace(/\s+xmlns:r="[^"]*"/g,""),i=i.replace(/\s+xmlns:wp="[^"]*"/g,""),o+=i}return W(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),W(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),ph(o)}function ph(e){return eu(e)}function gh(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(mh,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function vs(e){return $(e,"t")||$(e,"delText")?e.textContent||"":$(e,"br")||$(e,"cr")?`
153
+ `:$(e,"tab")?" ":$(e,"noBreakHyphen")?"\u2011":$(e,"softHyphen")?"\xAD":""}function ys(e){return $(e,"t")||$(e,"delText")||$(e,"br")||$(e,"cr")||$(e,"tab")||$(e,"noBreakHyphen")||$(e,"softHyphen")}function ka(e){let t="",r=[];return e.forEach((n,o)=>{let a=n.parentNode;for(let i=n.firstChild;i;i=i.nextSibling)if($(i,"r"))t+=Lo(i,n,a,t.length,r).text;else if($(i,"hyperlink"))for(let l=i.firstChild;l;l=l.nextSibling)$(l,"r")&&(t+=Lo(l,n,a,t.length,r).text);else if($(i,"ins"))for(let l=i.firstChild;l;l=l.nextSibling)$(l,"r")&&(t+=Lo(l,n,a,t.length,r).text);else if($(i,"sdt")){let l=Array.from(i.childNodes||[]).find(s=>$(s,"sdtContent"));if(l)for(let s=l.firstChild;s;s=s.nextSibling)$(s,"r")&&(t+=Lo(s,n,a,t.length,r).text)}else if($(i,"smartTag"))for(let l=i.firstChild;l;l=l.nextSibling)$(l,"r")&&(t+=Lo(l,n,a,t.length,r).text);t=Fn(t,o,e.length)}),{fullText:t,textSpans:r}}function Lo(e,t,r,n,o){let a=Ue(e,"w:rPr"),i=n,l=[];for(let s=e.firstChild;s;s=s.nextSibling)if($(s,"t")){let c=s.textContent||"";if(c.length===0)continue;o.push({charStart:i,charEnd:i+c.length,textElement:s,runElement:e,paragraph:t,container:r,rPr:a}),i+=c.length,l.push(c)}else if(ys(s)){let c=vs(s);o.push({charStart:i,charEnd:i+1,textElement:s,runElement:e,paragraph:t,container:r,rPr:a}),i+=1,l.push(c)}return{text:l.join("")}}function Ma(e){let t=e.slice().sort((o,a)=>o.charStart-a.charStart||o.charEnd-a.charEnd),r=t.map(o=>o.charStart),n=t.map(o=>o.charEnd);return{spans:t,starts:r,ends:n}}function Bo(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=Ns(e.ends,t);for(;o<e.spans.length;){let a=e.spans[o];if(a.charStart>=r)break;n(a),o++}}function bs(e,t){if(e.spans.length===0)return null;let r=Ns(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function xs(e,t){let r=hh(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function Is(e,t){let r=Ns(e.ends,t)-1;return r>=0?e.spans[r]:null}function Ns(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 hh(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 ku(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=bs(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,a=xs(e,t)||(t>0?Is(e,t):null),i=e.spans.find(l=>l.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:a,rightSpan:i,containingSpan:n,isInterior:o,fallbackParagraph:r}}var wh=new Set(["ins","del"]);function jt(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if($(n,"rPr")||!ys(n))continue;let o=vs(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function It(e){return e.length===0?0:e[e.length-1].end}function Pt(e,t,r,n,o){let a=[];return n<=r||t.forEach(i=>{let l=Math.max(r,i.start),s=Math.min(n,i.end);if(s<=l)return;let c=l-i.start,f=s-i.start,u=i.text.slice(c,f);a.push(xh(e,i.node,u,o))}),a}function $r(e,t,r){let n=F(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function rn(e,t,r,n,o){if(n.length===0)return null;let a=$r(e,n,o);return t.insertBefore(a,r),a}function La(e,t,r,n=null){let o=bh(t);if(!wh.has(o))throw new TypeError("splitTrackChangeCarrier requires a w:ins or w:del carrier.");if(!Number.isInteger(r)||r<0)throw new RangeError("splitOffset must be a non-negative integer.");let a=Array.from(t.childNodes||[]),i=a.reduce((d,m)=>d+($(m,"r")?It(jt(m)):0),0);if(r>i)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${i}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===i)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let l=t.cloneNode(!1),s=t.cloneNode(!1),c=0;for(let d of a){if(!$(d,"r")){(c<=r?l:s).appendChild(d.cloneNode(!0));continue}let m=jt(d),p=It(m),g=c+p;if(g<=r)l.appendChild(d.cloneNode(!0));else if(c>=r)s.appendChild(d.cloneNode(!0));else{let h=r-c,v=Array.from(d.childNodes||[]).find(S=>$(S,"rPr"))||null,w=o==="del",y=Pt(e,m,0,h,w),b=Pt(e,m,h,p,w);l.appendChild($r(e,y,v));let x=$r(e,b,v);s.appendChild(x)}c=g}let f=vh(e,n);Ft(s,f);let u=f.next();return yh(s,"id",String(u)),f._receiptCollector?.recordRevision(u,o),{leftCarrier:l,rightCarrier:s}}function vh(e,t){return t instanceof De?t:lr(e)||_r(e)}function yh(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(B,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function bh(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function xh(e,t,r,n){if(n&&($(t,"delText")||$(t,"t"))){let a=F(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}if($(t,"t")){let a=t.cloneNode(!1);return a.textContent=r,/^\s|\s$/.test(r)&&a.setAttribute("xml:space","preserve"),a}if(r===`
154
+ `&&($(t,"br")||$(t,"cr"))||r===" "&&$(t,"tab")||r==="\u2011"&&$(t,"noBreakHyphen")||r==="\xAD"&&$(t,"softHyphen"))return t.cloneNode(!0);if(n){let a=F(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}let o=F(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function Bu(e,t,r,n,o,a,i){if(o.length===0)return!1;let l=t.rPr,s=Qt(l),c={...s};if(o.forEach(S=>Object.assign(c,S.format)),!["bold","italic","underline","strikethrough"].some(S=>!!c[S]!==s[S]))return!1;let d=t.runElement.parentNode;if(!d)return!1;let m=t.textElement.textContent||"",p=t.charStart,g=r-p,h=n-p,v=m.substring(0,g),w=m.substring(g,h),y=m.substring(h);if(v.length>0){let S=Br(e,v,l,!1);d.insertBefore(S,t.runElement)}let b=Gn(e,l,c,a,i),x=hs(e,w,b,!1);if(d.insertBefore(x,t.runElement),y.length>0){let S=Br(e,y,l,!1);d.insertBefore(S,t.runElement)}return d.removeChild(t.runElement),!0}function As(e,t,r,n,o,a,i=null){let l=[];if(Bo(t,r,n,m=>{l.push(m)}),l.length===0)return!1;let s=new Map;l.forEach(m=>{m.runElement?.parentNode&&(s.has(m.runElement)||s.set(m.runElement,[]),s.get(m.runElement).push(m))});let c=[];s.forEach((m,p)=>{let g=p.parentNode;if(!g)return;let h=jt(p);if(h.length===0)return;let v=1/0,w=-1/0;m.forEach(y=>{let b=h.find(A=>A.node===y.textElement);if(!b)return;let x=Math.max(0,r-y.charStart),S=Math.min(y.charEnd-y.charStart,n-y.charStart);S<=x||(v=Math.min(v,b.start+x),w=Math.max(w,b.start+S))}),!(!Number.isFinite(v)||w<=v)&&c.push({runElement:p,parent:g,rPr:m[0].rPr,beforePieces:Pt(e,h,0,v,!1),deletedPieces:Pt(e,h,v,w,!0),afterPieces:Pt(e,h,w,It(h),!1),globalStart:Math.max(r,Math.min(...m.map(y=>y.charStart))),globalEnd:Math.min(n,Math.max(...m.map(y=>y.charEnd))),carrierGlobalStart:$(g,"ins")?Fu(t,g):null})});let f=[];for(let m of c){let p=f[f.length-1],g=p?.[p.length-1];g&&g.parent===m.parent&&Th(g.runElement)===m.runElement?p.push(m):f.push([m])}let u=!1,d=!1;for(let m of f){let p=m[0],g=null;if(a&&m.some(w=>w.deletedPieces.length>0)){let w=i?d?{...i,id:ue(o,e,"del").id}:i:null;d=!0,g=tr(e,"del",null,o,w)}for(let w of m){let{parent:y,runElement:b}=w;rn(e,y,b,w.beforePieces,w.rPr),g&&w===p&&y.insertBefore(g,b),g&&w.deletedPieces.length>0&&g.appendChild($r(e,w.deletedPieces,w.rPr));let x=rn(e,y,b,w.afterPieces,w.rPr);w.globalEnd===n&&!$(y,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:y,referenceNode:x||b.nextSibling,rPr:w.rPr})),y.removeChild(b),u=!0}let h=$(p.parent,"ins")?p.parent:null,v=Math.max(...m.map(w=>w.globalEnd));if(h&&v===n){let w=p.carrierGlobalStart,y=m.filter(x=>x.globalStart<n).reduce((x,S)=>x+S.deletedPieces.reduce((A,E)=>A+(E.textContent||"").length,0),0),b=Math.max(0,n-w-y);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:b,rPr:p.rPr})}}return u}function Yn(e,t,r,n,o,a=[],i=0,l=!0,s=null,c=null,f=null,u="merge-same-author"){let d=t.revisionInsertionAnchors?.get(r)||null;if(d&&u==="slice-cross-author"&&Lu(d.carrier)&&Ss(d.carrier,o))return t.revisionInsertionAnchors.delete(r),Ts(e,d.carrier,d.splitOffset,n,d.rPr,o,a,i,l,c);let m=t.replacementInsertionAnchors?.get(r)||null;if(m&&!f&&Lu(m.parent)&&(!m.referenceNode||m.referenceNode.parentNode===m.parent))return t.replacementInsertionAnchors.delete(r),Dr(e,m.parent,m.referenceNode,n,m.rPr,o,a,i,l,c),!0;if(!f){let x=bs(t,r);if(!x&&r>0&&(x=xs(t,r)),!x&&r>0&&(x=Is(t,r)),!x&&t.spans.length>0&&(x=t.spans[t.spans.length-1]),!x)return s?(Dr(e,s,null,n,null,o,a,i,l,c),!0):!1;let S=x.runElement.parentNode;if(!S)return s?(Dr(e,s,null,n,x.rPr,o,a,i,l,c),!0):!1;let A=l&&!(u==="slice-cross-author"&&Nh(S,o));if(l&&u==="slice-cross-author"&&Ss(S,o))return Ts(e,S,Mu(t,S,r),n,x.rPr,o,a,i,l,c);let E=jt(x.runElement),I=E.find(N=>N.node===x.textElement),R=I?I.start+Math.max(0,Math.min(r-x.charStart,x.charEnd-x.charStart)):r<=x.charStart?0:It(E);if(R>0&&R<It(E)){let N=Pt(e,E,0,R,!1),O=Pt(e,E,R,It(E),!1);return rn(e,S,x.runElement,N,x.rPr),Dr(e,S,x.runElement,n,x.rPr,o,a,i,A,c),rn(e,S,x.runElement,O,x.rPr),S.removeChild(x.runElement),!0}let T=r<=x.charStart?x.runElement:x.runElement.nextSibling;return Dr(e,S,T,n,x.rPr,o,a,i,A,c),!0}let p=ku(t,r,s),g=p.leftSpan&&$(p.leftSpan.runElement?.parentNode,"hyperlink"),h=p.rightSpan&&$(p.rightSpan.runElement?.parentNode,"hyperlink"),v=p.containingSpan&&$(p.containingSpan.runElement?.parentNode,"hyperlink");if(f.hyperlink==="outside"){if(p.isInterior&&v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(f.hyperlink==="inside"&&!g&&!h&&!v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let w=null;if(f.formatting==="none"?w=null:f.formatting==="right"?w=p.rightSpan?.rPr||null:f.formatting==="left"?w=p.leftSpan?.rPr||null:w=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let x=p.containingSpan,S=x.runElement.parentNode||s;if(!S)return!1;let A=jt(x.runElement),E=A.find(R=>R.node===x.textElement),I=E?E.start+Math.max(0,Math.min(r-x.charStart,x.charEnd-x.charStart)):r<=x.charStart?0:It(A);if(I>0&&I<It(A)){let R=Pt(e,A,0,I,!1),T=Pt(e,A,I,It(A),!1);return rn(e,S,x.runElement,R,x.rPr),Dr(e,S,x.runElement,n,w,o,a,i,l,c),rn(e,S,x.runElement,T,x.rPr),S.removeChild(x.runElement),!0}}let y=null,b=null;if(f.hyperlink==="outside"){if(h){let x=p.rightSpan.runElement.parentNode;y=x.parentNode||s,b=x}else if(g){let x=p.leftSpan.runElement.parentNode;y=x.parentNode||s,b=x.nextSibling}}else f.hyperlink==="inside"&&(h?(y=p.rightSpan.runElement.parentNode,b=p.rightSpan.runElement):g&&(y=p.leftSpan.runElement.parentNode,b=p.leftSpan.runElement.nextSibling));if(y||(p.rightSpan?(y=p.rightSpan.runElement.parentNode||s,b=p.rightSpan.runElement):p.leftSpan?(y=p.leftSpan.runElement.parentNode||s,b=p.leftSpan.runElement.nextSibling):(y=s,b=null)),f.bookmark&&y&&(f.bookmark==="outside"?(b&&$(b.previousSibling,"bookmarkStart")&&(b=b.previousSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling.nextSibling)):f.bookmark==="inside"&&(b&&$(b,"bookmarkStart")&&(b=b.nextSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling))),f.comment&&y)if(f.comment==="outside"){if(b&&$(b.previousSibling,"commentRangeStart")&&(b=b.previousSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let x=p.leftSpan.runElement.nextSibling.nextSibling;x&&($(x,"commentReference")||$(x,"r"))&&Array.from(x.childNodes||[]).some(A=>$(A,"commentReference"))&&(x=x.nextSibling),b=x}}else f.comment==="inside"&&(b&&$(b,"commentRangeStart")&&(b=b.nextSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(b=p.leftSpan.runElement.nextSibling));if(l&&f.revision==="coalesce_same_author"){let x=null,S=null;if(p.leftSpan&&$(p.leftSpan.runElement.parentNode,"ins")){let A=p.leftSpan.runElement.parentNode;(A.getAttribute("w:author")||A.getAttributeNS(B,"author"))===o&&(x=A,S=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&$(p.rightSpan.runElement.parentNode,"ins")){let A=p.rightSpan.runElement.parentNode;(A.getAttribute("w:author")||A.getAttributeNS(B,"author"))===o&&(x=A,S=p.rightSpan.runElement)}if(x){let A=Br(e,n,w,!1);return x.insertBefore(A,S),!0}}return l&&u==="slice-cross-author"&&Ss(y,o)?Ts(e,y,Mu(t,y,r),n,w,o,a,i,l,c):(Dr(e,y,b,n,w,o,a,i,l,c),!0)}function Ts(e,t,r,n,o,a,i,l,s,c){let f=t.parentNode;if(!f)return!1;let{leftCarrier:u,rightCarrier:d}=La(e,t,r);return u&&f.insertBefore(u,t),Dr(e,f,t,n,Ih(o),a,i,l,s,c),d&&f.insertBefore(d,t),f.removeChild(t),!0}function Ih(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>$(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Mu(e,t,r){let n=Fu(e,t),o=e.spans.filter(a=>a.runElement?.parentNode===t).reduce((a,i)=>a+(i.charEnd-i.charStart),0);return Math.max(0,Math.min(r-n,o))}function Fu(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 Ss(e,t){return $(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function Nh(e,t){return $(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function Th(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Lu(e){return!!e?.parentNode}function Dr(e,t,r,n,o,a,i,l,s,c=null){let f=sr(i,l,l+n.length);if(f.length===0){let d=Br(e,n,o,!1);if(s){let m=tr(e,"ins",d,a,c);t.insertBefore(m,r)}else t.insertBefore(d,r);return}let u=Pa(e,n,o,f,l,a,s);if(s){let d=tr(e,"ins",null,a,c);u.forEach(m=>d.appendChild(m)),t.insertBefore(d,r)}else u.forEach(d=>t.insertBefore(d,r))}function $u(e,t,r,n=!1){let o=[];if(Bo(e,t,r,m=>o.push(m)),o.length===0)return{safe:!1};let a=o[0].runElement,i=a?.parentNode;if(!i)return{safe:!1};if(!o.every(m=>m.runElement?.parentNode===i))return{safe:!1,structuralBoundary:!0};let s=i.localName||i.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(s)||s==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let m of o){let p=m.runElement;for(let g of Array.from(p.childNodes||[]))if(g.nodeType===1){let h=g.localName||g.nodeName.replace(/^.*:/,"");if(c.has(h)||h==="fldChar")return{safe:!1,structuralBoundary:!0}}}let f=o[o.length-1].runElement,u=a;for(;u&&u!==f;){if(u!==a){let m=u.localName||u.nodeName.replace(/^.*:/,"");if(c.has(m))return{safe:!1,structuralBoundary:!0}}u=u.nextSibling}function d(m){if(!m||m.nodeType!==1)return!1;let p=m.localName||m.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let g of Array.from(m.childNodes||[]))if(g.nodeType===1&&d(g))return!0;return!1}return d(a.previousSibling)||d(f.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function zu(e,t,r,n,o,a,i=!0,l=null,s={},c={}){let f=l?[l]:xt(e),{fullText:u,textSpans:d}=ka(f),m=c.existingRevisions==="slice-cross-author"?Wc(u,r):null,p=m||Ah(Co(u,r,s),s),g=Ma(d),h=c.pairReplacements===!0,v=[],w=0,y=0,b=!1,x=m?Rh(m):[];if(x.length>1&&a.length===0)for(let E of x.slice().reverse()){let I=ka(f).textSpans,R=Ma(I),T=E.text.replace(/\n/g," ");if(T.length===0)continue;let N=Yn(e,R,E.originalPos,T,o,a,E.newPos,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(N&&typeof N=="object"&&N.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:N.error});N===!0&&(b=!0)}else if(a.length===0){let E=Eh(p);for(let I of E.reverse()){let R=Ma(ka(f).textSpans);if(I.type==="insert"){let O=Yn(e,R,I.start,I.text.replace(/\n/g," "),o,a,I.newPos,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(O&&typeof O=="object"&&O.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:O.error});O===!0&&(b=!0);continue}let T=null,N=null;if(I.type==="replace"&&h&&i&&I.text.replace(/\n/g," ")){let O=$u(R,I.start,I.end,c?.existingRevisions==="slice-cross-author");if(O.safe){let C=Eo(o,e);T={id:C.deletionId,author:C.author,date:C.date},N={id:C.insertionId,author:C.author,date:C.date}}else O.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(As(e,R,I.start,I.end,o,i,T)&&(b=!0),I.type==="replace"){let O=Yn(e,R,I.end,I.text.replace(/\n/g," "),o,a,I.newPos,i,f[0]||null,N,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(O&&typeof O=="object"&&O.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:O.error});O===!0&&(b=!0)}}}else for(let E=0;E<p.length;E++){let[I,R]=p[E];if(I===0){let T=R.length,N=w,O=w+T;Bo(g,N,O,C=>{let P=Math.max(C.charStart,N),M=Math.min(C.charEnd,O),_=M-P,k=P-N,L=y+k,D=L+_,z=sr(a,L,D);Bu(e,C,P,M,z,o,i)&&(b=!0)}),w+=T,y+=T}else if(I===-1){let T=E+1<p.length&&p[E+1][0]===1,N=!1,O=null,C=null;if(h&&i&&T&&p[E+1][1].replace(/\n/g," ").length>0){let _=$u(g,w,w+R.length,c?.existingRevisions==="slice-cross-author");if(_.safe){let k=Eo(o,e);O={id:k.deletionId,author:k.author,date:k.date},C={id:k.insertionId,author:k.author,date:k.date},N=!0}else _.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(As(e,g,w,w+R.length,o,i,O)&&(b=!0),w+=R.length,N){E++;let[,P]=p[E],M=P.replace(/\n/g," ");if(M.length>0){let _=Yn(e,g,w,M,o,a,y,i,f[0]||null,C,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(_&&typeof _=="object"&&_.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:_.error});_===!0&&(b=!0)}y+=P.length}}else if(I===1){let T=R.replace(/\n/g," ");if(T.length>0){let N=Yn(e,g,w,T,o,a,y,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(N&&typeof N=="object"&&N.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:N.error});N===!0&&(b=!0)}y+=R.length}}let S=f.map(E=>Y(E)).join(`
155
+ `),A=String(r).replace(/\r\n/g,`
156
+ `);if(c.existingRevisions==="slice-cross-author"&&S!==A){let E=Sh(A,S);return Ce({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:E,expectedExcerpt:Du(A,E),actualExcerpt:Du(S,E),expectedCodePoint:Uu(A,E),actualCodePoint:Uu(S,E)},...v.length>0?{warnings:[...new Set(v)]}:{}})}return Ce({oxml:n.serializeToString(e),hasChanges:b,...v.length>0?{warnings:[...new Set(v)]}:{}})}function Sh(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 Du(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}function Uu(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function Ah(e,t){let r=[];for(let n=0;n<e.length;n++){let[o,a]=e[n],i=e[n+1];if(o===-1&&i?.[0]===1&&a!==i[1]&&a.length===i[1].length&&a.replace(/\u00a0/g," ")===i[1].replace(/\u00a0/g," ")){r.push(...jc(a,i[1],t)),n++;continue}r.push([o,a])}return r}function Eh(e){let t=[],r=0,n=0;for(let o=0;o<e.length;o++){let[a,i]=e[o];if(a===0){r+=i.length,n+=i.length;continue}if(a===-1){let l=e[o+1];l?.[0]===1?(t.push({type:"replace",start:r,end:r+i.length,newPos:n,text:l[1]}),r+=i.length,n+=l[1].length,o++):(t.push({type:"delete",start:r,end:r+i.length,newPos:n,text:""}),r+=i.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:i}),n+=i.length}return t}function Rh(e){let t=[],r=0,n=0;for(let[o,a]of e)o===0?(r+=a.length,n+=a.length):o===-1?r+=a.length:o===1&&(t.push({originalPos:r,newPos:n,text:a}),n+=a.length);return t}var Vu=gc(ns(),1);var ju=new Vu.diff_match_patch;function Wu(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Ph(e,t){return e?.getAttributeNS?.(B,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Xu(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let o=0,a=t-1;for(;o<=a;){let i=Math.floor((o+a)/2);e[i].end<=r?o=i+1:a=i-1}t=o}for(;t<e.length&&e[t].end<=r;)t++;let n=e[t];return n&&n.start<=r&&r<n.end?n:null}}}function Ch(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 Ku(e,t,r=null){let n=e.documentElement,o=$(n,"body")||Wu(n)==="package",a=r||xt(e),i=lt(e,B,"body");!i&&o&&(i=n);let l="",s=[],c=[],f=[],u=new Map,d=new Map,m=new Set,p={nextCharCode:57344},g=new Set;a.forEach((T,N)=>{let O=l.length;Array.from(T.childNodes).forEach(_=>{l=Lh(_,l,s,f,u,d,p,m)}),l=Fn(l,N,a.length);let C=l.length,P=lt(T,B,"pPr"),M=T.parentNode;M&&g.add(M),c.push({start:O,end:C,pPr:P,paragraph:T,container:M||i})});let h="";for(let T=0;T<l.length;T++){let N=l[T];h+=m.has(N)?`
157
+ `:N}let v=kh(h,t,f);v=Oh(h,l,v,m),d.forEach((T,N)=>{let O=N.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");v=v.replace(new RegExp(O,"g"),T)}),v=Mh(l,v,u);let w=new Map;g.forEach(T=>{w.set(T,e.createDocumentFragment())}),i&&!w.has(i)&&w.set(i,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let y=new Map,b=new Set(c.map(T=>T.start)),x=Xu(c),S=Xu(s),A=Ch(f);return{paragraphs:a,body:i||e,paragraphMap:c,paragraphStarts:b,propertyMap:s,sentinelMap:f,sentinelMapByStart:A,referenceMap:u,tokenToCharMap:d,containerFragments:w,replacementContainers:y,originalFullText:l,processedModifiedText:v,getParagraphInfo:T=>{let N=x.at(T);return N||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:i||e})},getRunProperties:T=>{let N=S.at(T);return N?{rPr:N.rPr,wrapper:N.wrapper}:{rPr:null}},getPropertySpanLength:(T,N)=>{let O=S.at(T);return O?Math.min(O.end-T,N):1},isParagraphStart:T=>b.has(T)}}function Ba(e,t){let r=xt(e);if(r.length===0)return[];let n=Gu(t),o=r.map(_h);if(!n){let i=o.findIndex(l=>l==="");return i>=0?[r[i]]:null}if(r.length===1&&o[0]==="")return r;let a=[i=>i,i=>i.trim(),i=>i.replace(/\s+/g," ").trim()];for(let i of a){let l=i(n);for(let s=0;s<r.length;s++){let c="";for(let f=s;f<r.length;f++)if(c+=(f===s?"":`
158
+ `)+o[f],i(c)===l)return r.slice(s,f+1)}}return null}function Gu(e){return String(e??"").replace(/\r\n?/g,`
159
+ `).replace(/\u00a0/g," ")}function _h(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&($(o,"pPr")||$(o,"del")||$(o,"moveFrom")||($(o,"t")?t+=o.textContent||"":$(o,"tab")?t+=" ":$(o,"br")||$(o,"cr")?t+=`
160
+ `:$(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),Gu(t)}function Oh(e,t,r,n){if(n.size===0)return r;let o=ju.diff_main(e,r),a=0,i="";for(let[l,s]of o)if(l===0){for(let c=0;c<s.length;c++){let f=t[a+c];i+=n.has(f)?f:s[c]}a+=s.length}else l===-1?a+=s.length:i+=s;return i}function kh(e,t,r){let n=new Map;if(r.forEach(u=>{u.zeroWidth&&n.set(u.start,u)}),n.size===0)return t;let o="",a=0,i=new Map;for(let u=0;u<e.length;u++){let d=n.get(u);if(d){i.has(a)||i.set(a,[]),i.get(a).push({char:e[u],affinity:d.affinity||"right",emitted:!1});continue}o+=e[u],a++}let l=ju.diff_main(o,t),s=0,c="",f=(u,d)=>{let m=i.get(u)||[];for(let p of m)p.emitted||d&&p.affinity!==d||(c+=p.char,p.emitted=!0)};for(let[u,d]of l){if(u===1){f(s,"left"),c+=d;continue}for(let m=0;m<d.length;m++)f(s),u===0&&(c+=d[m]),s++}return f(s),c}function Mh(e,t,r){let n=t;for(let o of r.keys()){if(n.includes(o))continue;let a=e.indexOf(o);if(a<0)continue;let i=e.slice(0,a),l=e.slice(a+o.length);if(i&&n.startsWith(i)){n=`${n.slice(0,i.length)}${o}${n.slice(i.length)}`;continue}if(l&&n.endsWith(l)){let s=n.length-l.length;n=`${n.slice(0,s)}${o}${n.slice(s)}`}}return n}function Lh(e,t,r,n,o,a,i,l){return $(e,"r")?Bh(e,t,r,n,o,a,i,l):$(e,"hyperlink")||$(e,"fldSimple")?Fh(e,t,r):$(e,"sdt")||$(e,"oMath")||Wu(e)==="oMath"||$(e,"bookmarkStart")||$(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):(($(e,"commentRangeStart")||$(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function Bh(e,t,r,n,o,a,i,l){let s=t,c=lt(e,B,"rPr");return Array.from(e.childNodes).forEach(f=>{if($(f,"t")){let u=f.textContent||"";u.length>0&&(r.push({start:s.length,end:s.length+u.length,rPr:c}),s+=u)}else if($(f,"br")||$(f,"cr")){let u=String.fromCharCode(i.nextCharCode++);o.set(u,f),l.add(u),s+=u,r.push({start:s.length-1,end:s.length,rPr:c})}else if($(f,"tab"))s+=" ",r.push({start:s.length-1,end:s.length,rPr:c});else if($(f,"noBreakHyphen"))s+="\u2011",r.push({start:s.length-1,end:s.length,rPr:c});else if(["drawing","pict","object","fldChar","instrText","sym"].some(u=>$(f,u))){let u=lt(f,B,"txbxContent"),d=$(f,"pict")&&!!u,m=$(f,"fldChar")||$(f,"instrText"),p=$(f,"fldChar")?f.getAttributeNS?.(B,"fldCharType")||f.getAttribute("w:fldCharType")||f.getAttribute("fldCharType"):null;n.push({start:s.length,node:f,wrapInRun:!0,rPr:c,zeroWidth:m,affinity:p==="end"?"left":"right",isTextBox:d,originalContainer:d?u:void 0}),s+="\uFFFC",r.push({start:s.length-1,end:s.length,rPr:c})}else if($(f,"footnoteReference")||$(f,"endnoteReference")){let u=Ph(f,"id");if(u){let m=`{{__${$(f,"footnoteReference")?"FN":"EN"}_${u}__}}`,p=String.fromCharCode(i.nextCharCode++);o.set(p,f),a.set(m,p),s+=p,r.push({start:s.length-1,end:s.length,rPr:c})}}else $(f,"commentReference")&&n.push({start:s.length,node:f,isCommentMarker:!0})}),s}function Fh(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!$(o,"r"))return;let a=lt(o,B,"rPr");st(o,B,"t").forEach(l=>{let s=l.textContent||"";s.length!==0&&(r.push({start:n.length,end:n.length+s.length,rPr:a,wrapper:e}),n+=s)})}),n}var Hu="http://schemas.microsoft.com/office/word/2010/wordml",$h=["paraId","textId"];function Es(e,t){let r=Array.from(e.childNodes).find(o=>$(o,"pPr")),n=r&&Array.from(r.childNodes).find(o=>$(o,"rPr"));return!!n&&Array.from(n.childNodes).some(o=>$(o,t))}function Dh(e){e.forEach((t,r)=>{let n=t.find(o=>!Es(o,"ins")&&!Es(o,"del"))||t.find(o=>!Es(o,"del"))||t[0];n&&$h.forEach(o=>{let a=r.getAttributeNS?.(Hu,o)||r.getAttribute?.(`w14:${o}`);a&&n.setAttributeNS(Hu,`w14:${o}`,a)})})}function Yu(e,t,r,n,o,a,i=!0,l={}){let{paragraphs:s,containerFragments:c,sentinelMapByStart:f,referenceMap:u,replacementContainers:d,getParagraphInfo:m,getRunProperties:p,getPropertySpanLength:g,isParagraphStart:h}=r,v=new Map,w=(_,k=null)=>{let L=F(e,"w:p");if(k&&(v.has(k)||v.set(k,[]),v.get(k).push(L)),_){let D=_.cloneNode(!0),z=lt(D,B,"sectPr");z&&D.removeChild(z),L.appendChild(D)}return L},y=m(0),b=w(y.pPr,y.paragraph),x=c.get(y.container);x&&x.appendChild(b);let S=0,A=0,E=l?.pairReplacements===!0,I=null,R=null,T=new WeakSet;for(let _=0;_<t.length;_++){let[k,L]=t[_];if(k===0||k===-1){let D=k===0?"equal":"delete";if(k===0)I=null,R=null;else if(I===null){I=S;let G=!1;for(let ee=_+1;ee<t.length;ee++){if(t[ee][0]===1){G=!0;break}if(t[ee][0]===0)break}E&&i&&G&&(R=Eo(o,e,{deferReceipt:!0}))}let z=0;for(;z<L.length;){let G=S+z,ee=p(G),J=g(G,L.length-z),Z=L.substring(z,z+J);b=qu(e,Z,D,ee.rPr,ee.wrapper,G,b,c,f,u,d,m,w,o,a,A,i,T,R).currentParagraph,k===0&&(A+=J),z+=J}S+=L.length;continue}if(k===1){let D=I!==null?I:S>0&&!h(S)?S-1:S,z=p(D);b=qu(e,L,"insert",z.rPr,z.wrapper,S,b,c,f,u,d,m,w,o,a,A,i,T,R,I!==null).currentParagraph,A+=L.length,I=null,R=null}}for(let _ of Array.from(f.keys()).sort((k,L)=>k-L))for(let k of f.get(_))if(!(!k.isCommentMarker||T.has(k.node)))if(T.add(k.node),$(k.node,"commentReference")){let L=F(e,"w:r");L.appendChild(k.node.cloneNode(!0)),b.appendChild(L)}else b.appendChild(k.node.cloneNode(!0));i&&c.forEach(_=>{Array.from(_.childNodes).forEach(k=>{if($(k,"p")){let L=Array.from(k.getElementsByTagNameNS(B,"t")).length>0,D=Array.from(k.getElementsByTagNameNS(B,"delText")).length>0;s.length===1&&!L&&(D||r.originalFullText.trim()!=="")&&Qr(k,{author:o,revisionIdAllocator:e})}})}),c.forEach(_=>{let k=Array.from(_.childNodes).filter(L=>$(L,"p"));if(k.length>1){let L=k[0],D=k[k.length-1],z=lt(L,B,"pPr"),G=z?lt(z,B,"sectPr"):null;if(G){z.removeChild(G);let ee=lt(D,B,"pPr");ee||(ee=F(e,"w:pPr"),D.insertBefore(ee,D.firstChild||null)),ee.appendChild(G)}}}),Dh(v);let N=new Set(s),O=new Map;s.forEach(_=>{let k=_.parentNode;if(!k||O.has(k))return;let L=_.nextSibling;for(;L&&N.has(L);)L=L.nextSibling;O.set(k,L)}),s.forEach(_=>{_.parentNode&&_.parentNode.removeChild(_)});let C=!1,P="";return c.forEach((_,k)=>{let L=d.get(k),D=L||k;if(D.nodeType===9){C=!0,_.childNodes.length===1?D.appendChild(_.firstChild):P=Array.from(_.childNodes).map(G=>n.serializeToString(G)).join("");return}let z=L?null:O.get(k);z&&z.parentNode===D?D.insertBefore(_,z):D.appendChild(_)}),{oxml:C&&P?P:n.serializeToString(e),hasChanges:!0}}function qu(e,t,r,n,o,a,i,l,s,c,f,u,d,m,p=[],g=0,h=!0,v=new WeakSet,w=null,y=!1){let b=a,x=g,S=i,A=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(I=>{let R=s.get(b)||[],T=R.filter(C=>C.isCommentMarker&&!v.has(C.node)),N=y?new Set(T.filter(C=>$(C.node,"commentRangeEnd")).map(C=>C.node.getAttributeNS?.(B,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id"))):new Set;if(T.forEach(C=>{v.add(C.node);let P=C.node.getAttributeNS?.(B,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id");if(y&&N.has(P)&&($(C.node,"commentRangeEnd")||$(C.node,"commentReference"))){A.push(C.node);return}if($(C.node,"commentReference")){let M=F(e,"w:r");M.appendChild(C.node.cloneNode(!0)),S.appendChild(M)}else S.appendChild(C.node.cloneNode(!0))}),I===`
161
+ `){let C=u(b+1),P=d(C.pPr,C.paragraph);h&&r==="insert"?Zr(S,{author:m,revisionIdAllocator:e}):h&&r==="delete"&&Qr(S,{author:m,revisionIdAllocator:e});let M=l.get(C.container);M&&(M.appendChild(P),S=P),b++,r!=="delete"&&x++;return}if(I==="\uFFFC"){let C=R.find(P=>!P.isCommentMarker)||R[0];if(C){let P=C.node.cloneNode(!0);if(C.isTextBox&&C.originalContainer){let M=lt(P,B,"txbxContent");if(M){for(;M.firstChild;)M.removeChild(M.firstChild);f.set(C.originalContainer,M)}}if(C.wrapInRun){let M=F(e,"w:r");C.rPr&&M.appendChild(C.rPr.cloneNode(!0)),M.appendChild(P),S.appendChild(M)}else S.appendChild(P)}b++,r!=="delete"&&x++;return}if(c.has(I)){if(r==="delete"&&h){let C=c.get(I);if(C){let P=F(e,"w:r");n&&P.appendChild(n.cloneNode(!0)),P.appendChild(C.cloneNode(!0));let M=null;if(w){let _=w.usedDeletionId?ue(m,e,"del").id:w.deletionId;w.usedDeletionId||w.recordUsed?.("del"),w.usedDeletionId=!0,M={id:_,author:w.author,date:w.date}}S.appendChild(tr(e,"del",P,m,M))}}if(r!=="delete"){let C=c.get(I);if(C){let P=C.cloneNode(!0),M=F(e,"w:r");n&&M.appendChild(n.cloneNode(!0)),M.appendChild(P),S.appendChild(M)}}b++,r!=="delete"&&x++;return}if(I.length===0)return;let O=S;if(o){let C=o.cloneNode(!1);O=C,S.appendChild(C)}if(r==="delete"){let C=F(e,"w:r");n&&C.appendChild(n.cloneNode(!0));let P=F(e,"w:delText");if(P.setAttribute("xml:space","preserve"),P.textContent=I,C.appendChild(P),h){let M=null;if(w){let k=w.usedDeletionId?ue(m,e,"del").id:w.deletionId;w.usedDeletionId||w.recordUsed?.("del"),w.usedDeletionId=!0,M={id:k,author:w.author,date:w.date}}let _=tr(e,"del",C,m,M);O.appendChild(_)}}else{let C=sr(p,x,x+I.length),P=Pa(e,I,n,C,x,m,h);if(r==="insert"&&h){let M=null;if(w){let k=w.usedInsertionId?ue(m,e,"ins").id:w.insertionId;w.usedInsertionId||w.recordUsed?.("ins"),w.usedInsertionId=!0,M={id:k,author:w.author,date:w.date}}let _=tr(e,"ins",null,m,M);P.forEach(k=>_.appendChild(k)),O.appendChild(_)}else P.forEach(M=>O.appendChild(M))}r!=="delete"&&(x+=I.length),b+=I.length}),A.forEach(I=>{if($(I,"commentReference")){let R=F(e,"w:r");R.appendChild(I.cloneNode(!0)),S.appendChild(R)}else S.appendChild(I.cloneNode(!0))}),{currentParagraph:S}}function Ps(e,t,r,n,o,a,i=!0,l={},s={}){let c=Ba(e,t);if(c===null)return Ce({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 f=Ku(e,r,c);if(f.paragraphs.length===0)return Ce({oxml:n.serializeToString(e),hasChanges:!1});let u=Co(f.originalFullText,f.processedModifiedText,{...l,atomicChars:new Set(f.referenceMap.keys())}),d=Vh(Uh(u,f.referenceMap),f);return Ce(Yu(e,d,f,n,o,a,i,s))}function Ju(e,t,r){let n=0;for(;n<e.length;){if(e[n][0]===0){t(e[n]),n++;continue}let o=[];for(;n<e.length&&e[n][0]!==0;)o.push(e[n++]);r(o,o.filter(([a])=>a===-1).map(([,a])=>a).join(""),o.filter(([a])=>a===1).map(([,a])=>a).join(""))}}function Rs(e,t,r){if(t===r){t&&e.push([0,t]);return}t&&e.push([-1,t]),r&&e.push([1,r])}function Uh(e,t){if(t.size===0)return e;let r=[];return Ju(e,n=>r.push(n),(n,o,a)=>{let i=[...o].filter(f=>t.has(f)&&a.includes(f)),l=[...a].filter(f=>i.includes(f));if(i.length===0||i.join("")!==l.join("")){r.push(...n);return}let s=0,c=0;for(let f of i){let u=o.indexOf(f,s),d=a.indexOf(f,c);Rs(r,o.slice(s,u),a.slice(c,d)),r.push([0,f]),s=u+1,c=d+1}Rs(r,o.slice(s),a.slice(c))}),r}function zh(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}function Xh(e,t,r){let n=0;for(;n<r&&e[e.length-1-n]===t[t.length-1-n];)n++;return n}function Vh(e,t){let r=a=>t.getRunProperties(a).wrapper||null,n=[],o=0;return Ju(e,a=>{n.push(a),o+=a[1].length},(a,i,l)=>{let s=o,c=s+i.length;o=c;let f=m=>m>s&&m<c&&r(m-1)!==r(m),u=0,d=0;if(i&&l){let m=Xh(i,l,Math.min(i.length,l.length));for(let g=m;g>0;g--)if(f(c-g)){d=g;break}let p=Math.min(zh(i,l),Math.min(i.length,l.length)-d);for(let g=p;g>0;g--)if(f(s+g)){u=g;break}}if(u===0&&d===0){n.push(...a);return}u>0&&n.push([0,i.slice(0,u)]),Rs(n,i.slice(u,i.length-d),l.slice(u,l.length-d)),d>0&&n.push([0,i.slice(i.length-d)])}),n}function Wt(e,t){return Ce({oxml:e.serializeToString(t),hasChanges:!1})}function Zu(e,t,r,n,o,a=!0){let i=st(e,B,"tbl"),l=bt(t),s=l.rows.length>0||l.headers.length>0;if(i.length===0||!s)return Wt(r,e);let c=i[0],f=rs(c),u=fu(f,l);if(u.length===0)return Wt(r,e);let d={generateRedlines:a,author:o,revisionIdAllocator:lr(e)},m=du(f,u,d),p=`<root xmlns:w="${B}">${m}</root>`,g=j(p,"application/xml").doc;if(!g)return Wt(r,e);let h=Fe(g);if(h)return Le("[OxmlEngine] Failed to parse reconciled table OOXML:",h.textContent),Wt(r,e);let v=lt(g,B,"tbl");if(!v)return Le("[OxmlEngine] No table found in reconciled OOXML"),Wt(r,e);let w=e.importNode(v,!0);return c.parentNode.replaceChild(w,c),Ce({oxml:r.serializeToString(e),hasChanges:!0})}function Qu(e,t,r,n,o,a){let i=lr(e),l=bt(t);if(!l||l.rows.length===0&&l.headers.length===0)return W("[OxmlEngine] Failed to parse table data from Markdown"),Wt(r,e);let s=mr(l,{generateRedlines:a,author:o,revisionIdAllocator:i,trackAsBlock:!0}),c=j(`<root xmlns:w="${B}">${s}</root>`,"application/xml").doc;if(!c)return Wt(r,e);let f=Fe(c);if(f)return Le("[OxmlEngine] Failed to parse generated table OOXML:",f.textContent),Wt(r,e);let u=Ge(c,B,"tbl");if(u||(u=Ge(c,B,"ins")),!u)return Le("[OxmlEngine] No table element found in generated OOXML"),Wt(r,e);let d=e,m=We(d,B,"p");if(m.length===0)return W("[OxmlEngine] No paragraphs found to replace"),Wt(r,d);let p=m[0],g=p.parentNode;if(g&&g.nodeType===9){let v=j(`<w:document xmlns:w="${B}"><w:body/></w:document>`,"application/xml").doc;if(!v)return Wt(r,d);let w=Ge(v,B,"body");m.forEach(y=>w.appendChild(v.importNode(y,!0))),d=v,Cr(d,i),m=We(d,B,"p"),p=m[0],g=p.parentNode}let h=d.importNode(u,!0);return a?m.forEach(v=>{Qr(v,{author:o,revisionIdAllocator:d}),We(v,B,"r").forEach(y=>{We(y,B,"t").forEach(A=>{let E=A.textContent||"";if(E.trim()){let I=F(d,"w:delText");I.textContent=E,A.parentNode.replaceChild(I,A)}});let x=F(d,"w:del"),S=ue(o,d,"del");x.setAttribute("w:id",String(S.id)),x.setAttribute("w:author",S.author),x.setAttribute("w:date",S.date),y.parentNode.insertBefore(x,y),x.appendChild(y)})}):m.slice(1).forEach(v=>v.parentNode.removeChild(v)),g.insertBefore(h,p),a||g.removeChild(p),W("[OxmlEngine] Text-to-table transformation complete"),Ce({oxml:r.serializeToString(d),hasChanges:!0})}function hr(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 Fa(e){return typeof e=="string"?e.trim().toLowerCase():""}function jh(e){return!!e&&e.nodeType===1}function _t(e,t){return jh(e)&&e.namespaceURI===B&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function Xe(e,t){return Array.from(e.getElementsByTagNameNS(B,t))}function Cs(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=Fa(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 Ct(e,t){if(t.allAuthors)return!0;let r=Fa(hr(e,"author"));return!!r&&r===t.normalizedAuthor}function _s(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 i=`<w:body xmlns:w="${B}">${r}</w:body>`,l=j(i,"application/xml");l.error||(o=l,n=!0)}let a=o.doc?Fe(o.doc):null;if(o.error||a){let i=o.error?.message||a?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${i}`,warnings:o.warnings,error:{code:"PARSE_ERROR",message:i}}}return{xmlDoc:o.doc,serializer:le(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function $e(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function $a(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function ef(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function tf(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(`
162
+ `)}function Wh(e){let t=0,r=Xe(e,"ins");for(let n of r){if(!n.parentNode||Ua(n))continue;let o=ef(n);for(;_t(o,"ins")&&Fa(hr(o,"author"))===Fa(hr(n,"author"))&&tf(o)===tf(n);){let a=ef(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=a}}return t}function Da(e){let t=e?.parentNode;return _t(t,"trPr")&&_t(t?.parentNode,"tr")}function Ua(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return _t(t,"rPr")&&_t(r,"pPr")&&_t(n,"p")}function of(e){return Ua(e)?e.parentNode.parentNode.parentNode:null}function Kh(e){let t=e?.nextSibling||null;for(;t;){if(_t(t,"p"))return t;t=t.nextSibling}return null}function af(e,t="accept",r=null){if(!e?.parentNode)return!1;let n=Kh(e);if(!n){if(_t(e.parentNode,"tc")){let i=Xe(e.parentNode,"p").length<=1;if(t==="reject"||i)return i&&r&&r.add(e),!1}return $e(e)}let o=Array.from(e.childNodes||[]).filter(i=>!_t(i,"pPr")),a=n.firstChild||null;_t(a,"pPr")&&(a=a.nextSibling||null);for(let i of o)n.insertBefore(i,a);return $e(e)}function nn(e,t={}){let r=[],n=Cs(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=_s(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let l=0,s=new Set;for(let u of Xe(a,"ins"))if(!(!u.parentNode||!Ct(u,n))){if(Ua(u)){$e(u)&&(l+=1);continue}if(Da(u)){$e(u)&&(l+=1);continue}$a(u)&&(l+=1)}for(let u of Xe(a,"del")){if(!u.parentNode||!Ct(u,n))continue;let d=of(u);if(d){(af(d,"accept",s)||$e(u))&&(l+=1);continue}if(Da(u)){let m=u.parentNode?.parentNode;$e(m)&&(l+=1);continue}$e(u)&&(l+=1)}for(let u of Xe(a,"tbl")){if(!u.parentNode)continue;let d=Xe(u,"tc");d.length>0&&d.every(p=>{let g=Xe(p,"p");return g.length===1&&s.has(g[0])&&!Array.from(g[0].childNodes||[]).some(h=>!_t(h,"pPr"))})&&$e(u)&&(l+=1)}for(let u of Xe(a,"moveFrom"))!u.parentNode||!Ct(u,n)||$e(u)&&(l+=1);for(let u of Xe(a,"moveTo"))!u.parentNode||!Ct(u,n)||$a(u)&&(l+=1);l+=sf(a,n);let c=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of c)for(let d of Xe(a,u))!d.parentNode||!Ct(d,n)||$e(d)&&(l+=1);return{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(a),hasChanges:l>0,acceptedCount:l,warnings:r}}function rf(e,t){for(let r of Array.from(t.getElementsByTagNameNS(B,"delText"))){let n=F(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 Gh(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!==B)return $e(e);let o=Array.from(e.childNodes||[]).find(s=>s.nodeType===1&&s.namespaceURI===B&&String(s.localName||"").toLowerCase()===n.toLowerCase());if(!o)return $e(e);let a=Array.from(o.childNodes||[]),i=n.toLowerCase()==="ppr"?["rpr","sectpr"]:[],l=Array.from(r.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===B&&i.includes(String(s.localName||"").toLowerCase()));for(;r.firstChild;)r.removeChild(r.firstChild);for(let s of a){let c=Hh(r.ownerDocument,s);r.appendChild(c)}for(let s of l)r.appendChild(s);return!0}function Hh(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function nf(e,t,r){let n=new Set;for(let o of Xe(e,t)){if(!Ct(o,r))continue;let a=hr(o,"id");a&&n.add(a)}return n}function sf(e,t){let r=0,n=nf(e,"moveFromRangeStart",t),o=nf(e,"moveToRangeStart",t),a=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",o,!0],["moveToRangeEnd",o,!1]];for(let[i,l,s]of a)for(let c of Xe(e,i)){if(!c.parentNode)continue;let f=hr(c,"id");f&&(t.allAuthors||l.has(f)||s&&Ct(c,t))&&$e(c)&&(r+=1)}return r}function Ur(e,t={}){let r=[],n=Cs(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=_s(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let l=0;for(let f of Xe(a,"ins")){if(!f.parentNode||!Ct(f,n))continue;let u=of(f);if(u){(af(u,"reject")||$e(f))&&(l+=1);continue}if(Da(f)){let d=f.parentNode?.parentNode;$e(d)&&(l+=1);continue}$e(f)&&(l+=1)}for(let f of Xe(a,"tbl")){if(!f.parentNode)continue;!Array.from(f.childNodes||[]).some(d=>_t(d,"tr"))&&$e(f)&&(l+=1)}for(let f of Xe(a,"del"))if(!(!f.parentNode||!Ct(f,n))){if(Ua(f)){$e(f)&&(l+=1);continue}if(Da(f)){$e(f)&&(l+=1);continue}rf(a,f),$a(f)&&(l+=1)}for(let f of Xe(a,"moveFrom"))!f.parentNode||!Ct(f,n)||(rf(a,f),$a(f)&&(l+=1));for(let f of Xe(a,"moveTo"))!f.parentNode||!Ct(f,n)||$e(f)&&(l+=1);l+=sf(a,n);let s=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let f of s)for(let u of Xe(a,f))!u.parentNode||!Ct(u,n)||Gh(u,f)&&(l+=1);return Wh(a),{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(f=>i.serializeToString(f)).join(""):i.serializeToString(a),hasChanges:l>0,rejectedCount:l,warnings:r}}function qh(e,t){let r=new Set,n=Xe(e,"comment");for(let o of n){if(!Ct(o,t))continue;let a=hr(o,"id");a&&r.add(a)}return{targetIds:r,commentNodes:n}}function Yh(e,t){let r=0;for(let n of e){let o=hr(n,"id");!o||!t.has(o)||$e(n)&&(r+=1)}return r}function Jh(e){return _t(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!==B)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function Zh(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let o of n)for(let a of Xe(e,o)){if(!a.parentNode)continue;let i=hr(a,"id");if(!(!i||!t.has(i))){if(o==="commentReference"&&Jh(a.parentNode)){$e(a.parentNode)&&(r+=1);continue}$e(a)&&(r+=1)}}return r}function Os(e,t={}){let r=[],n=Cs(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=_s(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let{targetIds:l,commentNodes:s}=qh(a,n);if(n.allAuthors)for(let u of["commentRangeStart","commentRangeEnd","commentReference"])for(let d of Xe(a,u)){let m=hr(d,"id");m&&l.add(m)}let c=Yh(s,l),f=Zh(a,l);return{oxml:i.serializeToString(a),hasChanges:c>0||f>0,commentsRemoved:c,referencesRemoved:f,warnings:r}}var Qh=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 wr(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:Qh[t]||null,...r}))}var ew=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function rt(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Fo(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function on(e,t){return Fo(e).find(r=>rt(r)===t)||null}function za(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Xa(e){return String(e||"").trim().toLowerCase()}function tw(e){return rt(e)!=="r"?!1:Fo(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(rt(t)))}function ks(e){return ew.has(rt(e))||tw(e)}function Ms(e){return rt(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(rt(e))?Fo(e).filter(r=>!ks(r)&&rt(r)!=="sdtPr").every(Ms):!1}function rw(e){let t=e?.ownerDocument?.documentElement||null;if(!t)return!1;let r=new Set;for(let n of[t,...Array.from(t.getElementsByTagName?.("*")||[])]){if(n===e&&r.size>0)return!0;let o=rt(n),a=za(n,"id");o==="moveFromRangeStart"&&a!==""&&r.add(a),o==="moveFromRangeEnd"&&a!==""&&r.delete(a)}return!1}function lf(e){let t=on(e,"pPr"),r=on(t,"rPr");return on(r,"del")}function nw(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=rt(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,o=!1;for(;n&&n!==e;){let a=rt(n);if(a==="del"||a==="moveFrom"){o=!0;break}n=n.parentNode}if(!o&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function zr(e,t){let r=lf(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=za(r,"author")||null,o=!n||Xa(n)!==Xa(t),i=Fo(e).filter(l=>!ks(l)).every(Ms);return{matches:o&&i,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:i,ownerAuthor:n,markDeletion:r}}function an(e,t={}){let r=on(e,"pPr");if(on(r,"sectPr"))return{code:"SECTION_BREAK_PARAGRAPH",message:"Refusing to restore a deleted paragraph whose paragraph properties contain a section break."};let n=e?.parentNode||null;for(;n;){if(rt(n)==="moveFrom")return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};n=n.parentNode}if(rw(e)||e?.getElementsByTagName?.("*")&&Array.from(e.getElementsByTagName("*")).some(i=>["moveFrom","moveFromRangeStart","moveFromRangeEnd"].includes(rt(i))))return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};let o=e?.parentNode||null;for(;o&&rt(o)!=="tr";)o=o.parentNode;let a=on(o,"trPr");if(a&&on(a,"del"))return{code:"UNSAFE_DELETED_TABLE_ROW",message:"Refusing to restore a paragraph inside a table row with a pending row deletion."};if(t.requireFollowingParagraph!==!1){let i=e?.nextSibling||null;for(;i&&(i.nodeType!==1||rt(i)!=="p");)i=i.nextSibling;if(!i)return{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Refusing to restore a deleted paragraph without a following paragraph in the same structural container."}}return null}function cf(e){let t=rt(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>rt(n)==="p"),r=[];for(let n of t){let o=lf(n);if(!o)continue;let a=za(o,"author")||null,i=Fo(n).filter(c=>!ks(c)),l=i.filter(c=>rt(c)!=="ins"||!nw(c)?!1:Xa(za(c,"author"))!==Xa(a)),s=i.every(c=>Ms(c)||l.includes(c));l.length>0&&s&&r.push({paragraph:n,markDeletion:o,ownerAuthor:a,foreignInsertions:l})}return r}function ow(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of st(e,B,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 ja(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===B&&r.localName===t)||null}function aw(e,t){let r=ja(ja(ja(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(B,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(B,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(B,"date")||""}}function iw(e,t){let r=e.cloneNode(!1),n=ja(e,"pPr");return n&&r.appendChild(gt(n)),t.serializeToString(r)}function sw(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:xt(r.doc)[0];return n?(cu(n,t),Be(r.doc)):e}async function $o(e,t,r,n={}){let o=e,a=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let i=n.generateRedlines??!0,l=n.author||ae(),s=le(),c=[],f=[],u=!1,d=null,m=n.existingRevisions||"merge-same-author",p=m==="accept-all-first-keep-normalized",g=K=>{let V={...K};u&&V.hasChanges===!1&&V.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(V.oxml=a,V.hasChanges=!0,V.warnings=[...Array.isArray(V.warnings)?V.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(V.oxml=a,V.hasChanges=!0,V.warnings=[...Array.isArray(V.warnings)?V.warnings:[],"Existing revisions were accepted before redlining."]):V.oxml=o);let ye=[...c,...f,...Array.isArray(V.warnings)?V.warnings:[]];return ye.length>0&&(V.warnings=[...new Set(ye)]),V.status||(V.status=V.hasChanges?"ok":"no-op"),d&&V.hasChanges&&typeof V.oxml=="string"&&(V.oxml=sw(V.oxml,d)),Ce(V)},h=()=>g(u&&p?{oxml:a,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),v=j(o,"text/xml");c=v.warnings;let w=v.doc;m==="auto"&&(m=Lr("auto",w,l),n={...n,existingRevisions:m});let y=w?Fe(w):null;if(v.error||y){let K=v.error?.message||y?.textContent||"Could not parse OOXML input.";return Le("[OxmlEngine] XML parse error:",K),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:K}})}let b=n?._revisionIdAllocator instanceof De?n._revisionIdAllocator:new De;cr(w,b);let x=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:xt(w);if(x.length===1&&r.length>0){let K=zr(x[0],l);if(K.matches){let V=K.ownerAuthor||"unattributed";return g({oxml:o,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${V}). Use explicit paragraph restoration when supported.`,ownerAuthor:V}})}}if(fr(w))if(m==="merge-same-author"||m==="slice-cross-author"){let K=Mr(w),V=String(l||"").trim().toLowerCase();if(K.length>0&&!dr(w)&&K.every(Pe=>Pe.trim().toLowerCase()===V)){let Pe=ow(w);if(Pe.length>0)return g({oxml:o,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:Pe}});W("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let X=x.length===1?x[0]:null;d=aw(X,l);let Q=Ur(o,{author:l});if(Q.status==="error")return g(Q);a=d&&!String(Q.oxml||"").trim()?iw(X,s):Q.oxml,u=!0;let Te=j(a,"text/xml");c.push(...Te.warnings),w=Te.doc;let Se=w?Fe(w):null;if(Te.error||Se){let Je=Te.error?.message||Se?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return Le("[OxmlEngine] XML parse error after rejecting same-author revisions:",Je),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Je}})}if(fr(w))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});cr(w,b);let Ae=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:xt(w);t=Ae.length>0?Ae.map(Je=>Y(Je)).join(`
163
+ `):""}else{if(m==="merge-same-author")return W("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${K.length?K.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:K,currentPolicy:m}});if(["moveFrom","moveTo"].some(X=>st(w,B,X).length>0))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});W("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(m==="accept-all-first"||m==="accept-all-first-keep-normalized"){W("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let K=nn(o,{allAuthors:!0});if(K.status==="error")return g(K);a=K.oxml,u=!0;let V=j(a,"text/xml");c.push(...V.warnings),w=V.doc;let ye=w?Fe(w):null;if(V.error||ye){let Pe=V.error?.message||ye?.textContent||"Could not parse OOXML after accepting existing revisions.";return Le("[OxmlEngine] XML parse error after accepting existing revisions:",Pe),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Pe}})}cr(w,b)}else return W("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let S=Ou(w,t,n);if(S.hasTableWrapper&&S.targetParagraph&&!n._isolatedTableCell){W("[OxmlEngine] Isolating table-cell paragraph before diff");let K=Mo(w,S.targetParagraph,s),V=await $o(K,t,r,{...n,_isolatedTableCell:!0});return!V.hasChanges&&V.status==="no-op"?h():V}let A=n.sanitizeInput===!0?Ls(r):r;A!==r&&f.push("Input was sanitized; pass sanitizeInput: false to disable.");let E=null;if(n.structuredContent!==!1&&n.literalTextEdit!==!0)if(E=Ea(A),E.valid)E.requiresStructuredContent&&(A=E.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let K=E.issues.map(V=>`${V.code}: ${V.message}`).join(" ");return g({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:K},warnings:E.issues.map(V=>V.message)})}E=null}let{cleanText:I,formatHints:R}=n.plainTextContent===!0?{cleanText:A,formatHints:[]}:qe(A),{existingFormatHints:T,textSpans:N,paragraphs:O}=Tu(w),C=m==="slice-cross-author"?I!==t:I.trim()!==t.trim(),P=!C&&n.explicitStructuredContent===!0&&Mn(I)&&!lw(O,I),M=C||P,_=R.length>0,k=T.length>0,{textSpans:L}=Ra(O),D=L.map(K=>uf(K)).join(""),z=t.includes(`
164
+ `)||t.includes("\r")?t.split(/\r?\n/).map(Va).filter(Boolean).every(K=>O.some(V=>{let ye=L.filter(Pe=>Pe.paragraph===V).map(uf).join("");return Va(ye).includes(K)})):D.includes(t.trim())||D.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||Va(D).includes(Va(t));if(M&&typeof t=="string"&&t.trim()&&!z)return W("[OxmlEngine] Target text not found in OOXML"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let G=null,ee=()=>(G||(G=Ca(w,O,N)),G),J=(K=null)=>{let V=_u(w,t,R,s,l,i,K);return V.useNativeApi?(W("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),Ps(w,t,I,s,l,R,i)):V};W(`[OxmlEngine] Text changes: ${M}, New format hints: ${R.length}, Existing format hints: ${T.length}`);let Z=n.removeFormatting===!0&&!M&&!_&&k;if(!M&&!_&&!k)return wr(n,"noChange"),W("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),h();if(!M&&!_&&k&&!Z)return W("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),h();if(Z){wr(n,"formatOnly",{removeFormatting:!0}),W("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let K=S,V=K.targetParagraph||null;if(!V){let X=Au(ee(),t);X&&(V=X.paragraph)}let ye=T;V&&(ye=T.filter(X=>Ru(X.run)===V));let Pe=Cu(w,N,ye,s,l,i);return K.hasTableWrapper&&V?g({oxml:Mo(w,V,s),hasChanges:Pe.hasChanges}):g(Pe)}if(!M&&_){wr(n,"formatOnly",{removeFormatting:!1}),W(`[OxmlEngine] Format-only change detected: ${R.length} format hints`);let K=S,V={textSpans:N,paragraphs:O,paragraphInfos:ee()};if(K.hasTableWrapper&&K.targetParagraph){W("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let ye=J(V);return W("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),g({oxml:Mo(w,K.targetParagraph,s),hasChanges:ye.hasChanges})}return g(J(V))}let ne=st(w,B,"tbl").length>0,re=/^\|.+\|/.test(I.trim())&&I.includes(`
165
+ `),je=n.literalTextEdit!==!0&&Mn(I),ge=n.structuredContent!==!1&&E?.requiresStructuredContent===!0,he=S,Me=ne||m==="slice-cross-author";W(`[OxmlEngine] Mode: ${Me?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${R.length}, isMarkdownTable: ${re}, isTargetList: ${je}, isTableCellParagraph: ${he.isTableCellParagraph}`);try{if(re&&!ne)return wr(n,"table",{transformation:"text-to-table"}),W("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),g(Qu(w,I,s,null,l,i));if(ne&&re)return wr(n,"table",{transformation:"table-reconciliation"}),g(Zu(w,I,s,null,l,i));if(Me){wr(n,"surgical",{tableScoped:ne});let K=he.hasTableWrapper&&he.targetParagraph?he.targetParagraph:null;K&&W("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let V=zu(w,t,I,s,l,R,i,K,{},n);return V.status==="error"&&V.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?g({...V,oxml:o,hasChanges:!1}):he.hasTableWrapper&&V.hasChanges&&he.targetParagraph?(W("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),g({oxml:Mo(w,he.targetParagraph,s),hasChanges:!0})):g(V)}if(je||ge){let K=st(w,B,"p"),V=K.length===1;wr(n,V?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:K.length}),W(`[OxmlEngine] \u{1F3AF} Using ${V?"direct list generation":"compatibility pipeline"} for list reconciliation`);let ye;if(V){let Pe=Dn(a,{xmlDoc:w}),X=Po(K[0]);ye=await Wn({cleanText:I,numberingContext:X,originalRunModel:Pe.runModel,originalText:Pe.acceptedText,generateRedlines:i,author:l,font:n.font||null,revisionIdAllocator:b,numberingService:new ur})}else ye=await new _o({author:l,generateRedlines:i,revisionIdAllocator:b}).execute(a,A,{xmlDoc:w});if(ye.error?.code==="DIFF_TOKEN_LIMIT")return g({oxml:o,hasChanges:!1,status:"error",error:ye.error});if(ye.isValid&&ye.ooxml&&ye.ooxml!==a){let Pe=ye.includeNumbering===!0;W(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${Pe}`);let X=kr(ye.ooxml,{includeNumbering:Pe,numberingXml:ye.numberingXml});return W(`[OxmlEngine] \u2705 Wrapped OOXML length: ${X.length}`),g({oxml:X,hasChanges:!0,...Array.isArray(ye.warnings)?{warnings:ye.warnings}:{}})}return h()}return wr(n,"reconstruction"),g(Ps(w,t,I,s,l,R,i,{},n))}catch(K){if(Xc(K))return g({oxml:o,hasChanges:!1,status:"error",error:{code:K.code,message:K.message}});throw K}}function lw(e,t){let r=String(t).split(/\r?\n/).filter(n=>n.trim()).length;return e.length===r&&e.every(n=>it(n).numPr!=null)}function Va(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function uf(e){let t=e?.textElement,r=String(t?.localName||t?.nodeName||"").replace(/^.*:/,"");return r==="tab"?" ":r==="br"||r==="cr"?`
166
+ `:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function Ls(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 Ve(e){return j(e,"application/xml").doc}function Kt(e){return Be(e)}function Wa(e){return Array.from(e||[])}function Do(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function ht(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var fe="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function ff(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=Wa(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=Wa(e.getElementsByTagName(`w:${t}`));return r.length>0?r:Wa(e.getElementsByTagName(t))}function _e(e){return e?Y(e):""}function se(e){if(!e)return[];let t=ff(e,"body"),r=t.length>0?t[0]:e;return ff(r,"p")}function He(e){return e&&Wa(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function Ot(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:Y(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:se(e.ownerDocument||e).indexOf(e)+1,a=t.paragraphId===void 0?He(e):t.paragraphId,i=typeof t.inTable=="boolean"?t.inTable:Uo(e),s=`${a||""}${o}${i?"table":"body"}${r==="rejected"?"rejected":""}${n}`,c=2166136261;for(let f=0;f<s.length;f++)c^=s.charCodeAt(f),c=Math.imul(c,16777619)>>>0;return`fnv1a32:${c.toString(16).padStart(8,"0")}`}function rr(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=se(e),o=[],a=new Map,i=new Map,l=new Map;for(let s=0;s<n.length;s++){let c=n[s],f=Y(c,{revisionView:r}),u=He(c),d=Uo(c),m=q(f),p=Object.freeze({paragraph:c,index:s+1,paragraphId:u,text:f,normalizedText:m,revisionView:r,fingerprint:Ot(c,{text:f,index:s+1,paragraphId:u,inTable:d,revisionView:r}),inTable:d});o.push(p),a.set(c,p),u&&!i.has(u)&&i.set(u,p),m&&(l.has(m)||l.set(m,[]),l.get(m).push(p))}for(let[s,c]of l)l.set(s,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:a,byId:i,byNormalizedText:l})}function q(e){return String(e||"").replace(/\s+/g," ").trim()}function sn(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
167
+ `)}function Fs(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 cw(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function uw(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 df(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 ut(e,t,r=fe){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function Ka(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,a=o?null:se(e),i=String(t||"").trim();if(!i)return null;let l=o?o.find(c=>c.text.trim()===i)?.paragraph:a.find(c=>_e(c).trim()===i);if(l)return l;let s=q(i);return n?.byNormalizedText?n.byNormalizedText.get(s)?.[0]?.paragraph||null:a.find(c=>q(_e(c))===s)||null}function Bs(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,a=o?.entries||null,i=a?null:se(e),l=String(t||"").trim();if(!l)return null;let s=Ka(e,l,{paragraphMetadataIndex:o});if(s)return s;let c=q(l),f=a?a.find(h=>h.normalizedText.length>10&&c.startsWith(h.normalizedText))?.paragraph||null:i.find(h=>{let v=q(_e(h));return v.length>10&&c.startsWith(v)});if(f)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${_e(f).trim().slice(0,60)}..."`),f;let u=a?a.find(h=>h.normalizedText.length>15&&c.includes(h.normalizedText))?.paragraph||null:i.find(h=>{let v=q(_e(h));return v.length>15&&c.includes(v)});if(u)return n(`[Fuzzy] Contains match: "${_e(u).trim().slice(0,60)}..."`),u;let d=0,m=null,p=new Set(c.toLowerCase().split(/\s+/).filter(h=>h.length>2)),g=a?.length??i.length;for(let h=0;h<g;h++){let v=a?.[h]?.paragraph??i[h],w=(a?.[h]?.text??_e(v)).trim();if(!w)continue;let x=q(w).toLowerCase().split(/\s+/).filter(S=>S.length>2).filter(S=>p.has(S)).length/Math.max(p.size,1);x>d&&x>.5&&(d=x,m=v)}return m?(n(`[Fuzzy] Best word-overlap match (${(d*100).toFixed(0)}%): "${_e(m).trim().slice(0,60)}..."`),m):null}function ln(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},o=t.opType||"operation",a=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,i=a?.revisionView==="rejected"?"rejected":"accepted",l=String(a?.exactText??a?.text??t.targetText??"").trim(),s=Fs(a?.index??a?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,f=t.paragraphMetadataIndex||null;if(f&&f.revisionView!==i?f=t.metadataIndices?.[i]||rr(e,{revisionView:i}):f||(f=rr(e,{revisionView:i})),a?.paragraphId){let d=dw(e,a.paragraphId,f);if(!d)throw ht("TARGET_NOT_FOUND",`Target paragraphId not found: "${a.paragraphId}".`);let m=f?.byParagraph?.get(d)||null,p=m?.index??se(e).indexOf(d)+1,g=m?.fingerprint||Ot(d,{revisionView:i}),h=m?.inTable??Uo(d),v=m?.normalizedText||q(Y(d,{revisionView:i}));if(s!=null&&s!==p)throw ht("TARGET_INDEX_MISMATCH",`Target paragraphId "${a.paragraphId}" (index ${p}) does not match requested index ${s}.`,m?[Gt(m)]:null);if(a.fingerprint&&a.fingerprint!==g){let w=i==="rejected"?"accepted":"rejected",y=Ot(d,{revisionView:w}),b=a.fingerprint===y?` The supplied fingerprint matches the ${w} view; set target.revisionView to "${w}" or use a fingerprint extracted from the ${i} view.`:"";throw ht("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches its source fingerprint.${b}`,m?[Gt(m)]:null)}if(typeof a.inTable=="boolean"&&a.inTable!==h)throw ht("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" does not match the requested table context.`,m?[Gt(m)]:null);if(l&&v!==q(l)){let w=i==="rejected"?"accepted":"rejected",b=q(Y(d,{revisionView:w}))===q(l)?` The supplied text matches the ${w} view; set target.revisionView to "${w}".`:"";throw ht("TARGET_TEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches the supplied text.${b}`,m?[Gt(m)]:null)}if(a.occurrence!=null){let y=Ga(e,l||v,f),b=y.findIndex(x=>x.paragraph===d)+1;if(b===0||b!==a.occurrence)throw ht("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${a.paragraphId}" matches occurrence ${b}, not requested occurrence ${a.occurrence}.`,y.map(Gt))}return{paragraph:d,resolvedBy:"paragraph_id"}}if(a?.fingerprint&&!l&&!s){let d=(f?.entries||[]).filter(m=>m.fingerprint===a.fingerprint);if(typeof a.inTable=="boolean"&&(d=d.filter(m=>m.inTable===a.inTable)),d.length===1)return{paragraph:d[0].paragraph,resolvedBy:"fingerprint"};throw d.length>1?ht("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",d.map(Gt)):ht("TARGET_NOT_FOUND",`Target fingerprint not found: "${a.fingerprint}".`)}let u=[];if(l){let d=Ga(e,l,f);if(u=fw(d,a),a?.fingerprint&&d.length>0&&u.length===0)throw ht("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",d.map(Gt));if(typeof a?.inTable=="boolean"&&d.length>0&&u.length===0)throw ht("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",d.map(Gt));if(a?.occurrence){let m=u[a.occurrence-1]||null;if(!m)throw ht("TARGET_NOT_FOUND",`Target occurrence ${a.occurrence} was not found.`,u.map(Gt));return{paragraph:m.paragraph,resolvedBy:"occurrence"}}if(c){if(s){let m=u.find(p=>p.index===s)||null;if(m)return{paragraph:m.paragraph,resolvedBy:"ref"};if(a?.fingerprint&&u.length>0)throw ht("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`,u.map(Gt));if(u.length===1)return{paragraph:u[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(u.length>1)throw ht("AMBIGUOUS_TARGET",`Target text matched ${u.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,u.map(Gt));if(u.length===0)throw Do(`Target paragraph not found: "${l}"`)}if(!s&&u.length===1)return{paragraph:u[0].paragraph,resolvedBy:a?.fingerprint?"fingerprint":"strict_text"}}if(s){let d=df(e,s,f);if(d){let m=f?.byParagraph?.get(d)||null;if(a?.fingerprint&&a.fingerprint!==m?.fingerprint)throw ht("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`);if(typeof a?.inTable=="boolean"&&a.inTable!==m?.inTable)throw ht("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${s}] does not match requested table context.`);if(l){let p=Ka(e,l,{paragraphMetadataIndex:f}),g=(m?.text||Y(d,{revisionView:i})).trim(),h=q(g),v=q(l),w=h!==v;if(w&&p&&p!==d)return r(`[Target] [P${s}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let y=Bs(e,l,{onInfo:r,paragraphMetadataIndex:f});if(y&&y!==d)return r(`[Target] [P${s}] drifted for ${o}; using fuzzy text rematch.`),{paragraph:y,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${s}] fallback for ${o}; target text drifted.`)}else p&&p!==d&&r(`[Target] [P${s}] disambiguated duplicate target text for ${o}.`)}else r(`[Target] Using [P${s}] fallback for ${o}.`);return{paragraph:d,resolvedBy:"ref"}}n(`[WARN] Target reference [P${s}] not found; falling back to text matching for ${o}.`)}if(l&&!c){let d=Ka(e,l,{paragraphMetadataIndex:f});if(d){let p=u.length;if(p>1){let g=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(g),{paragraph:d,resolvedBy:"strict_text",warnings:[g]}}return{paragraph:d,resolvedBy:"strict_text"}}let m=Bs(e,l,{onInfo:r,paragraphMetadataIndex:f});if(m)return{paragraph:m,resolvedBy:"fuzzy_text"}}throw Do(l?`Target paragraph not found: "${l}"`:s?`Target paragraph reference not found: [P${s}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function Uo(e){return!!ut(e,"tbl")}function Ga(e,t,r=null){let n=q(t);if(!n)return[];let o=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,a=r?.revisionView||o?.revisionView||"accepted";if(o?.byNormalizedText&&o.revisionView===a)return Array.from(o.byNormalizedText.get(n)||[]);let i=se(e),l=[];for(let s=0;s<i.length;s++){let c=i[s],f=Y(c,{revisionView:a}).trim();f&&q(f)===n&&l.push({paragraph:c,index:s+1,inTable:Uo(c),paragraphId:He(c),fingerprint:Ot(c,{text:f,index:s+1,revisionView:a}),text:f,revisionView:a})}return l}function Gt(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function fw(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 dw(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:se(e).find(n=>He(n)===t)||null:null}function mw(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let o=n.filter(a=>a.inTable===r);o.length>0&&(n=o)}return Number.isInteger(t)&&t>0&&n.sort((o,a)=>Math.abs(o.index-t)-Math.abs(a.index-t)),n[0]||null}function $s(e,t=null){let r=t?.entries||null,n=r?null:se(e),o=new Map,a=r?.length??n.length;for(let i=0;i<a;i++){let l=r?.[i]?.paragraph??n[i],s=(r?.[i]?.text??_e(l)).trim();o.set(i+1,{text:s,normalizedText:r?.[i]?.normalizedText??q(s),inTable:r?.[i]?.inTable??Uo(l)})}return o}function Jn(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=ln(e,t),o=Fs(t.targetRef);if(!o||n?.resolvedBy!=="ref")return n;let a=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(o)||null;if(!a)return n;let i=String(t.targetText||"").trim(),l=i||a.text||"",s=q(l);if(!s||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||q(_e(n.paragraph)))===s)return n;let f=[];if(i&&f.push(i),a.text){let d=q(a.text);d&&!f.some(m=>q(m)===d)&&f.push(a.text)}let u=null;for(let d of f){let m=Ga(e,d,t.paragraphMetadataIndex||null),p=mw(m,o,a.inTable);if(p&&(u||(u=p),p.paragraph!==n.paragraph)){u=p;break}}if(u&&u.paragraph!==n.paragraph){let d=t.opType||"operation";return r(`[Target] [P${o}] appears stale after prior edits; using strict text rematch for ${d}.`),{paragraph:u.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw Do(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function cn(e,t,r,n={}){if(!e||!t||!r)return null;let o=n?.opType||"redline",a=n?.targetRefSnapshot||null,i=typeof n?.onInfo=="function"?n.onInfo:()=>{},l=typeof n?.onWarn=="function"?n.onWarn:()=>{},s=Jn(e,{targetRef:t,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:l})?.paragraph;if(!s)return null;let c=Jn(e,{targetRef:r,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:l})?.paragraph;if(!c)return null;let f=Array.from(e.getElementsByTagNameNS("*","p")),u=f.indexOf(s),d=f.indexOf(c);if(u<0||d<u)return null;let m=f.slice(u,d+1);if(m.length===0)return null;let p=m[0]?.parentNode||null;return!p||!m.every(g=>g&&g.parentNode===p)?null:m}function Ha(e,t,r={}){if(!e||!e.parentNode)return{valid:!0};let n=t===""||r.operationKind==="delete",o=typeof t=="string"&&t.includes(`
168
+ `),a=r.targetEndParagraph||null,i=ut(e,"tc");if(i){if(n&&Array.from(i.childNodes).filter(c=>$(c,"p")).length<=1)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete the sole terminal paragraph of a table cell."};if(a&&ut(a,"tc")!==i)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across different table cells."}}else if(a&&ut(a,"tc"))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across table boundaries."};if(e.getElementsByTagNameNS(fe,"sectPr").length>0&&n)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete paragraph containing section properties (w:sectPr)."};if(a){let s=e;for(;s&&s!==a;){if($(s,"p")&&s.getElementsByTagNameNS(fe,"sectPr").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across section break."};s=s.nextSibling}}if(o){if(e.getElementsByTagNameNS(fe,"fldSimple").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph containing a simple field instruction (w:fldSimple)."};let c=Array.from(e.getElementsByTagNameNS(fe,"fldChar"));if(c.length>0){let p=0;for(let g of c){let h=g.getAttributeNS(fe,"fldCharType")||g.getAttribute("w:fldCharType");h==="begin"?p++:h==="end"&&(p=Math.max(0,p-1))}if(p>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph across an unclosed field instruction."}}let f=Array.from(e.getElementsByTagNameNS(fe,"bookmarkStart")),u=Array.from(e.getElementsByTagNameNS(fe,"bookmarkEnd")),d=new Set(f.map(p=>p.getAttributeNS(fe,"id")||p.getAttribute("w:id"))),m=new Set(u.map(p=>p.getAttributeNS(fe,"id")||p.getAttribute("w:id")));for(let p of d)if(p&&!m.has(p))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:`Refusing to split paragraph across open bookmark range (ID: ${p}).`}}return{valid:!0}}function qa(e,t){if(!e)return null;for(let r of Array.from(e.childNodes||[]))if(r?.nodeType===1&&r.localName===t)return r;return null}function mf(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(fe,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function un(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=Zt(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function gf(e){let t=String(e||"").split(/\r?\n/g),r=[],n=!1;for(let o of t){let a=o.trimEnd();if(!a.trim())continue;let i=qr(a,{indentSpaces:2});if(i){n=!0,r.push({kind:"list",markerType:i.markerType,level:i.level,marker:i.marker,outlineLevel:i.outlineLevel,text:un(i.text)});continue}r.push({kind:"text",text:a.trim()})}return{items:r,hasListMarkers:n}}function pf(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function zo(e,t){return q(e)===q(t)}function Ya(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function pw(e,t,r){if(!Array.isArray(e)||e.length<2||!Number.isInteger(r)||r<0)return!1;let n=e[0],o=e.slice(1).filter(a=>a.kind==="list");if(o.length===0||o.some(a=>a.markerType!=="bullet")||o.some(a=>Number.isInteger(a.outlineLevel)))return!1;if(n?.kind==="text")return zo(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let a=n.level||0;return o.some(l=>(l.level||0)>a)?!1:zo(n.text,t)}return!1}function gw(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 hw(e,t,r,n){let o=e[0],a=e.slice(1).filter(i=>i.kind==="list");if(o?.kind==="text"&&zo(o.text,t)&&a.length>0){let i=a[0].level;return a.map(l=>({ilvl:Ya(l,r,i),markerType:l.markerType||n,text:l.text}))}if(e.every(i=>i.kind==="list")){let i=e[0];if(!i||!zo(i.text,t))return null;let l=i.level;return e.slice(1).map(s=>({ilvl:Ya(s,r,l),markerType:s.markerType||n,text:s.text})).filter(s=>s.text)}return null}function Oe(e){if(!e)return null;let t=qa(e,"pPr");if(!t)return null;let r=qa(t,"numPr");if(!r)return null;let n=qa(r,"numId");if(!n)return null;let o=mf(n);if(!o||o==="0")return null;let a=qa(r,"ilvl"),i=mf(a),l=Number.parseInt(i||"0",10);return{numId:String(o),ilvl:Number.isFinite(l)?l:0}}function hf(e){let t=Oe(e);if(!t)return null;let r=e.parentNode;if(!r)return null;let n=Array.from(r.childNodes||[]).filter(l=>l&&l.nodeType===1&&l.namespaceURI===fe&&l.localName==="p"),o=n.indexOf(e);if(o<0)return null;let a=o;for(;a>0;){let l=Oe(n[a-1]);if(!l||l.numId!==t.numId)break;a--}let i=o;for(;i<n.length-1;){let l=Oe(n[i+1]);if(!l||l.numId!==t.numId)break;i++}return n.slice(a,i+1)}function Ds(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
169
+ `)||!Oe(e))return null;let l=hf(e);if(!l||l.length===0)return null;let s=gf(a);if(!s.hasListMarkers||s.items.length<2)return null;let c=q(r.currentParagraphText||_e(e)),u=s.items.filter(A=>A.kind==="list")[0]?.markerType||"bullet",d=l.map(A=>({paragraph:A,list:Oe(A),text:String(_e(A)||"").trim()})),m=l.indexOf(e);if(m<0)return null;let p=Math.min(...d.map(A=>A.list?.ilvl??0)),g=d.map(A=>pf((A.list?.ilvl??0)-p,u,A.text)),h=null,v=s.items[0],w=s.items.slice(1).filter(A=>A.kind==="list");if(v?.kind==="text"&&zo(v.text,c)&&w.length>0){let A=Math.max(0,(d[m].list?.ilvl??0)-p),E=w[0].level;h=[{level:A,markerType:u,text:d[m].text},...w.map(I=>({level:Ya(I,A,E),markerType:I.markerType||u,text:I.text}))]}else if(s.items.every(A=>A.kind==="list")){let A=Math.max(0,(d[m].list?.ilvl??0)-p),E=s.items[0].level;h=s.items.map(I=>({level:Ya(I,A,E),markerType:I.markerType||u,text:I.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let y=h.map(A=>pf(A.level,A.markerType,A.text)),b=g.slice(0,m).concat(y).concat(g.slice(m+1)),x=g.join(`
170
+ `),S=b.join(`
171
+ `);return S===x?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:l,originalText:x,modifiedText:S})}function Us(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
172
+ `))return null;let i=Oe(e);if(!i)return null;let l=gf(a);if(!l.hasListMarkers||l.items.length<2)return null;let s=q(r.currentParagraphText||_e(e)),f=l.items.filter(m=>m.kind==="list")[0]?.markerType||"bullet",u=Math.max(0,i.ilvl),d=hw(l.items,s,u,f);return!d||d.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(pw(l.items,s,u)&&(d=gw(d,u),n("[List] Promoted bullet insertion to child depth for nested numbered-list intent.")),n("[List] Planned insertion-only list redline entries (no block rewrite)."),{targetParagraph:e,numId:i.numId,entries:d})}function Xo(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
173
+ `),n=[];for(let i of r){if(!i.trim())continue;let l=qr(i,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});if(l){n.push({type:l.markerType,level:l.level,text:l.text.trim(),marker:l.marker});continue}n.push({type:"text",level:0,text:i.trim()})}if(n.length===0)return null;let o=n.some(i=>i.type==="numbered"),a=n.some(i=>i.type==="bullet");return{type:o?"numbered":a?"bullet":"text",items:n}}function zs(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function ww(e,t,r){let n=new Map,o=[];for(let a of e){let i=Math.max(0,Number(a?.level)||0);for(let f of Array.from(n.keys()))f>i&&n.delete(f);let l=(n.get(i)||0)+1;n.set(i,l);let s=yw(l,t,r),c=" ".repeat(i*4);o.push(`${c}${s} ${a.text||""}`.trimEnd())}return o.join(`
174
+ `)}function vw(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let o=String(n??""),a=o.match(/^(\s*)/),i=a?a[1].length:0,l=Math.floor(i/r),s=o.trim(),c=null,f=Xt(s,{allowZeroSpaceAfterMarker:!0});return f&&(c=f[2].trim()||null,s=Zt(s,{allowZeroSpaceAfterMarker:!0})),{text:s.trim(),level:l,removedMarker:c}})}function yw(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${wf(e,!1)}.`;case"upperAlpha":return`${wf(e,!0)}.`;case"lowerRoman":return`${vf(e,!1)}.`;case"upperRoman":return`${vf(e,!0)}.`;default:return`${e}.`}}function wf(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 vf(e,t=!1){let r=Math.max(1,Number(e)||1),n=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],o="";for(let[a,i]of n)for(;r>=a;)o+=i,r-=a;return t?o:o.toLowerCase()}function Ja(e){let t=String(e||"");if(!t.trim()||t.includes(`
175
+ `))return null;let r=Xo(t);if(!r||!zs(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let o=String(n.marker||"").trim(),a=n.type==="numbered"?So(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:a,startAt:xw(o,a),contentText:String(n.text||"").trim(),normalizedContent:q(String(n.text||""))}}function Xs(e){let t=Ja(e);return t?String(t.contentText||"").trim():String(e||"").trim()}var yf={i:1,v:5,x:10,l:50,c:100,d:500,m:1e3};function bw(e){let t=String(e||"").toLowerCase();if(!/^[ivxlcdm]+$/.test(t))return null;let r=0;for(let n=0;n<t.length;n++){let o=yf[t[n]],a=yf[t[n+1]]||0;r+=o<a?-o:o}return r}function xw(e,t){let r=String(e||"").trim(),n=null;if(t==="decimal"){let o=r.match(/^(\d+)\.?$/);n=o?Number.parseInt(o[1],10):null}else if(t==="lowerRoman"||t==="upperRoman"){let o=r.match(/^([A-Za-z]+)[.)]?$/);n=o?bw(o[1]):null}else if(t==="lowerAlpha"||t==="upperAlpha"){let o=r.match(/^([A-Za-z])[.)]?$/);n=o?o[1].toLowerCase().charCodeAt(0)-96:null}else return null;return!Number.isFinite(n)||n<1||t!=="decimal"&&n===1?null:n}function Za(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let o=t?.explicitByNumberingKey;if(!(o instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let a=o.get(r)||null;return a&&a.numId!=null&&Number.isInteger(a.nextStartAt)&&a.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(a.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function Qa(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 Vo(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function fn(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 ei(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,o=t?.clearParagraphPropertyChanges!==!1,a=t?.removeListPropertyNode!==!1,i=t?.trackPropertyChange||null,l=(Array.isArray(e)?e:[]).filter(c=>c&&c.nodeType===1&&c.localName==="p"),s=0;for(let c of l){let f=c.ownerDocument;if(!f)continue;let u=fn(c,"pPr");u||(u=F(f,"w:pPr"),c.insertBefore(u,c.firstChild));let d=i?gt(u):null;if(o){let h=fn(u,"pPrChange");h&&u.removeChild(h)}if(a){let h=fn(u,"listPr");h&&u.removeChild(h)}let m=fn(u,"numPr");m||(m=F(f,"w:numPr"),u.appendChild(m));let p=fn(m,"ilvl");p||(p=F(f,"w:ilvl"),m.appendChild(p)),p.setAttribute("w:val",String(n));let g=fn(m,"numId");if(g||(g=F(f,"w:numId"),m.appendChild(g)),g.setAttribute("w:val",String(r)),i&&!fn(u,"pPrChange")){let h=ue(i.author,i.revisionIdAllocator||f,"pPrChange"),v=F(f,"w:pPrChange");v.setAttribute("w:id",String(h.id)),v.setAttribute("w:author",h.author),v.setAttribute("w:date",h.date),v.appendChild(d||F(f,"w:pPr")),u.appendChild(v)}s++}return s}function xf(e){let t=String(e||""),r=/xmlns:w\s*=/.test(t);return j(r?t:`<w:root xmlns:w="${B}">${t}</w:root>`,"application/xml").doc}function Iw(e){let t=xf(e);return!t||Fe(t)?null:se(t)[0]||null}function Nw(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function Tw(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function Zn(e,t){let r=Tw(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function bf(e,t){e.setAttribute("w:val",String(t))}function Sw(e){let t=xf(e);if(!t||Fe(t))return null;let n=se(t);for(let o of n){let a=Vt(o);for(let i of a){let l=Zn(i,["w:val","val"]);if(l!=null)return String(l)}}return null}function Aw(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,a=le(),i=j(e,"application/xml").doc;if(!i||Fe(i))return e;let c=Array.from(i.getElementsByTagNameNS("*","num")).find(p=>{let g=Zn(p,["w:numId","numId"]);return g!=null&&String(g)===String(t)});if(!c)return e;let f=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,u=Zn(f,["w:val","val"]),d=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>Zn(p,["w:ilvl","ilvl"])===0)||null;d||(d=F(i,"w:lvlOverride"),d.setAttribute("w:ilvl","0"),c.appendChild(d));let m=Array.from(d.getElementsByTagNameNS("*","startOverride"))[0]||null;if(m||(m=F(i,"w:startOverride"),d.appendChild(m)),bf(m,r),o&&u!=null){let g=Array.from(i.getElementsByTagNameNS("*","abstractNum")).find(h=>{let v=Zn(h,["w:abstractNumId","abstractNumId"]);return v!=null&&v===u})||null;if(g){let h=Array.from(g.getElementsByTagNameNS("*","lvl")).find(w=>Zn(w,["w:ilvl","ilvl"])===0)||null;h||(h=F(i,"w:lvl"),h.setAttribute("w:ilvl","0"),g.appendChild(h));let v=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;v||(v=F(i,"w:start"),h.insertBefore(v,h.firstChild)),bf(v,r)}}return a.serializeToString(i)}function dn(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),o=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let a=Iw(t);if(!a)return null;let i=Oe(a);if(i&&!o)return null;let l=qe(n).cleanText||n,s=Ja(n)||Ja(l);if(!s)return null;let c=Ja(r),f=q(r)===q(l),u=!!c&&c.type===s.type&&c.normalizedContent===s.normalizedContent;return!f&&!u?null:{listInput:`${s.marker} ${s.contentText}`.trim(),numberingKey:`${s.type}:${s.numberingStyle}:single`,originalText:r,wasListParagraph:!!i,numberingStyle:s.numberingStyle,startAt:s.startAt}}async function Qn(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 Wn({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new ur}),a=o?.oxml||o?.ooxml||"",i=Nw(a),l=Sw(i),s=Aw(o?.numberingXml||null,l,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=o?.isValid!==!1;return!i||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:i,numberingXml:s,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}function If(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 eo(e,t,r=null){let n=Number.isInteger(e)&&e>0?e:1,o=t instanceof Set?t:new Set;for(;o.has(n);)n+=1;if(Number.isInteger(r)&&r>0&&n>r){for(let a=1;a<=r;a+=1)if(!o.has(a))return a}return n}function Ht(e,t={}){let r=Number.isInteger(t?.minId)&&t.minId>0?t.minId:1,n=Number.isInteger(t?.maxPreferred)&&t.maxPreferred>=r?t.maxPreferred:32767,o=new Set,a=new Set;if(String(e||"").trim())try{let f=Ve(e),u=Array.from(f.getElementsByTagNameNS("*","abstractNum")),d=Array.from(f.getElementsByTagNameNS("*","num"));for(let m of u){let p=If(m,["w:abstractNumId","abstractNumId"]);p!=null&&a.add(p)}for(let m of d){let p=If(m,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let i=o.size>0?Math.max(...o):0,l=a.size>0?Math.max(...a):0,s=Math.max(r,i+1),c=Math.max(r,l+1);return{sourceNumberingXml:String(e||""),nextNumId:eo(s,o,n),nextAbstractNumId:eo(c,a,n),usedNumIds:o,usedAbstractNumIds:a,minId:r,maxPreferred:n}}function Ew(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=eo(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=eo(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function Wo(e,t="num"){let r=Ew(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=eo(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=eo(o+1,r.usedNumIds,r.maxPreferred)),o)}function to(e){let t=Wo(e,"num"),r=Wo(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function $t(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function jo(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===fe&&e.localName===t)}function Rw(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function ft(e,t){let r=Rw(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Nf(e,t,r){e?.setAttribute?.(t,String(r))}function Vs(e,t){e?.setAttribute?.("w:val",String(t))}function ti(e,t){if(!(!Array.isArray(e)||t==null)){for(let r of e)if(!kt(r))for(let n of Vt(r))Vs(n,t)}}function ri(e){for(let t of e||[])for(let r of Vt(t)){let n=ft(r,["w:val","val"]);if(n!=null)return String(n)}return null}function ni(e,t,r){let n=String(e),o=String(t),a=Number.isInteger(r)&&r>0?r:1,i=Array.from({length:9},(l,s)=>{let c=Array.from({length:s+1},(u,d)=>`%${d+1}`).join(".")+".",f=720*(s+1);return`
176
+ <w:lvl w:ilvl="${s}">
176
177
  <w:start w:val="1"/>
177
178
  <w:numFmt w:val="decimal"/>
178
179
  <w:lvlText w:val="${c}"/>
179
180
  <w:lvlJc w:val="left"/>
180
- <w:pPr><w:ind w:left="${u}" w:hanging="360"/></w:pPr>
181
+ <w:pPr><w:ind w:left="${f}" w:hanging="360"/></w:pPr>
181
182
  </w:lvl>`}).join("");return`
182
- <w:numbering xmlns:w="${Oe}">
183
+ <w:numbering xmlns:w="${fe}">
183
184
  <w:abstractNum w:abstractNumId="${o}">
184
185
  <w:multiLevelType w:val="multilevel"/>
185
186
  ${i}
@@ -190,41 +191,43 @@ var Af=Object.create;var _s=Object.defineProperty;var Ef=Object.getOwnPropertyDe
190
191
  <w:startOverride w:val="${a}"/>
191
192
  </w:lvlOverride>
192
193
  </w:num>
193
- </w:numbering>`.trim()}function Bi(e){if(!e||e.nodeType!==1||e.localName!=="p")return!1;let t=Array.from(e.childNodes||[]).find(n=>Vr(n,"pPr")),r=t&&Array.from(t.childNodes||[]).find(n=>Vr(n,"rPr"));return!!r&&Array.from(r.childNodes||[]).some(n=>Vr(n,"del"))}function Li(e){return Array.from(e?.getElementsByTagNameNS?.("*","numId")||[]).filter(t=>t.parentNode?.localName==="numPr")}function kc(e){let t=new Map;for(let r of Array.from(e?.getElementsByTagNameNS?.("*","lvl")||[])){let n=xt(r,["w:ilvl","ilvl"]),o=Array.from(r.getElementsByTagNameNS("*","numFmt"))[0]?.getAttribute("w:val")||null;n!=null&&o&&t.set(n,o)}return t}function Mc(e){return e==="bullet"||e==="circle"||e==="square"?"bullet":e}function Lc(e,t){let r=Array.from(e.getElementsByTagNameNS("*","num")).find(o=>xt(o,["w:numId","numId"])===t),n=r&&xt(Array.from(r.getElementsByTagNameNS("*","abstractNumId"))[0],["w:val","val"]);return n==null?null:Array.from(e.getElementsByTagNameNS("*","abstractNum")).find(o=>xt(o,["w:abstractNumId","abstractNumId"])===n)||null}function Bc(e,t,r,n){let o=n?.sourceNumberingXml;if(!e||!String(o||"").trim()||!Array.isArray(t))return null;let a=new Set;for(let p of r||[])for(let g of Li(p)){let h=xt(g,["w:val","val"]);h!=null&&h!==0&&a.add(h)}if(a.size!==1)return null;let[i]=a,s=ft(o),l=ft(e);if(ro(s)||ro(l))return null;let c=Lc(s,i);if(!c)return null;let u=kc(c),f=[];for(let p of t)if(!Bi(p))for(let g of Li(p)){let h=Array.from(g.parentNode.childNodes||[]).find(y=>y.localName==="ilvl");f.push({numId:xt(g,["w:val","val"]),ilvl:h?xt(h,["w:val","val"])??0:0})}if(f.length===0)return null;let d=new Map;for(let{numId:p,ilvl:g}of f){if(p==null)return null;if(!d.has(p)){let w=Lc(l,p);if(!w)return null;d.set(p,kc(w))}let h=d.get(p).get(g),y=u.get(g);if(!h||!y||Mc(h)!==Mc(y))return null}let m=t.map(p=>p?.cloneNode?p.cloneNode(!0):p);for(let p of m)if(!Bi(p))for(let g of Li(p))la(g,i);return{numId:i,replacementNodes:m}}function yn(e,t,r){let n=ft(e);if(ro(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let o=new Map,a=new Map,i=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of i){let u=xt(c,["w:abstractNumId","abstractNumId"]);if(u==null)continue;let f=to(r,"abstract");f!=null&&(o.set(u,f),_c(c,"w:abstractNumId",f))}let s=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of s){let u=xt(c,["w:numId","numId"]);if(u==null)continue;let f=to(r,"num");if(f==null)continue;a.set(u,f),_c(c,"w:numId",f);let d=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(d){let m=xt(d,["w:val","val"]);m!=null&&o.has(m)&&la(d,o.get(m))}}let l=Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[];for(let c of l){if(Bi(c))continue;let u=Array.from(c?.getElementsByTagNameNS?.("*","numId")||[]);for(let f of u){let d=xt(f,["w:val","val"]);d!=null&&a.has(d)&&la(f,a.get(d))}}return{numberingXml:Yt(n),replacementNodes:l}}function ma(e,t){let r=String(e||""),n=String(t||"");if(!n.trim())return r;if(!r.trim())return n;try{let o=ft(r),a=ft(n);if(ro(o)||ro(a))return r;let i=o.documentElement,s=a.documentElement;if(!i||!s)return r;let l=new Set(Array.from(i.childNodes||[]).filter(u=>Vr(u,"abstractNum")).map(u=>hn(u,["w:abstractNumId","abstractNumId"])).filter(u=>u!=null)),c=new Set(Array.from(i.childNodes||[]).filter(u=>Vr(u,"num")).map(u=>hn(u,["w:numId","numId"])).filter(u=>u!=null));for(let u of Array.from(s.childNodes||[])){if(!Vr(u,"abstractNum"))continue;let f=hn(u,["w:abstractNumId","abstractNumId"]);f==null||l.has(f)||(Oc(i,o.importNode(u,!0),"abstract"),l.add(f))}for(let u of Array.from(s.childNodes||[])){if(!Vr(u,"num"))continue;let f=hn(u,["w:numId","numId"]);f==null||c.has(f)||(Oc(i,o.importNode(u,!0),"num"),c.add(f))}return Yt(o)}catch{return r}}var Np=new Set(["ins","del","rPrChange","pPrChange"]),Ip=/^\d{4}-\d{2}-\d{2}T/;function br(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Wr(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>br(r)===t)}function jr(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function Tp(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function Sp(e){return br(e.parentNode)==="rPr"}function Ap(e){let t=r=>{let n=Bs(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="${B}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function pt(e){let t=[],r=(f,d,m)=>t.push({code:f,severity:d,message:m}),n=e&&typeof e=="object"&&(e.nodeType===9||e.nodeType===1);if(!n&&(typeof e!="string"||e.trim()===""))return r("PARSE_ERROR","error","Input is not non-empty OOXML or a parsed XML DOM."),{valid:!1,issues:t};let{doc:o,error:a}=n?{doc:e.nodeType===9?e:e.ownerDocument}:Ap(e);if(!o)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${a}`),{valid:!1,issues:t};let i=Wr(o,"ins"),s=Wr(o,"del"),l=i.concat(s);for(let f of Wr(o,"p")){let d=Array.from(f.getElementsByTagName("*")).find(m=>m!==f&&br(m)==="p");d&&r("NESTED_PARAGRAPH","error",`<${f.nodeName}> contains nested <${d.nodeName}>.`)}for(let f of Wr(o,"body")){let d=Array.from(f.childNodes||[]).filter(p=>p.nodeType===1),m=d.map((p,g)=>br(p)==="sectPr"?g:-1).filter(p=>p>=0);m.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):m.length===1&&m[0]!==d.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let f of l){let m=Array.from(f.getElementsByTagName("*")).filter(p=>p!==f&&["ins","del"].includes(br(p))).find(p=>br(f)!=="ins"||br(p)!=="del"?!0:p.parentNode!==f);m&&r("NESTED_REVISION","error",`<${f.nodeName}> (w:id="${jr(f,"id")}") contains invalid nested <${m.nodeName}>.`)}for(let f of s)Wr(f,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${jr(f,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let f of l){let d=[];jr(f,"id")||d.push("w:id"),jr(f,"author")||d.push("w:author"),Ip.test(jr(f,"date"))||d.push("w:date"),d.length>0&&r("MISSING_REVISION_METADATA","error",`<${f.nodeName}> is missing or has malformed ${d.join(", ")}.`)}let c=new Set;for(let f of Array.from(o.getElementsByTagName("*"))){if(!Np.has(br(f)))continue;let d=jr(f,"id");d&&(c.has(d)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${d} appears more than once.`),c.add(d))}let u=Wr(o,"t").concat(Wr(o,"delText"));for(let f of u){let d=f.textContent||"";/^\s|\s$/.test(d)&&Tp(f)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${f.nodeName}> has boundary whitespace without xml:space="preserve".`),d===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${f.nodeName}> is empty.`)}for(let f of l){if(Sp(f))continue;Array.from(f.childNodes||[]).some(m=>m.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${f.nodeName}> (w:id="${jr(f,"id")}") wraps no content.`)}for(let f of vc(o)){let d=f.ownerAuthor||"unattributed";r("FOREIGN_PARAGRAPH_MARK_DELETION","warning",`Paragraph deleted by ${d} also contains non-empty insertion content from another author; Accept/Reject lifecycle may not preserve the apparent restoration.`)}return{valid:!t.some(f=>f.severity==="error"),issues:t}}function pa(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Oe&&r.localName===t):[]}function Ep(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function Rp(e){let t=pa(e,"tr"),r=t.map(o=>pa(o,"tc").map(i=>{let s=pa(i,"p");return s.length===0?q(Ie(i)):s.map(c=>q(Ie(c))).filter(Boolean).join(`
194
- `)})),n=r.reduce((o,a)=>Math.max(o,a.length),0);return r.forEach(o=>{for(;o.length<n;)o.push("")}),{matrix:r,rowElements:t,columnCount:n}}function Pp(e,t){if(!Array.isArray(e)||e.length===0||t<=0)return null;let r=e.map(s=>{let l=Array.isArray(s)?s.slice(0,t):[];for(;l.length<t;)l.push("");return l}),n=r[0],o=new Array(t).fill("---"),a=r.slice(1),i=s=>`| ${s.map(l=>Ep(l)).join(" | ")} |`;return[i(n),i(o),...a.map(i)].join(`
195
- `)}function Cp(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>q(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function Dc(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 Di(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:Ie;if(!e||!e.parentNode)return null;let o=[e],a=e.nextSibling,i=0;for(;a&&i<r;){i+=1;let s=a.nextSibling;if(a.nodeType!==1||a.namespaceURI!==Oe||a.localName!=="p"){a=s;continue}let l=String(n(a)||"").trim();if(!l){if(o.length>1)break;a=s;continue}if(!Dc(l))break;o.push(a),a=s}return o.length>1?o:null}function Fi(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
196
- `)||Ur(a))return null;let i=a.split(/\r?\n/g).map(b=>b.trim()).filter(Boolean);if(i.length<2)return null;let s=r.tableElement||He(e,"tbl"),l=He(e,"tr"),c=He(e,"tc");if(!s||!l||!c)return null;let u=q(r.currentParagraphText||Ie(e)),f=q(i[0]);if(u&&f&&f!==u)return o("[Table] Multiline cell text did not anchor to original cell text; skipping table-row synthesis heuristic."),null;let{matrix:d,rowElements:m,columnCount:p}=Rp(s);if(d.length===0||p===0)return null;let g=m.indexOf(l),y=pa(l,"tc").indexOf(c);if(g<0||y<0||y>=p)return null;d[g][y]=i[0];let w=Cp(d[g]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let b=1;b<i.length;b++){let x=g+b,T=i[b];if(x<d.length&&!q(d[x][y]))if(w)for(let I=0;I<p;I++)q(d[x][I])||(d[x][I]=T);else d[x][y]=T;else{let I=new Array(p).fill("");if(w)for(let N=0;N<p;N++)I[N]=T;else I[y]=T;d.splice(Math.min(x,d.length),0,I)}}let v=Pp(d,p);return v?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),v):null}function Op(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!Ee(e)}function Fc(e){let t=W(e,"application/xml");return t.error||Op(t.doc)?{...t,doc:null}:t}function $c(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(B,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function $i(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===B&&n.localName===t)return n;return null}function Nr(e,t){return Array.from(e?.getElementsByTagNameNS?.(B,t)||[])}function no(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function _p(e){let t=$i(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=Nr(t,"rStyle")[0]||null,n=no(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),a=n.includes("italic")||n.includes("emphasis");return{bold:Nr(t,"b").length>0||o,italic:Nr(t,"i").length>0||a}}function Uc(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(B,"r")||[]);for(let n of r){if(!kr(n,e,"accepted"))continue;let o=Mr(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,..._p(n)})}return t}function Ui(e){return String(e||"").replace(/\r/g,"").split(`
194
+ </w:numbering>`.trim()}function kt(e){if(!e||e.nodeType!==1||e.localName!=="p")return!1;let t=Array.from(e.childNodes||[]).find(n=>jo(n,"pPr")),r=t&&Array.from(t.childNodes||[]).find(n=>jo(n,"rPr"));return!!r&&Array.from(r.childNodes||[]).some(n=>jo(n,"del"))}function mn(e,t,r){let n=Ve(e);if($t(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let o=new Map,a=new Map,i=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of i){let f=ft(c,["w:abstractNumId","abstractNumId"]);if(f==null)continue;let u=Wo(r,"abstract");u!=null&&(o.set(f,u),Nf(c,"w:abstractNumId",u))}let l=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of l){let f=ft(c,["w:numId","numId"]);if(f==null)continue;let u=Wo(r,"num");if(u==null)continue;a.set(f,u),Nf(c,"w:numId",u);let d=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(d){let m=ft(d,["w:val","val"]);m!=null&&o.has(m)&&Vs(d,o.get(m))}}let s=Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[];for(let c of s)if(!kt(c))for(let f of Bn(c)){let u=ft(f,["w:val","val"]);u!=null&&a.has(u)&&Vs(f,a.get(u))}return{numberingXml:Kt(n),replacementNodes:s}}var Pw=new Set(["ins","del","rPrChange","pPrChange"]),Cw=/^\d{4}-\d{2}-\d{2}T/;function Xr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function pn(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>Xr(r)===t)}function gn(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function _w(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function Ow(e){return Xr(e.parentNode)==="rPr"}function kw(e){let t=r=>{let n=vc(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="${B}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function Mt(e){let t=[],r=(u,d,m)=>t.push({code:u,severity:d,message:m}),n=e&&typeof e=="object"&&(e.nodeType===9||e.nodeType===1);if(!n&&(typeof e!="string"||e.trim()===""))return r("PARSE_ERROR","error","Input is not non-empty OOXML or a parsed XML DOM."),{valid:!1,issues:t};let{doc:o,error:a}=n?{doc:e.nodeType===9?e:e.ownerDocument}:kw(e);if(!o)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${a}`),{valid:!1,issues:t};let i=pn(o,"ins"),l=pn(o,"del"),s=i.concat(l);for(let u of pn(o,"p")){let d=Array.from(u.getElementsByTagName("*")).find(m=>m!==u&&Xr(m)==="p");d&&r("NESTED_PARAGRAPH","error",`<${u.nodeName}> contains nested <${d.nodeName}>.`)}for(let u of pn(o,"body")){let d=Array.from(u.childNodes||[]).filter(p=>p.nodeType===1),m=d.map((p,g)=>Xr(p)==="sectPr"?g:-1).filter(p=>p>=0);m.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):m.length===1&&m[0]!==d.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let u of s){let m=Array.from(u.getElementsByTagName("*")).filter(p=>p!==u&&["ins","del"].includes(Xr(p))).find(p=>Xr(u)!=="ins"||Xr(p)!=="del"?!0:p.parentNode!==u);m&&r("NESTED_REVISION","error",`<${u.nodeName}> (w:id="${gn(u,"id")}") contains invalid nested <${m.nodeName}>.`)}for(let u of l)pn(u,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${gn(u,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let u of s){let d=[];gn(u,"id")||d.push("w:id"),gn(u,"author")||d.push("w:author"),Cw.test(gn(u,"date"))||d.push("w:date"),d.length>0&&r("MISSING_REVISION_METADATA","error",`<${u.nodeName}> is missing or has malformed ${d.join(", ")}.`)}let c=new Set;for(let u of Array.from(o.getElementsByTagName("*"))){if(!Pw.has(Xr(u)))continue;let d=gn(u,"id");d&&(c.has(d)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${d} appears more than once.`),c.add(d))}let f=pn(o,"t").concat(pn(o,"delText"));for(let u of f){let d=u.textContent||"";/^\s|\s$/.test(d)&&_w(u)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${u.nodeName}> has boundary whitespace without xml:space="preserve".`),d===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${u.nodeName}> is empty.`)}for(let u of s){if(Ow(u))continue;Array.from(u.childNodes||[]).some(m=>m.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${u.nodeName}> (w:id="${gn(u,"id")}") wraps no content.`)}for(let u of cf(o)){let d=u.ownerAuthor||"unattributed";r("FOREIGN_PARAGRAPH_MARK_DELETION","warning",`Paragraph deleted by ${d} also contains non-empty insertion content from another author; Accept/Reject lifecycle may not preserve the apparent restoration.`)}return{valid:!t.some(u=>u.severity==="error"),issues:t}}function oi(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===fe&&r.localName===t):[]}function Mw(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function Lw(e){let t=oi(e,"tr"),r=t.map(o=>oi(o,"tc").map(i=>{let l=oi(i,"p");return l.length===0?q(_e(i)):l.map(c=>q(_e(c))).filter(Boolean).join(`
195
+ `)})),n=r.reduce((o,a)=>Math.max(o,a.length),0);return r.forEach(o=>{for(;o.length<n;)o.push("")}),{matrix:r,rowElements:t,columnCount:n}}function Bw(e,t){if(!Array.isArray(e)||e.length===0||t<=0)return null;let r=e.map(l=>{let s=Array.isArray(l)?l.slice(0,t):[];for(;s.length<t;)s.push("");return s}),n=r[0],o=new Array(t).fill("---"),a=r.slice(1),i=l=>`| ${l.map(s=>Mw(s)).join(" | ")} |`;return[i(n),i(o),...a.map(i)].join(`
196
+ `)}function Fw(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>q(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function Tf(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 js(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:_e;if(!e||!e.parentNode)return null;let o=[e],a=e.nextSibling,i=0;for(;a&&i<r;){i+=1;let l=a.nextSibling;if(a.nodeType!==1||a.namespaceURI!==fe||a.localName!=="p"){a=l;continue}let s=String(n(a)||"").trim();if(!s){if(o.length>1)break;a=l;continue}if(!Tf(s))break;o.push(a),a=l}return o.length>1?o:null}function Ws(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
197
+ `)||sn(a))return null;let i=a.split(/\r?\n/g).map(b=>b.trim()).filter(Boolean);if(i.length<2)return null;let l=r.tableElement||ut(e,"tbl"),s=ut(e,"tr"),c=ut(e,"tc");if(!l||!s||!c)return null;let f=q(r.currentParagraphText||_e(e)),u=q(i[0]);if(f&&u&&u!==f)return o("[Table] Multiline cell text did not anchor to original cell text; skipping table-row synthesis heuristic."),null;let{matrix:d,rowElements:m,columnCount:p}=Lw(l);if(d.length===0||p===0)return null;let g=m.indexOf(s),v=oi(s,"tc").indexOf(c);if(g<0||v<0||v>=p)return null;d[g][v]=i[0];let w=Fw(d[g]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let b=1;b<i.length;b++){let x=g+b,S=i[b];if(x<d.length&&!q(d[x][v]))if(w)for(let A=0;A<p;A++)q(d[x][A])||(d[x][A]=S);else d[x][v]=S;else{let A=new Array(p).fill("");if(w)for(let E=0;E<p;E++)A[E]=S;else A[v]=S;d.splice(Math.min(x,d.length),0,A)}}let y=Bw(d,p);return y?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),y):null}var Af=8,ai=["start","numFmt","lvlRestart","pStyle","isLgl","suff","lvlText","lvlPicBulletId","legacy","lvlJc","pPr","rPr"],ze=(e,t)=>Array.from(e?.childNodes||[]).filter(r=>jo(r,t)),wt=(e,t)=>Array.from(e?.getElementsByTagNameNS?.("*",t)||[]),nr=e=>{let t=e?.getAttribute?.("w:val")??e?.getAttribute?.("val"),r=Number.parseInt(String(t??""),10);return Number.isFinite(r)?r:null};function Ko(e,t){if(e.nodeType===3||e.nodeType===4){let o=String(e.nodeValue||"").trim();return o?JSON.stringify(o):""}if(e.nodeType!==1)return"";let r=Array.from(e.attributes||[]).filter(o=>!/^xmlns(:|$)/.test(o.name)).filter(o=>!(t&&/^(w:)?(abstractNumId|numId)$/.test(o.name))).map(o=>`${o.localName||o.name}=${o.value}`).sort().join(",");if(t&&e.localName==="abstractNumId"&&e.parentNode?.localName==="num")return`<abstractNumId ${r.replace(/val=[^,]*/,"val=*")}/>`;let n=Array.from(e.childNodes||[]).map(o=>Ko(o,t)).join("");return`<${e.localName} ${r}>${n}</>`}function $w(e,t){let r=typeof e=="string"?Ve(e):e;if(!r||$t(r))return null;let n=wt(r,"num").find(i=>ft(i,["w:numId","numId"])===Number(t));if(!n)return null;let o=nr(ze(n,"abstractNumId")[0]),a=wt(r,"abstractNum").find(i=>ft(i,["w:abstractNumId","abstractNumId"])===o);return`${Ko(n,!0)}|${a?Ko(a,!0):"missing-abstract"}`}function Go(e,t){let r=wt(e,"num").find(o=>ft(o,["w:numId","numId"])===Number(t)),n=nr(ze(r,"abstractNumId")[0]);return n==null?null:wt(e,"abstractNum").find(o=>ft(o,["w:abstractNumId","abstractNumId"])===n)||null}function hn(e,t,r,n){let o=ze(t,r)[0];if(!o){o=e.createElementNS(fe,`w:${r}`);let a=ai.indexOf(r),i=Array.from(t.childNodes||[]).find(l=>l.nodeType===1&&ai.indexOf(l.localName)>a);i?t.insertBefore(o,i):t.appendChild(o)}o.setAttribute("w:val",String(n))}function Dw(e,t){let r=e.createElementNS(fe,"w:lvl");r.setAttribute("w:ilvl",String(t)),hn(e,r,"start",1),hn(e,r,"numFmt","decimal"),hn(e,r,"lvlText",`%${t+1}.`),hn(e,r,"lvlJc","left");let n=e.createElementNS(fe,"w:pPr"),o=e.createElementNS(fe,"w:ind");return o.setAttribute("w:left",String(720*(t+1))),o.setAttribute("w:hanging","360"),n.appendChild(o),r.appendChild(n),r}function Uw(e,t){let r=t.ownerDocument;for(let n of["suff","lvlJc","pPr","rPr"]){for(let s of ze(t,n))t.removeChild(s);let o=ze(e,n)[0];if(!o)continue;let a=r.importNode(o,!0),i=ai.indexOf(n),l=Array.from(t.childNodes||[]).find(s=>s.nodeType===1&&ai.indexOf(s.localName)>i);l?t.insertBefore(a,l):t.appendChild(a)}}function Ef(e,t){let r=e.ownerDocument,n=Object.entries(t||{}).map(([o,a])=>[Number(o),Number(a)]).filter(([o,a])=>Number.isInteger(o)&&o>=0&&o<=Af&&Number.isInteger(a)&&a>=0).sort((o,a)=>o[0]-a[0]);for(let[o,a]of n){for(let s of ze(e,"lvlOverride"))wn(s)===o&&e.removeChild(s);let i=r.createElementNS(fe,"w:lvlOverride");i.setAttribute("w:ilvl",String(o));let l=r.createElementNS(fe,"w:startOverride");l.setAttribute("w:val",String(a)),i.appendChild(l),e.appendChild(i)}}function wn(e){return ft(e,["w:ilvl","ilvl"])}function Ho(e){let{numberingIdState:t,sourceNumberingXml:r,sourceNumId:n,levels:o=[],startOverrides:a}=e||{},i=to(t);if(!i)return null;let l=String(r||"").trim()?Ve(r):null,s=l&&!$t(l)&&n!=null?Go(l,n):null,c=new Map(wt(s,"lvl").map(w=>[wn(w),w]).filter(([w])=>w!=null)),f=Ve(`<w:numbering xmlns:w="${fe}"/>`),u=f.documentElement,d=f.createElementNS(fe,"w:abstractNum");d.setAttribute("w:abstractNumId",String(i.abstractNumId));let m=f.createElementNS(fe,"w:multiLevelType");m.setAttribute("w:val",ze(s,"multiLevelType")[0]?.getAttribute("w:val")||"multilevel"),d.appendChild(m);let p=new Map(o.filter(w=>Number.isInteger(w?.ilvl)).map(w=>[w.ilvl,w])),g=Math.max(Af,...c.keys(),...p.keys());for(let w=0;w<=g;w+=1){let y=c.get(w),b=y?f.importNode(y,!0):Dw(f,w);for(let S of ze(b,"pStyle"))b.removeChild(S);b.removeAttribute("w:tplc"),b.removeAttribute("w:tentative");let x=p.get(w);if(x){x.numFmt!=null&&hn(f,b,"numFmt",x.numFmt),x.lvlText!=null&&hn(f,b,"lvlText",x.lvlText),x.start!=null&&hn(f,b,"start",x.start);for(let S of x.dropChildren||[])for(let A of ze(b,S))b.removeChild(A);if(x.dropRunFonts)for(let S of ze(b,"rPr")){for(let A of ze(S,"rFonts"))S.removeChild(A);Array.from(S.childNodes||[]).some(A=>A.nodeType===1)||b.removeChild(S)}}d.appendChild(b)}let h=f.createElementNS(fe,"w:num");h.setAttribute("w:numId",String(i.numId));let v=f.createElementNS(fe,"w:abstractNumId");return v.setAttribute("w:val",String(i.abstractNumId)),h.appendChild(v),Ef(h,a),u.appendChild(d),u.appendChild(h),{numId:i.numId,abstractNumId:i.abstractNumId,numberingXml:Kt(f)}}function Sf(e){let t=new Map;for(let r of wt(e,"lvl")){let n=wn(r),o=wt(r,"numFmt")[0]?.getAttribute("w:val")||null;n!=null&&o&&t.set(n,o)}return t}function Ks(e){return e==="bullet"||e==="circle"||e==="square"?"bullet":e}function Gs(e){return Vt(e).map(t=>{let r=ze(t.parentNode,"ilvl")[0];return{numIdElement:t,numId:nr(t),ilvl:r?nr(r)??0:0}})}function zw(e,t,r,n){let o=n?.sourceNumberingXml;if(!e||!String(o||"").trim()||!Array.isArray(t))return null;let a=new Set;for(let p of r||[])for(let{numId:g}of Gs(p))g!=null&&g!==0&&a.add(g);if(a.size!==1)return null;let[i]=a,l=Ve(o),s=Ve(e);if($t(l)||$t(s))return null;let c=Go(l,i);if(!c)return null;let f=Sf(c),u=[];for(let p of t)kt(p)||u.push(...Gs(p));if(u.length===0)return null;let d=new Map;for(let{numId:p,ilvl:g}of u){if(p==null)return null;if(!d.has(p)){let w=Go(s,p);if(!w)return null;d.set(p,Sf(w))}let h=d.get(p).get(g),v=f.get(g);if(!h||!v||Ks(h)!==Ks(v))return null}let m=t.map(p=>p?.cloneNode?p.cloneNode(!0):p);for(let p of m)if(!kt(p))for(let g of Vt(p))g.setAttribute("w:val",String(i));return{numId:i,replacementNodes:m}}function Hs(e){let{numberingXml:t,replacementNodes:r,sourceParagraphs:n,numberingIdState:o,allowContinueSource:a=!0}=e||{};if(t&&o&&a){let i=zw(t,r,n,o);if(i)return{policy:"continue-source",numberingXml:null,replacementNodes:i.replacementNodes,numId:i.numId}}if(t&&o){let i=mn(t,r,o);return{policy:"allocate",numberingXml:i.numberingXml,replacementNodes:i.replacementNodes}}return{policy:"passthrough",numberingXml:t??null,replacementNodes:r}}function Xw(e,t,r){let n=String(r||"").replace(/%\d+/g,"").trim()||".";return`list-format:${e}:${t}:${e==="bullet"?"":n}`}function Vw(e,t){let r=[];for(let p of t||[])kt(p)||r.push(...Gs(p));if(r.length===0)return null;let{numId:n,ilvl:o}=r[0];if(n==null||n===0||r.some(p=>p.numId!==n||p.ilvl!==o))return null;let a=Ve(e);if($t(a))return null;let i=wt(a,"num").find(p=>ft(p,["w:numId","numId"])===Number(n)),l=Go(a,n),s=wt(l,"lvl").find(p=>wn(p)===o),c=wt(s,"numFmt")[0]?.getAttribute("w:val");if(!i||!s||!c)return null;let f=wt(s,"lvlText")[0]?.getAttribute("w:val")||"",u=ze(i,"lvlOverride").find(p=>wn(p)===o),d=nr(ze(u,"startOverride")[0])??nr(wt(s,"start")[0])??1,m=Ks(c)==="bullet";return{numId:n,ilvl:o,count:r.length,isBullet:m,start:d,key:Xw(m?"bullet":c,o,f)}}function Rf({numberingXml:e,replacementNodes:t,sequence:r,isNumIdLive:n}){if(!(r instanceof Map)||!e)return null;let o=Vw(e,t);if(!o)return null;let a=r.get(o.key)||null,l=a&&a.numId!=null&&(typeof n!="function"||n(a.numId))&&(o.isBullet||a.nextStartAt===o.start),s=o.isBullet?null:o.start+o.count;if(!l)return r.set(o.key,{numId:String(o.numId),nextStartAt:s}),null;let c=t.map(f=>f?.cloneNode?f.cloneNode(!0):f);for(let f of c)if(!kt(f))for(let u of Vt(f))u.setAttribute("w:val",String(a.numId));return r.set(o.key,{numId:String(a.numId),nextStartAt:s}),{numId:a.numId,replacementNodes:c}}function jw(e,t,r){let n=Array.from(e.childNodes||[]).filter(a=>a&&a.nodeType===1&&a.namespaceURI===fe),o=r==="abstract"?n.find(a=>a.localName==="num"||a.localName==="numIdMacAtCleanup"):n.find(a=>a.localName==="numIdMacAtCleanup");o?e.insertBefore(t,o):e.appendChild(t)}function Pf(e,t,r={}){let n=String(e||""),o=String(t||"");if(!o.trim())return n;if(!n.trim())return o;try{let a=Ve(n),i=Ve(o);if($t(a)||$t(i))return n;let l=a.documentElement,s=i.documentElement;if(!l||!s)return n;for(let[c,f,u]of[["abstract","abstractNum","abstractNumId"],["num","num","numId"]]){let d=new Map(ze(l,f).map(m=>[ft(m,[`w:${u}`,u]),m]).filter(([m])=>m!=null));for(let m of ze(s,f)){let p=ft(m,[`w:${u}`,u]);if(p==null)continue;let g=d.get(p);if(g){typeof r?.onConflict=="function"&&Ko(g,!1)!==Ko(m,!1)&&r.onConflict({kind:f,id:p});continue}let h=a.importNode(m,!0);jw(l,h,c),d.set(p,h)}}return Kt(a)}catch{return n}}function vr(e,t,r={}){let n=String(e||"");for(let o of(Array.isArray(t)?t:[t]).filter(Boolean))n=Pf(n,o,r);return n}function Cf(e,t,r=0){let n=Number(t),o=String(e?.sourceNumberingXml||""),a=o.trim()?Ve(o):null,i=a&&!$t(a)?wt(a,"num").find(f=>ft(f,["w:numId","numId"])===n):null;if(!i)return e?.usedNumIds instanceof Set&&e.usedNumIds.has(n)?{ok:!0}:{ok:!1,reason:"unknown-num",message:`numbering.numId ${n} does not exist in the document's numbering definitions.`};let l=Go(a,n);if(!l)return{ok:!1,reason:"missing-abstract",message:`numId ${n} points at an abstractNum that does not exist.`};let s=f=>ze(f,"lvl").some(u=>Number.parseInt(u.getAttribute("w:ilvl")??u.getAttribute("ilvl")??"0",10)===r),c=ze(i,"lvlOverride").some(f=>s(f));return!s(l)&&!c?{ok:!1,reason:"undefined-level",message:`numId ${n} does not define list level ${r}.`}:{ok:!0}}function ro(e,t){let r=[],n=new Set,o=(u,d,m={})=>{let p=`${u}:${m.numId??""}:${m.abstractNumId??""}:${m.ilvl??""}`;n.has(p)||(n.add(p),r.push({code:u,severity:"error",message:d,...m}))},a=typeof e=="string"?Ve(e):e;if(!a||$t(a))return r;let i=typeof t=="string"?t.trim()?Ve(t):null:t||null,l=i&&!$t(i),s=new Map,c=new Map;if(l){for(let[u,d,m]of[["abstractNum","abstractNumId",s],["num","numId",c]])for(let p of wt(i,u)){let g=ft(p,[`w:${d}`,d]);g!=null&&(m.has(g)?o("NUMBERING_DUPLICATE_ID",`Numbering part defines ${u} ${g} more than once.`,{[d]:g}):m.set(g,p))}for(let[u,d]of c){let m=nr(ze(d,"abstractNumId")[0]);m==null?o("NUMBERING_ABSTRACT_UNDEFINED",`w:num ${u} has no w:abstractNumId.`,{numId:u}):s.has(m)||o("NUMBERING_ABSTRACT_UNDEFINED",`w:num ${u} references missing w:abstractNum ${m}.`,{numId:u,abstractNumId:m})}}let f=(u,d)=>{let m=c.get(u),p=s.get(nr(ze(m,"abstractNumId")[0]));return!p||wt(p,"lvl").some(g=>wn(g)===d)?!0:ze(m,"lvlOverride").some(g=>wn(g)===d&&ze(g,"lvl").length>0)};for(let u of Array.from(a.getElementsByTagNameNS(fe,"p"))){let d=[it(u).numPr,Oc(u)?.numPr];for(let m of d){if(!m?.numIdElement)continue;let p=nr(m.numIdElement);if(p==null||p===0)continue;if(!l||!c.has(p)){o("NUMBERING_NUM_UNDEFINED",`w:numId ${p} is used in the document but no w:num defines it.`,{numId:p});continue}let g=m.ilvlElement?nr(m.ilvlElement):null;g!=null&&!f(p,g)&&o("NUMBERING_LEVEL_UNDEFINED",`w:ilvl ${g} is used with w:numId ${p} but its abstractNum does not define that level.`,{numId:p,ilvl:g})}}return r}function Ww(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!Fe(e)}function _f(e){let t=j(e,"application/xml");return t.error||Ww(t.doc)?{...t,doc:null}:t}function Of(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(B,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function qo(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function Kw(e){let t=_c(e);if(!t)return{bold:!1,italic:!1};let r=et(t,"rStyle"),n=qo(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),a=n.includes("italic")||n.includes("emphasis");return{bold:!!et(t,"b")||o,italic:!!et(t,"i")||a}}function kf(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(B,"r")||[]);for(let n of r){if(!tn(n,e,"accepted"))continue;let o=gr(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...Kw(n)})}return t}function qs(e){return String(e||"").replace(/\r/g,"").split(`
197
198
  `).map(r=>r.replace(/[ \t]+/g," ").trim()).join(`
198
- `).trim()}function kp(e,t){let r=String(e||"");if(!r)return"";if(!t?.bold&&!t?.italic)return r;let n=r.match(/^(\s*)([\s\S]*?)(\s*)$/);if(!n)return r;let o=n[1]||"",a=n[2]||"",i=n[3]||"";if(!a.trim())return r;let s=a;return t.bold&&t.italic?s=`***${a}***`:t.bold?s=`**${a}**`:t.italic&&(s=`*${a}*`),`${o}${s}${i}`}function Mp(e){let t=$i(e,"pPr");if(!t)return null;let r=Nr(t,"pStyle")[0]||null,n=no(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=Nr(t,"outlineLvl")[0]||null,a=no(o,["w:val","val"]),i=Number.parseInt(a,10);return Number.isInteger(i)&&i>=0?Math.min(i+1,6):null}function Lp(e){let t=$i(e,"pPr");if(!t)return null;let r=Nr(t,"numPr")[0]||null;if(!r)return null;let n=Nr(r,"ilvl")[0]||null,o=Nr(r,"numId")[0]||null,a=Number.parseInt(no(n,["w:val","val"]),10),i=no(o,["w:val","val"]);return{level:Number.isInteger(a)&&a>=0?a:0,marker:i==="1"?"-":"1."}}function Bp(e){let t=Uc(e).map(r=>r.text).join("");return Ui(t)}function Dp(e){let r=Uc(e).map(i=>kp(i.text,i)).join(""),n=Ui(r);if(!n)return"";let o=Mp(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let a=Lp(e);return a?`${" ".repeat(a.level)}${a.marker} ${n}`:n}function Fp(e){return zc(e).text}function zc(e){let t=Fc(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=$c(r);return n.length===0?{text:Ui(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(Bp).join(`
199
+ `).trim()}function Gw(e,t){let r=String(e||"");if(!r)return"";if(!t?.bold&&!t?.italic)return r;let n=r.match(/^(\s*)([\s\S]*?)(\s*)$/);if(!n)return r;let o=n[1]||"",a=n[2]||"",i=n[3]||"";if(!a.trim())return r;let l=a;return t.bold&&t.italic?l=`***${a}***`:t.bold?l=`**${a}**`:t.italic&&(l=`*${a}*`),`${o}${l}${i}`}function Hw(e){let{pPr:t,pStyleElement:r,outlineLvlElement:n}=it(e);if(!t)return null;let o=qo(r,["w:val","val"]);if(o){let l=o.match(/^heading\s*([1-9])$/i);if(l){let s=Number.parseInt(l[1],10);if(Number.isInteger(s))return Math.min(Math.max(s,1),6)}}let a=qo(n,["w:val","val"]),i=Number.parseInt(a,10);return Number.isInteger(i)&&i>=0?Math.min(i+1,6):null}function qw(e){let{numPr:t}=it(e);if(!t)return null;let r=t.ilvlElement,n=t.numIdElement,o=Number.parseInt(qo(r,["w:val","val"]),10),a=qo(n,["w:val","val"]);return{level:Number.isInteger(o)&&o>=0?o:0,marker:a==="1"?"-":"1."}}function Yw(e){let t=kf(e).map(r=>r.text).join("");return qs(t)}function Jw(e){let r=kf(e).map(i=>Gw(i.text,i)).join(""),n=qs(r);if(!n)return"";let o=Hw(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let a=qw(e);return a?`${" ".repeat(a.level)}${a.marker} ${n}`:n}function Zw(e){return Mf(e).text}function Mf(e){let t=_f(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Of(r);return n.length===0?{text:qs(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(Yw).join(`
199
200
 
200
- `).trim(),status:"ok",warnings:t.warnings}}function $p(e){return Xc(e).text}function Xc(e){let t=Fc(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=$c(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(Dp).join(`
201
+ `).trim(),status:"ok",warnings:t.warnings}}function Qw(e){return Lf(e).text}function Lf(e){let t=_f(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Of(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(Jw).join(`
201
202
 
202
- `).trim(),status:"ok",warnings:t.warnings}}var vn="http://schemas.microsoft.com/office/word/2010/wordml",Ge="http://schemas.microsoft.com/office/word/2012/wordml";function zi(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 oo(e,t,r,n,o=zi(e)){let a=t.split(" ").map(l=>l[0]).join("").toUpperCase()||"AI",i=je(r),s=je(t);return`<w:comment w:id="${e}" w:author="${s}" w:date="${n}" w:initials="${a}">
203
- <w:p w14:paraId="${je(o)}" xmlns:w14="${vn}">
203
+ `).trim(),status:"ok",warnings:t.warnings}}var no="http://schemas.microsoft.com/office/word/2010/wordml",dt="http://schemas.microsoft.com/office/word/2012/wordml";function Ys(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 Yo(e,t,r,n,o=Ys(e)){let a=t.split(" ").map(s=>s[0]).join("").toUpperCase()||"AI",i=Qe(r),l=Qe(t);return`<w:comment w:id="${e}" w:author="${l}" w:date="${n}" w:initials="${a}">
204
+ <w:p w14:paraId="${Qe(o)}" xmlns:w14="${no}">
204
205
  <w:r><w:t>${i}</w:t></w:r>
205
206
  </w:p>
206
- </w:comment>`}function Xi(e){if(!e||e.length===0)return`<w:comments xmlns:w="${B}"></w:comments>`;let t=e.map(r=>oo(r.id,r.author,r.content,r.date,r.paraId)).join(`
207
+ </w:comment>`}function Js(e){if(!e||e.length===0)return`<w:comments xmlns:w="${B}"></w:comments>`;let t=e.map(r=>Yo(r.id,r.author,r.content,r.date,r.paraId)).join(`
207
208
  `);return`<w:comments xmlns:w="${B}">
208
209
  ${t}
209
- </w:comments>`}function Vc(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${je(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${je(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${Ge}">${t}</w15:commentsEx>`}var ot=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function ha(e){let t=Array.from(e?.getElementsByTagNameNS?.("*","p")||[]);return t.length?t[t.length-1]:null}function at(e){return ot(ha(e),"w14:paraId","paraId").toUpperCase()}function Ki(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=ot(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=ot(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function wa(e,t){let r=zi(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}var Vi=(e,t)=>{let r=W(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}};function ya({commentsXml:e,commentsExtendedXml:t=null,commentId:r,resolved:n=!0}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"Resolving a comment requires an existing word/comments.xml part."}};let o=Vi(e,"word/comments.xml");if(o.error)return{status:"error",error:o.error};let a=o.doc,i=S=>ot(S,"w:id","id"),s=Array.from(a.getElementsByTagNameNS("*","comment")),l=s.find(S=>i(S)===String(r));if(!l)return{status:"error",error:{code:"COMMENT_NOT_FOUND",message:`Comment '${r}' was not found.`}};let c;if(t){let S=Vi(t,"word/commentsExtended.xml");if(S.error)return{status:"error",error:S.error};c=S.doc}else c=Vi(`<w15:commentsEx xmlns:w15="${Ge}"/>`,"word/commentsExtended.xml").doc;let u=c.documentElement,f=S=>Array.from(u.getElementsByTagNameNS("*","commentEx")).find(O=>ot(O,"w15:paraId","paraId").toUpperCase()===S)||null,d=Ki(a,c),m=!1,g=(S=>{let O=at(S);return O||(O=wa(i(S),d),ha(S)?.setAttributeNS(vn,"w14:paraId",O),m=!0),O})(l),h=f(g),y=h&&ot(h,"w15:paraIdParent","paraIdParent").toUpperCase()||g,w=new Set([y,g]);for(let S of Array.from(u.getElementsByTagNameNS("*","commentEx")))ot(S,"w15:paraIdParent","paraIdParent").toUpperCase()===y&&w.add(ot(S,"w15:paraId","paraId").toUpperCase());let v=n?"1":"0",b=!t;for(let S of w){let O=f(S);O?ot(O,"w15:done","done")!==v&&(O.setAttributeNS(Ge,"w15:done",v),b=!0):(O=c.createElementNS(Ge,"w15:commentEx"),O.setAttributeNS(Ge,"w15:paraId",S),S!==y&&O.setAttributeNS(Ge,"w15:paraIdParent",y),O.setAttributeNS(Ge,"w15:done",v),u.appendChild(O),b=!0)}let x=new Map(s.map(S=>[at(S),S])),T=[...w].map(S=>x.get(S)).filter(Boolean).map(i),I=x.get(y),N=oe(),A=b||m;return{status:"ok",hasChanges:A,resolved:n,threadRootId:I?i(I):String(r),commentIds:T,...A?{commentsExtendedXml:N.serializeToString(c)}:{},...m?{commentsXml:N.serializeToString(a)}:{}}}var ga="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Wc(e,t,r){let n=new Set(t.map(String)),o=g=>ot(g,"w:id","id"),a=g=>Array.from(e.getElementsByTagNameNS("*",g)).filter(h=>n.has(o(h))),i=a("commentRangeStart"),s=a("commentReference");if(!i.length||!s.length)return!1;let l=i[i.length-1],c=s[s.length-1],u=c.parentNode?.localName==="r"?c.parentNode:c,f=(g,h)=>{let y=e.createElementNS(ga,`w:${g}`);return y.setAttributeNS(ga,"w:id",String(r)),h&&h.appendChild(y),y},d=(g,h)=>g.parentNode.insertBefore(h,g.nextSibling);d(l,f("commentRangeStart"));let m=f("commentRangeEnd"),p=e.createElementNS(ga,"w:r");return p.appendChild(e.createElementNS(ga,"w:rPr")),f("commentReference",p),d(u,m),d(m,p),!0}var Wi="http://schemas.microsoft.com/office/word/2016/wordml/cid",ji="http://schemas.microsoft.com/office/word/2018/wordml/cex",Up=(e,t)=>{let r=(Number.parseInt(e,16)^625341585)&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");for(;t.has(n);)r=r+2&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");return t.add(n),n};function jc({commentsXml:e,commentsIdsXml:t=null,commentsExtensibleXml:r=null}){let n={};if(!e||!t&&!r)return n;let o=W(e,"application/xml");if(!o.doc||o.error)return n;let a=oe(),i=new Map;for(let m of Array.from(o.doc.getElementsByTagNameNS("*","comment"))){let p=at(m);p&&i.set(p,m)}let s=null,l=new Map,c=new Set,u=!1;if(t){let m=W(t,"application/xml");if(!m.doc||m.error)return n;s=m.doc;let p=s.documentElement;for(let g of Array.from(p.getElementsByTagNameNS("*","commentId"))){let h=ot(g,"w16cid:paraId","paraId").toUpperCase(),y=ot(g,"w16cid:durableId","durableId").toUpperCase();if(y&&c.add(y),!i.has(h)){p.removeChild(g),u=!0;continue}l.set(h,y)}for(let g of i.keys()){if(l.has(g))continue;let h=Up(g,c),y=s.createElementNS(Wi,"w16cid:commentId");y.setAttributeNS(Wi,"w16cid:paraId",g),y.setAttributeNS(Wi,"w16cid:durableId",h),p.appendChild(y),l.set(g,h),u=!0}}let f=null,d=!1;if(r&&s){let m=W(r,"application/xml");if(m.doc&&!m.error){f=m.doc;let p=f.documentElement,g=new Set(l.values()),h=new Set;for(let y of Array.from(p.getElementsByTagNameNS("*","commentExtensible"))){let w=ot(y,"w16cex:durableId","durableId").toUpperCase();g.has(w)?h.add(w):(p.removeChild(y),d=!0)}for(let[y,w]of l){if(h.has(w))continue;let v=ot(i.get(y),"w:date","date"),b=f.createElementNS(ji,"w16cex:commentExtensible");b.setAttributeNS(ji,"w16cex:durableId",w),v&&b.setAttributeNS(ji,"w16cex:dateUtc",v),p.appendChild(b),d=!0}}}return u&&(n.commentsIdsXml=a.serializeToString(s)),d&&(n.commentsExtensibleXml=a.serializeToString(f)),n}var zp=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Xp=new TextEncoder;function ao(e){let t;if(typeof e=="string")t=Xp.encode(e);else if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else throw new TypeError("sha256 input must be a string, Uint8Array, Buffer, or ArrayBuffer.");let r=t.length,n=r*8,o=Math.ceil((r+9)/64)*64,a=new Uint8Array(o);a.set(t,0),a[r]=128;let i=new DataView(a.buffer,a.byteOffset,a.byteLength),s=Math.floor(n/4294967296),l=n>>>0;i.setUint32(o-8,s,!1),i.setUint32(o-4,l,!1);let c=1779033703,u=3144134277,f=1013904242,d=2773480762,m=1359893119,p=2600822924,g=528734635,h=1541459225,y=new Uint32Array(64);for(let v=0;v<o;v+=64){for(let E=0;E<16;E++)y[E]=i.getUint32(v+E*4,!1);for(let E=16;E<64;E++){let k=y[E-15],C=(k>>>7|k<<25)^(k>>>18|k<<14)^k>>>3,P=y[E-2],_=(P>>>17|P<<15)^(P>>>19|P<<13)^P>>>10;y[E]=y[E-16]+C+y[E-7]+_|0}let b=c,x=u,T=f,I=d,N=m,A=p,S=g,O=h;for(let E=0;E<64;E++){let k=(N>>>6|N<<26)^(N>>>11|N<<21)^(N>>>25|N<<7),C=N&A^~N&S,P=O+k+C+zp[E]+y[E]|0,_=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),R=b&x^b&T^x&T,M=_+R|0;O=S,S=A,A=N,N=I+P|0,I=T,T=x,x=b,b=P+M|0}c=c+b|0,u=u+x|0,f=f+T|0,d=d+I|0,m=m+N|0,p=p+A|0,g=g+S|0,h=h+O|0}let w=v=>(v>>>0).toString(16).padStart(8,"0");return w(c)+w(u)+w(f)+w(d)+w(m)+w(p)+w(g)+w(h)}var xn=new TextEncoder;function Kc(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 Hi({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=xn.encode("docx-redline-revision-token\0"),n=1,o=xn.encode(e),a=[],i=new Set,s=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let d of s){if(!d)continue;let m=Array.isArray(d)?d[0]:d.name,p=Array.isArray(d)?d[1]:d.payload??d.bytes;if(m==null)continue;let g=Kc(String(m));if(i.has(g))throw new Error(`Duplicate normalized entry path detected: "${g}"`);i.add(g);let h;typeof p=="string"?h=xn.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),a.push({name:g,nameBytes:xn.encode(g),payloadBytes:h})}a.sort((d,m)=>d.name<m.name?-1:d.name>m.name?1:0);let l=r.length+4+4+o.length+4;for(let d of a)l+=4+d.nameBytes.length+4+d.payloadBytes.length;let c=new Uint8Array(l),u=new DataView(c.buffer,c.byteOffset,c.byteLength),f=0;c.set(r,f),f+=r.length,u.setUint32(f,n,!1),f+=4,u.setUint32(f,o.length,!1),f+=4,c.set(o,f),f+=o.length,u.setUint32(f,a.length,!1),f+=4;for(let d of a)u.setUint32(f,d.nameBytes.length,!1),f+=4,c.set(d.nameBytes,f),f+=d.nameBytes.length,u.setUint32(f,d.payloadBytes.length,!1),f+=4,c.set(d.payloadBytes,f),f+=d.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:a.map(d=>d.name)}}async function Hc({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:a}=Hi({scope:e,entries:t}),i="";if(typeof r=="function")i=await r(n);else if(typeof globalThis.crypto?.subtle?.digest=="function"){let s=await globalThis.crypto.subtle.digest("SHA-256",n),l=new Uint8Array(s);i=Array.from(l).map(c=>c.toString(16).padStart(2,"0")).join("")}else i=ao(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function io({scope:e,entries:t=[],digestFn:r=null}){if(r!=null&&typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn when specified.");let{framing:n,coveredParts:o,version:a}=Hi({scope:e,entries:t}),i=typeof r=="function"?r(n):ao(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function va(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 so(e,t={}){let r=va(e);return Hc({scope:"document-parts",entries:r,digestFn:t.digestFn})}function Kr(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 Hr(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=xn.encode(r),a=xn.encode(n),i=0;for(let s=0;s<o.length;s++)i|=o[s]^a[s];return i===0}var he=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",Pt=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(B,t)||[]),Zt=(e,t)=>Pt(e,t)[0]||null,Gr=(e,t)=>Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))||null,Gi=e=>Gr(e,"pPr");function Gc(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))return!0;r=r.parentNode}return!1}function xa(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=W(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function Vp(e){let t=Gr(Gi(e),"numPr");if(!t)return null;let r=he(Gr(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(he(Gr(t,"ilvl"),"val")||"0",10)||0}}function Wp(e){let t=new Map;for(let n of Pt(e,"abstractNum")){let o=new Map;for(let a of Pt(n,"lvl")){let i=Number.parseInt(he(a,"ilvl")||"0",10)||0;o.set(i,{start:Number.parseInt(he(Zt(a,"start"),"val")||"1",10)||1,format:he(Zt(a,"numFmt"),"val")||"decimal",text:he(Zt(a,"lvlText"),"val")||`%${i+1}.`})}t.set(he(n,"abstractNumId"),o)}let r=new Map;for(let n of Pt(e,"num")){let o=he(Zt(n,"abstractNumId"),"val"),a=new Map(t.get(o)||[]);for(let i of Pt(n,"lvlOverride")){let s=Number.parseInt(he(i,"ilvl")||"0",10)||0,l=Zt(i,"lvl"),c={...a.get(s)||{start:1,format:"decimal",text:`%${s+1}.`}};l&&(c.start=Number.parseInt(he(Zt(l,"start"),"val")||String(c.start),10)||c.start,c.format=he(Zt(l,"numFmt"),"val")||c.format,c.text=he(Zt(l,"lvlText"),"val")||c.text);let u=Zt(i,"startOverride");u&&(c.start=Number.parseInt(he(u,"val")||String(c.start),10)||c.start),a.set(s,c)}r.set(he(n,"numId"),a)}return r}function qc(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 Yc(e){let t=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],r=e,n="";for(let[o,a]of t)for(;r>=o;)n+=a,r-=o;return n}function jp(e,t){return t==="lowerLetter"?qc(e,!1):t==="upperLetter"?qc(e,!0):t==="lowerRoman"?Yc(e).toLowerCase():t==="upperRoman"?Yc(e):String(e)}function Kp(e){let t=e?Wp(e):new Map,r=new Map;return n=>{if(!n?.numId)return null;let o=t.get(String(n.numId));if(!o)return{...n,label:null,format:null};let a=r.get(n.numId)||[],i=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};a[n.level]=a[n.level]==null?i.start:a[n.level]+1,a.length=n.level+1,r.set(n.numId,a);let s=i.text.replace(/%([1-9])/g,(l,c)=>{let u=Number(c)-1,f=o.get(u)||i;return jp(a[u]??f.start,f.format)});return{...n,label:s,format:i.format}}}function Hp(e){let t=Gi(e),n=he(Gr(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(he(Gr(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function Gp(e,t){let r=[];for(let[s,l]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of Pt(e,s))r.push({type:l,id:he(c,"id")||null});let n=e.parentNode;for(;n&&n.localName!=="tc";)n=n.parentNode;let o=n?.parentNode;for(;o&&o.localName!=="tr";)o=o.parentNode;let a=o?.parentNode;for(;a&&a.localName!=="tbl";)a=a.parentNode;let i=e.ownerDocument;return{references:r,table:a?{tableIndex:Array.from(i.getElementsByTagNameNS(B,"tbl")).indexOf(a)+1,rowIndex:Array.from(a.getElementsByTagNameNS(B,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(B,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Zc(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of Pt(e,r))he(n,"author")&&t.add(he(n,"author"));return[...t].sort()}function qp(e){let t=new Map;for(let r of Pt(e,"comment")){let n=Pt(r,"p");t.set(he(r,"id"),{id:he(r,"id"),author:he(r,"author")||null,date:he(r,"date")||null,text:n.map(o=>te(o)).join(`
210
- `),paraId:at(r)||null})}return t}function Yp(e,t){if(!t)return;let r=new Map([...e.values()].filter(n=>n.paraId).map(n=>[n.paraId.toUpperCase(),n]));for(let n of Array.from(t.getElementsByTagNameNS("*","commentEx"))){let o=n.getAttribute("w15:paraId")||n.getAttribute("paraId")||"",a=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",i=r.get(o.toUpperCase());i&&(i.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",a&&(i.parentParaId=a,i.parentCommentId=r.get(a.toUpperCase())?.id||null))}}function Zp(e,t){let r=new Map,n=new Map,o=null,a=s=>{for(let l of r.values())l.text+=s},i=s=>{for(let l of Array.from(s?.childNodes||[])){if(l?.nodeType!==1)continue;let c=l.localName;if(!(t==="accepted"&&(c==="del"||c==="moveFrom")||t==="rejected"&&(c==="ins"||c==="moveTo")))if(c==="commentRangeStart")r.set(he(l,"id"),{text:""});else if(c==="commentRangeEnd"){let u=he(l,"id");r.has(u)&&(n.set(u,r.get(u).text),r.delete(u))}else c==="r"?a(Mr(l,{revisionView:t,boundary:o})):i(l)}};return e.forEach((s,l)=>{o=s,i(s),l<e.length-1&&r.size&&a(`
211
- `)}),n}function Jp(e,t){let r=e;if(t.revisedOnly&&(r=r.filter(p=>p.hasRevisions)),t.inTable!=null&&(r=r.filter(p=>p.inTable===!!t.inTable)),t.skipEmpty&&(r=r.filter(p=>p.text.length>0)),t.search){let p=String(t.search).toLowerCase();r=r.filter(g=>g.text.toLowerCase().includes(p))}if(Array.isArray(t.indexes)){let p=new Set(t.indexes);r=r.filter(g=>p.has(g.index))}let n=1,o=e.length;t.range&&(n=Number(t.range.start??t.range[0]),o=Number(t.range.end??t.range[1]),r=r.filter(p=>p.index>=n&&p.index<=o));let a=r.length,i=Number.isInteger(t.after)&&t.after>0?t.after:null,s=i==null?r:r.filter(p=>p.index>i),l=Number.isInteger(t.limit)&&t.limit>0?t.limit:null,c=l==null?s:s.slice(0,l),u=c.length<s.length,f=Number.isInteger(t.around)&&t.around>0?t.around:0,d=!!t.search||f>0||l!=null||i!=null,m=c;if(f>0&&t.search){let p=new Set(c.map(y=>y.index)),g=new Map;for(let y of c){let w=Math.max(n,y.index-f),v=Math.min(o,y.index+f);for(let b=w;b<=v;b++){if(p.has(b))continue;let x=g.get(b)||[];x.push(y.index),g.set(b,x)}}let h=new Set([...p,...g.keys()]);m=e.filter(y=>h.has(y.index)).map(y=>p.has(y.index)?{...y,selectionRole:"match"}:{...y,selectionRole:"context",contextFor:g.get(y.index)||[]})}else d&&(m=c.map(p=>({...p,selectionRole:"match"})));return{paragraphs:m,...d?{selection:{...t.search?{search:String(t.search),caseSensitive:!1}:{},totalMatches:a,returnedMatches:c.length,returnedParagraphs:m.length,truncated:u,nextAfter:u&&c.length>0?c[c.length-1].index:null,...l!=null?{limit:l}:{},...i!=null?{after:i}:{},...f>0?{around:f}:{}}}:{}}}function ba(e,t={}){let r=xa(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=xa(e?.commentsXml,"word/comments.xml"),o=xa(e?.commentsExtendedXml,"word/commentsExtended.xml"),a=xa(e?.numberingXml,"word/numbering.xml"),i=[...r.warnings||[]];n.error&&i.push(n.error.message),o.error&&i.push(o.error.message),a.error&&i.push(a.error.message);let s=qp(n.doc);Yp(s,o.doc);let l=Kp(a.doc),c=null,u=le(r.doc),f=t.revisionView==="rejected"?"rejected":"accepted",d=Zp(u,f),m=u.map((v,b)=>{let x=te(v,{revisionView:f}),T=Hp(v);T&&(c={level:T,text:x});let I=[...new Set([...Pt(v,"commentRangeStart"),...Pt(v,"commentReference")].map(M=>he(M,"id")).filter(Boolean))],N=Zc(v),A=l(Vp(v)),S=he(Gr(Gi(v),"pStyle"),"val")||null,O=Gp(v,x),E=b+1,k=A?.label&&A.format!=="bullet"?A.label:null,C=c?.text||null,P=x.slice(0,t.excerptLength||120),_=T?x:k?[k,C].filter(Boolean).join(" \u2014 "):C?[C,P].filter(Boolean).join(" \u2014 "):P,R=Uo(v);return{index:E,ref:`P${E}`,paragraphId:Xe(v),fingerprint:dt(v,{text:x,index:E,revisionView:f}),revisionView:f,text:x,exactText:x,excerpt:P,humanReference:_,provision:k,inTable:Gc(v,"tc"),table:O.table,styleId:S,headingLevel:T,nearestHeading:c,list:A,structuralReferences:O.references,hasRevisions:N.length>0,revisionAuthors:N,commentIds:I,segments:R}});for(let v of m)for(let b of v.commentIds){let x=s.get(b)||{id:b,author:null,date:null,text:""};x.paragraphIndex??(x.paragraphIndex=v.index),x.targetRef??(x.targetRef=v.ref),x.anchoredText??(x.anchoredText=d.get(b)||v.text),s.set(b,x)}let p=Jp(m,t);if(t.search&&p.selection&&p.selection.totalMatches===0){let v=String(t.search).toLowerCase(),b=f==="accepted"?"rejected":"accepted",x=1,T=u.length;t.range&&(x=Number(t.range.start??t.range[0]),T=Number(t.range.end??t.range[1]));let I=0;for(let N=0;N<u.length;N++){let A=N+1;if(t.range&&(A<x||A>T)||Array.isArray(t.indexes)&&!t.indexes.includes(A))continue;let S=u[N];if(t.inTable!=null&&Gc(S,"tc")!==!!t.inTable||t.revisedOnly&&Zc(S).length===0)continue;let O=te(S,{revisionView:b});t.skipEmpty&&O.length===0||O.toLowerCase().includes(v)&&I++}I>0&&(p.selection.hint=f==="accepted"?`0 matches in accepted view, but ${I} match${I===1?"":"es"} found in --view rejected. If searching for deleted text to restore, re-run with --view rejected.`:`0 matches in rejected view, but ${I} match${I===1?"":"es"} found in --view accepted. Re-run with --view accepted.`)}m=p.paragraphs;let g=[...new Set(m.flatMap(v=>v.revisionAuthors))].sort(),h=va(e),y=h.map(v=>v.name).sort(),w=null;return typeof t.digestFn=="function"&&(w=io({scope:"document-parts",entries:h,digestFn:t.digestFn})),{status:"ok",revisionToken:w,coveredParts:y,paragraphs:m,...p.selection?{selection:p.selection}:{},comments:[...s.values()],revisionAuthors:g,commentAuthors:[...new Set([...s.values()].map(v=>v.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:s.size,revisedParagraphs:m.filter(v=>v.hasRevisions).length},warnings:i}}function bn(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Dn(e,"w:r"),o=[],a="";for(let i of n){if(!kr(i,e,r))continue;let s=a.length,l=Mr(i,{revisionView:r,boundary:e});a+=l,o.push({run:i,start:s,end:a.length})}return{fullText:a,runOffsets:o}}function Jc(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 Qc(e){return String(e).replace(/[ \u00a0]/g," ")}function co(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function eu(e,t,r){let n=null,o=null,a=0,i=0;for(let{run:s,start:l,end:c}of e.runOffsets)t.start>=l&&t.start<c&&(n=s,a=t.start-l),t.end>l&&t.end<=c&&(o=s,i=t.end-l);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:a,endRun:o,endOffset:i}}function tu(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 ru(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(tu(n,["del"]))return{found:!1,error:co("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(tu(n,["moveFrom","moveTo"]))return{found:!1,error:co("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function uo(e,t){let r=String(t??""),n=Jc(e.fullText,r);if(n.length>1)return{found:!1,error:co("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=eu(e,n[0],"exact_anchor");if(s)return ru(e,s)}let o=Qc(r),a=Qc(e.fullText),i=Jc(a,o);if(i.length>1)return{found:!1,error:co("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${i.length} locations in the target paragraph.`,i)};if(i.length===1){let s=eu(e,i[0],"space_equivalent_anchor");if(s)return ru(e,s)}return{found:!1,error:co("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function lo(e,t,r,n,o=!1){let a=D(e,"w:r");if(t){let s=t.cloneNode(!0);o||Lt(s,n),a.appendChild(s)}let i=D(e,"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=r,a.appendChild(i),a}function nu(e,t,r,n,o=null,a=null,i=null){let s=o||bn(t),l=i||uo(s,r);if(!l.found||!l.startRun)return!1;let c=D(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let u=D(e,"w:commentRangeEnd");u.setAttribute("w:id",String(n));let f=D(e,"w:r"),d=D(e,"w:commentReference");if(d.setAttribute("w:id",String(n)),f.appendChild(d),l.startRun===l.endRun){let h=l.startRun,y=Ce(h,"w:t");if(!y)return h.parentNode.insertBefore(c,h),h.nextSibling?(h.parentNode.insertBefore(u,h.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(h.parentNode.appendChild(u),h.parentNode.appendChild(f)),!0;let w=y.textContent||"",v=w.substring(0,l.startOffset),b=w.substring(l.startOffset,l.endOffset),x=w.substring(l.endOffset),T=Ce(h,"w:rPr"),I=h.parentNode;return v&&(I.insertBefore(lo(e,T,v,a,!0),h),Lt(T,a)),I.insertBefore(c,h),y.textContent=b,h.nextSibling?I.insertBefore(u,h.nextSibling):I.appendChild(u),I.insertBefore(f,u.nextSibling||null),x&&I.insertBefore(lo(e,T,x,a),f.nextSibling||null),!0}let m=Ce(l.startRun,"w:t");if(m&&l.startOffset>0){let h=m.textContent||"",y=h.substring(0,l.startOffset),w=h.substring(l.startOffset);if(y){let v=Ce(l.startRun,"w:rPr");l.startRun.parentNode.insertBefore(lo(e,v,y,a,!0),l.startRun),Lt(v,a)}m.textContent=w}l.startRun.parentNode.insertBefore(c,l.startRun);let p=l.endRun||l.startRun,g=Ce(p,"w:t");if(g&&l.endOffset<(g.textContent||"").length){let h=g.textContent||"",y=h.substring(0,l.endOffset),w=h.substring(l.endOffset);if(g.textContent=y,w){let v=Ce(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(lo(e,v,w,a),p.nextSibling):p.parentNode.appendChild(lo(e,v,w,a))}}return p.nextSibling?(p.parentNode.insertBefore(u,p.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(p.parentNode.appendChild(u),p.parentNode.appendChild(f)),!0}var Nn="http://schemas.microsoft.com/office/2006/xmlPackage",fo="http://schemas.openxmlformats.org/package/2006/relationships";function ou(e,t){let r=oe(),n=W(e,"text/xml"),o=n.doc,a=o?Ee(o):null;if(n.error||a)return Te("[CommentEngine] Failed to parse package:",n.error?.message||a?.textContent),e;let i=o.documentElement,s=o.createElementNS(Nn,"pkg:part");s.setAttribute("pkg:name","/word/comments.xml"),s.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let l=o.createElementNS(Nn,"pkg:xmlData"),c=W(t,"text/xml").doc;if(!c)return e;l.appendChild(o.importNode(c.documentElement,!0)),s.appendChild(l),i.appendChild(s);let f=_e(i,Nn,"part").find(d=>d.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let d=_e(f,Nn,"xmlData");if(d.length>0){let m=_e(d[0],fo,"Relationships");if(m.length>0){let p=m[0],g=_e(p,fo,"Relationship");if(!g.some(y=>y.getAttribute("Type")?.includes("comments"))){let y=0;g.forEach(v=>{let b=v.getAttribute("Id"),x=parseInt(b?.replace("rId","")||"0",10);x>y&&(y=x)});let w=o.createElementNS(fo,"Relationship");w.setAttribute("Id",`rId${y+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let d=o.createElementNS(Nn,"pkg:part");d.setAttribute("pkg:name","/word/_rels/document.xml.rels"),d.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let m=o.createElementNS(Nn,"pkg:xmlData"),p=o.createElementNS(fo,"Relationships"),g=o.createElementNS(fo,"Relationship");g.setAttribute("Id","rId1"),g.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),g.setAttribute("Target","comments.xml"),p.appendChild(g),m.appendChild(p),d.appendChild(m),i.appendChild(d)}return r.serializeToString(o)}function Qp(e,t){let r=W(e,"text/xml"),n=r.doc?Ee(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 qi(e,t,r={}){let n=r?.author||re(),o=Ro(),a=[],i=[],s=[],l=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=oe(),u=Qp(e,h=>`Failed to parse OXML: ${h}`);if(a.push(...u.warnings||[]),!u.xmlDoc)return Te("[CommentEngine] Parse failure:",u.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:u.error,warnings:[...a,u.warning]};let f=u.xmlDoc,d=ur(f),m=Dn(f,"w:p");V(`[CommentEngine] Found ${m.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let y=h.paragraphIndex-1;if(y<0||y>=m.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${m.length})`;a.push(w),l.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(y,(p.get(y)||0)+1)}let g=new Map;for(let[h,y]of t.entries()){let w=y.paragraphIndex-1;if(w<0||w>=m.length)continue;let v=m[w],b=g.get(w);b||(b=bn(v),g.set(w,b));let x=String(y.textToFind??""),T=uo(b,x),I=(p.get(w)||1)-1;if(p.set(w,I),!T.found){let S={...T.error,requestIndex:h+1,paragraphIndex:y.paragraphIndex};l.push(S),a.push(S.message),I===0&&g.delete(w);continue}let N=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():Hs();if(!nu(f,v,x,N,b,d,T)){let S={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${y.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:y.paragraphIndex};l.push(S),a.push(S.message),I===0&&g.delete(w);continue}i.push({id:N,content:y.commentContent,author:n,date:o}),s.push({requestIndex:h+1,paragraphIndex:y.paragraphIndex,text:x,resolvedBy:T.resolvedBy,start:T.start,end:T.end}),I>0?g.set(w,bn(v)):g.delete(w)}return i.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:a,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}:{oxml:c.serializeToString(f),hasChanges:!0,commentsXml:Xi(i),commentsApplied:i.length,placedComments:i,warnings:a,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}}function eg(e,t){return ou(e,t)}var tg="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Jt(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function Na(e,t){let r=W(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}}function Yi({commentsXml:e,commentsExtendedXml:t=null,documentXml:r=null,parentCommentId:n,commentId:o,commentContent:a,author:i,date:s=new Date().toISOString()}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing word/comments.xml part."}};let l=Na(e,"word/comments.xml");if(l.error)return{status:"error",error:l.error};let c=l.doc,u=Array.from(c.getElementsByTagNameNS("*","comment")).find(O=>Jt(O,"w:id","id")===String(n));if(!u)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${n}' was not found.`}};let f=null;if(t){let O=Na(t,"word/commentsExtended.xml");if(O.error)return{status:"error",error:O.error};f=O.doc}let d=Ki(c,f);if(r)for(let O of String(r).matchAll(/w14:paraId="([0-9A-Fa-f]{8})"/g))d.add(O[1].toUpperCase());let m=ha(u);if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${n}' has no paragraph.`}};let p=at(u);p?p=p.toUpperCase():(p=wa(n,d),m.setAttributeNS(vn,"w14:paraId",p));for(let O of Array.from(f?.getElementsByTagNameNS("*","commentEx")||[]))if(Jt(O,"w15:paraId","paraId").toUpperCase()===p){let E=Jt(O,"w15:paraIdParent","paraIdParent").toUpperCase();E&&(p=E);break}let g=[],h=Array.from(c.getElementsByTagNameNS("*","comment")),y=new Map(Array.from(f?.getElementsByTagNameNS("*","commentEx")||[]).map(O=>[Jt(O,"w15:paraId","paraId").toUpperCase(),Jt(O,"w15:paraIdParent","paraIdParent").toUpperCase()]));for(let O of h){let E=at(O);(E===p||y.get(E)===p)&&g.push(Jt(O,"w:id","id"))}let w=Jt(h.find(O=>at(O)===p),"w:id","id")||String(n),v=wa(o,d),b=Na(`<w:comments xmlns:w="${tg}" xmlns:w14="${vn}">${oo(o,i,a,s,v)}</w:comments>`,"reply comment");c.documentElement.appendChild(c.importNode(b.doc.documentElement.firstChild,!0)),f||(f=Na(Vc([]),"word/commentsExtended.xml").doc);let x=f.documentElement,I=Array.from(x.getElementsByTagNameNS("*","commentEx")).find(O=>Jt(O,"w15:paraId","paraId").toUpperCase()===p);if(!I){let O=f.createElementNS(Ge,"w15:commentEx");O.setAttributeNS(Ge,"w15:paraId",p),O.setAttributeNS(Ge,"w15:done","0"),x.appendChild(O)}let N=Jt(I,"w15:done","done")==="1"?"1":"0",A=f.createElementNS(Ge,"w15:commentEx");A.setAttributeNS(Ge,"w15:paraId",v),A.setAttributeNS(Ge,"w15:paraIdParent",p),A.setAttributeNS(Ge,"w15:done",N),x.appendChild(A);let S=oe();return{status:"ok",hasChanges:!0,commentsXml:S.serializeToString(c),commentsExtendedXml:S.serializeToString(f),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:o,parentCommentId:String(n),paraId:v,parentParaId:p,threadRootCommentId:w,threadCommentIds:g.length?g:[w]}}function In(e){e?.parentNode&&e.parentNode.removeChild(e)}function au(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(In)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(o=>{let a=n[o];a&&r.querySelectorAll(`${a}, ${a.replace("w:","")}`).forEach(In)})}return r.children.length>0?r:null}function rg(e,t,r){if(!t||!e)return e;let n=ft(e);if(!n)return e;let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=n.getElementsByTagNameNS(o,"r"),i=n.getElementsByTagNameNS(o,"ins"),s=[...Array.from(a)];for(let l of i){let c=l.getElementsByTagNameNS(o,"r");s.push(...Array.from(c))}for(let l of s){let c=l.getElementsByTagNameNS(o,"t"),u=Array.from(c).map(f=>f.textContent).join("");if(u.includes(t)||u===t){let f=l.getElementsByTagNameNS(o,"rPr");if(f.length>0){let d=f[0],m=au(d,r);m?d.parentNode&&d.parentNode.replaceChild(m,d):In(d)}}}return Yt(n)}var ng={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 og(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=ng[r.toLowerCase()]||"yellow",i=n?.generateRedlines??!1,s=n?.author||re(),l=t;l?l=t.cloneNode(!0):l=D(e,"w:rPr");let c=null;i&&(c=D(e,"w:rPr"),Array.from(l.childNodes).forEach(d=>{d.nodeName!=="w:rPrChange"&&c.appendChild(d.cloneNode(!0))}));let u=l.getElementsByTagNameNS(o,"highlight");Array.from(u).forEach(In);let f=D(e,"w:highlight");if(f.setAttributeNS(o,"w:val",a),l.appendChild(f),i&&c){let d=D(e,"w:rPrChange"),m=ie(s,e);d.setAttribute("w:id",String(m.id)),d.setAttribute("w:author",m.author),d.setAttribute("w:date",m.date),d.appendChild(c);let p=l.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(In),l.appendChild(d)}return l}function Zi(e,t,r="yellow",n={}){if(!t||!e)return e;let o=ft(e);if(!o)return e;let a;n?._revisionIdAllocator instanceof Pe?(a=n._revisionIdAllocator,Wt(o,a)):a=ur(o);let i="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=f=>{let d=f.getElementsByTagNameNS(i,"t");return Array.from(d).map(m=>m.textContent).join("")},l=Array.from(o.getElementsByTagNameNS(i,"r")),c=new WeakSet,u=(f,d,m)=>{let p=f.cloneNode(!0);c.has(f)?Lt(p,a):c.add(f);let g=p.getElementsByTagNameNS(i,"t");Array.from(g).forEach(In);let h=D(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=d,p.appendChild(h),m){let y=p.getElementsByTagNameNS(i,"rPr"),w=y.length>0?y[0]:null,v=og(o,w,r,n);w?p.replaceChild(v,w):p.insertBefore(v,p.firstChild)}return p};for(let f of l){let d=s(f);if(!d)continue;let m=[],p=0;for(;p<=d.length-t.length;){let w=d.indexOf(t,p);if(w===-1)break;m.push(w),p=w+t.length}if(m.length===0)continue;let g=f.parentNode;if(!g){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),y=0;for(let w of m)w>y&&h.appendChild(u(f,d.slice(y,w),!1)),h.appendChild(u(f,d.slice(w,w+t.length),!0)),y=w+t.length;y<d.length&&h.appendChild(u(f,d.slice(y),!1)),g.replaceChild(h,f)}return Yt(o)}var Qt="application/vnd.openxmlformats-officedocument.wordprocessingml",mo="http://schemas.openxmlformats.org/officeDocument/2006/relationships",iu=Object.freeze([{id:"document",path:"word/document.xml",pathPattern:null,contentType:`${Qt}.document.main+xml`,legacyContentTypes:[],relType:`${mo}/officeDocument`,relTarget:null,verified:!0},{id:"numbering",path:"word/numbering.xml",pathPattern:null,contentType:`${Qt}.numbering+xml`,legacyContentTypes:[],relType:`${mo}/numbering`,relTarget:"numbering.xml",verified:!1},{id:"comments",path:"word/comments.xml",pathPattern:null,contentType:`${Qt}.comments+xml`,legacyContentTypes:[],relType:`${mo}/comments`,relTarget:"comments.xml",verified:!0},{id:"commentsExtended",path:"word/commentsExtended.xml",pathPattern:null,contentType:`${Qt}.commentsExtended+xml`,legacyContentTypes:["application/vnd.ms-word.commentsExtended+xml"],relType:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",relTarget:"commentsExtended.xml",verified:!0},{id:"commentsIds",path:"word/commentsIds.xml",pathPattern:null,contentType:`${Qt}.commentsIds+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",relTarget:"commentsIds.xml",verified:!0},{id:"commentsExtensible",path:"word/commentsExtensible.xml",pathPattern:null,contentType:`${Qt}.commentsExtensible+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible",relTarget:"commentsExtensible.xml",verified:!0},{id:"people",path:"word/people.xml",pathPattern:null,contentType:`${Qt}.people+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2011/relationships/people",relTarget:"people.xml",verified:!1},{id:"header",path:null,pathPattern:/^word\/header\d+\.xml$/i,contentType:`${Qt}.header+xml`,legacyContentTypes:[],relType:`${mo}/header`,relTarget:null,verified:!0},{id:"footer",path:null,pathPattern:/^word\/footer\d+\.xml$/i,contentType:`${Qt}.footer+xml`,legacyContentTypes:[],relType:`${mo}/footer`,relTarget:null,verified:!0}].map(e=>Object.freeze(e))),ag=new Map(iu.map(e=>[e.id,e]));function qr(e){let t=ag.get(e);if(!t)throw new Error(`Unknown package part: ${e}`);return t}function ig(e){return String(e||"").replace(/^\/+/,"")}function Ji(e){let t=ig(e),r=t.toLowerCase();return iu.find(n=>n.path?n.path.toLowerCase()===r:n.pathPattern?.test(t))||null}function su(e,t){let r=Ji(e);return!r||!r.legacyContentTypes.includes(t)?null:r.contentType}var Ve="http://schemas.openxmlformats.org/wordprocessingml/2006/main",sg="http://schemas.openxmlformats.org/package/2006/content-types",lg="http://schemas.openxmlformats.org/package/2006/relationships",rs=qr("numbering"),ns=qr("comments"),os=qr("commentsExtended"),cu=rs.relType,uu=rs.contentType,fu=ns.relType,du=ns.contentType,mu=os.relType,Qi=os.contentType,lu=qr("document").path,Ia=rs.path,po=ns.path,es=os.path,Qe="[Content_Types].xml",bt="word/_rels/document.xml.rels";function Me(e,t="xml"){let r=W(e,"application/xml");if(r.error||!r.doc){let n=new Error(`[XML parse error] ${t}: ${r.error?.message||"Unknown"}`);throw n.code="PARSE_ERROR",n}return r.doc}function Ta(e){return!!e&&e.nodeType===1&&e.namespaceURI===Ve&&e.localName==="sectPr"}function as(e){return e.getElementsByTagNameNS("*","body")[0]||null}function pu(e){for(let t of Array.from(e.childNodes||[]))if(Ta(t))return t;return null}function cg(e,t){let r=pu(e);r?e.insertBefore(t,r):e.appendChild(t)}function Sa(e){let t=as(e);if(!t)return;let r=pu(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function ug(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(Ve,"tc"),o=0;for(let a of Array.from(n)){let i=Array.from(a.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===Ve&&s.localName==="p");for(let s of i){let l=Array.from(s.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===Ve&&c.localName==="p");for(let c of l)a.insertBefore(c,s),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function ts(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function fg(e){let t=oe(),r=Me(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(f=>ts(f)==="/word/document.xml");if(!o)throw new Error("Package output missing /word/document.xml part");let a=o.getElementsByTagNameNS("*","xmlData")[0];if(!a)throw new Error("Package document part missing pkg:xmlData");let i=Array.from(a.childNodes||[]).find(f=>f.nodeType===1);if(!i)throw new Error("Package document part missing XML payload");let s=i.getElementsByTagNameNS("*","body")[0],l=s?Array.from(s.childNodes||[]).filter(f=>f.nodeType===1&&!Ta(f)):[i],c=n.find(f=>ts(f)==="/word/numbering.xml"),u=null;if(c){let f=c.getElementsByTagNameNS("*","xmlData")[0],d=f?Array.from(f.childNodes||[]).find(m=>m.nodeType===1):null;d&&(u=t.serializeToString(d))}return{replacementNodes:l,numberingXml:u,sourceType:"package"}}function is(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 fg(e);if(e.includes("<w:document")){let o=Me(e,"document OOXML"),a=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:a?Array.from(a.childNodes||[]).filter(s=>s.nodeType===1&&!Ta(s)):Array.from(o.childNodes||[]).filter(s=>s.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${Ve}">${e}</root>`,r=Me(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 ss(e,t,r){let o=Array.from(e.getElementsByTagNameNS("*","Override")).find(i=>(i.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(o)return(o.getAttribute("ContentType")||"")===r?!1:(o.setAttribute("ContentType",r),!0);let a=e.createElementNS(sg,"Override");return a.setAttribute("PartName",t),a.setAttribute("ContentType",r),e.documentElement.appendChild(a),!0}function ls(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,a=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(a.some(u=>(u.getAttribute("Type")||"")===t))return!1;let s=0;for(let u of a){let f=u.getAttribute("Id")||"",d=Number.parseInt(f.replace(/^rId/i,""),10);Number.isFinite(d)&&(s=Math.max(s,d))}let l=`rId${s+1}`,c=e.createElementNS(lg,"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 qe(e,t){let r=e.file(t);return r?r.async("string"):null}async function Aa(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},o=typeof r?.mergeNumberingXml=="function"?r.mergeNumberingXml:null,a=typeof r?.onWarn=="function"?r.onWarn:St,i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0)return;let s=await qe(e,Ia);s&&!o&&a("[Deprecation] Replacing an existing numbering.xml without mergeNumberingXml is deprecated and will throw in the next major version.");let l=s||null;for(let d of i){if(!l){l=d;continue}l=o?o(l,d):d}n(s?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(Ia,l);let c=oe(),u=await qe(e,Qe);if(u){let d=Me(u,Qe);ss(d,"/word/numbering.xml",uu)&&e.file(Qe,c.serializeToString(d))}let f=await qe(e,bt);if(f){let d=Me(f,bt);ls(d,cu,"numbering.xml",r)&&e.file(bt,c.serializeToString(d))}}async function cs(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=oe(),a=await qe(e,po);if(!a||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(po,t);else{let l=Me(a,"word/comments.xml (existing)"),c=Me(t,"word/comments.xml (incoming)"),u=l.documentElement,f=new Set(Array.from(u.getElementsByTagNameNS(Ve,"comment")).map(d=>d.getAttribute("w:id")||d.getAttribute("id")).filter(Boolean));for(let d of Array.from(c.documentElement.getElementsByTagNameNS(Ve,"comment"))){let m=d.getAttribute("w:id")||d.getAttribute("id");if(m&&f.has(m))throw new Error(`Duplicate comment id: ${m}`);u.appendChild(l.importNode(d,!0))}e.file(po,o.serializeToString(l))}let i=await qe(e,Qe);if(i){let l=Me(i,Qe);ss(l,"/word/comments.xml",du)&&e.file(Qe,o.serializeToString(l))}let s=await qe(e,bt);if(s){let l=Me(s,bt);ls(l,fu,"comments.xml",r)&&e.file(bt,o.serializeToString(l))}}async function Ea(e,t,r={}){if(!t)return;Me(t,"word/commentsExtended.xml"),e.file(es,t);let n=oe(),o=await qe(e,Qe);if(o){let i=Me(o,Qe);ss(i,"/word/commentsExtended.xml",Qi)&&e.file(Qe,n.serializeToString(i))}let a=await qe(e,bt);if(a){let i=Me(a,bt);ls(i,mu,"commentsExtended.xml",r)&&e.file(bt,n.serializeToString(i))}}async function Tn(e){let t=await qe(e,Qe);if(!t)return[];let r=Me(t,Qe),n=[];for(let o of Array.from(r.getElementsByTagNameNS("*","Override"))){let a=o.getAttribute("PartName")||"",i=o.getAttribute("ContentType")||"",s=su(a,i);s&&(o.setAttribute("ContentType",s),n.push({partName:a,from:i,to:s}))}return n.length>0&&e.file(Qe,oe().serializeToString(r)),n}async function Ir(e){let t=await qe(e,lu);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=Me(t,lu);Sa(r);let n=as(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(h=>h.nodeType===1),a=o.map((h,y)=>({node:h,index:y})).filter(h=>Ta(h.node)).map(h=>h.index);if(a.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(a.length===1&&a[0]!==o.length-1)throw new Error("Validation failed: w:sectPr not last");let i=r.getElementsByTagNameNS(Ve,"tc");for(let h of Array.from(i))for(let y of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(y.namespaceURI===Ve&&y.localName==="p"&&Array.from(y.childNodes||[]).some(v=>v.nodeType===1&&v.namespaceURI===Ve&&v.localName==="p"))throw new Error("Validation failed: nested w:p");let s=r.getElementsByTagNameNS(Ve,"numPr").length>0,l=r.getElementsByTagNameNS(Ve,"commentRangeStart").length>0||r.getElementsByTagNameNS(Ve,"commentRangeEnd").length>0||r.getElementsByTagNameNS(Ve,"commentReference").length>0,c=await qe(e,Ia),u=await qe(e,po),f=await qe(e,es);if(f&&!u)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)Me(c,Ia);else if(s)throw new Error("Validation failed: numbering used but part missing");if(u){let h=Me(u,po),y=(_,R)=>Array.from(_.getElementsByTagNameNS(Ve,R)).map(M=>M.getAttribute("w:id")||M.getAttribute("id")).filter(M=>M!==""),w=new Set(y(r,"commentRangeStart")),v=new Set(y(r,"commentRangeEnd")),b=new Set(y(r,"commentReference")),x=y(h,"comment"),T=new Set(x),I=_=>Array.from(_).sort((R,M)=>Number(R)-Number(M)||R.localeCompare(M)),N=(_,R)=>I(new Set(Array.from(_).filter(M=>!R.has(M)))),A=I(new Set(x.filter((_,R)=>x.indexOf(_)!==R)));if(A.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${A.join(", ")}`);let S=N(w,v),O=N(v,w);if(S.length>0||O.length>0){let _=[];throw S.length>0&&_.push(`start without end: ${S.join(", ")}`),O.length>0&&_.push(`end without start: ${O.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${_.join("; ")})`)}let E=N(new Set([...w,...v]),b);if(E.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${E.join(", ")}`);let k=N(new Set([...w,...v,...b]),T);if(k.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${k.join(", ")}`);let C=new Set;if(f){let _=Me(f,es),R=new Map;for(let X of Array.from(h.getElementsByTagNameNS("*","comment"))){let z=X.getAttribute("w:id")||X.getAttribute("id"),H=at(X);H&&R.set(H,z)}let M=new Set(R.keys()),U=new Set;for(let X of Array.from(_.getElementsByTagNameNS("*","commentEx"))){let z=X.getAttribute("w15:paraId")||X.getAttribute("paraId"),H=X.getAttribute("w15:paraIdParent")||X.getAttribute("paraIdParent");if(!z||!M.has(z.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${z||"(missing)"}`);if(U.has(z.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${z}`);if(U.add(z.toUpperCase()),H){if(!M.has(H.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${H}`);C.add(R.get(z.toUpperCase()))}}}let P=N(new Set([...T].filter(_=>!C.has(_))),b);if(P.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${P.join(", ")}`)}else if(l)throw new Error("Validation failed: comments used but part missing");let d=await qe(e,Qe);if(!d)throw new Error(`Validation failed: missing ${Qe}`);let m=Me(d,Qe),p=await qe(e,bt);if(!p)throw new Error(`Validation failed: missing ${bt}`);let g=Me(p,bt);if(c){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===uu),y=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===cu);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!y)throw new Error("Validation failed: numbering rel missing")}if(u){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===du),y=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===fu);if(!h)throw new Error("Validation failed: comments CT override missing");if(!y)throw new Error("Validation failed: comments rel missing")}{let h=new Map;for(let b of Array.from(g.getElementsByTagNameNS("*","Relationship")))h.set(b.getAttribute("Id")||"",{type:b.getAttribute("Type")||"",target:b.getAttribute("Target")||""});let y=qr("header"),w=qr("footer"),v=new Map(Array.from(m.getElementsByTagNameNS("*","Override")).map(b=>[(b.getAttribute("PartName")||"").toLowerCase(),b.getAttribute("ContentType")||""]));for(let b of[...Array.from(r.getElementsByTagNameNS(Ve,"headerReference")),...Array.from(r.getElementsByTagNameNS(Ve,"footerReference"))]){let x=b.getAttributeNS?.("http://schemas.openxmlformats.org/officeDocument/2006/relationships","id")||b.getAttribute("r:id")||"",T=b.localName==="headerReference"?y:w,I=h.get(x);if(!I)throw new Error(`Validation failed: ${b.localName} ${x||"(no r:id)"} has no document relationship`);if(I.type!==T.relType)throw new Error(`Validation failed: ${b.localName} ${x} points at a relationship of the wrong type (${I.type})`);let N=I.target.startsWith("/")?I.target:`/word/${I.target}`,A=await qe(e,N.slice(1));if(!A)throw new Error(`Validation failed: ${b.localName} ${x} targets a missing part: ${N}`);Me(A,N.slice(1));let S=v.get(N.toLowerCase());if(S!==T.contentType)throw new Error(`Validation failed: ${N} content type is ${S?`'${S}'`:"missing"}; Word expects '${T.contentType}'`)}}if(f){let h=Array.from(m.getElementsByTagNameNS("*","Override")).find(v=>(v.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml");if(h&&h.getAttribute("ContentType")!==Qi)throw new Error(`Validation failed: commentsExtended CT override has wrong content type '${h.getAttribute("ContentType")}' (Word expects '${Qi}')`);let y=!!h,w=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(v=>(v.getAttribute("Type")||"")===mu);if(!y)throw new Error("Validation failed: commentsExtended CT override missing");if(!w)throw new Error("Validation failed: commentsExtended rel missing")}}var Sn=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 hu(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
212
- `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function dg(e={}){let t=e.originalText||"",r=hu(e.newContent||""),n=Qn(r)||{type:"text",items:[]};return r.includes(`
213
- `)&&n.type!=="text"?{kind:Sn.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:gu(t),hasInlineFormatting:Ra(r),hasBlockElements:Pa(r),hasMarkdownTable:go(r)}}:gu(t)?Ra(r)?{kind:Sn.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:Pa(r),hasMarkdownTable:go(r)}}:{kind:Sn.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:Pa(r),hasMarkdownTable:go(r)}}:Pa(r)?{kind:Sn.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:Ra(r),hasBlockElements:!0,hasMarkdownTable:go(r)}}:{kind:Sn.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:Ra(r),hasBlockElements:!1,hasMarkdownTable:go(r)}}}function gu(e){return!e||e.trim().length===0}function go(e){if(!e||!e.includes("|"))return!1;let t=rt(e);return t.rows.length>0||t.headers.length>0}function Ra(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function Pa(e){if(!e)return!1;let t=/^[\s]*[-*+]\s+/m.test(e),r=/^[\s]*\d+\.\s+/m.test(e),n=/^[\s]*\d+\.\d+(?:\.\d+)*\.?\s+/m.test(e),o=/^[\s]*[A-Za-z]\.\s+/m.test(e),a=/^[\s]*[ivxlcIVXLC]+\.\s+/m.test(e),i=/^[\s]*\([a-z]\)\s+/m.test(e),s=/\|.*\|.*\n/.test(e),l=/^#{1,9}\s/m.test(e),c=e.includes(`
210
+ </w:comments>`}function Bf(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${Qe(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${Qe(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${dt}">${t}</w15:commentsEx>`}var Nt=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function si(e){let t=Array.from(e?.getElementsByTagNameNS?.("*","p")||[]);return t.length?t[t.length-1]:null}function Tt(e){return Nt(si(e),"w14:paraId","paraId").toUpperCase()}function tl(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=Nt(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=Nt(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function li(e,t){let r=Ys(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}var Zs=(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 ci({commentsXml:e,commentsExtendedXml:t=null,commentId:r,resolved:n=!0}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"Resolving a comment requires an existing word/comments.xml part."}};let o=Zs(e,"word/comments.xml");if(o.error)return{status:"error",error:o.error};let a=o.doc,i=R=>Nt(R,"w:id","id"),l=Array.from(a.getElementsByTagNameNS("*","comment")),s=l.find(R=>i(R)===String(r));if(!s)return{status:"error",error:{code:"COMMENT_NOT_FOUND",message:`Comment '${r}' was not found.`}};let c;if(t){let R=Zs(t,"word/commentsExtended.xml");if(R.error)return{status:"error",error:R.error};c=R.doc}else c=Zs(`<w15:commentsEx xmlns:w15="${dt}"/>`,"word/commentsExtended.xml").doc;let f=c.documentElement,u=R=>Array.from(f.getElementsByTagNameNS("*","commentEx")).find(T=>Nt(T,"w15:paraId","paraId").toUpperCase()===R)||null,d=tl(a,c),m=!1,g=(R=>{let T=Tt(R);return T||(T=li(i(R),d),si(R)?.setAttributeNS(no,"w14:paraId",T),m=!0),T})(s),h=u(g),v=h&&Nt(h,"w15:paraIdParent","paraIdParent").toUpperCase()||g,w=new Set([v,g]);for(let R of Array.from(f.getElementsByTagNameNS("*","commentEx")))Nt(R,"w15:paraIdParent","paraIdParent").toUpperCase()===v&&w.add(Nt(R,"w15:paraId","paraId").toUpperCase());let y=n?"1":"0",b=!t;for(let R of w){let T=u(R);T?Nt(T,"w15:done","done")!==y&&(T.setAttributeNS(dt,"w15:done",y),b=!0):(T=c.createElementNS(dt,"w15:commentEx"),T.setAttributeNS(dt,"w15:paraId",R),R!==v&&T.setAttributeNS(dt,"w15:paraIdParent",v),T.setAttributeNS(dt,"w15:done",y),f.appendChild(T),b=!0)}let x=new Map(l.map(R=>[Tt(R),R])),S=[...w].map(R=>x.get(R)).filter(Boolean).map(i),A=x.get(v),E=le(),I=b||m;return{status:"ok",hasChanges:I,resolved:n,threadRootId:A?i(A):String(r),commentIds:S,...I?{commentsExtendedXml:E.serializeToString(c)}:{},...m?{commentsXml:E.serializeToString(a)}:{}}}var ii="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Ff(e,t,r){let n=new Set(t.map(String)),o=g=>Nt(g,"w:id","id"),a=g=>Array.from(e.getElementsByTagNameNS("*",g)).filter(h=>n.has(o(h))),i=a("commentRangeStart"),l=a("commentReference");if(!i.length||!l.length)return!1;let s=i[i.length-1],c=l[l.length-1],f=c.parentNode?.localName==="r"?c.parentNode:c,u=(g,h)=>{let v=e.createElementNS(ii,`w:${g}`);return v.setAttributeNS(ii,"w:id",String(r)),h&&h.appendChild(v),v},d=(g,h)=>g.parentNode.insertBefore(h,g.nextSibling);d(s,u("commentRangeStart"));let m=u("commentRangeEnd"),p=e.createElementNS(ii,"w:r");return p.appendChild(e.createElementNS(ii,"w:rPr")),u("commentReference",p),d(f,m),d(m,p),!0}var Qs="http://schemas.microsoft.com/office/word/2016/wordml/cid",el="http://schemas.microsoft.com/office/word/2018/wordml/cex",ev=(e,t)=>{let r=(Number.parseInt(e,16)^625341585)&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");for(;t.has(n);)r=r+2&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");return t.add(n),n};function $f({commentsXml:e,commentsIdsXml:t=null,commentsExtensibleXml:r=null}){let n={};if(!e||!t&&!r)return n;let o=j(e,"application/xml");if(!o.doc||o.error)return n;let a=le(),i=new Map;for(let m of Array.from(o.doc.getElementsByTagNameNS("*","comment"))){let p=Tt(m);p&&i.set(p,m)}let l=null,s=new Map,c=new Set,f=!1;if(t){let m=j(t,"application/xml");if(!m.doc||m.error)return n;l=m.doc;let p=l.documentElement;for(let g of Array.from(p.getElementsByTagNameNS("*","commentId"))){let h=Nt(g,"w16cid:paraId","paraId").toUpperCase(),v=Nt(g,"w16cid:durableId","durableId").toUpperCase();if(v&&c.add(v),!i.has(h)){p.removeChild(g),f=!0;continue}s.set(h,v)}for(let g of i.keys()){if(s.has(g))continue;let h=ev(g,c),v=l.createElementNS(Qs,"w16cid:commentId");v.setAttributeNS(Qs,"w16cid:paraId",g),v.setAttributeNS(Qs,"w16cid:durableId",h),p.appendChild(v),s.set(g,h),f=!0}}let u=null,d=!1;if(r&&l){let m=j(r,"application/xml");if(m.doc&&!m.error){u=m.doc;let p=u.documentElement,g=new Set(s.values()),h=new Set;for(let v of Array.from(p.getElementsByTagNameNS("*","commentExtensible"))){let w=Nt(v,"w16cex:durableId","durableId").toUpperCase();g.has(w)?h.add(w):(p.removeChild(v),d=!0)}for(let[v,w]of s){if(h.has(w))continue;let y=Nt(i.get(v),"w:date","date"),b=u.createElementNS(el,"w16cex:commentExtensible");b.setAttributeNS(el,"w16cex:durableId",w),y&&b.setAttributeNS(el,"w16cex:dateUtc",y),p.appendChild(b),d=!0}}}return f&&(n.commentsIdsXml=a.serializeToString(l)),d&&(n.commentsExtensibleXml=a.serializeToString(u)),n}var tv=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rv=new TextEncoder;function Jo(e){let t;if(typeof e=="string")t=rv.encode(e);else if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else throw new TypeError("sha256 input must be a string, Uint8Array, Buffer, or ArrayBuffer.");let r=t.length,n=r*8,o=Math.ceil((r+9)/64)*64,a=new Uint8Array(o);a.set(t,0),a[r]=128;let i=new DataView(a.buffer,a.byteOffset,a.byteLength),l=Math.floor(n/4294967296),s=n>>>0;i.setUint32(o-8,l,!1),i.setUint32(o-4,s,!1);let c=1779033703,f=3144134277,u=1013904242,d=2773480762,m=1359893119,p=2600822924,g=528734635,h=1541459225,v=new Uint32Array(64);for(let y=0;y<o;y+=64){for(let N=0;N<16;N++)v[N]=i.getUint32(y+N*4,!1);for(let N=16;N<64;N++){let O=v[N-15],C=(O>>>7|O<<25)^(O>>>18|O<<14)^O>>>3,P=v[N-2],M=(P>>>17|P<<15)^(P>>>19|P<<13)^P>>>10;v[N]=v[N-16]+C+v[N-7]+M|0}let b=c,x=f,S=u,A=d,E=m,I=p,R=g,T=h;for(let N=0;N<64;N++){let O=(E>>>6|E<<26)^(E>>>11|E<<21)^(E>>>25|E<<7),C=E&I^~E&R,P=T+O+C+tv[N]+v[N]|0,M=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),_=b&x^b&S^x&S,k=M+_|0;T=R,R=I,I=E,E=A+P|0,A=S,S=x,x=b,b=P+k|0}c=c+b|0,f=f+x|0,u=u+S|0,d=d+A|0,m=m+E|0,p=p+I|0,g=g+R|0,h=h+T|0}let w=y=>(y>>>0).toString(16).padStart(8,"0");return w(c)+w(f)+w(u)+w(d)+w(m)+w(p)+w(g)+w(h)}var oo=new TextEncoder;function Df(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 rl({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=oo.encode("docx-redline-revision-token\0"),n=1,o=oo.encode(e),a=[],i=new Set,l=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let d of l){if(!d)continue;let m=Array.isArray(d)?d[0]:d.name,p=Array.isArray(d)?d[1]:d.payload??d.bytes;if(m==null)continue;let g=Df(String(m));if(i.has(g))throw new Error(`Duplicate normalized entry path detected: "${g}"`);i.add(g);let h;typeof p=="string"?h=oo.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),a.push({name:g,nameBytes:oo.encode(g),payloadBytes:h})}a.sort((d,m)=>d.name<m.name?-1:d.name>m.name?1:0);let s=r.length+4+4+o.length+4;for(let d of a)s+=4+d.nameBytes.length+4+d.payloadBytes.length;let c=new Uint8Array(s),f=new DataView(c.buffer,c.byteOffset,c.byteLength),u=0;c.set(r,u),u+=r.length,f.setUint32(u,n,!1),u+=4,f.setUint32(u,o.length,!1),u+=4,c.set(o,u),u+=o.length,f.setUint32(u,a.length,!1),u+=4;for(let d of a)f.setUint32(u,d.nameBytes.length,!1),u+=4,c.set(d.nameBytes,u),u+=d.nameBytes.length,f.setUint32(u,d.payloadBytes.length,!1),u+=4,c.set(d.payloadBytes,u),u+=d.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:a.map(d=>d.name)}}async function Uf({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:a}=rl({scope:e,entries:t}),i="";if(typeof r=="function")i=await r(n);else if(typeof globalThis.crypto?.subtle?.digest=="function"){let l=await globalThis.crypto.subtle.digest("SHA-256",n),s=new Uint8Array(l);i=Array.from(s).map(c=>c.toString(16).padStart(2,"0")).join("")}else i=Jo(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function Zo({scope:e,entries:t=[],digestFn:r=null}){if(r!=null&&typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn when specified.");let{framing:n,coveredParts:o,version:a}=rl({scope:e,entries:t}),i=typeof r=="function"?r(n):Jo(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function ui(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 Qo(e,t={}){let r=ui(e);return Uf({scope:"document-parts",entries:r,digestFn:t.digestFn})}function vn(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 yn(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=oo.encode(r),a=oo.encode(n),i=0;for(let l=0;l<o.length;l++)i|=o[l]^a[l];return i===0}var Ie=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",qt=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(B,t)||[]),yr=(e,t)=>qt(e,t)[0]||null,bn=(e,t)=>Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))||null,nl=e=>bn(e,"pPr");function zf(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))return!0;r=r.parentNode}return!1}function fi(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 nv(e){let t=bn(nl(e),"numPr");if(!t)return null;let r=Ie(bn(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(Ie(bn(t,"ilvl"),"val")||"0",10)||0}}function ov(e){let t=new Map;for(let n of qt(e,"abstractNum")){let o=new Map;for(let a of qt(n,"lvl")){let i=Number.parseInt(Ie(a,"ilvl")||"0",10)||0;o.set(i,{start:Number.parseInt(Ie(yr(a,"start"),"val")||"1",10)||1,format:Ie(yr(a,"numFmt"),"val")||"decimal",text:Ie(yr(a,"lvlText"),"val")||`%${i+1}.`})}t.set(Ie(n,"abstractNumId"),o)}let r=new Map;for(let n of qt(e,"num")){let o=Ie(yr(n,"abstractNumId"),"val"),a=new Map(t.get(o)||[]);for(let i of qt(n,"lvlOverride")){let l=Number.parseInt(Ie(i,"ilvl")||"0",10)||0,s=yr(i,"lvl"),c={...a.get(l)||{start:1,format:"decimal",text:`%${l+1}.`}};s&&(c.start=Number.parseInt(Ie(yr(s,"start"),"val")||String(c.start),10)||c.start,c.format=Ie(yr(s,"numFmt"),"val")||c.format,c.text=Ie(yr(s,"lvlText"),"val")||c.text);let f=yr(i,"startOverride");f&&(c.start=Number.parseInt(Ie(f,"val")||String(c.start),10)||c.start),a.set(l,c)}r.set(Ie(n,"numId"),a)}return r}function Xf(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 Vf(e){let t=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],r=e,n="";for(let[o,a]of t)for(;r>=o;)n+=a,r-=o;return n}function av(e,t){return t==="lowerLetter"?Xf(e,!1):t==="upperLetter"?Xf(e,!0):t==="lowerRoman"?Vf(e).toLowerCase():t==="upperRoman"?Vf(e):String(e)}function iv(e){let t=e?ov(e):new Map,r=new Map;return n=>{if(!n?.numId)return null;let o=t.get(String(n.numId));if(!o)return{...n,label:null,format:null};let a=r.get(n.numId)||[],i=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};a[n.level]=a[n.level]==null?i.start:a[n.level]+1,a.length=n.level+1,r.set(n.numId,a);let l=i.text.replace(/%([1-9])/g,(s,c)=>{let f=Number(c)-1,u=o.get(f)||i;return av(a[f]??u.start,u.format)});return{...n,label:l,format:i.format}}}function sv(e){let t=nl(e),n=Ie(bn(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(Ie(bn(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function lv(e,t){let r=[];for(let[l,s]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of qt(e,l))r.push({type:s,id:Ie(c,"id")||null});let n=e.parentNode;for(;n&&n.localName!=="tc";)n=n.parentNode;let o=n?.parentNode;for(;o&&o.localName!=="tr";)o=o.parentNode;let a=o?.parentNode;for(;a&&a.localName!=="tbl";)a=a.parentNode;let i=e.ownerDocument;return{references:r,table:a?{tableIndex:Array.from(i.getElementsByTagNameNS(B,"tbl")).indexOf(a)+1,rowIndex:Array.from(a.getElementsByTagNameNS(B,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(B,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function jf(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of qt(e,r))Ie(n,"author")&&t.add(Ie(n,"author"));return[...t].sort()}function cv(e){let t=new Map;for(let r of qt(e,"comment")){let n=qt(r,"p");t.set(Ie(r,"id"),{id:Ie(r,"id"),author:Ie(r,"author")||null,date:Ie(r,"date")||null,text:n.map(o=>Y(o)).join(`
211
+ `),paraId:Tt(r)||null})}return t}function uv(e,t){if(!t)return;let r=new Map([...e.values()].filter(n=>n.paraId).map(n=>[n.paraId.toUpperCase(),n]));for(let n of Array.from(t.getElementsByTagNameNS("*","commentEx"))){let o=n.getAttribute("w15:paraId")||n.getAttribute("paraId")||"",a=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",i=r.get(o.toUpperCase());i&&(i.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",a&&(i.parentParaId=a,i.parentCommentId=r.get(a.toUpperCase())?.id||null))}}function fv(e,t){let r=new Map,n=new Map,o=null,a=l=>{for(let s of r.values())s.text+=l},i=l=>{for(let s of Array.from(l?.childNodes||[])){if(s?.nodeType!==1)continue;let c=s.localName;if(!(t==="accepted"&&(c==="del"||c==="moveFrom")||t==="rejected"&&(c==="ins"||c==="moveTo")))if(c==="commentRangeStart")r.set(Ie(s,"id"),{text:""});else if(c==="commentRangeEnd"){let f=Ie(s,"id");r.has(f)&&(n.set(f,r.get(f).text),r.delete(f))}else c==="r"?a(gr(s,{revisionView:t,boundary:o})):i(s)}};return e.forEach((l,s)=>{o=l,i(l),s<e.length-1&&r.size&&a(`
212
+ `)}),n}function dv(e,t){let r=e;if(t.revisedOnly&&(r=r.filter(p=>p.hasRevisions)),t.inTable!=null&&(r=r.filter(p=>p.inTable===!!t.inTable)),t.skipEmpty&&(r=r.filter(p=>p.text.length>0)),t.search){let p=String(t.search).toLowerCase();r=r.filter(g=>g.text.toLowerCase().includes(p))}if(Array.isArray(t.indexes)){let p=new Set(t.indexes);r=r.filter(g=>p.has(g.index))}let n=1,o=e.length;t.range&&(n=Number(t.range.start??t.range[0]),o=Number(t.range.end??t.range[1]),r=r.filter(p=>p.index>=n&&p.index<=o));let a=r.length,i=Number.isInteger(t.after)&&t.after>0?t.after:null,l=i==null?r:r.filter(p=>p.index>i),s=Number.isInteger(t.limit)&&t.limit>0?t.limit:null,c=s==null?l:l.slice(0,s),f=c.length<l.length,u=Number.isInteger(t.around)&&t.around>0?t.around:0,d=!!t.search||u>0||s!=null||i!=null,m=c;if(u>0&&t.search){let p=new Set(c.map(v=>v.index)),g=new Map;for(let v of c){let w=Math.max(n,v.index-u),y=Math.min(o,v.index+u);for(let b=w;b<=y;b++){if(p.has(b))continue;let x=g.get(b)||[];x.push(v.index),g.set(b,x)}}let h=new Set([...p,...g.keys()]);m=e.filter(v=>h.has(v.index)).map(v=>p.has(v.index)?{...v,selectionRole:"match"}:{...v,selectionRole:"context",contextFor:g.get(v.index)||[]})}else d&&(m=c.map(p=>({...p,selectionRole:"match"})));return{paragraphs:m,...d?{selection:{...t.search?{search:String(t.search),caseSensitive:!1}:{},totalMatches:a,returnedMatches:c.length,returnedParagraphs:m.length,truncated:f,nextAfter:f&&c.length>0?c[c.length-1].index:null,...s!=null?{limit:s}:{},...i!=null?{after:i}:{},...u>0?{around:u}:{}}}:{}}}function di(e,t={}){let r=fi(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=fi(e?.commentsXml,"word/comments.xml"),o=fi(e?.commentsExtendedXml,"word/commentsExtended.xml"),a=fi(e?.numberingXml,"word/numbering.xml"),i=[...r.warnings||[]];n.error&&i.push(n.error.message),o.error&&i.push(o.error.message),a.error&&i.push(a.error.message);let l=cv(n.doc);uv(l,o.doc);let s=iv(a.doc),c=null,f=se(r.doc),u=t.revisionView==="rejected"?"rejected":"accepted",d=fv(f,u),m=f.map((y,b)=>{let x=Y(y,{revisionView:u}),S=sv(y);S&&(c={level:S,text:x});let A=[...new Set([...qt(y,"commentRangeStart"),...qt(y,"commentReference")].map(k=>Ie(k,"id")).filter(Boolean))],E=jf(y),I=s(nv(y)),R=Ie(bn(nl(y),"pStyle"),"val")||null,T=lv(y,x),N=b+1,O=I?.label&&I.format!=="bullet"?I.label:null,C=c?.text||null,P=x.slice(0,t.excerptLength||120),M=S?x:O?[O,C].filter(Boolean).join(" \u2014 "):C?[C,P].filter(Boolean).join(" \u2014 "):P,_=Oa(y);return{index:N,ref:`P${N}`,paragraphId:He(y),fingerprint:Ot(y,{text:x,index:N,revisionView:u}),revisionView:u,text:x,exactText:x,excerpt:P,humanReference:M,provision:O,inTable:zf(y,"tc"),table:T.table,styleId:R,headingLevel:S,nearestHeading:c,list:I,structuralReferences:T.references,hasRevisions:E.length>0,revisionAuthors:E,commentIds:A,segments:_}});for(let y of m)for(let b of y.commentIds){let x=l.get(b)||{id:b,author:null,date:null,text:""};x.paragraphIndex??(x.paragraphIndex=y.index),x.targetRef??(x.targetRef=y.ref),x.anchoredText??(x.anchoredText=d.get(b)||y.text),l.set(b,x)}let p=dv(m,t);if(t.search&&p.selection&&p.selection.totalMatches===0){let y=String(t.search).toLowerCase(),b=u==="accepted"?"rejected":"accepted",x=1,S=f.length;t.range&&(x=Number(t.range.start??t.range[0]),S=Number(t.range.end??t.range[1]));let A=0;for(let E=0;E<f.length;E++){let I=E+1;if(t.range&&(I<x||I>S)||Array.isArray(t.indexes)&&!t.indexes.includes(I))continue;let R=f[E];if(t.inTable!=null&&zf(R,"tc")!==!!t.inTable||t.revisedOnly&&jf(R).length===0)continue;let T=Y(R,{revisionView:b});t.skipEmpty&&T.length===0||T.toLowerCase().includes(y)&&A++}A>0&&(p.selection.hint=u==="accepted"?`0 matches in accepted view, but ${A} match${A===1?"":"es"} found in --view rejected. If searching for deleted text to restore, re-run with --view rejected.`:`0 matches in rejected view, but ${A} match${A===1?"":"es"} found in --view accepted. Re-run with --view accepted.`)}m=p.paragraphs;let g=[...new Set(m.flatMap(y=>y.revisionAuthors))].sort(),h=ui(e),v=h.map(y=>y.name).sort(),w=null;return typeof t.digestFn=="function"&&(w=Zo({scope:"document-parts",entries:h,digestFn:t.digestFn})),{status:"ok",revisionToken:w,coveredParts:v,paragraphs:m,...p.selection?{selection:p.selection}:{},comments:[...l.values()],revisionAuthors:g,commentAuthors:[...new Set([...l.values()].map(y=>y.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:l.size,revisedParagraphs:m.filter(y=>y.hasRevisions).length},warnings:i}}var Wf=e=>[e.author??null,e.text??"",e.anchoredText||""];function mv(e=[]){return e.filter(t=>t.kind!=="baseline").reduce((t,r)=>{let n={kind:r.kind,author:r.author||null,text:r.text,acceptedStart:r.acceptedStart??null,rejectedStart:r.rejectedStart??null},o=t.at(-1),a=i=>o[i]==null&&n[i]==null||o[i]!=null&&o[i]+o.text.length===n[i];return o&&o.kind===n.kind&&o.author===n.author&&a("acceptedStart")&&a("rejectedStart")?o.text+=n.text:t.push(n),t},[])}function ol(e){let t=e?.comments||[];return{paragraphs:(e?.paragraphs||[]).map(r=>({text:r.exactText,inTable:r.inTable===!0,table:r.table?[r.table.rowIndex,r.table.cellIndex]:null,list:r.list?[r.list.format,r.list.level,r.list.label]:null,review:{present:r.hasRevisions===!0,authors:[...r.revisionAuthors||[]].sort(),segments:mv(r.segments)}})),comments:t.map(r=>{let n=r.parentCommentId!=null?t.find(o=>String(o.id)===String(r.parentCommentId)):null;return[...Wf(r),r.done===!0,n?Wf(n):r.parentCommentId!=null||r.parentParaId?"unresolved parent":null]}).map(r=>JSON.stringify(r)).sort()}}function pv(e,t){let r=ol(e),n=ol(t),o=[],a=(l,s,c)=>{o.length<10&&JSON.stringify(s)!==JSON.stringify(c)&&o.push({path:l,expected:s,actual:c})};a("paragraphs.length",r.paragraphs.length,n.paragraphs.length);let i=Math.max(r.paragraphs.length,n.paragraphs.length);for(let l=0;l<i;l++){let s=r.paragraphs[l]??null,c=n.paragraphs[l]??null;if(!s||!c){a(`paragraphs[${l}]`,s,c);continue}for(let f of["text","inTable","table","list","review"])a(`paragraphs[${l}].${f}`,s[f],c[f])}return a("comments",r.comments,n.comments),{matches:o.length===0,differences:o}}function ao(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Ro(e,"w:r"),o=[],a="";for(let i of n){if(!tn(i,e,r))continue;let l=a.length,s=gr(i,{revisionView:r,boundary:e});a+=s,o.push({run:i,start:l,end:a.length})}return{fullText:a,runOffsets:o}}function Kf(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 Gf(e){return String(e).replace(/[ \u00a0]/g," ")}function ta(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Hf(e,t,r){let n=null,o=null,a=0,i=0;for(let{run:l,start:s,end:c}of e.runOffsets)t.start>=s&&t.start<c&&(n=l,a=t.start-s),t.end>s&&t.end<=c&&(o=l,i=t.end-s);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:a,endRun:o,endOffset:i}}function qf(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 Yf(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(qf(n,["del"]))return{found:!1,error:ta("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(qf(n,["moveFrom","moveTo"]))return{found:!1,error:ta("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function ra(e,t){let r=String(t??""),n=Kf(e.fullText,r);if(n.length>1)return{found:!1,error:ta("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let l=Hf(e,n[0],"exact_anchor");if(l)return Yf(e,l)}let o=Gf(r),a=Gf(e.fullText),i=Kf(a,o);if(i.length>1)return{found:!1,error:ta("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${i.length} locations in the target paragraph.`,i)};if(i.length===1){let l=Hf(e,i[0],"space_equivalent_anchor");if(l)return Yf(e,l)}return{found:!1,error:ta("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function ea(e,t,r,n,o=!1){let a=F(e,"w:r");if(t){let l=t.cloneNode(!0);o||Ft(l,n),a.appendChild(l)}let i=F(e,"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=r,a.appendChild(i),a}function Jf(e,t,r,n,o=null,a=null,i=null){let l=o||ao(t),s=i||ra(l,r);if(!s.found||!s.startRun)return!1;let c=F(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let f=F(e,"w:commentRangeEnd");f.setAttribute("w:id",String(n));let u=F(e,"w:r"),d=F(e,"w:commentReference");if(d.setAttribute("w:id",String(n)),u.appendChild(d),s.startRun===s.endRun){let h=s.startRun,v=Ue(h,"w:t");if(!v)return h.parentNode.insertBefore(c,h),h.nextSibling?(h.parentNode.insertBefore(f,h.nextSibling),f.parentNode.insertBefore(u,f.nextSibling)):(h.parentNode.appendChild(f),h.parentNode.appendChild(u)),!0;let w=v.textContent||"",y=w.substring(0,s.startOffset),b=w.substring(s.startOffset,s.endOffset),x=w.substring(s.endOffset),S=Ue(h,"w:rPr"),A=h.parentNode;return y&&(A.insertBefore(ea(e,S,y,a,!0),h),Ft(S,a)),A.insertBefore(c,h),v.textContent=b,h.nextSibling?A.insertBefore(f,h.nextSibling):A.appendChild(f),A.insertBefore(u,f.nextSibling||null),x&&A.insertBefore(ea(e,S,x,a),u.nextSibling||null),!0}let m=Ue(s.startRun,"w:t");if(m&&s.startOffset>0){let h=m.textContent||"",v=h.substring(0,s.startOffset),w=h.substring(s.startOffset);if(v){let y=Ue(s.startRun,"w:rPr");s.startRun.parentNode.insertBefore(ea(e,y,v,a,!0),s.startRun),Ft(y,a)}m.textContent=w}s.startRun.parentNode.insertBefore(c,s.startRun);let p=s.endRun||s.startRun,g=Ue(p,"w:t");if(g&&s.endOffset<(g.textContent||"").length){let h=g.textContent||"",v=h.substring(0,s.endOffset),w=h.substring(s.endOffset);if(g.textContent=v,w){let y=Ue(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(ea(e,y,w,a),p.nextSibling):p.parentNode.appendChild(ea(e,y,w,a))}}return p.nextSibling?(p.parentNode.insertBefore(f,p.nextSibling),f.parentNode.insertBefore(u,f.nextSibling)):(p.parentNode.appendChild(f),p.parentNode.appendChild(u)),!0}var io="http://schemas.microsoft.com/office/2006/xmlPackage",na="http://schemas.openxmlformats.org/package/2006/relationships";function Zf(e,t){let r=le(),n=j(e,"text/xml"),o=n.doc,a=o?Fe(o):null;if(n.error||a)return Le("[CommentEngine] Failed to parse package:",n.error?.message||a?.textContent),e;let i=o.documentElement,l=o.createElementNS(io,"pkg:part");l.setAttribute("pkg:name","/word/comments.xml"),l.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let s=o.createElementNS(io,"pkg:xmlData"),c=j(t,"text/xml").doc;if(!c)return e;s.appendChild(o.importNode(c.documentElement,!0)),l.appendChild(s),i.appendChild(l);let u=We(i,io,"part").find(d=>d.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(u){let d=We(u,io,"xmlData");if(d.length>0){let m=We(d[0],na,"Relationships");if(m.length>0){let p=m[0],g=We(p,na,"Relationship");if(!g.some(v=>v.getAttribute("Type")?.includes("comments"))){let v=0;g.forEach(y=>{let b=y.getAttribute("Id"),x=parseInt(b?.replace("rId","")||"0",10);x>v&&(v=x)});let w=o.createElementNS(na,"Relationship");w.setAttribute("Id",`rId${v+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let d=o.createElementNS(io,"pkg:part");d.setAttribute("pkg:name","/word/_rels/document.xml.rels"),d.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let m=o.createElementNS(io,"pkg:xmlData"),p=o.createElementNS(na,"Relationships"),g=o.createElementNS(na,"Relationship");g.setAttribute("Id","rId1"),g.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),g.setAttribute("Target","comments.xml"),p.appendChild(g),m.appendChild(p),d.appendChild(m),i.appendChild(d)}return r.serializeToString(o)}function gv(e,t){let r=j(e,"text/xml"),n=r.doc?Fe(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 al(e,t,r={}){let n=r?.author||ae(),o=Ia(),a=[],i=[],l=[],s=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=le(),f=gv(e,h=>`Failed to parse OXML: ${h}`);if(a.push(...f.warnings||[]),!f.xmlDoc)return Le("[CommentEngine] Parse failure:",f.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:f.error,warnings:[...a,f.warning]};let u=f.xmlDoc,d=_r(u),m=Ro(u,"w:p");W(`[CommentEngine] Found ${m.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let v=h.paragraphIndex-1;if(v<0||v>=m.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${m.length})`;a.push(w),s.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(v,(p.get(v)||0)+1)}let g=new Map;for(let[h,v]of t.entries()){let w=v.paragraphIndex-1;if(w<0||w>=m.length)continue;let y=m[w],b=g.get(w);b||(b=ao(y),g.set(w,b));let x=String(v.textToFind??""),S=ra(b,x),A=(p.get(w)||1)-1;if(p.set(w,A),!S.found){let R={...S.error,requestIndex:h+1,paragraphIndex:v.paragraphIndex};s.push(R),a.push(R.message),A===0&&g.delete(w);continue}let E=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():Pc();if(!Jf(u,y,x,E,b,d,S)){let R={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${v.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:v.paragraphIndex};s.push(R),a.push(R.message),A===0&&g.delete(w);continue}i.push({id:E,content:v.commentContent,author:n,date:o}),l.push({requestIndex:h+1,paragraphIndex:v.paragraphIndex,text:x,resolvedBy:S.resolvedBy,start:S.start,end:S.end}),A>0?g.set(w,ao(y)):g.delete(w)}return i.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:a,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}:{oxml:c.serializeToString(u),hasChanges:!0,commentsXml:Js(i),commentsApplied:i.length,placedComments:i,warnings:a,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}}function hv(e,t){return Zf(e,t)}var wv="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function br(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function mi(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 il({commentsXml:e,commentsExtendedXml:t=null,documentXml:r=null,parentCommentId:n,commentId:o,commentContent:a,author:i,date:l=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=mi(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let c=s.doc,f=Array.from(c.getElementsByTagNameNS("*","comment")).find(T=>br(T,"w:id","id")===String(n));if(!f)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${n}' was not found.`}};let u=null;if(t){let T=mi(t,"word/commentsExtended.xml");if(T.error)return{status:"error",error:T.error};u=T.doc}let d=tl(c,u);if(r)for(let T of String(r).matchAll(/\bw14:paraId="([0-9A-Fa-f]{8})"/g))d.add(T[1].toUpperCase());let m=si(f);if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${n}' has no paragraph.`}};let p=Tt(f);p?p=p.toUpperCase():(p=li(n,d),m.setAttributeNS(no,"w14:paraId",p));for(let T of Array.from(u?.getElementsByTagNameNS("*","commentEx")||[]))if(br(T,"w15:paraId","paraId").toUpperCase()===p){let N=br(T,"w15:paraIdParent","paraIdParent").toUpperCase();N&&(p=N);break}let g=[],h=Array.from(c.getElementsByTagNameNS("*","comment")),v=new Map(Array.from(u?.getElementsByTagNameNS("*","commentEx")||[]).map(T=>[br(T,"w15:paraId","paraId").toUpperCase(),br(T,"w15:paraIdParent","paraIdParent").toUpperCase()]));for(let T of h){let N=Tt(T);(N===p||v.get(N)===p)&&g.push(br(T,"w:id","id"))}let w=br(h.find(T=>Tt(T)===p),"w:id","id")||String(n),y=li(o,d),b=mi(`<w:comments xmlns:w="${wv}" xmlns:w14="${no}">${Yo(o,i,a,l,y)}</w:comments>`,"reply comment");c.documentElement.appendChild(c.importNode(b.doc.documentElement.firstChild,!0)),u||(u=mi(Bf([]),"word/commentsExtended.xml").doc);let x=u.documentElement,A=Array.from(x.getElementsByTagNameNS("*","commentEx")).find(T=>br(T,"w15:paraId","paraId").toUpperCase()===p);if(!A){let T=u.createElementNS(dt,"w15:commentEx");T.setAttributeNS(dt,"w15:paraId",p),T.setAttributeNS(dt,"w15:done","0"),x.appendChild(T)}let E=br(A,"w15:done","done")==="1"?"1":"0",I=u.createElementNS(dt,"w15:commentEx");I.setAttributeNS(dt,"w15:paraId",y),I.setAttributeNS(dt,"w15:paraIdParent",p),I.setAttributeNS(dt,"w15:done",E),x.appendChild(I);let R=le();return{status:"ok",hasChanges:!0,commentsXml:R.serializeToString(c),commentsExtendedXml:R.serializeToString(u),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:o,parentCommentId:String(n),paraId:y,parentParaId:p,threadRootCommentId:w,threadCommentIds:g.length?g:[w]}}function so(e){e?.parentNode&&e.parentNode.removeChild(e)}function Qf(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(so)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(o=>{let a=n[o];a&&r.querySelectorAll(`${a}, ${a.replace("w:","")}`).forEach(so)})}return r.children.length>0?r:null}function vv(e,t,r){if(!t||!e)return e;let n=Ve(e);if(!n)return e;let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=n.getElementsByTagNameNS(o,"r"),i=n.getElementsByTagNameNS(o,"ins"),l=[...Array.from(a)];for(let s of i){let c=s.getElementsByTagNameNS(o,"r");l.push(...Array.from(c))}for(let s of l){let c=s.getElementsByTagNameNS(o,"t"),f=Array.from(c).map(u=>u.textContent).join("");if(f.includes(t)||f===t){let u=s.getElementsByTagNameNS(o,"rPr");if(u.length>0){let d=u[0],m=Qf(d,r);m?d.parentNode&&d.parentNode.replaceChild(m,d):so(d)}}}return Kt(n)}var yv={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 bv(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=yv[r.toLowerCase()]||"yellow",i=n?.generateRedlines??!1,l=n?.author||ae(),s=t;s?s=t.cloneNode(!0):s=F(e,"w:rPr");let c=null;i&&(c=F(e,"w:rPr"),Array.from(s.childNodes).forEach(d=>{d.nodeName!=="w:rPrChange"&&c.appendChild(d.cloneNode(!0))}));let f=s.getElementsByTagNameNS(o,"highlight");Array.from(f).forEach(so);let u=F(e,"w:highlight");if(u.setAttributeNS(o,"w:val",a),s.appendChild(u),i&&c){let d=F(e,"w:rPrChange"),m=ue(l,e);d.setAttribute("w:id",String(m.id)),d.setAttribute("w:author",m.author),d.setAttribute("w:date",m.date),d.appendChild(c);let p=s.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(so),s.appendChild(d)}return s}function sl(e,t,r="yellow",n={}){if(!t||!e)return e;let o=Ve(e);if(!o)return e;let a;n?._revisionIdAllocator instanceof De?(a=n._revisionIdAllocator,cr(o,a)):a=_r(o);let i="http://schemas.openxmlformats.org/wordprocessingml/2006/main",l=u=>{let d=u.getElementsByTagNameNS(i,"t");return Array.from(d).map(m=>m.textContent).join("")},s=Array.from(o.getElementsByTagNameNS(i,"r")),c=new WeakSet,f=(u,d,m)=>{let p=u.cloneNode(!0);c.has(u)?Ft(p,a):c.add(u);let g=p.getElementsByTagNameNS(i,"t");Array.from(g).forEach(so);let h=F(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=d,p.appendChild(h),m){let v=p.getElementsByTagNameNS(i,"rPr"),w=v.length>0?v[0]:null,y=bv(o,w,r,n);w?p.replaceChild(y,w):p.insertBefore(y,p.firstChild)}return p};for(let u of s){let d=l(u);if(!d)continue;let m=[],p=0;for(;p<=d.length-t.length;){let w=d.indexOf(t,p);if(w===-1)break;m.push(w),p=w+t.length}if(m.length===0)continue;let g=u.parentNode;if(!g){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),v=0;for(let w of m)w>v&&h.appendChild(f(u,d.slice(v,w),!1)),h.appendChild(f(u,d.slice(w,w+t.length),!0)),v=w+t.length;v<d.length&&h.appendChild(f(u,d.slice(v),!1)),g.replaceChild(h,u)}return Kt(o)}var xr="application/vnd.openxmlformats-officedocument.wordprocessingml",oa="http://schemas.openxmlformats.org/officeDocument/2006/relationships",ed=Object.freeze([{id:"document",path:"word/document.xml",pathPattern:null,contentType:`${xr}.document.main+xml`,legacyContentTypes:[],relType:`${oa}/officeDocument`,relTarget:null,verified:!0},{id:"numbering",path:"word/numbering.xml",pathPattern:null,contentType:`${xr}.numbering+xml`,legacyContentTypes:[],relType:`${oa}/numbering`,relTarget:"numbering.xml",verified:!1},{id:"comments",path:"word/comments.xml",pathPattern:null,contentType:`${xr}.comments+xml`,legacyContentTypes:[],relType:`${oa}/comments`,relTarget:"comments.xml",verified:!0},{id:"commentsExtended",path:"word/commentsExtended.xml",pathPattern:null,contentType:`${xr}.commentsExtended+xml`,legacyContentTypes:["application/vnd.ms-word.commentsExtended+xml"],relType:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",relTarget:"commentsExtended.xml",verified:!0},{id:"commentsIds",path:"word/commentsIds.xml",pathPattern:null,contentType:`${xr}.commentsIds+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",relTarget:"commentsIds.xml",verified:!0},{id:"commentsExtensible",path:"word/commentsExtensible.xml",pathPattern:null,contentType:`${xr}.commentsExtensible+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible",relTarget:"commentsExtensible.xml",verified:!0},{id:"people",path:"word/people.xml",pathPattern:null,contentType:`${xr}.people+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2011/relationships/people",relTarget:"people.xml",verified:!1},{id:"header",path:null,pathPattern:/^word\/header\d+\.xml$/i,contentType:`${xr}.header+xml`,legacyContentTypes:[],relType:`${oa}/header`,relTarget:null,verified:!0},{id:"footer",path:null,pathPattern:/^word\/footer\d+\.xml$/i,contentType:`${xr}.footer+xml`,legacyContentTypes:[],relType:`${oa}/footer`,relTarget:null,verified:!0}].map(e=>Object.freeze(e))),xv=new Map(ed.map(e=>[e.id,e]));function xn(e){let t=xv.get(e);if(!t)throw new Error(`Unknown package part: ${e}`);return t}function Iv(e){return String(e||"").replace(/^\/+/,"")}function ll(e){let t=Iv(e),r=t.toLowerCase();return ed.find(n=>n.path?n.path.toLowerCase()===r:n.pathPattern?.test(t))||null}function td(e,t){let r=ll(e);return!r||!r.legacyContentTypes.includes(t)?null:r.contentType}var nt="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Nv="http://schemas.openxmlformats.org/package/2006/content-types",Tv="http://schemas.openxmlformats.org/package/2006/relationships",dl=xn("numbering"),ml=xn("comments"),pl=xn("commentsExtended"),nd=dl.relType,od=dl.contentType,ad=ml.relType,id=ml.contentType,sd=pl.relType,cl=pl.contentType,rd=xn("document").path,pi=dl.path,aa=ml.path,ul=pl.path,vt="[Content_Types].xml",Dt="word/_rels/document.xml.rels";function Ke(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 gi(e){return!!e&&e.nodeType===1&&e.namespaceURI===nt&&e.localName==="sectPr"}function gl(e){return e.getElementsByTagNameNS("*","body")[0]||null}function ld(e){for(let t of Array.from(e.childNodes||[]))if(gi(t))return t;return null}function Sv(e,t){let r=ld(e);r?e.insertBefore(t,r):e.appendChild(t)}function hi(e){let t=gl(e);if(!t)return;let r=ld(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function Av(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(nt,"tc"),o=0;for(let a of Array.from(n)){let i=Array.from(a.childNodes||[]).filter(l=>l.nodeType===1&&l.namespaceURI===nt&&l.localName==="p");for(let l of i){let s=Array.from(l.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===nt&&c.localName==="p");for(let c of s)a.insertBefore(c,l),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function fl(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function Ev(e){let t=le(),r=Ke(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(u=>fl(u)==="/word/document.xml");if(!o)throw new Error("Package output missing /word/document.xml part");let a=o.getElementsByTagNameNS("*","xmlData")[0];if(!a)throw new Error("Package document part missing pkg:xmlData");let i=Array.from(a.childNodes||[]).find(u=>u.nodeType===1);if(!i)throw new Error("Package document part missing XML payload");let l=i.getElementsByTagNameNS("*","body")[0],s=l?Array.from(l.childNodes||[]).filter(u=>u.nodeType===1&&!gi(u)):[i],c=n.find(u=>fl(u)==="/word/numbering.xml"),f=null;if(c){let u=c.getElementsByTagNameNS("*","xmlData")[0],d=u?Array.from(u.childNodes||[]).find(m=>m.nodeType===1):null;d&&(f=t.serializeToString(d))}return{replacementNodes:s,numberingXml:f,sourceType:"package"}}function hl(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 Ev(e);if(e.includes("<w:document")){let o=Ke(e,"document OOXML"),a=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:a?Array.from(a.childNodes||[]).filter(l=>l.nodeType===1&&!gi(l)):Array.from(o.childNodes||[]).filter(l=>l.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${nt}">${e}</root>`,r=Ke(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 wl(e,t,r){let o=Array.from(e.getElementsByTagNameNS("*","Override")).find(i=>(i.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(o)return(o.getAttribute("ContentType")||"")===r?!1:(o.setAttribute("ContentType",r),!0);let a=e.createElementNS(Nv,"Override");return a.setAttribute("PartName",t),a.setAttribute("ContentType",r),e.documentElement.appendChild(a),!0}function vl(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,a=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(a.some(f=>(f.getAttribute("Type")||"")===t))return!1;let l=0;for(let f of a){let u=f.getAttribute("Id")||"",d=Number.parseInt(u.replace(/^rId/i,""),10);Number.isFinite(d)&&(l=Math.max(l,d))}let s=`rId${l+1}`,c=e.createElementNS(Tv,"Relationship");return c.setAttribute("Id",s),c.setAttribute("Type",t),c.setAttribute("Target",r),o.appendChild(c),n?._receiptCollector?n._receiptCollector.recordRelationship(s):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(s),!0}async function mt(e,t){let r=e.file(t);return r?r.async("string"):null}async function wi(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},o=(Array.isArray(t)?t:[t]).filter(Boolean);if(o.length===0)return;let a=await mt(e,pi),i=[],l=vr(a,o,{onConflict:u=>i.push(u)});if(i.length>0){let u=i.map(d=>`${d.kind} ${d.id}`).join(", ");throw Object.assign(new Error(`Numbering id conflict: ${u} already exist with different content. Generated list numbering must be allocated from the document's own numbering state (pass the current numbering part to the operation runner).`),{code:"NUMBERING_ID_CONFLICT",conflicts:i})}n(a?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(pi,l);let s=le(),c=await mt(e,vt);if(c){let u=Ke(c,vt);wl(u,"/word/numbering.xml",od)&&e.file(vt,s.serializeToString(u))}let f=await mt(e,Dt);if(f){let u=Ke(f,Dt);vl(u,nd,"numbering.xml",r)&&e.file(Dt,s.serializeToString(u))}}async function yl(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=le(),a=await mt(e,aa);if(!a||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(aa,t);else{let s=Ke(a,"word/comments.xml (existing)"),c=Ke(t,"word/comments.xml (incoming)"),f=s.documentElement,u=new Set(Array.from(f.getElementsByTagNameNS(nt,"comment")).map(d=>d.getAttribute("w:id")||d.getAttribute("id")).filter(Boolean));for(let d of Array.from(c.documentElement.getElementsByTagNameNS(nt,"comment"))){let m=d.getAttribute("w:id")||d.getAttribute("id");if(m&&u.has(m))throw new Error(`Duplicate comment id: ${m}`);f.appendChild(s.importNode(d,!0))}e.file(aa,o.serializeToString(s))}let i=await mt(e,vt);if(i){let s=Ke(i,vt);wl(s,"/word/comments.xml",id)&&e.file(vt,o.serializeToString(s))}let l=await mt(e,Dt);if(l){let s=Ke(l,Dt);vl(s,ad,"comments.xml",r)&&e.file(Dt,o.serializeToString(s))}}async function vi(e,t,r={}){if(!t)return;Ke(t,"word/commentsExtended.xml"),e.file(ul,t);let n=le(),o=await mt(e,vt);if(o){let i=Ke(o,vt);wl(i,"/word/commentsExtended.xml",cl)&&e.file(vt,n.serializeToString(i))}let a=await mt(e,Dt);if(a){let i=Ke(a,Dt);vl(i,sd,"commentsExtended.xml",r)&&e.file(Dt,n.serializeToString(i))}}async function lo(e){let t=await mt(e,vt);if(!t)return[];let r=Ke(t,vt),n=[];for(let o of Array.from(r.getElementsByTagNameNS("*","Override"))){let a=o.getAttribute("PartName")||"",i=o.getAttribute("ContentType")||"",l=td(a,i);l&&(o.setAttribute("ContentType",l),n.push({partName:a,from:i,to:l}))}return n.length>0&&e.file(vt,le().serializeToString(r)),n}async function Vr(e){let t=await mt(e,rd);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=Ke(t,rd);hi(r);let n=gl(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(h=>h.nodeType===1),a=o.map((h,v)=>({node:h,index:v})).filter(h=>gi(h.node)).map(h=>h.index);if(a.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(a.length===1&&a[0]!==o.length-1)throw new Error("Validation failed: w:sectPr not last");let i=r.getElementsByTagNameNS(nt,"tc");for(let h of Array.from(i))for(let v of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(v.namespaceURI===nt&&v.localName==="p"&&Array.from(v.childNodes||[]).some(y=>y.nodeType===1&&y.namespaceURI===nt&&y.localName==="p"))throw new Error("Validation failed: nested w:p");let l=r.getElementsByTagNameNS(nt,"numPr").length>0,s=r.getElementsByTagNameNS(nt,"commentRangeStart").length>0||r.getElementsByTagNameNS(nt,"commentRangeEnd").length>0||r.getElementsByTagNameNS(nt,"commentReference").length>0,c=await mt(e,pi),f=await mt(e,aa),u=await mt(e,ul);if(u&&!f)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)Ke(c,pi);else if(l)throw new Error("Validation failed: numbering used but part missing");if(f){let h=Ke(f,aa),v=(M,_)=>Array.from(M.getElementsByTagNameNS(nt,_)).map(k=>k.getAttribute("w:id")||k.getAttribute("id")).filter(k=>k!==""),w=new Set(v(r,"commentRangeStart")),y=new Set(v(r,"commentRangeEnd")),b=new Set(v(r,"commentReference")),x=v(h,"comment"),S=new Set(x),A=M=>Array.from(M).sort((_,k)=>Number(_)-Number(k)||_.localeCompare(k)),E=(M,_)=>A(new Set(Array.from(M).filter(k=>!_.has(k)))),I=A(new Set(x.filter((M,_)=>x.indexOf(M)!==_)));if(I.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${I.join(", ")}`);let R=E(w,y),T=E(y,w);if(R.length>0||T.length>0){let M=[];throw R.length>0&&M.push(`start without end: ${R.join(", ")}`),T.length>0&&M.push(`end without start: ${T.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${M.join("; ")})`)}let N=E(new Set([...w,...y]),b);if(N.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${N.join(", ")}`);let O=E(new Set([...w,...y,...b]),S);if(O.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${O.join(", ")}`);let C=new Set;if(u){let M=Ke(u,ul),_=new Map;for(let D of Array.from(h.getElementsByTagNameNS("*","comment"))){let z=D.getAttribute("w:id")||D.getAttribute("id"),G=Tt(D);G&&_.set(G,z)}let k=new Set(_.keys()),L=new Set;for(let D of Array.from(M.getElementsByTagNameNS("*","commentEx"))){let z=D.getAttribute("w15:paraId")||D.getAttribute("paraId"),G=D.getAttribute("w15:paraIdParent")||D.getAttribute("paraIdParent");if(!z||!k.has(z.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${z||"(missing)"}`);if(L.has(z.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${z}`);if(L.add(z.toUpperCase()),G){if(!k.has(G.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${G}`);C.add(_.get(z.toUpperCase()))}}}let P=E(new Set([...S].filter(M=>!C.has(M))),b);if(P.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${P.join(", ")}`)}else if(s)throw new Error("Validation failed: comments used but part missing");let d=await mt(e,vt);if(!d)throw new Error(`Validation failed: missing ${vt}`);let m=Ke(d,vt),p=await mt(e,Dt);if(!p)throw new Error(`Validation failed: missing ${Dt}`);let g=Ke(p,Dt);if(c){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===od),v=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===nd);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!v)throw new Error("Validation failed: numbering rel missing")}if(f){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===id),v=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===ad);if(!h)throw new Error("Validation failed: comments CT override missing");if(!v)throw new Error("Validation failed: comments rel missing")}{let h=new Map;for(let b of Array.from(g.getElementsByTagNameNS("*","Relationship")))h.set(b.getAttribute("Id")||"",{type:b.getAttribute("Type")||"",target:b.getAttribute("Target")||""});let v=xn("header"),w=xn("footer"),y=new Map(Array.from(m.getElementsByTagNameNS("*","Override")).map(b=>[(b.getAttribute("PartName")||"").toLowerCase(),b.getAttribute("ContentType")||""]));for(let b of[...Array.from(r.getElementsByTagNameNS(nt,"headerReference")),...Array.from(r.getElementsByTagNameNS(nt,"footerReference"))]){let x=b.getAttributeNS?.("http://schemas.openxmlformats.org/officeDocument/2006/relationships","id")||b.getAttribute("r:id")||"",S=b.localName==="headerReference"?v:w,A=h.get(x);if(!A)throw new Error(`Validation failed: ${b.localName} ${x||"(no r:id)"} has no document relationship`);if(A.type!==S.relType)throw new Error(`Validation failed: ${b.localName} ${x} points at a relationship of the wrong type (${A.type})`);let E=A.target.startsWith("/")?A.target:`/word/${A.target}`,I=await mt(e,E.slice(1));if(!I)throw new Error(`Validation failed: ${b.localName} ${x} targets a missing part: ${E}`);Ke(I,E.slice(1));let R=y.get(E.toLowerCase());if(R!==S.contentType)throw new Error(`Validation failed: ${E} content type is ${R?`'${R}'`:"missing"}; Word expects '${S.contentType}'`)}}if(u){let h=Array.from(m.getElementsByTagNameNS("*","Override")).find(y=>(y.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml");if(h&&h.getAttribute("ContentType")!==cl)throw new Error(`Validation failed: commentsExtended CT override has wrong content type '${h.getAttribute("ContentType")}' (Word expects '${cl}')`);let v=!!h,w=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(y=>(y.getAttribute("Type")||"")===sd);if(!v)throw new Error("Validation failed: commentsExtended CT override missing");if(!w)throw new Error("Validation failed: commentsExtended rel missing")}}var co=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 ud(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
213
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function Rv(e={}){let t=e.originalText||"",r=ud(e.newContent||""),n=Xo(r)||{type:"text",items:[]};return r.includes(`
214
+ `)&&n.type!=="text"?{kind:co.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:cd(t),hasInlineFormatting:yi(r),hasBlockElements:bi(r),hasMarkdownTable:ia(r)}}:cd(t)?yi(r)?{kind:co.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:bi(r),hasMarkdownTable:ia(r)}}:{kind:co.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:bi(r),hasMarkdownTable:ia(r)}}:bi(r)?{kind:co.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:yi(r),hasBlockElements:!0,hasMarkdownTable:ia(r)}}:{kind:co.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:yi(r),hasBlockElements:!1,hasMarkdownTable:ia(r)}}}function cd(e){return!e||e.trim().length===0}function ia(e){if(!e||!e.includes("|"))return!1;let t=bt(e);return t.rows.length>0||t.headers.length>0}function yi(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function bi(e){if(!e)return!1;let t=/^[\s]*[-*+]\s+/m.test(e),r=/^[\s]*\d+\.\s+/m.test(e),n=/^[\s]*\d+\.\d+(?:\.\d+)*\.?\s+/m.test(e),o=/^[\s]*[A-Za-z]\.\s+/m.test(e),a=/^[\s]*[ivxlcIVXLC]+\.\s+/m.test(e),i=/^[\s]*\([a-z]\)\s+/m.test(e),l=/\|.*\|.*\n/.test(e),s=/^#{1,9}\s/m.test(e),c=e.includes(`
214
215
 
215
- `);return t||r||n||o||a||i||s||l||c}function mg(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 ho=class{constructor(){this.receipts=[],this.activeReceipt=null}beginOperation(t,r=null,n=null){this.activeReceipt={operationIndex:typeof t=="number"?t:1,...r?{operationId:String(r)}:{},attemptedDisposition:"applied",finalDisposition:"applied",committed:!0,...n?{authorUsed:String(n)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}recordRevision(t,r="structural",n="word/document.xml"){if(!this.activeReceipt||t==null)return;let o=String(t);this.activeReceipt.revisionItems.some(a=>a.id===o&&a.kind===r&&a.partName===n)||this.activeReceipt.revisionItems.push({id:o,kind:r,partName:n})}recordComment(t,r="word/comments.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.commentIds.includes(n)||this.activeReceipt.commentIds.push(n)}recordNumbering(t,r="word/numbering.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.numberingIds.includes(n)||this.activeReceipt.numberingIds.push(n)}recordRelationship(t,r="word/_rels/document.xml.rels"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.relationshipIds.includes(n)||this.activeReceipt.relationshipIds.push(n)}recordAffectedTarget(t){!this.activeReceipt||!t||this.activeReceipt.affectedTargets.push(JSON.parse(JSON.stringify(t)))}recordWarning(t){!this.activeReceipt||!t||this.activeReceipt.warnings.push(String(t))}commitOperation(t="applied"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=t==="applied";let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.receipts.push(r),this.activeReceipt=null,r}abortOperation(t="refused"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=!1;let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.activeReceipt=null,r}createSavepoint(){return{receipts:JSON.parse(JSON.stringify(this.receipts)),activeReceipt:this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}}restoreSavepoint(t){t&&(this.receipts=Array.isArray(t.receipts)?JSON.parse(JSON.stringify(t.receipts)):[],this.activeReceipt=t.activeReceipt?JSON.parse(JSON.stringify(t.activeReceipt)):null)}clear(){this.receipts=[],this.activeReceipt=null}markRolledBack(){for(let t of this.receipts)t.attemptedDisposition==="applied"&&(t.finalDisposition="rolled_back",t.committed=!1);this.activeReceipt=null}getReceipts(){return JSON.parse(JSON.stringify(this.receipts))}getCurrentReceipt(){return this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}};function Le(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 wo(e,t){if(!Array.isArray(t)||t.length===0)return{valid:!0};let r=t.filter(l=>l&&l.committed===!0&&l.finalDisposition==="applied");if(r.length===0)return{valid:!0};let n=new Set;if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?(?:ins|del|rPrChange|pPrChange|moveFrom|moveTo)\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=l.exec(e.documentXml))!==null;)n.add(c[1])}let o=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let l=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=l.exec(e.commentsXml))!==null;)o.add(c[1])}let a=new Set,i=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
216
- `);if(i){let l=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=l.exec(i))!==null;)a.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=l.exec(e.documentXml))!==null;)a.add(c[1])}let s=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let l=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=l.exec(e.relationshipsXml))!==null;)s.add(c[1])}for(let l of r){if(Array.isArray(l.revisionItems)){for(let c of l.revisionItems)if(c.partName==="word/document.xml"&&!n.has(String(c.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${c.id}' (kind: ${c.kind}) was not found in word/document.xml.`}}}if(Array.isArray(l.commentIds)){for(let c of l.commentIds)if(!o.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${c}' was not found in word/comments.xml.`}}}if(Array.isArray(l.numberingIds)){for(let c of l.numberingIds)if(!a.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(l.relationshipIds)){for(let c of l.relationshipIds)if(!s.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}var wu="http://schemas.openxmlformats.org/wordprocessingml/2006/main",pg="http://schemas.openxmlformats.org/officeDocument/2006/relationships",gg=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tcPrChange","trPrChange","numberingChange"]),hg=new Set(["ins","del","moveFrom","moveTo"]),Ca=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function wg(e){let t=String(e||"");if(t.startsWith("/"))return t.replace(/^\/+/,"");let r=["word"];for(let n of t.split("/"))n===".."?r.pop():n&&n!=="."&&r.push(n);return r.join("/")}function us({documentXml:e,relsXml:t=null,settingsXml:r=null}){if(!e||!t)return[];let n=W(e,"application/xml"),o=W(t,"application/xml");if(!n.doc||n.error||!o.doc||o.error)return[];let a=new Map;for(let u of Array.from(o.doc.getElementsByTagNameNS("*","Relationship")))a.set(u.getAttribute("Id")||"",u.getAttribute("Target")||"");let i=!!r&&/<w:evenAndOddHeaders\b(?![^>]*w:val="(?:0|false|off)")/.test(r),s=new Map,l=new Map;return Array.from(n.doc.getElementsByTagNameNS(wu,"sectPr")).forEach((u,f)=>{let d=Array.from(u.childNodes||[]).some(m=>m.localName==="titlePg"&&!/^(0|false|off)$/i.test(Ca(m,"w:val","val")));for(let m of Array.from(u.childNodes||[])){if(m.nodeType!==1||m.localName!=="headerReference"&&m.localName!=="footerReference")continue;let p=m.getAttributeNS?.(pg,"id")||m.getAttribute("r:id")||"",g=a.get(p);if(!g)continue;let h=wg(g),y=m.localName==="headerReference"?"header":"footer",w=Ca(m,"w:type","type")||"default",v=s.get(h)||{path:h,kind:y,type:w,sections:[],applies:[],titlePgSections:0};v.sections.includes(f)||v.sections.push(f),d&&(v.titlePgSections+=1),s.set(h,v),l.set(`${y}:${w}`,h)}for(let m of l.values()){let p=s.get(m);p&&!p.applies.includes(f)&&p.applies.push(f)}}),Array.from(s.values()).map(u=>({path:u.path,kind:u.kind,type:u.type,sections:u.sections,appliesToSections:u.applies,sharedBySections:u.applies.length>1,active:u.type==="first"?u.titlePgSections>0:u.type==="even"?i:!0}))}function fs(e,t){let r=a=>({path:a.path,kind:a.kind,type:a.type,sections:a.sections,appliesToSections:a.appliesToSections});if(typeof t=="string"){let a=t.replace(/^\/+/,"").toLowerCase(),i=e.find(s=>s.path.toLowerCase()===a||s.path.toLowerCase()===`word/${a}`);return i?{part:i}:{error:{code:"PART_NOT_FOUND",message:`No header/footer part '${t}' is referenced by the document.`,candidates:e.map(r)}}}if(!t||typeof t!="object"||t.kind!=="header"&&t.kind!=="footer")return{error:{code:"INVALID_OPERATION",message:'part must be a part path or { kind: "header"|"footer", type?: "default"|"first"|"even", section?: number }.'}};let n=t.type||"default";if(!["default","first","even"].includes(n))return{error:{code:"INVALID_OPERATION",message:`part.type must be default, first or even (got '${n}').`}};let o=e.filter(a=>a.kind===t.kind&&a.type===n);return Number.isInteger(t.section)&&(o=o.filter(a=>a.appliesToSections.includes(t.section))),o.length===1?{part:o[0]}:o.length===0?{error:{code:"PART_NOT_FOUND",message:`The document has no ${n} ${t.kind}${Number.isInteger(t.section)?` for section ${t.section}`:""}.`,candidates:e.map(r)}}:{error:{code:"PART_AMBIGUOUS",message:`Several ${n} ${t.kind} parts exist; add "section" or use the part path.`,candidates:o.map(r)}}}function yu(e){let t=Ji(e);return t?.id==="header"||t?.id==="footer"}function ds(e){let t=W(e,"application/xml");if(!t.doc||t.error)return 0;let r=0,n=0,o=a=>{for(let i of Array.from(a.childNodes||[])){if(i.nodeType!==1)continue;let s=i.localName;if(s==="fldChar"){let l=Ca(i,"w:fldCharType","fldCharType");l==="begin"?r+=1:l==="end"&&(r=Math.max(0,r-1));continue}if(hg.has(s)&&r>0&&(n+=1),s==="fldSimple"){r+=1,o(i),r-=1;continue}o(i)}};return o(t.doc.documentElement),n}function vu(e){let t=new Set;for(let r of String(e||"").matchAll(/<w:(?:ins|del|moveFrom|moveTo|rPrChange|pPrChange|sectPrChange|tblPrChange|tblGridChange|tcPrChange|trPrChange|numberingChange)\b[^>]*?\bw:id="(\d+)"/g))t.add(r[1]);return t}function xu(e,t){let r=W(e,"application/xml");if(!r.doc||r.error)return{xml:e,renumbered:0,idMap:new Map};let n=new Map,o=1+Math.max(0,...Array.from(t,l=>Number(l)).filter(Number.isFinite)),a=new Set(t),i=0,s=l=>{for(let c of Array.from(l.childNodes||[]))if(c.nodeType===1){if(gg.has(c.localName)){let u=Ca(c,"w:id","id");if(u&&a.has(u)){for(;a.has(String(o));)o+=1;c.setAttributeNS(wu,"w:id",String(o)),n.set(u,String(o)),a.add(String(o)),i+=1}else u&&a.add(u)}s(c)}};return s(r.doc.documentElement),i>0?{xml:oe().serializeToString(r.doc),renumbered:i,idMap:n}:{xml:e,renumbered:0,idMap:n}}var yg=Object.freeze({INVALID_OPERATION:["request","request_fixable","change_request"],INVALID_AGENT_REQUEST:["request","request_fixable","change_request"],INVALID_FILTER:["request","request_fixable","change_request"],INVALID_OPERATIONS_FILE:["request","request_fixable","change_request"],OPERATIONS_REQUIRED:["request","request_fixable","change_request"],UNKNOWN_OPTION:["request","request_fixable","change_request"],UNEXPECTED_ARGUMENT:["request","request_fixable","change_request"],INVALID_ACTION:["request","request_fixable","change_request"],INVALID_PROFILE:["request","request_fixable","change_request"],INVALID_REVISION_TOKEN:["revision-check","request_fixable","change_request"],BATCH_OPERATION_FAILED:["batch-execution","request_fixable","inspect_failed_operations"],REVISION_TOKEN_SCOPE_MISMATCH:["revision-check","request_fixable","change_request"],REVISION_MISMATCH:["revision-check","target_refresh_required","reinspect"],TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],SOURCE_TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],TARGET_TEXT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_FINGERPRINT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_INDEX_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_OCCURRENCE_MISMATCH:["target-resolution","candidate_selection_required","choose_candidate"],STALE_TARGET_HANDLE:["target-resolution","target_refresh_required","reinspect"],TARGET_HANDLE_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],AMBIGUOUS_TARGET:["target-resolution","candidate_selection_required","choose_candidate"],TARGET_RANGE_INVALID:["target-resolution","request_fixable","change_target_range"],ANCHOR_NOT_FOUND:["anchor-resolution","request_fixable","change_anchor"],AMBIGUOUS_ANCHOR:["anchor-resolution","candidate_selection_required","choose_candidate"],PATCH_SOURCE_NOT_FOUND:["patch-compilation","request_fixable","change_patch"],AMBIGUOUS_PATCH_SOURCE:["patch-compilation","candidate_selection_required","choose_occurrence"],OVERLAPPING_PATCHES:["patch-compilation","source_conflict","combine_patches"],CONFLICTING_PATCHES:["patch-compilation","source_conflict","combine_patches"],PATCH_ROUNDTRIP_MISMATCH:["patch-validation","request_fixable","reinspect_and_narrow"],DIFF_TOKEN_LIMIT:["patch-compilation","request_fixable","narrow_operation"],STRUCTURED_CONTENT_INVALID:["request","request_fixable","change_request"],UNSUPPORTED_INSERTION_AFFINITY:["request","request_fixable","change_request"],EXISTING_REVISIONS:["target-safety","policy_choice_required","set_option"],PART_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PART_AMBIGUOUS:["target-resolution","candidate_selection_required","choose_candidate"],COMMENT_IN_HEADER_FOOTER:["request","request_fixable","change_request"],FIELD_EDIT_REFUSED:["target-safety","request_fixable","change_request"],COMMENT_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PARENT_ANCHOR_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],COMMENTED_CONTENT_MERGE:["target-safety","user_authorization_required","resolve_comments"],COMMENTED_CONTENT_DELETE:["target-safety","user_authorization_required","resolve_comments"],OVERLAPPING_SOURCE_TARGETS:["batch-compilation","source_conflict","consolidate_operations"],OVERLAPPING_TEXT_EDITS:["batch-compilation","source_conflict","consolidate_operations"],REVISION_ORDER_CONFLICT:["batch-compilation","source_conflict","split_or_consolidate_operations"],TARGET_CONSUMED_BY_OPERATION:["batch-execution","source_conflict","use_created_content_dependency"],CAPTURE_FANOUT_CONFLICT:["batch-compilation","source_conflict","split_or_chain_capture_consumers"],DUPLICATE_CAPTURE_KEY:["batch-compilation","request_fixable","rename_capture"],CAPTURE_NOT_FOUND:["batch-compilation","request_fixable","add_or_correct_capture"],CAPTURE_DEPENDENCY_CYCLE:["batch-compilation","source_conflict","replan_batch"],AMBIGUOUS_CAPTURE_SELECTION:["batch-compilation","candidate_selection_required","choose_candidate"],CAPTURE_STALE:["batch-execution","source_conflict","replan_batch"],GENERATED_OOXML_INVALID:["validation","library_or_builder_failure","report_library_failure"],DOCUMENT_SERIALIZATION_FAILED:["serialization","library_or_builder_failure","report_library_failure"],PACKAGE_OPERATION_FAILED:["package","library_or_builder_failure","report_library_failure"],PACKAGE_VALIDATION:["package-validation","library_or_builder_failure","report_library_failure"],MUTATION_RECEIPT_MISMATCH:["receipt-validation","library_or_builder_failure","report_library_failure"],FOREIGN_PARAGRAPH_MARK_DELETION:["target-safety","policy_choice_required","use_restore_or_leave_deleted"],RESTORATION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],RESTORATION_COUNT_MISMATCH:["request","request_fixable","change_request"],REJECTED_INSERTION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],UNSAFE_REVISION_NESTING:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_REVISION_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_DELETED_TABLE_ROW:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_MOVE_REVISION:["target-safety","manual_document_resolution","manual_resolution"],SECTION_BREAK_PARAGRAPH:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_PLACEMENT:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_REVISION_VIEW_MUTATION:["target-safety","manual_document_resolution","manual_resolution"]});function vg(e){let t=Array.isArray(e?.generatedIssues)?e.generatedIssues:Array.isArray(e?.issues)?e.issues:null;if(!t)return null;let r=new Map;for(let n of t){let o=n?.code||"UNKNOWN";r.set(o,(r.get(o)||0)+1)}return{total:t.length,byCode:Array.from(r,([n,o])=>({code:n,count:o}))}}function xg(e){return yg[e]||["operation","manual_document_resolution","inspect_error"]}function et(e,t={}){let r=e&&typeof e=="object"?e:{},n=typeof r.code=="string"&&r.code?r.code:"OPERATION_ERROR",[o,a,i]=xg(n),s={};for(let[m,p]of Object.entries(r))m==="name"||m==="stack"||m==="message"||m==="code"||(s[m]=p);let u={action:i,sameArgumentsSafe:!1,requiresReinspection:a==="target_refresh_required"||n==="PATCH_ROUNDTRIP_MISMATCH",requiresUserAuthorization:a==="user_authorization_required",...n==="EXISTING_REVISIONS"?{field:"existingRevisions",recommendedValue:"slice-cross-author"}:{},...r.recovery&&typeof r.recovery=="object"?r.recovery:{}},f=vg(r),d={...t,...Array.isArray(r.revisionAuthors)?{revisionAuthors:r.revisionAuthors}:{},...r.currentPolicy?{currentPolicy:r.currentPolicy}:{}};return["TARGET_TEXT_MISMATCH","TARGET_FINGERPRINT_MISMATCH"].includes(n)&&Array.isArray(r.candidates)&&r.candidates.length===1&&(d.currentTarget=r.candidates[0],d.requiresRecomposeModified=!0),{recoveryVersion:1,code:n,message:r.message||String(e),stage:r.stage||o,category:r.category||a,...s,...Object.keys(d).length>0||r.context?{context:{...r.context||{},...d}}:{},...f?{issueSummary:f}:{},recovery:u}}function er({atomic:e=!1,rolledBack:t=!1,results:r=[],receipts:n=[],operationCount:o=null}={}){let a=Number.isInteger(o)?o:Math.max(r.length,n.length),i=new Set(r.map(f=>f?.index).filter(Number.isInteger)),s=r.filter(f=>f?.status==="error").map(f=>f.index).filter(Number.isInteger),l=n.filter(f=>f?.committed===!0).map(f=>f.operationIndex).filter(Number.isInteger),c=[];for(let f=1;f<=a;f+=1)i.has(f)||c.push(f);let u=t||e||l.length===0?"original":"output";return{base:u,committedIndexes:l,failedIndexes:s,unattemptedIndexes:c,replayWholeBatch:u==="original",sameArgumentsSafe:!1}}function Yr(e,t,r){return et({code:r,message:e,...t?{field:t}:{},recovery:{action:"change_request",sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function Oa(e,t,r,n,o={}){return et({code:e,message:t,field:r,...o,recovery:{action:n,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function bg(e,t){let r=[],n=0;for(;n<=e.length-t.length;){let o=e.indexOf(t,n);if(o<0)break;r.push(o),n=o+1}return r}function yo(e,t){return(e===" "||e==="\xA0")&&(t===" "||t==="\xA0")}function Ng(e,t){let r=[];for(let n=0;n<=e.length-t.length;n+=1){let o=!0;for(let a=0;a<t.length;a+=1){let i=e[n+a],s=t[a];if(i!==s&&!yo(i,s)){o=!1;break}}o&&r.push(n)}return r}function Ig(e,t){let r=bg(e,t);return r.length>0?{offsets:r,matchMode:"exact"}:{offsets:Ng(e,t),matchMode:"space_equivalent"}}function Tg(e,t,r){let n=r.split(""),o=0;for(;o<t.length&&o<r.length&&(t[o]===r[o]||yo(t[o],r[o]));)yo(e[o],r[o])&&(n[o]=e[o]),o+=1;let a=t.length-1,i=r.length-1;for(;a>=o&&i>=o&&(t[a]===r[i]||yo(t[a],r[i]));)yo(e[a],r[i])&&(n[i]=e[a]),a-=1,i-=1;return n.join("")}function Sg(e,t,r){let n=Math.max(0,t-40),o=Math.min(e.length,t+r+40);return{start:t,end:t+r,excerpt:e.slice(n,o)}}function bu(e,t,r,n=120){let o=String(e??""),a=Math.max(0,Math.min(o.length,t)),i=Math.max(a,Math.min(o.length,r)),s=Math.floor((a+i)/2),l=Math.max(0,s-Math.floor(n/2)),c=Math.min(o.length,l+n);l=Math.max(0,c-n);let u=l>0?"\u2026":"",f=c<o.length?"\u2026":"",d=Math.max(0,n-u.length-f.length);return`${u}${o.slice(l,l+d)}${f}`}function _a(e,t="replacements",{invalidCode:r="INVALID_OPERATION"}={}){if(!Array.isArray(e)||e.length===0)return{ok:!1,error:Yr("replacements must be a non-empty array.",t,r)};let n=[];for(let o=0;o<e.length;o+=1){let a=e[o],i=`${t}[${o}]`;if(!a||typeof a!="object"||Array.isArray(a))return{ok:!1,error:Yr(`${i} must be an object.`,i,r)};if(typeof a.find!="string"||a.find.length===0)return{ok:!1,error:Yr(`${i}.find must be a non-empty string.`,`${i}.find`,r)};if(typeof a.replace!="string")return{ok:!1,error:Yr(`${i}.replace must be a string.`,`${i}.replace`,r)};if(a.find===a.replace)return{ok:!1,error:Yr(`${i} must change the matched text.`,i,r)};let s=a.occurrence==null?null:Number(a.occurrence);if(s!=null&&(!Number.isInteger(s)||s<1))return{ok:!1,error:Yr(`${i}.occurrence must be a positive integer.`,`${i}.occurrence`,r)};n.push({find:a.find,replace:a.replace,...s==null?{}:{occurrence:s}})}return{ok:!0,replacements:n}}function Nu(e,t,r="replacements",n={}){let o=n.invalidCode||"INVALID_OPERATION";if(typeof e!="string")return{ok:!1,error:Yr("Localized replacements require string source text.",r,o)};let a=_a(t,r,{invalidCode:o});if(!a.ok)return a;let i=[];for(let u=0;u<a.replacements.length;u+=1){let f=a.replacements[u],d=`${r}[${u}]`,m=f.occurrence??null,{offsets:p,matchMode:g}=Ig(e,f.find);if(p.length===0||m!=null&&m>p.length)return{ok:!1,error:Oa("PATCH_SOURCE_NOT_FOUND",m==null?`Patch source was not found: "${f.find}".`:`Occurrence ${m} of patch source was not found: "${f.find}".`,d,"change_patch",{matchCount:p.length})};if(m==null&&p.length>1)return{ok:!1,error:Oa("AMBIGUOUS_PATCH_SOURCE",`Patch source matched ${p.length} locations; provide occurrence.`,d,"choose_occurrence",{candidates:p.map(w=>Sg(e,w,f.find.length))})};let h=p[(m||1)-1],y=e.slice(h,h+f.find.length);i.push({requestIndex:u,start:h,end:h+f.find.length,find:f.find,replace:f.replace,effectiveReplace:g==="space_equivalent"?Tg(y,f.find,f.replace):f.replace,matchMode:g,occurrence:m||1})}i.sort((u,f)=>u.start-f.start||u.end-f.end||u.requestIndex-f.requestIndex);let s=[];for(let u of i){let f=s.at(-1);if(f&&u.start===f.start&&u.end===f.end){if(u.effectiveReplace!==f.effectiveReplace)return{ok:!1,error:Oa("CONFLICTING_PATCHES",`Localized replacements ${f.requestIndex+1} and ${u.requestIndex+1} assign different text to the same source range.`,r,"combine_patches",{replacementIndexes:[f.requestIndex+1,u.requestIndex+1]})};continue}if(f&&u.start<f.end)return{ok:!1,error:Oa("OVERLAPPING_PATCHES",`Localized replacements ${f.requestIndex+1} and ${u.requestIndex+1} overlap.`,r,"combine_patches",{replacementIndexes:[f.requestIndex+1,u.requestIndex+1]})};s.push(u)}let l=0,c="";for(let u of s)c+=e.slice(l,u.start),c+=u.effectiveReplace,l=u.end;return c+=e.slice(l),{ok:!0,desiredText:c,replacements:s.map(u=>({requestIndex:u.requestIndex+1,start:u.start,end:u.end,find:u.find,replace:u.replace,matchMode:u.matchMode,occurrence:u.occurrence,removedLength:u.end-u.start,insertedLength:u.effectiveReplace.length}))}}function Iu(e,t,r={},n=null){if(!e||typeof e!="object")return null;let o=String(e.sourceText??""),a=String(e.desiredText??""),i=Array.isArray(e.replacements)?e.replacements:[],s=0,l=i.map(c=>{let u=c.start+s,f=u+c.replace.length;return s+=c.replace.length-(c.end-c.start),{find:c.find,replace:c.replace,...c.matchMode==="space_equivalent"?{matchMode:c.matchMode}:{},occurrence:c.occurrence,beforeExcerpt:bu(o,c.start,c.end),afterExcerpt:bu(a,u,f)}});return{kind:"localized_replacement",committed:!0,finalDisposition:"applied",target:{...r.paragraphId?{paragraphId:r.paragraphId}:{},...Number.isInteger(r.index)?{index:r.index}:{},...r.fingerprint?{fingerprint:r.fingerprint}:{},...n?.humanReference?{humanReference:n.humanReference}:{}},...n?{context:{...n}}:{},replacements:l,verification:{acceptedViewMatchesCompiledText:typeof t=="string"&&t===a}}}var Ag=new Set(["redline","replace","format","character-format","paragraph-format","list-change","table-reconciliation","insert","restore","delete","comment","comment_reply","comment_resolve","highlight"]),Tu=Object.freeze(["merge-same-author","slice-cross-author","reject-input","accept-all-first","accept-all-first-keep-normalized"]);function vo(e){return Tu.includes(e)}function Ct(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ve(e){return typeof e=="string"&&e.trim().length>0}function Eg(e){return e==="comment_reply"||e==="comment_resolve"}function Rg(e){let t=e?.type;return t==="insert"&&e?.target?.revisionView==="rejected"?"rejected-insert":t==="restore"?"restore":t==="comment"||t==="comment_reply"||t==="comment_resolve"||t==="highlight"?t:t==="paragraph-format"?"paragraph-format":t==="character-format"||t==="format"&&(e?.textToFormat!=null||e?.properties!=null)?"format":"redline"}function ka(e,t=null,r="accepted"){let n=r==="rejected"?"rejected":"accepted";return Ct(e)?{text:typeof e.exactText=="string"?e.exactText:typeof e.text=="string"?e.text:"",index:e.index??e.paragraphIndex??t??null,paragraphId:ve(e.paragraphId)?e.paragraphId.trim():null,occurrence:Number.isInteger(e.occurrence)&&e.occurrence>0?e.occurrence:null,inTable:typeof e.inTable=="boolean"?e.inTable:null,fingerprint:ve(e.fingerprint)?e.fingerprint.trim():ve(e.sourceFingerprint)?e.sourceFingerprint.trim():null,revisionView:e.revisionView==="rejected"?"rejected":e.revisionView==="accepted"?"accepted":n,captureRef:ve(e.captureRef)?e.captureRef.trim():null,select:typeof e.select=="string"?e.select:null}:{text:typeof e=="string"?e:"",index:t??null,paragraphId:null,occurrence:null,inTable:null,fingerprint:null,revisionView:n}}function it(e){let t=Ct(e)?e:{},r=Rg(t),n=r==="restore"?"rejected":"accepted",o=ka(t.target,t.targetRef,n),a=t.targetEnd!=null?ka(t.targetEnd,t.targetEndRef,n):null;return{...t,operationId:ve(t.operationId)?t.operationId.trim():null,captureKey:ve(t.captureKey)?t.captureKey.trim():null,operationKind:r,anchor:Ct(t.anchor)?{exactText:typeof t.anchor.exactText=="string"?t.anchor.exactText:"",occurrence:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0?t.anchor.occurrence:1,occurrenceExplicit:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0,offset:Number.isInteger(t.anchor.offset)?t.anchor.offset:null}:null,targetDescriptor:o,targetEndDescriptor:a,target:o.text,targetRef:o.index,targetEndRef:a?.index??t.targetEndRef??null,...t.type==="delete"&&t.modified==null?{modified:""}:{}}}function tr(e){if(!Ct(e))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation must be an object."}};let t=e.type;if(t!=null&&t!==""&&!Ag.has(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:`Unsupported operation type: "${String(t)}".`}};let r=it(e);if(Ct(e.target)&&e.target.revisionView!=null&&e.target.revisionView!=="accepted"&&e.target.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(Ct(e.targetEnd)&&e.targetEnd.revisionView!=null&&e.targetEnd.revisionView!=="accepted"&&e.targetEnd.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(e.operationId!=null&&(!ve(e.operationId)||e.operationId.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"operationId must be a non-empty string under 256 characters when provided."}};if(e.captureKey!=null&&(!ve(e.captureKey)||e.captureKey.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"captureKey must be a non-empty string under 256 characters when provided."}};if(Ct(e.target)&&e.target.captureRef!=null&&(!ve(e.target.captureRef)||e.target.captureRef.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.captureRef must be a non-empty string under 256 characters when provided."}};if(Ct(e.target)&&e.target.select!=null&&typeof e.target.select!="string")return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.select must be a string when provided."}};let n=r.targetDescriptor;if(!Eg(r.operationKind)&&!ve(n.text)&&n.index==null&&!n.paragraphId&&!n.fingerprint&&!n.captureRef)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation target must provide text, a paragraph index, a paragraphId, or a captureRef."}};if(n.occurrence!=null&&!ve(n.text))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Target occurrence requires target text."}};if(r.operationKind==="redline"){let o=typeof r.modified=="string",a=r.replacements!==void 0;if(o===a)return{valid:!1,error:{code:"INVALID_OPERATION",message:'Redline operations require exactly one of string "modified" or non-empty "replacements".'}};if(a){if(t!=null&&t!==""&&!["redline","replace"].includes(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements are supported only for redline or replace operations."}};if(n.revisionView!=="accepted"||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 require one batch-start accepted-view paragraph target without captures, target occurrence, or a target range."}};let i=_a(r.replacements);if(!i.ok)return{valid:!1,error:i.error};if(i.replacements.some(s=>/\r|\n/.test(s.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 cannot insert paragraph breaks."}};if(i.replacements.some(s=>/\r|\n/.test(s.find)))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Localized replacements v1 cannot span a line break; use one replacement per line or a full "modified" paragraph.'}};r.replacements=i.replacements}}if(r.operationKind==="rejected-insert"){if(!ve(r.modified))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require non-empty string "modified" text.'}};if(!r.anchor||!ve(r.anchor.exactText)||!Number.isInteger(r.anchor.offset)||r.anchor.offset<0||r.anchor.offset>r.anchor.exactText.length)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Rejected-view insert operations require anchor.exactText, a positive occurrence, and an offset within the anchor text."}};if(r.existingRevisions!=="slice-cross-author")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require existingRevisions: "slice-cross-author".'}}}if(r.operationKind==="restore"){let o=e.modified!==void 0,a=e.replacements!==void 0,i=ve(r.modified),s=Array.isArray(r.modified)&&r.modified.length>0&&r.modified.every(ve);if(o&&a)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations accept modified or replacements, not both."}};if(o&&!i&&!s)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore modified must be a non-empty string or non-empty string array."}};if(!o&&(n.revisionView!=="rejected"||!n.paragraphId&&!n.fingerprint||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Verbatim and localized restore require one strong batch-start rejected-view paragraph target without captures, target occurrence, or a target range."}};if(a){let l=_a(r.replacements);if(!l.ok)return{valid:!1,error:l.error};if(l.replacements.some(c=>/\r|\n/.test(c.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized restore cannot insert paragraph breaks."}};r.replacements=l.replacements}if(r.generateRedlines===!1)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations require tracked changes and cannot set generateRedlines to false."}}}if(r.structuredContent!=null&&typeof r.structuredContent!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"structuredContent must be a boolean when provided."}};if(r.pairReplacements!=null&&typeof r.pairReplacements!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"pairReplacements must be a boolean when provided."}};if(r.existingRevisions!=null&&!vo(r.existingRevisions))return{valid:!1,error:{code:"INVALID_OPERATION",message:`existingRevisions must be one of: ${Tu.join(", ")}.`}};if(r.insertionAffinity!=null){if(!Ct(r.insertionAffinity))return{valid:!1,error:{code:"INVALID_OPERATION",message:"insertionAffinity must be an object when provided."}};let{formatting:o,hyperlink:a,revision:i,bookmark:s,comment:l}=r.insertionAffinity;if(o!=null&&!["left","right","none"].includes(o))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.formatting must be "left", "right", or "none".'}};if(a!=null&&!["inside","outside","preserve"].includes(a))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.hyperlink must be "inside", "outside", or "preserve".'}};if(i!=null&&!["coalesce_same_author","separate"].includes(i))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.revision must be "coalesce_same_author" or "separate".'}};if(s!=null&&!["inside","outside"].includes(s))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.bookmark must be "inside" or "outside".'}};if(l!=null&&!["inside","outside"].includes(l))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.comment must be "inside" or "outside".'}}}if(r.operationKind==="comment"&&!ve(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment operations require a non-empty "commentContent" field.'}};if(r.operationKind==="comment_reply"){if(!ve(String(r.parentCommentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a "parentCommentId".'}};if(!ve(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a non-empty "commentContent" field.'}}}if(r.operationKind==="comment_resolve"){if(!ve(String(r.commentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve operations require a "commentId".'}};if(r.resolved!=null&&typeof r.resolved!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve "resolved" must be a boolean when provided.'}}}if(r.operationKind==="highlight"){if(!ve(r.textToHighlight))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Highlight operations require a non-empty "textToHighlight" field.'}};if(r.color!=null&&!ve(r.color))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Highlight color must be a non-empty string when provided."}}}if(r.operationKind==="format"){if(!ve(r.textToFormat))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a non-empty "textToFormat" field.'}};if(r.textOccurrence!=null&&(!Number.isInteger(r.textOccurrence)||r.textOccurrence<1))return{valid:!1,error:{code:"INVALID_OPERATION",message:"textOccurrence must be a positive integer when provided."}};if(!Ct(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a "properties" object.'}};if(r.formattingRevisionPolicy!=null&&!["always","coalesce-own-insertion"].includes(r.formattingRevisionPolicy))return{valid:!1,error:{code:"INVALID_OPERATION",message:'formattingRevisionPolicy must be "always" or "coalesce-own-insertion".'}}}return r.operationKind==="paragraph-format"&&!Ct(r.properties)?{valid:!1,error:{code:"INVALID_OPERATION",message:'Paragraph-format operations require a "properties" object.'}}:r.author!=null&&!ve(r.author)?{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation author must be a non-empty string when provided."}}:{valid:!0,operation:r}}function Nt(e,t,r){return ve(e?.author)?e.author.trim():ve(t)?t.trim():ve(r)?r.trim():"Author"}var Tr=class{constructor(t,r={}){if(this.originalDocumentXml=typeof t=="string"?t:"",this.currentDocumentXml=this.originalDocumentXml,this.serializer=oe(),this.parseResult=W(this.originalDocumentXml,"application/xml"),this.document=this.parseResult.doc||null,this.revisionIdAllocator=null,this.initialTargetReferenceSnapshot=null,this.paragraphIndex=null,this.invalidated=!1,this.hasChanges=!1,this.documentHasChanges=!1,this.deferSerialization=r?._deferDocumentSerialization===!0,this.instrumentation=r?._sessionInstrumentation||null,this.runtimeContext=null,this.commentsXml=null,this.commentsExtendedXml=null,this.commentsXmlMode="merge",this.commentsExtendedXmlMode="merge",this.numberingXmlParts=[],this.results=[],this.executionOrder=[],this.authorsUsed=new Set,this.captureTable=new Map,this.sourceTargetRegistry=null,this.nextCaptureParaId=1,this.receiptCollector=new ho,this.document){this.instrumentation?.onDocumentParse?.(this.originalDocumentXml),this.revisionIdAllocator=r?._revisionIdAllocator instanceof Pe?r._revisionIdAllocator:new Pe,this.revisionIdAllocator._receiptCollector=this.receiptCollector,Wt(this.document,this.revisionIdAllocator),cr(this.document,this.revisionIdAllocator);let n=this.getParagraphMetadataIndex();this.initialTargetReferenceSnapshot=Ci(this.document,n)}}get valid(){return!!this.document&&!this.parseResult.error}setDocumentXml(t){this.currentDocumentXml=t,this.invalidateParagraphIndex()}invalidateParagraphIndex(){this.invalidated=!0,this.paragraphIndex=null}serialize(){return this.document?(this.instrumentation?.onDocumentSerialize?.(this.document),this.serializer.serializeToString(this.document)):this.currentDocumentXml}serializeCurrent(){return this.hasChanges?this.documentHasChanges?(this.currentDocumentXml=this.serialize(),this.currentDocumentXml):this.currentDocumentXml:this.originalDocumentXml}markMutationCommitted(t=!0){this.hasChanges=!0,this.documentHasChanges=this.documentHasChanges||t,t&&this.invalidateParagraphIndex()}generateParagraphId(){return(1073741824+this.nextCaptureParaId++).toString(16).toUpperCase()}createSavepoint(){return this.document?{document:this.document.cloneNode(!0),allocatorNextId:this.revisionIdAllocator?.nextId,allocatorOccupiedIds:this.revisionIdAllocator?.occupiedIds instanceof Set?new Set(this.revisionIdAllocator.occupiedIds):null,hasChanges:this.hasChanges,documentHasChanges:this.documentHasChanges,currentDocumentXml:this.currentDocumentXml,commentsXml:this.commentsXml,commentsExtendedXml:this.commentsExtendedXml,commentsXmlMode:this.commentsXmlMode,commentsExtendedXmlMode:this.commentsExtendedXmlMode,captureTable:Su(this.captureTable),sourceTargetRegistry:this.sourceTargetRegistry?.createSavepoint?.(this.document)||null,nextCaptureParaId:this.nextCaptureParaId,receiptCollector:this.receiptCollector?this.receiptCollector.createSavepoint():null}:null}restoreSavepoint(t){t?.document&&(this.document=t.document,this.hasChanges=t.hasChanges,this.documentHasChanges=t.documentHasChanges===!0,this.currentDocumentXml=t.currentDocumentXml,this.commentsXml=t.commentsXml,this.commentsExtendedXml=t.commentsExtendedXml,this.commentsXmlMode=t.commentsXmlMode||"merge",this.commentsExtendedXmlMode=t.commentsExtendedXmlMode||"merge",this.captureTable=t.captureTable?Su(t.captureTable):new Map,this.sourceTargetRegistry?.restoreSavepoint?.(this.document,t.sourceTargetRegistry),typeof t.nextCaptureParaId=="number"&&(this.nextCaptureParaId=t.nextCaptureParaId),this.revisionIdAllocator&&(this.revisionIdAllocator.nextId=t.allocatorNextId,t.allocatorOccupiedIds instanceof Set&&(this.revisionIdAllocator.occupiedIds=new Set(t.allocatorOccupiedIds)),this.revisionIdAllocator._receiptCollector=this.receiptCollector,cr(this.document,this.revisionIdAllocator)),t.receiptCollector&&this.receiptCollector&&this.receiptCollector.restoreSavepoint(t.receiptCollector),this.invalidateParagraphIndex())}getParagraphIndex(){return this.getParagraphMetadataIndex().entries}getParagraphMetadataIndex(){return this.paragraphIndex?this.paragraphIndex:(this.paragraphIndex=Dt(this.document),this.invalidated=!1,this.paragraphIndex)}rollback(){return this.currentDocumentXml=this.originalDocumentXml,this.hasChanges=!1,this.documentHasChanges=!1,this.captureTable.clear(),this.sourceTargetRegistry=null,this.receiptCollector?.clear(),this.originalDocumentXml}};function Su(e){let t=new Map;if(e instanceof Map)for(let[r,n]of e.entries())t.set(r,JSON.parse(JSON.stringify(n)));return t}function An(e,t={}){let r=t?._revisionIdAllocator instanceof Pe?t._revisionIdAllocator:new Pe;return t?._documentOperationSession?.receiptCollector&&(r._receiptCollector=t._documentOperationSession.receiptCollector),Wt(e,r),cr(e,r),r}function Au(e){if(!e||typeof e!="object")return{};let t={...e};return e.listFallbackSharedNumIdByKey instanceof Map&&(t.listFallbackSharedNumIdByKey=new Map(e.listFallbackSharedNumIdByKey)),e.tableStructuralRedlineKeys instanceof Set&&(t.tableStructuralRedlineKeys=new Set(e.tableStructuralRedlineKeys)),e.numberingIdState&&typeof e.numberingIdState=="object"&&(t.numberingIdState={...e.numberingIdState,usedNumIds:e.numberingIdState.usedNumIds instanceof Set?new Set(e.numberingIdState.usedNumIds):e.numberingIdState.usedNumIds,usedAbstractNumIds:e.numberingIdState.usedAbstractNumIds instanceof Set?new Set(e.numberingIdState.usedAbstractNumIds):e.numberingIdState.usedAbstractNumIds}),e.listFallbackSequenceState&&typeof e.listFallbackSequenceState=="object"&&(t.listFallbackSequenceState={...e.listFallbackSequenceState,explicitByNumberingKey:e.listFallbackSequenceState.explicitByNumberingKey instanceof Map?new Map(e.listFallbackSequenceState.explicitByNumberingKey):e.listFallbackSequenceState.explicitByNumberingKey}),t}function Eu(e,t){if(!(!e||typeof e!="object")){if(e.listFallbackSharedNumIdByKey instanceof Map&&t.listFallbackSharedNumIdByKey instanceof Map){e.listFallbackSharedNumIdByKey.clear();for(let r of t.listFallbackSharedNumIdByKey)e.listFallbackSharedNumIdByKey.set(...r);t.listFallbackSharedNumIdByKey=e.listFallbackSharedNumIdByKey}if(e.tableStructuralRedlineKeys instanceof Set&&t.tableStructuralRedlineKeys instanceof Set){e.tableStructuralRedlineKeys.clear();for(let r of t.tableStructuralRedlineKeys)e.tableStructuralRedlineKeys.add(r);t.tableStructuralRedlineKeys=e.tableStructuralRedlineKeys}if(e.numberingIdState&&t.numberingIdState){for(let r of["usedNumIds","usedAbstractNumIds"])if(e.numberingIdState[r]instanceof Set&&t.numberingIdState[r]instanceof Set){e.numberingIdState[r].clear();for(let n of t.numberingIdState[r])e.numberingIdState[r].add(n);t.numberingIdState[r]=e.numberingIdState[r]}Object.assign(e.numberingIdState,t.numberingIdState),t.numberingIdState=e.numberingIdState}if(e.listFallbackSequenceState&&t.listFallbackSequenceState){let r=e.listFallbackSequenceState.explicitByNumberingKey,n=t.listFallbackSequenceState.explicitByNumberingKey;if(r instanceof Map&&n instanceof Map){r.clear();for(let o of n)r.set(...o);t.listFallbackSequenceState.explicitByNumberingKey=r}Object.assign(e.listFallbackSequenceState,t.listFallbackSequenceState),t.listFallbackSequenceState=e.listFallbackSequenceState}Object.assign(e,t)}}var Pg=new Set(["redline","restore","rejected-insert"]),Cg=new Set(["highlight","format","paragraph-format"]);function Og(e){let t={};if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="name"||r==="stack"||r==="message"||r==="code"||(t[r]=n);return{code:typeof e?.code=="string"&&e.code?e.code:"OPERATION_ERROR",message:e?.message||String(e),...t}}function _g(e,t){return!!t&&le(e).includes(t)}function kg(e=[]){let t=[];for(let r of e)if(!(!r||r.nodeType!==1)){r.localName==="p"&&t.push(r);for(let n of Array.from(r.getElementsByTagNameNS?.("*","p")||[]))t.includes(n)||t.push(n)}return t}var ms=class{constructor(t){this.document=t,this.nextId=1,this.entries=new Map,this.idsByNode=new WeakMap}register(t,r={}){let n=this.idsByNode.get(t);if(n)return n;let o=`S${this.nextId++}`;return this.entries.set(o,{sourceId:o,paragraph:t,sourceIndex:r.index||null,paragraphId:r.paragraphId||null,fingerprint:r.fingerprint||null,text:r.text||"",revisionView:r.revisionView==="rejected"?"rejected":"accepted",consumed:!1,consumedByOperation:null}),this.idsByNode.set(t,o),o}describe(t){let r=this.entries.get(t);return r?{sourceId:t,index:r.sourceIndex,paragraphId:r.paragraphId,fingerprint:r.fingerprint,text:r.text,revisionView:r.revisionView}:null}resolve(t,r=this.document){let n=this.entries.get(t);return n?n.consumed?{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} was consumed by operation ${n.consumedByOperation}.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:_g(r,n.paragraph)?{paragraph:n.paragraph,resolvedBy:"batch_source"}:{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} is no longer present in the live document.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:{error:{code:"SOURCE_TARGET_NOT_FOUND",message:`Compiled source target ${String(t)} was not found.`}}}createSavepoint(t=this.document){let r=le(t);return new Map(Array.from(this.entries,([n,o])=>[n,{paragraphIndex:r.indexOf(o.paragraph),consumed:o.consumed,consumedByOperation:o.consumedByOperation}]))}restoreSavepoint(t,r){this.document=t,this.idsByNode=new WeakMap;let n=le(t);for(let[o,a]of this.entries){let i=r instanceof Map?r.get(o):null;a.consumed=i?.consumed===!0,a.consumedByOperation=i?.consumedByOperation||null,a.paragraph=Number.isInteger(i?.paragraphIndex)&&i.paragraphIndex>=0&&n[i.paragraphIndex]||null,a.paragraph&&this.idsByNode.set(a.paragraph,o)}}commitMutation(t,r,n,o){let a=this.entries.get(t);if(!a||!Array.isArray(r)||!r.includes(a.paragraph))return;let i=kg(n),s=a.paragraphId?i.filter(c=>Xe(c)===a.paragraphId):[],l=s.length===1?s[0]:i.length===1?i[0]:null;if(l){a.paragraph=l,this.idsByNode.set(l,t);return}a.paragraph=null,a.consumed=!0,a.consumedByOperation=o}};function Mg(e,t){return{index:e.index,paragraphId:e.paragraphId,fingerprint:e.fingerprint,text:e.text,inTable:e.inTable,revisionView:t}}function Ru(e,t,r,n,o,a={}){let i=t?.revisionView==="rejected"?"rejected":"accepted";o[i]||(o[i]=Dt(e,{revisionView:i}));let s=o[i],l=zr(e,{targetText:t.text,targetRef:t.index,targetDescriptor:t,opType:r,strictAmbiguity:n,paragraphMetadataIndex:s,metadataIndices:o,onInfo:a.onInfo,onWarn:a.onWarn}),c=s.byParagraph.get(l.paragraph);return{paragraph:l.paragraph,resolvedBy:l.resolvedBy,metadata:Mg(c,i)}}function Pu(e,t,r,n,o){return{code:e,message:t,operationIndexes:r.map(a=>a.index).sort((a,i)=>a-i),target:n,recovery:{action:o,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}}}function En(e,t=[],r={}){let n=Array.isArray(t)?t:[],o=r.strictTargets!==!1,a=new ms(e),i={accepted:Dt(e,{revisionView:"accepted"}),rejected:null},s=[],l=[];for(let p=0;p<n.length;p+=1){let g=n[p],h=tr(g),y=h.operation||it(g),w={index:p+1,operationKind:y.operationKind,operationId:y.operationId,sourceIds:[],warnings:[]},v={...g},b=y.targetDescriptor?.occurrence!=null&&!y.targetDescriptor?.paragraphId&&!y.targetDescriptor?.fingerprint,x=typeof y.targetDescriptor?.text=="string"&&/\r|\n/.test(y.targetDescriptor.text)&&!y.targetEndDescriptor&&!(Array.isArray(y.replacements)&&(y.targetDescriptor.paragraphId||y.targetDescriptor.fingerprint));if((b||x)&&(w.dynamic=!0),h.valid&&y.operationKind!=="comment_reply"&&y.operationKind!=="comment_resolve"&&!y.targetDescriptor?.captureRef&&!w.dynamic)try{let T=Ru(e,y.targetDescriptor,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:A=>w.warnings.push(String(A))}),I=a.register(T.paragraph,T.metadata);if(w.sourceIds.push(I),w.resolvedBy=T.resolvedBy,w.resolvedTarget=T.metadata,v._compiledSourceId=I,v._compiledResolvedBy=T.resolvedBy,w.warnings.length>0&&(v._compiledWarnings=w.warnings),Array.isArray(y.replacements)){let A=Nu(T.metadata.text,y.replacements);if(!A.ok)throw Object.assign(new Error(A.error.message),A.error);v.modified=A.desiredText,delete v.replacements,v._localizedReplacementCompilation={sourceText:T.metadata.text,desiredText:A.desiredText,replacements:A.replacements};let S=tr(v);if(!S.valid)throw Object.assign(new Error(S.error.message),S.error)}else if(y.operationKind==="restore"&&g.modified===void 0){v.modified=T.metadata.text;let A=tr(v);if(!A.valid)throw Object.assign(new Error(A.error.message),A.error)}let N=y.targetEndDescriptor||(y.targetEndRef!=null?ka(null,y.targetEndRef,y.targetDescriptor.revisionView):null);if(N){let A=Ru(e,N,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:C=>w.warnings.push(String(C))}),S=a.register(A.paragraph,A.metadata);v._compiledSourceEndId=S;let O=le(e),E=O.indexOf(T.paragraph),k=O.indexOf(A.paragraph);if(E<0||k<E)throw Object.assign(new Error("Target range is not a forward contiguous paragraph range."),{code:"TARGET_RANGE_INVALID"});for(let C of O.slice(E,k+1)){let _=(i[y.targetDescriptor.revisionView]||i.accepted).byParagraph.get(C);w.sourceIds.push(a.register(C,_||{}))}w.sourceIds=[...new Set(w.sourceIds)],w.resolvedTargetEnd=A.metadata}}catch(T){w.error=Og(T)}s.push(w),l.push(v)}let c=new Set(l.map(p=>p?.captureKey).filter(Boolean)),u=1;for(let p of s){if(p.error?.code!=="TARGET_NOT_FOUND")continue;let g=p.index-1,y=it(n[g]).targetDescriptor?.text;if(!y)continue;let w=n.flatMap((T,I)=>I===g||typeof T?.modified!="string"?[]:T.modified.split(/\r?\n/).map(A=>A.trim()).filter(Boolean).includes(y.trim())?[{candidate:T,producerIndex:I}]:[]);if(w.length!==1)continue;let[{candidate:v,producerIndex:b}]=w,x=v.captureKey||l[b].captureKey;if(!x){do x=`__batch_created_${u++}`;while(c.has(x));c.add(x),l[b].captureKey=x}l[g].target={captureRef:x,select:y},delete l[g]._compiledSourceId,delete l[g]._compiledResolvedBy,delete p.error,p.sourceIds=[],p.resolvedBy="created_content_dependency",p.createdByOperation=b+1,p.captureRef=x}let f=new Map;for(let p of s)if(!(p.error||p.dynamic))for(let g of p.sourceIds)f.has(g)||f.set(g,[]),f.get(g).push(p);let d=[],m=new Set;for(let[p,g]of f){let h=g.filter(w=>Pg.has(w.operationKind)),y=g.filter(w=>Cg.has(w.operationKind));if(h.length>1){let w=`text:${h.map(v=>v.index).sort().join(",")}`;m.has(w)||(m.add(w),d.push(Pu("OVERLAPPING_SOURCE_TARGETS",`Operations ${h.map(v=>v.index).join(", ")} contain incompatible text writes to the same batch-start source target.`,h,a.describe(p),"consolidate_operations")))}if(h.length>0&&y.length>0){let w=[...h,...y],v=`format:${w.map(b=>b.index).sort().join(",")}`;m.has(v)||(m.add(v),d.push(Pu("REVISION_ORDER_CONFLICT",`Operations ${w.map(b=>b.index).join(", ")} combine text and formatting writes on the same batch-start source target.`,w,a.describe(p),"split_or_consolidate_operations")))}}return{valid:d.length===0&&s.every(p=>!p.error),compiledOperations:l,bindings:s,conflicts:d,registry:a}}function Cu(e){return`${e?.source||""}${e?.severity||""}${e?.code||""}${e?.message||""}`}function Zr(e=[],t=[]){let r=new Map;for(let n of t||[]){let o=Cu(n);r.set(o,(r.get(o)||0)+1)}return(e||[]).filter(n=>{let o=Cu(n),a=r.get(o)||0;return a===0?!0:(r.set(o,a-1),!1)})}function Jr(e=[]){return(e||[]).filter(t=>t?.severity==="error")}var Lg=/^(\s*)((?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|[ivxlcIVXLC]+\.|[-*+\u2022]))\s+(.*)$/,Ou=/(?:^|\s)(?:\d+(?:\.\d+)*\.?|[A-Za-z]\.|[ivxlcIVXLC]+\.)\s+/g;function Bg(e){let t=String(e||"").trim();if(!/^\d+(?:\.\d+)+\.?$/.test(t))return null;let r=t.replace(/\.$/,"").split(".");return Math.max(0,r.length-1)}function Dg(e){let t=String(e||"").split(/\r?\n/g).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);if(t.length<2)return null;let r=[];for(let n of t){let o=n.match(Lg);if(!o)return null;let a=o[2],i=/^[-*+\u2022]$/.test(a)?"bullet":"numbered";r.push({marker:a,markerType:i,level:Math.floor((o[1]||"").length/2),outlineLevel:i==="numbered"?Bg(a):null,text:Xr(o[3])})}return r.length>=2?r:null}function _u(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=Dg(t);if(!r)return null;let n=e.map(d=>q(Ie(d))),o=r.map(d=>q(d.text));if(n.some(d=>!d)||o.some(d=>!d))return null;let a=e.map(d=>mt(d));if(a.some(d=>!d||!d.numId))return null;let i=String(a[0].numId);if(a.some(d=>String(d.numId)!==i))return null;let s=[],l=0;for(let d=0;d<o.length&&l<n.length;d+=1)o[d]===n[l]&&(s.push({originalIndex:l,modifiedIndex:d}),l+=1);if(l!==n.length)return null;let c=new Set(s.map(d=>d.modifiedIndex)),u=[];for(let d=0;d<r.length;d+=1)c.has(d)||u.push(d);if(u.length===0)return null;let f=r[0]?.level||0;return u.map(d=>{let m=s.find(b=>b.modifiedIndex>d)||null,p=[...s].reverse().find(b=>b.modifiedIndex<d)||null,g=m||p;if(!g)return null;let h=a[g.originalIndex]||a[0];if(!h)return null;let y=r[d],w=Math.max(0,y.level-f),v=Number.isInteger(y.outlineLevel)?y.outlineLevel:null;return{text:y.text,markerType:y.markerType,ilvl:v??Math.max(0,(h.ilvl||0)+w),numId:String(h.numId),insertBeforeOriginalIndex:m?m.originalIndex:null}}).filter(Boolean)}function Fg(e){return String(e||"").trim().split(/\s+/).filter(Boolean).length}function $g(e){let t=String(e||"");if(!t)return!1;let r=0,n=new RegExp(Ou.source,Ou.flags);for(;n.exec(t);)if(r+=1,r>=2)return!0;return!1}function ku(e,t){let r=String(e||"").trim(),n=String(t||"").trim();if(!r||!n||n===r||n.includes(`
217
- `))return null;let o=q(r),a=l=>Xr(String(l||"").trim()).trim(),i=(l,c)=>{let u=a(c),f=q(u);return!u||u===r||Fg(u)<6||$g(u)||o&&f.includes(o)?null:{position:l,text:u}};if(n.endsWith(r)){let l=i("before",n.slice(0,-r.length));if(l)return l}if(n.startsWith(r)){let l=i("after",n.slice(r.length));if(l)return l}let s=q(n);if(!o||o===s)return null;if(s.endsWith(o)){let l=i("before",s.slice(0,-o.length));if(l)return l}if(s.startsWith(o)){let l=i("after",s.slice(o.length));if(l)return l}return null}function Mu(e,t){let r=String(e||"").trim(),n=String(t||"");if(!r||!n||!n.includes(`
218
- `))return null;let o=n.split(/\r?\n/g).map(s=>String(s||"").trim()).filter(Boolean);if(o.length<2)return null;let a=s=>q(String(s||"")),i=a(r);if(a(o[o.length-1])===i){let s=o.slice(0,-1).filter(Boolean);if(s.length>0)return{position:"before",paragraphs:s}}if(a(o[0])===i){let s=o.slice(1).filter(Boolean);if(s.length>0)return{position:"after",paragraphs:s}}return null}function Lu(e){let t=String(e||"").split(/\r?\n/g).map(a=>a.trimEnd()).filter(a=>a.trim().length>0);if(t.length<3||t.findIndex(a=>a.trim().startsWith("|"))!==1)return null;let n=t.slice(1);if(!n.every(a=>a.trim().startsWith("|")))return null;let o=n[1].replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(o)?{paragraphMarkdown:t[0].trim(),tableText:n.join(`
219
- `)}:null}function rr(e,t){let r=new Error(t);return r.code=e,r}function Bu(e,t,r){let n=[],o=!1,a=!1;for(let m of r||[])m&&(m.localName==="tbl"?(o=!0,n.push(...Array.from(m.getElementsByTagNameNS(B,"p")))):m.localName==="p"&&(m.getElementsByTagNameNS(B,"numPr").length>0&&(a=!0),n.push(m)));let i=o?"table":a?"list":n.length>1?"range":"paragraph",s=[],l=[],c=[],u=[],f=e.document,d=le(f);for(let m of n){let p=Xe(m)||"";s.push(p);let g=te(m);c.push(g);let h=d.indexOf(m)+1;l.push(dt(m,{text:g,paragraphId:p||null,index:h>0?h:void 0,inTable:o||!!He(m,"tbl")}));let y=m.parentNode?.localName||"body";u.push(`${y}/${m.localName}`)}return{captureKey:t.captureKey,operationIndex:typeof t.index=="number"?t.index:0,kind:i,generatedParagraphIds:s,fingerprints:l,expectedText:c,structuralPathHints:u,stale:!1}}function Du(e,t){if(!e||!(e instanceof Map)||!Array.isArray(t)||t.length===0)return;let r=new Set;for(let n of t)if(n){if(n.localName==="p"){let o=Xe(n);o&&r.add(o)}else if(typeof n.getElementsByTagNameNS=="function")for(let o of Array.from(n.getElementsByTagNameNS(B,"p"))){let a=Xe(o);a&&r.add(a)}}if(r.size!==0)for(let[,n]of e)n.stale||n.generatedParagraphIds.some(o=>o&&r.has(o))&&(n.stale=!0)}function Fu(e,t,r,n="redline",o={}){let a=r?.captureRef;if(!a)throw rr("INVALID_OPERATION","Operation target is missing captureRef.");if(!t||!t.captureTable||!t.captureTable.has(a))throw rr("CAPTURE_NOT_FOUND",`Capture "${a}" was not found in the session capture table.`);let i=t.captureTable.get(a);if(i.stale)throw rr("CAPTURE_STALE",`Capture "${a}" is stale; the captured content was modified or removed.`);let s=t.getParagraphMetadataIndex(),l=[];for(let d=0;d<i.expectedText.length;d++){let m=i.generatedParagraphIds[d],p=i.expectedText[d],g=null;if(m&&s.byId.has(m)&&(g=s.byId.get(m).paragraph),!g){let y=s.entries.find(w=>w.text===p||w.fingerprint===i.fingerprints[d]);y&&(g=y.paragraph)}if(!g||!g.parentNode)throw i.stale=!0,rr("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} was removed from the document.`);let h=te(g);if(h!==p)throw i.stale=!0,rr("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} content drifted from "${p}" to "${h}".`);l.push(g)}if(l.length===0)throw i.stale=!0,rr("CAPTURE_STALE",`Capture "${a}" is stale; no live paragraphs found.`);let c=r.select;if(c==null||c===""){if(l.length===1)return{paragraph:l[0],resolvedBy:"capture"};throw rr("AMBIGUOUS_CAPTURE_SELECTION",`Capture "${a}" contains ${l.length} paragraphs; target.select is required to disambiguate.`)}let u=[],f=String(c).trim();if(f===":first"||f==="first")u=[l[0]];else if(f===":last"||f==="last")u=[l[l.length-1]];else if(/^\d+$/.test(f)){let d=parseInt(f,10);d>=1&&d<=l.length&&(u=[l[d-1]])}else{let d=l.filter(m=>te(m).trim()===f);d.length>0?u=d:u=l.filter(m=>te(m).includes(f))}if(u.length===0)throw rr("TARGET_NOT_FOUND",`Target selection "${c}" was not found in capture "${a}".`);if(u.length>1)throw rr("AMBIGUOUS_CAPTURE_SELECTION",`Target selection "${c}" matched ${u.length} paragraphs in capture "${a}".`);return{paragraph:u[0],resolvedBy:"capture"}}var ae="http://schemas.openxmlformats.org/wordprocessingml/2006/main",vs="http://schemas.microsoft.com/office/word/2010/wordml";function $u(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.(ae,r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Uu(e,t){return!t||typeof t!="object"?[]:e.map(r=>t[r]).filter(Boolean)}function Qr(e,t={}){let r=t?._documentOperationSession||null;return r?.valid&&r.document?{xmlDoc:r.document,serializer:r.serializer,operationSession:r}:{xmlDoc:W(e,"application/xml").doc,serializer:oe(),operationSession:null}}function st(e,t,r,n){return n?r:t.serializeToString(e)}async function Rn(e,t,r,n={}){let o=await Gn(e,t,r,n);return o?.useNativeApi&&typeof o?.oxml!="string"?Ne({...o,oxml:e,hasChanges:!1,warnings:[...Array.isArray(o?.warnings)?o.warnings:[],"Standalone mode cannot execute native Word API fallback for this operation."]}):o}async function Ug(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=rt(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await Rn(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}function xo(e){return Ie(e)}function zu(e,t=96){let r=String(e??"");return(r.length>t?`${r.slice(0,t)}\u2026`:r).replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\u00a0/g,"\\u00A0").replace(/\u202f/g,"\\u202F").replace(/\u2060/g,"\\u2060")}function Ma(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function zg(e,t){let r=String(e??""),n=String(t??"");if(r===n)return{mode:"exact"};let o=[],a=Math.min(r.length,n.length);for(let s=0;s<a&&o.length<8;s++)r[s]!==n[s]&&o.push({offset:s,sourceCodePoint:Ma(r,s),requestedCodePoint:Ma(n,s)});return r.length!==n.length&&o.length<8&&o.push({offset:a,sourceCodePoint:Ma(r,a),requestedCodePoint:Ma(n,a)}),{mode:r.length===n.length&&r.replace(/\u00a0/g," ")===n.replace(/\u00a0/g," ")?"space_equivalent":"normalized",differences:o,sourceExcerpt:zu(r),requestedExcerpt:zu(n)}}function ps(e,t,r,n,o){let a=o?.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",i=r?.revisionView===a?r:null,s=i?.index??le(e).indexOf(t)+1,l=i?.paragraphId??Xe(t),c=i?.inTable??!!He(t,"tbl"),u=i?.text??te(t,{revisionView:a}),f=i?.fingerprint??dt(t,{text:u,index:s,paragraphId:l,inTable:c,revisionView:a});return{index:s,paragraphId:l,text:u,fingerprint:f,revisionView:a,inTable:c,targetTextMatch:zg(u,o?.targetDescriptor?.text??o?.targetDescriptor?.exactText??n)}}function nr(e,t,r,n,o=null,a={}){let i=typeof a?.onInfo=="function"?a.onInfo:()=>{},s=typeof a?.onWarn=="function"?a.onWarn:()=>{},l=a?._documentOperationSession||null,c=l?.getParagraphMetadataIndex?.()||null;if(a?._compiledSourceId&&a?._sourceTargetRegistry){let f=a._sourceTargetRegistry.resolve(a._compiledSourceId,e);if(f?.error||!f?.paragraph)return f;if(f.resolvedBy=a._compiledResolvedBy||f.resolvedBy,a?._resolutionCapture){let d=f.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:ps(e,d,m,t,a)})}return f}if(a?.targetDescriptor?.captureRef)try{let f=Fu(e,l,a.targetDescriptor,n,a);if(a?._resolutionCapture&&f?.paragraph){let d=f.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:ps(e,d,m,t,a)})}return f}catch(f){return{error:{code:typeof f?.code=="string"&&f.code?f.code:"TARGET_NOT_FOUND",message:f?.message||String(f)}}}let u=Yn(e,{targetText:t,targetRef:r,opType:n,targetRefSnapshot:o?.targetRefSnapshot||null,targetDescriptor:a?.targetDescriptor||null,strictAmbiguity:a?.strictTargets===!0,paragraphMetadataIndex:c,onInfo:i,onWarn:s});if(a?._resolutionCapture&&u?.paragraph){let f=u.paragraph,d=c?.byParagraph?.get(f)||null;Object.assign(a._resolutionCapture,{resolvedBy:u.resolvedBy,resolvedTarget:ps(e,f,d,t,a)})}return u}function or(e){return is(e)}function Xg(e,t){if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||!t.includes("Paragraph expanded to list fragment"))return e;let r=e[e.length-1];return!r||r.localName!=="p"||Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.localName!=="pPr")?e:e.slice(0,-1)}function lt(e){Sa(e)}function Vg(e){for(let t of Array.from(e?.getElementsByTagNameNS?.(ae,"proofErr")||[]))t.parentNode?.removeChild(t)}function Wg(e){e&&Vg(e)}function tt(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI===ae&&r.localName===t)||null}function jg(e,t){if(!e||!t)return null;let n=Array.from(e.getElementsByTagNameNS(ae,"tbl")).indexOf(t);return n>=0?n+1:null}function Kg(e){return String(e||"").replace(/\r\n/g,`
216
+ `);return t||r||n||o||a||i||l||s||c}function Pv(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 sa=class{constructor(){this.receipts=[],this.activeReceipt=null}beginOperation(t,r=null,n=null){this.activeReceipt={operationIndex:typeof t=="number"?t:1,...r?{operationId:String(r)}:{},attemptedDisposition:"applied",finalDisposition:"applied",committed:!0,...n?{authorUsed:String(n)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}recordRevision(t,r="structural",n="word/document.xml"){if(!this.activeReceipt||t==null)return;let o=String(t);this.activeReceipt.revisionItems.some(a=>a.id===o&&a.kind===r&&a.partName===n)||this.activeReceipt.revisionItems.push({id:o,kind:r,partName:n})}recordComment(t,r="word/comments.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.commentIds.includes(n)||this.activeReceipt.commentIds.push(n)}recordNumbering(t,r="word/numbering.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.numberingIds.includes(n)||this.activeReceipt.numberingIds.push(n)}recordRelationship(t,r="word/_rels/document.xml.rels"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.relationshipIds.includes(n)||this.activeReceipt.relationshipIds.push(n)}recordAffectedTarget(t){!this.activeReceipt||!t||this.activeReceipt.affectedTargets.push(JSON.parse(JSON.stringify(t)))}recordWarning(t){!this.activeReceipt||!t||this.activeReceipt.warnings.push(String(t))}commitOperation(t="applied"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=t==="applied";let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.receipts.push(r),this.activeReceipt=null,r}abortOperation(t="refused"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=!1;let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.activeReceipt=null,r}createSavepoint(){return{receipts:JSON.parse(JSON.stringify(this.receipts)),activeReceipt:this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}}restoreSavepoint(t){t&&(this.receipts=Array.isArray(t.receipts)?JSON.parse(JSON.stringify(t.receipts)):[],this.activeReceipt=t.activeReceipt?JSON.parse(JSON.stringify(t.activeReceipt)):null)}clear(){this.receipts=[],this.activeReceipt=null}markRolledBack(){for(let t of this.receipts)t.attemptedDisposition==="applied"&&(t.finalDisposition="rolled_back",t.committed=!1);this.activeReceipt=null}getReceipts(){return JSON.parse(JSON.stringify(this.receipts))}getCurrentReceipt(){return this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}};function ke(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 la(e,t){if(!Array.isArray(t)||t.length===0)return{valid:!0};let r=t.filter(s=>s&&s.committed===!0&&s.finalDisposition==="applied");if(r.length===0)return{valid:!0};let n=new Set;if(e?.documentXml&&typeof e.documentXml=="string"){let s=/<(?:w:)?(?:ins|del|rPrChange|pPrChange|moveFrom|moveTo)\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=s.exec(e.documentXml))!==null;)n.add(c[1])}let o=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let s=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=s.exec(e.commentsXml))!==null;)o.add(c[1])}let a=new Set,i=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
217
+ `);if(i){let s=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=s.exec(i))!==null;)a.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let s=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=s.exec(e.documentXml))!==null;)a.add(c[1])}let l=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let s=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=s.exec(e.relationshipsXml))!==null;)l.add(c[1])}for(let s of r){if(Array.isArray(s.revisionItems)){for(let c of s.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(s.commentIds)){for(let c of s.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(s.numberingIds)){for(let c of s.numberingIds)if(!a.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(s.relationshipIds)){for(let c of s.relationshipIds)if(!l.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}var fd="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Cv="http://schemas.openxmlformats.org/officeDocument/2006/relationships",_v=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tcPrChange","trPrChange","numberingChange"]),Ov=new Set(["ins","del","moveFrom","moveTo"]),xi=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function kv(e){let t=String(e||"");if(t.startsWith("/"))return t.replace(/^\/+/,"");let r=["word"];for(let n of t.split("/"))n===".."?r.pop():n&&n!=="."&&r.push(n);return r.join("/")}function bl({documentXml:e,relsXml:t=null,settingsXml:r=null}){if(!e||!t)return[];let n=j(e,"application/xml"),o=j(t,"application/xml");if(!n.doc||n.error||!o.doc||o.error)return[];let a=new Map;for(let f of Array.from(o.doc.getElementsByTagNameNS("*","Relationship")))a.set(f.getAttribute("Id")||"",f.getAttribute("Target")||"");let i=!!r&&/<w:evenAndOddHeaders\b(?![^>]*w:val="(?:0|false|off)")/.test(r),l=new Map,s=new Map;return Array.from(n.doc.getElementsByTagNameNS(fd,"sectPr")).forEach((f,u)=>{let d=Array.from(f.childNodes||[]).some(m=>m.localName==="titlePg"&&!/^(0|false|off)$/i.test(xi(m,"w:val","val")));for(let m of Array.from(f.childNodes||[])){if(m.nodeType!==1||m.localName!=="headerReference"&&m.localName!=="footerReference")continue;let p=m.getAttributeNS?.(Cv,"id")||m.getAttribute("r:id")||"",g=a.get(p);if(!g)continue;let h=kv(g),v=m.localName==="headerReference"?"header":"footer",w=xi(m,"w:type","type")||"default",y=l.get(h)||{path:h,kind:v,type:w,sections:[],applies:[],titlePgSections:0};y.sections.includes(u)||y.sections.push(u),d&&(y.titlePgSections+=1),l.set(h,y),s.set(`${v}:${w}`,h)}for(let m of s.values()){let p=l.get(m);p&&!p.applies.includes(u)&&p.applies.push(u)}}),Array.from(l.values()).map(f=>({path:f.path,kind:f.kind,type:f.type,sections:f.sections,appliesToSections:f.applies,sharedBySections:f.applies.length>1,active:f.type==="first"?f.titlePgSections>0:f.type==="even"?i:!0}))}function xl(e,t){let r=a=>({path:a.path,kind:a.kind,type:a.type,sections:a.sections,appliesToSections:a.appliesToSections});if(typeof t=="string"){let a=t.replace(/^\/+/,"").toLowerCase(),i=e.find(l=>l.path.toLowerCase()===a||l.path.toLowerCase()===`word/${a}`);return i?{part:i}:{error:{code:"PART_NOT_FOUND",message:`No header/footer part '${t}' is referenced by the document.`,candidates:e.map(r)}}}if(!t||typeof t!="object"||t.kind!=="header"&&t.kind!=="footer")return{error:{code:"INVALID_OPERATION",message:'part must be a part path or { kind: "header"|"footer", type?: "default"|"first"|"even", section?: number }.'}};let n=t.type||"default";if(!["default","first","even"].includes(n))return{error:{code:"INVALID_OPERATION",message:`part.type must be default, first or even (got '${n}').`}};let o=e.filter(a=>a.kind===t.kind&&a.type===n);return Number.isInteger(t.section)&&(o=o.filter(a=>a.appliesToSections.includes(t.section))),o.length===1?{part:o[0]}:o.length===0?{error:{code:"PART_NOT_FOUND",message:`The document has no ${n} ${t.kind}${Number.isInteger(t.section)?` for section ${t.section}`:""}.`,candidates:e.map(r)}}:{error:{code:"PART_AMBIGUOUS",message:`Several ${n} ${t.kind} parts exist; add "section" or use the part path.`,candidates:o.map(r)}}}function dd(e){let t=ll(e);return t?.id==="header"||t?.id==="footer"}function Il(e){let t=j(e,"application/xml");if(!t.doc||t.error)return 0;let r=0,n=0,o=a=>{for(let i of Array.from(a.childNodes||[])){if(i.nodeType!==1)continue;let l=i.localName;if(l==="fldChar"){let s=xi(i,"w:fldCharType","fldCharType");s==="begin"?r+=1:s==="end"&&(r=Math.max(0,r-1));continue}if(Ov.has(l)&&r>0&&(n+=1),l==="fldSimple"){r+=1,o(i),r-=1;continue}o(i)}};return o(t.doc.documentElement),n}function md(e){let t=new Set;for(let r of String(e||"").matchAll(/<w:(?:ins|del|moveFrom|moveTo|rPrChange|pPrChange|sectPrChange|tblPrChange|tblGridChange|tcPrChange|trPrChange|numberingChange)\b[^>]*?\bw:id="(\d+)"/g))t.add(r[1]);return t}function pd(e,t){let r=j(e,"application/xml");if(!r.doc||r.error)return{xml:e,renumbered:0,idMap:new Map};let n=new Map,o=1+Math.max(0,...Array.from(t,s=>Number(s)).filter(Number.isFinite)),a=new Set(t),i=0,l=s=>{for(let c of Array.from(s.childNodes||[]))if(c.nodeType===1){if(_v.has(c.localName)){let f=xi(c,"w:id","id");if(f&&a.has(f)){for(;a.has(String(o));)o+=1;c.setAttributeNS(fd,"w:id",String(o)),n.set(f,String(o)),a.add(String(o)),i+=1}else f&&a.add(f)}l(c)}};return l(r.doc.documentElement),i>0?{xml:le().serializeToString(r.doc),renumbered:i,idMap:n}:{xml:e,renumbered:0,idMap:n}}var Mv=Object.freeze({INVALID_OPERATION:["request","request_fixable","change_request"],INVALID_AGENT_REQUEST:["request","request_fixable","change_request"],INVALID_FILTER:["request","request_fixable","change_request"],INVALID_OPERATIONS_FILE:["request","request_fixable","change_request"],OPERATIONS_REQUIRED:["request","request_fixable","change_request"],UNKNOWN_OPTION:["request","request_fixable","change_request"],UNEXPECTED_ARGUMENT:["request","request_fixable","change_request"],INVALID_ACTION:["request","request_fixable","change_request"],INVALID_PROFILE:["request","request_fixable","change_request"],INVALID_REVISION_TOKEN:["revision-check","request_fixable","change_request"],BATCH_OPERATION_FAILED:["batch-execution","request_fixable","inspect_failed_operations"],REVISION_TOKEN_SCOPE_MISMATCH:["revision-check","request_fixable","change_request"],REVISION_MISMATCH:["revision-check","target_refresh_required","reinspect"],TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],SOURCE_TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],TARGET_TEXT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_FINGERPRINT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_INDEX_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_OCCURRENCE_MISMATCH:["target-resolution","candidate_selection_required","choose_candidate"],STALE_TARGET_HANDLE:["target-resolution","target_refresh_required","reinspect"],TARGET_HANDLE_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],AMBIGUOUS_TARGET:["target-resolution","candidate_selection_required","choose_candidate"],TARGET_RANGE_INVALID:["target-resolution","request_fixable","change_target_range"],ANCHOR_NOT_FOUND:["anchor-resolution","request_fixable","change_anchor"],AMBIGUOUS_ANCHOR:["anchor-resolution","candidate_selection_required","choose_candidate"],PATCH_SOURCE_NOT_FOUND:["patch-compilation","request_fixable","change_patch"],AMBIGUOUS_PATCH_SOURCE:["patch-compilation","candidate_selection_required","choose_occurrence"],OVERLAPPING_PATCHES:["patch-compilation","source_conflict","combine_patches"],CONFLICTING_PATCHES:["patch-compilation","source_conflict","combine_patches"],PATCH_ROUNDTRIP_MISMATCH:["patch-validation","request_fixable","reinspect_and_narrow"],DIFF_TOKEN_LIMIT:["patch-compilation","request_fixable","narrow_operation"],STRUCTURED_CONTENT_INVALID:["request","request_fixable","change_request"],UNSUPPORTED_LIST_CONVERSION:["list-conversion","request_fixable","use_list_format_convert_plain"],UNSUPPORTED_LIST_FORMAT_CHANGE:["list-conversion","request_fixable","use_list_format_change_format"],LIST_MARKER_NOT_FOUND:["list-conversion","request_fixable","change_request"],LIST_MARKER_AMBIGUOUS:["list-conversion","request_fixable","set_list_format"],LIST_MARKER_UNSUPPORTED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_TARGET_IS_LIST:["list-conversion","request_fixable","use_paragraph_numbering"],LIST_FORMAT_STYLE_NUMBERED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_TARGET_NOT_LIST:["list-conversion","request_fixable","use_list_format_convert_plain"],LIST_FORMAT_MIXED_RANGE:["list-conversion","request_fixable","narrow_range"],LIST_FORMAT_STYLE_LINKED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_SPLIT_UNSUPPORTED:["list-conversion","request_fixable","extend_range_or_use_list_scope"],LIST_FORMAT_DEFINITION_UNSUPPORTED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_JOIN_INVALID:["list-conversion","request_fixable","change_request"],PARAGRAPH_NUMBERING_NOT_FOUND:["target-resolution","target_refresh_required","inspect_numbering"],PARAGRAPH_FORMAT_REVISION_CONFLICT:["target-safety","user_authorization_required","resolve_pending_revision"],UNSUPPORTED_INSERTION_AFFINITY:["request","request_fixable","change_request"],EXISTING_REVISIONS:["target-safety","policy_choice_required","set_option"],PART_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PART_AMBIGUOUS:["target-resolution","candidate_selection_required","choose_candidate"],COMMENT_IN_HEADER_FOOTER:["request","request_fixable","change_request"],FIELD_EDIT_REFUSED:["target-safety","request_fixable","change_request"],COMMENT_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PARENT_ANCHOR_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],COMMENTED_CONTENT_MERGE:["target-safety","user_authorization_required","resolve_comments"],COMMENTED_CONTENT_DELETE:["target-safety","user_authorization_required","resolve_comments"],OVERLAPPING_SOURCE_TARGETS:["batch-compilation","source_conflict","consolidate_operations"],OVERLAPPING_TEXT_EDITS:["batch-compilation","source_conflict","consolidate_operations"],REVISION_ORDER_CONFLICT:["batch-compilation","source_conflict","split_or_consolidate_operations"],LIST_FORMAT_COMPOSITION_CONFLICT:["batch-compilation","source_conflict","split_text_and_list_changes"],TARGET_CONSUMED_BY_OPERATION:["batch-execution","source_conflict","use_created_content_dependency"],CAPTURE_FANOUT_CONFLICT:["batch-compilation","source_conflict","split_or_chain_capture_consumers"],DUPLICATE_CAPTURE_KEY:["batch-compilation","request_fixable","rename_capture"],CAPTURE_NOT_FOUND:["batch-compilation","request_fixable","add_or_correct_capture"],CAPTURE_DEPENDENCY_CYCLE:["batch-compilation","source_conflict","replan_batch"],AMBIGUOUS_CAPTURE_SELECTION:["batch-compilation","candidate_selection_required","choose_candidate"],CAPTURE_STALE:["batch-execution","source_conflict","replan_batch"],GENERATED_OOXML_INVALID:["validation","library_or_builder_failure","report_library_failure"],REVISION_FIDELITY_VIOLATION:["verification","library_or_builder_failure","narrow_or_change_operation"],DOCUMENT_SERIALIZATION_FAILED:["serialization","library_or_builder_failure","report_library_failure"],PACKAGE_OPERATION_FAILED:["package","library_or_builder_failure","report_library_failure"],PACKAGE_VALIDATION:["package-validation","library_or_builder_failure","report_library_failure"],MUTATION_RECEIPT_MISMATCH:["receipt-validation","library_or_builder_failure","report_library_failure"],FOREIGN_PARAGRAPH_MARK_DELETION:["target-safety","policy_choice_required","use_restore_or_leave_deleted"],RESTORATION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],RESTORATION_COUNT_MISMATCH:["request","request_fixable","change_request"],REJECTED_INSERTION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],UNSAFE_REVISION_NESTING:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_REVISION_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_DELETED_TABLE_ROW:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_MOVE_REVISION:["target-safety","manual_document_resolution","manual_resolution"],SECTION_BREAK_PARAGRAPH:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_PLACEMENT:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_REVISION_VIEW_MUTATION:["target-safety","manual_document_resolution","manual_resolution"]});function Lv(e){let t=Array.isArray(e?.generatedIssues)?e.generatedIssues:Array.isArray(e?.issues)?e.issues:null;if(!t)return null;let r=new Map;for(let n of t){let o=n?.code||"UNKNOWN";r.set(o,(r.get(o)||0)+1)}return{total:t.length,byCode:Array.from(r,([n,o])=>({code:n,count:o}))}}function Bv(e){return Mv[e]||["operation","manual_document_resolution","inspect_error"]}function yt(e,t={}){let r=e&&typeof e=="object"?e:{},n=typeof r.code=="string"&&r.code?r.code:"OPERATION_ERROR",[o,a,i]=Bv(n),l={};for(let[m,p]of Object.entries(r))m==="name"||m==="stack"||m==="message"||m==="code"||(l[m]=p);let f={action:i,sameArgumentsSafe:!1,requiresReinspection:a==="target_refresh_required"||n==="PATCH_ROUNDTRIP_MISMATCH",requiresUserAuthorization:a==="user_authorization_required",...n==="EXISTING_REVISIONS"?{field:"existingRevisions",recommendedValue:"slice-cross-author"}:{},...r.recovery&&typeof r.recovery=="object"?r.recovery:{}},u=Lv(r),d={...t,...Array.isArray(r.revisionAuthors)?{revisionAuthors:r.revisionAuthors}:{},...r.currentPolicy?{currentPolicy:r.currentPolicy}:{}};return["TARGET_TEXT_MISMATCH","TARGET_FINGERPRINT_MISMATCH"].includes(n)&&Array.isArray(r.candidates)&&r.candidates.length===1&&(d.currentTarget=r.candidates[0],d.requiresRecomposeModified=!0),{recoveryVersion:1,code:n,message:r.message||String(e),stage:r.stage||o,category:r.category||a,...l,...Object.keys(d).length>0||r.context?{context:{...r.context||{},...d}}:{},...u?{issueSummary:u}:{},recovery:f}}function Ir({atomic:e=!1,rolledBack:t=!1,results:r=[],receipts:n=[],operationCount:o=null}={}){let a=Number.isInteger(o)?o:Math.max(r.length,n.length),i=new Set(r.map(u=>u?.index).filter(Number.isInteger)),l=r.filter(u=>u?.status==="error").map(u=>u.index).filter(Number.isInteger),s=n.filter(u=>u?.committed===!0).map(u=>u.operationIndex).filter(Number.isInteger),c=[];for(let u=1;u<=a;u+=1)i.has(u)||c.push(u);let f=t||e||s.length===0?"original":"output";return{base:f,committedIndexes:s,failedIndexes:l,unattemptedIndexes:c,replayWholeBatch:f==="original",sameArgumentsSafe:!1}}function In(e,t,r){return yt({code:r,message:e,...t?{field:t}:{},recovery:{action:"change_request",sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function Ii(e,t,r,n,o={}){return yt({code:e,message:t,field:r,...o,recovery:{action:n,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function Fv(e,t){let r=[],n=0;for(;n<=e.length-t.length;){let o=e.indexOf(t,n);if(o<0)break;r.push(o),n=o+1}return r}function ca(e,t){return(e===" "||e==="\xA0")&&(t===" "||t==="\xA0")}function $v(e,t){let r=[];for(let n=0;n<=e.length-t.length;n+=1){let o=!0;for(let a=0;a<t.length;a+=1){let i=e[n+a],l=t[a];if(i!==l&&!ca(i,l)){o=!1;break}}o&&r.push(n)}return r}function Dv(e,t){let r=Fv(e,t);return r.length>0?{offsets:r,matchMode:"exact"}:{offsets:$v(e,t),matchMode:"space_equivalent"}}function Uv(e,t,r){let n=r.split(""),o=0;for(;o<t.length&&o<r.length&&(t[o]===r[o]||ca(t[o],r[o]));)ca(e[o],r[o])&&(n[o]=e[o]),o+=1;let a=t.length-1,i=r.length-1;for(;a>=o&&i>=o&&(t[a]===r[i]||ca(t[a],r[i]));)ca(e[a],r[i])&&(n[i]=e[a]),a-=1,i-=1;return n.join("")}function zv(e,t,r){let n=Math.max(0,t-40),o=Math.min(e.length,t+r+40);return{start:t,end:t+r,excerpt:e.slice(n,o)}}function gd(e,t,r,n=120){let o=String(e??""),a=Math.max(0,Math.min(o.length,t)),i=Math.max(a,Math.min(o.length,r)),l=Math.floor((a+i)/2),s=Math.max(0,l-Math.floor(n/2)),c=Math.min(o.length,s+n);s=Math.max(0,c-n);let f=s>0?"\u2026":"",u=c<o.length?"\u2026":"",d=Math.max(0,n-f.length-u.length);return`${f}${o.slice(s,s+d)}${u}`}function Ni(e,t="replacements",{invalidCode:r="INVALID_OPERATION"}={}){if(!Array.isArray(e)||e.length===0)return{ok:!1,error:In("replacements must be a non-empty array.",t,r)};let n=[];for(let o=0;o<e.length;o+=1){let a=e[o],i=`${t}[${o}]`;if(!a||typeof a!="object"||Array.isArray(a))return{ok:!1,error:In(`${i} must be an object.`,i,r)};if(typeof a.find!="string"||a.find.length===0)return{ok:!1,error:In(`${i}.find must be a non-empty string.`,`${i}.find`,r)};if(typeof a.replace!="string")return{ok:!1,error:In(`${i}.replace must be a string.`,`${i}.replace`,r)};if(a.find===a.replace)return{ok:!1,error:In(`${i} must change the matched text.`,i,r)};let l=a.occurrence==null?null:Number(a.occurrence);if(l!=null&&(!Number.isInteger(l)||l<1))return{ok:!1,error:In(`${i}.occurrence must be a positive integer.`,`${i}.occurrence`,r)};n.push({find:a.find,replace:a.replace,...l==null?{}:{occurrence:l}})}return{ok:!0,replacements:n}}function hd(e,t,r="replacements",n={}){let o=n.invalidCode||"INVALID_OPERATION";if(typeof e!="string")return{ok:!1,error:In("Localized replacements require string source text.",r,o)};let a=Ni(t,r,{invalidCode:o});if(!a.ok)return a;let i=[];for(let f=0;f<a.replacements.length;f+=1){let u=a.replacements[f],d=`${r}[${f}]`,m=u.occurrence??null,{offsets:p,matchMode:g}=Dv(e,u.find);if(p.length===0||m!=null&&m>p.length)return{ok:!1,error:Ii("PATCH_SOURCE_NOT_FOUND",m==null?`Patch source was not found: "${u.find}".`:`Occurrence ${m} of patch source was not found: "${u.find}".`,d,"change_patch",{matchCount:p.length})};if(m==null&&p.length>1)return{ok:!1,error:Ii("AMBIGUOUS_PATCH_SOURCE",`Patch source matched ${p.length} locations; provide occurrence.`,d,"choose_occurrence",{candidates:p.map(w=>zv(e,w,u.find.length))})};let h=p[(m||1)-1],v=e.slice(h,h+u.find.length);i.push({requestIndex:f,start:h,end:h+u.find.length,find:u.find,replace:u.replace,effectiveReplace:g==="space_equivalent"?Uv(v,u.find,u.replace):u.replace,matchMode:g,occurrence:m||1})}i.sort((f,u)=>f.start-u.start||f.end-u.end||f.requestIndex-u.requestIndex);let l=[];for(let f of i){let u=l.at(-1);if(u&&f.start===u.start&&f.end===u.end){if(f.effectiveReplace!==u.effectiveReplace)return{ok:!1,error:Ii("CONFLICTING_PATCHES",`Localized replacements ${u.requestIndex+1} and ${f.requestIndex+1} assign different text to the same source range.`,r,"combine_patches",{replacementIndexes:[u.requestIndex+1,f.requestIndex+1]})};continue}if(u&&f.start<u.end)return{ok:!1,error:Ii("OVERLAPPING_PATCHES",`Localized replacements ${u.requestIndex+1} and ${f.requestIndex+1} overlap.`,r,"combine_patches",{replacementIndexes:[u.requestIndex+1,f.requestIndex+1]})};l.push(f)}let s=0,c="";for(let f of l)c+=e.slice(s,f.start),c+=f.effectiveReplace,s=f.end;return c+=e.slice(s),{ok:!0,desiredText:c,replacements:l.map(f=>({requestIndex:f.requestIndex+1,start:f.start,end:f.end,find:f.find,replace:f.replace,matchMode:f.matchMode,occurrence:f.occurrence,removedLength:f.end-f.start,insertedLength:f.effectiveReplace.length}))}}function wd(e,t,r={},n=null){if(!e||typeof e!="object")return null;let o=String(e.sourceText??""),a=String(e.desiredText??""),i=Array.isArray(e.replacements)?e.replacements:[],l=0,s=i.map(c=>{let f=c.start+l,u=f+c.replace.length;return l+=c.replace.length-(c.end-c.start),{find:c.find,replace:c.replace,...c.matchMode==="space_equivalent"?{matchMode:c.matchMode}:{},occurrence:c.occurrence,beforeExcerpt:gd(o,c.start,c.end),afterExcerpt:gd(a,f,u)}});return{kind:"localized_replacement",committed:!0,finalDisposition:"applied",target:{...r.paragraphId?{paragraphId:r.paragraphId}:{},...Number.isInteger(r.index)?{index:r.index}:{},...r.fingerprint?{fingerprint:r.fingerprint}:{},...n?.humanReference?{humanReference:n.humanReference}:{}},...n?{context:{...n}}:{},replacements:s,verification:{acceptedViewMatchesCompiledText:typeof t=="string"&&t===a}}}var vd=Object.freeze(["convert-plain","change-format","join"]),yd=Object.freeze(["decimal","upperLetter","lowerLetter","upperRoman","lowerRoman","bullet"]),Xv=Object.freeze(["marker","none"]),Vv=Object.freeze(["list","range"]),Nl=Object.freeze({"convert-plain":Object.freeze(["mode","kind","format","start","level","strip"]),"change-format":Object.freeze(["mode","kind","format","lvlText","start","level","scope"]),join:Object.freeze(["mode","continueFrom","scope"])}),xd=Object.freeze(["materializeMarker"]),jv=new Set([...Object.values(Nl).flat(),...xd]),Id="LIST_MARKER_NOT_FOUND",Nd="LIST_MARKER_AMBIGUOUS",ua="LIST_MARKER_UNSUPPORTED",Td="LIST_FORMAT_TARGET_IS_LIST",Ti="LIST_FORMAT_STYLE_NUMBERED",Sd="LIST_FORMAT_TARGET_NOT_LIST",Si="LIST_FORMAT_MIXED_RANGE",Ad="LIST_FORMAT_STYLE_LINKED",uo="LIST_FORMAT_SPLIT_UNSUPPORTED",Nn="LIST_FORMAT_DEFINITION_UNSUPPORTED",Ai="LIST_FORMAT_JOIN_INVALID",Ed="LIST_FORMAT_UNCHANGED",Wv="\u2022\\-*\u2013\xB7\u25AA\u25E6",jr="[ \\t\\u00a0]",Kv=new RegExp(`^(${jr}*)(?:(\\d{1,3})|([A-Za-z]{1,7}))([.)])(${jr}+)(?=\\S)`),Gv=new RegExp(`^(${jr}*)([${Wv}])(${jr}+)(?=\\S)`),Hv=new RegExp(`^${jr}*\\d+(?:\\.\\d+)+\\.?${jr}+\\S`),qv=new RegExp(`^${jr}*\\((?:\\d{1,3}|[A-Za-z]{1,7})\\)${jr}+\\S`),Yv=/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,bd={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3};function Rd(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var Ye=(e,t)=>({message:e,field:t});function Jv(e){return e.format!=null&&!yd.includes(e.format)?Ye(`list.format must be one of: ${yd.join(", ")}.`,"list.format"):e.kind!=null&&e.kind!=="bullet"&&e.kind!=="numbered"?Ye('list.kind must be "bullet" or "numbered".',"list.kind"):e.kind!=null&&e.format!=null&&e.kind==="bullet"!=(e.format==="bullet")?Ye(`list.kind "${e.kind}" contradicts list.format "${e.format}".`,"list.kind"):e.level!=null&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=8)?Ye("list.level must be an integer from 0 to 8.","list.level"):null}function Tl(e,{bullet:t=!1,level:r=null}={}){if(typeof e!="string"||e.length<1||e.length>32)return"list.lvlText must be a string of 1 to 32 characters.";let n=e.match(/%./g)||[];if(t)return e.includes("%")||e.length>4?"A bullet list.lvlText is the bullet itself: 1 to 4 characters without % placeholders.":null;if(n.length===0)return'A numbered list.lvlText needs a %1..%9 placeholder (for example "%1." or "(%1)").';if(n.some(o=>!/^%[1-9]$/.test(o)))return"list.lvlText placeholders must be %1 to %9.";if(r!=null){if(!n.includes(`%${r+1}`))return`list.lvlText for level ${r} must contain its own placeholder %${r+1}.`;if(n.some(o=>Number(o.slice(1))>r+1))return`list.lvlText for level ${r} cannot reference a deeper level than %${r+1}.`}return null}function Zv(e){return Rd(e)?["paragraphId","fingerprint","exactText","text"].some(r=>typeof e[r]=="string"&&e[r].trim())?e.captureRef!=null||e.occurrence!=null||e.revisionView!=null&&e.revisionView!=="accepted"?Ye("list.continueFrom targets a batch-start accepted-view paragraph (no captureRef, occurrence or rejected view).","list.continueFrom"):null:Ye("list.continueFrom needs paragraphId, fingerprint or exactText.","list.continueFrom"):Ye("join needs list.continueFrom: a paragraph target { paragraphId, fingerprint?, exactText? } of an item of the list to continue.","list.continueFrom")}function Pd(e){if(!Rd(e))return Ye('list-format operations require a "list" object.',"list");let t=Object.keys(e).filter(i=>!jv.has(i));if(t.length>0)return Ye(`list has unsupported ${t.length===1?"key":"keys"}: ${t.join(", ")}.`,`list.${t[0]}`);let r=Object.keys(e).filter(i=>xd.includes(i));if(r.length>0)return Ye(`list.${r[0]} is not supported yet (detach is a later release).`,`list.${r[0]}`);if(!vd.includes(e.mode))return Ye(`list.mode must be one of: ${vd.join(", ")} (detach is not available yet).`,"list.mode");let n=Object.keys(e).filter(i=>!Nl[e.mode].includes(i));if(n.length>0)return Ye(`list.${n[0]} does not apply to mode "${e.mode}" (it accepts: ${Nl[e.mode].filter(i=>i!=="mode").join(", ")}).`,`list.${n[0]}`);if(e.scope!=null&&!Vv.includes(e.scope))return Ye(`list.scope must be "list" (every paragraph of the target's list) or "range" (only the target range).`,"list.scope");let o=Jv(e);if(o)return o;if(e.mode==="join")return Zv(e.continueFrom);if(e.mode==="change-format"){if(e.format==null&&e.kind==null&&e.lvlText==null&&e.start==null)return Ye("change-format needs at least one of list.format, list.kind, list.lvlText or list.start.","list.format");if(e.kind==="numbered"&&e.format==null)return Ye('kind "numbered" does not say which numbering format; pass list.format (decimal, upperLetter, lowerLetter, upperRoman or lowerRoman).',"list.format");if(e.lvlText!=null){let i=(e.format??(e.kind==="bullet"?"bullet":null))==="bullet",l=Tl(e.lvlText,{bullet:i,level:Number.isInteger(e.level)?e.level:null});if(l)return Ye(l,"list.lvlText")}if(e.start!=null){if(!(Number.isInteger(e.start)&&e.start>=1&&e.start<=32767))return Ye("list.start must be an integer from 1 to 32767.","list.start");if(e.scope==="range")return Ye('scope "range" continues the source count across the split; list.start applies to scope "list" only.',"list.start")}return null}if(e.strip!=null&&!Xv.includes(e.strip))return{message:'list.strip must be "marker" or "none".',field:"list.strip"};let a=e.strip||"marker";if(e.start!=null){if(a==="marker")return{message:'list.start is derived from the typed marker when strip is "marker"; omit it, or use strip: "none".',field:"list.start"};if(!(Number.isInteger(e.start)&&e.start>=1&&e.start<=32767))return{message:"list.start must be an integer from 1 to 32767.",field:"list.start"}}return a==="none"&&e.format==null&&e.kind!=="bullet"?{message:'strip: "none" leaves the text alone, so list.format (or kind: "bullet") must state the list format.',field:"list.format"}:null}function Sl(e){let t=e.format||(e.kind==="bullet"?"bullet":null);return{mode:e.mode,format:t,kind:t?t==="bullet"?"bullet":"numbered":e.kind||null,level:Number.isInteger(e.level)?e.level:0,explicitLevel:Number.isInteger(e.level)?e.level:null,strip:e.strip||"marker",start:Number.isInteger(e.start)?e.start:null,lvlText:typeof e.lvlText=="string"?e.lvlText:null,scope:e.scope||"list",continueFrom:e.continueFrom??null}}function Qv(e){let t=e.toUpperCase();if(!t||!Yv.test(t))return null;let r=0;for(let n=0;n<t.length;n+=1){let o=bd[t[n]],a=bd[t[n+1]]||0;r+=o<a?-o:o}return r}function fo(e){let t=String(e??"");if(Hv.test(t))return{unsupported:"multilevel",marker:t.trim().split(/\s/)[0]};if(qv.test(t))return{unsupported:"parenthesized",marker:t.trim().split(/\s/)[0]};let r=Gv.exec(t);if(r)return{marker:r[2],terminator:"",bulletChar:r[2],prefixLength:r[0].length,candidates:[{format:"bullet",value:null}]};let n=Kv.exec(t);if(!n)return null;let[o,,a,i,l]=n,s=`${a??i}${l}`,c={marker:s,terminator:l,prefixLength:o.length};if(a!=null){let p=Number.parseInt(a,10);return p<1?{unsupported:"zero",marker:s}:{...c,candidates:[{format:"decimal",value:p}]}}let f=i===i.toUpperCase(),u=i===i.toLowerCase();if(!f&&!u)return null;let d=[];i.length===1&&d.push({format:f?"upperLetter":"lowerLetter",value:i.toLowerCase().charCodeAt(0)-96});let m=Qv(i);return m!=null&&d.push({format:f?"upperRoman":"lowerRoman",value:m}),d.length===0?null:{...c,candidates:d}}function Cd(e,t=null){if(e.length===0)return{error:{reason:"none"}};let r=new Set(e.map(i=>i.terminator)),n=new Set(e.filter(i=>i.bulletChar).map(i=>i.bulletChar));if(r.size>1||n.size>1)return{error:{reason:"mixed",markers:e.map(i=>i.marker)}};if(t){let i=e.find(l=>!l.candidates.some(s=>s.format===t));return i?{error:{reason:"format-mismatch",marker:i.marker,requestedFormat:t}}:{format:t}}let o=e[0].candidates.map(i=>i.format);for(let i of e.slice(1)){let l=i.candidates.map(s=>s.format);o=o.filter(s=>l.includes(s))}if(o.length===0)return{error:{reason:"mixed",markers:e.map(i=>i.marker)}};if(o.length===1)return{format:o[0]};let a=o.filter(i=>{if(e.length<2)return!1;let l=e.map(s=>s.candidates.find(c=>c.format===i).value);return l.every((s,c)=>c===0||s===l[c-1]+1)});return a.length===1?{format:a[0]}:{error:{reason:"ambiguous",marker:e[0].marker,formats:o}}}function _d(e,t){return e.candidates.find(r=>r.format===t)?.value??null}function Od({format:e,level:t,terminator:r=".",bulletChar:n=null}){return e==="bullet"?{ilvl:t,numFmt:"bullet",lvlText:n==="-"||n==="*"||!n?"\u2022":n}:{ilvl:t,numFmt:e,lvlText:`%${t+1}${r||"."}`}}function kd({format:e,level:t,terminator:r="",bulletChar:n=null}){return`list-format:${e}:${t}:${e==="bullet"?n||"":r||"."}`}var ey="LIST_MARKER_NOT_BOUND",ty="UNSUPPORTED_LIST_CONVERSION",ry="LIST_FORMAT_NOT_APPLIED",ny="UNSUPPORTED_LIST_FORMAT_CHANGE",oy="UNKNOWN_PARAGRAPH_FORMAT_PROPERTY";var Ld="PARAGRAPH_NUMBERING_NOT_FOUND",Bd="PARAGRAPH_FORMAT_REVISION_CONFLICT",mo=Object.freeze(["alignment","keepNext","keepLines","pageBreakBefore","style","numbering"]),ay=Object.freeze({bullet:"bullet",decimal:"decimal",lowerAlpha:"lowerLetter",upperAlpha:"upperLetter",lowerRoman:"lowerRoman",upperRoman:"upperRoman"}),Al=new Set(["bullet","decimal","lowerLetter","upperLetter","lowerRoman","upperRoman"]);function iy(e){return e==="literal"}function El(e={}){return iy(e.listMarkers)?"off":(e.strictListConversion!==void 0?e.strictListConversion===!0:e.atomic===!0)?"error":"warn"}function Fd(e,t=80){let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r}function Ei(e){let t=String(e??"");if(!t.trim()||/[\r\n]/.test(t))return null;let r=qr(t,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});return!r||!r.marker||r.markerType!=="bullet"&&!/[.)]$/.test(r.marker)?null:{marker:r.marker,kind:r.markerType==="bullet"?"bullet":"numbered",numberingStyle:r.numberingStyle,numFmt:ay[r.numberingStyle]||"decimal",text:String(r.text||"").trim()}}function $d({originalText:e,modifiedText:t,targetIsListItem:r}){if(r)return null;let n=Ei(t);if(!n)return null;let o=Ei(e);return o&&o.kind===n.kind&&o.numFmt===n.numFmt?null:n}function sy(e,t){if(t)return null;let r=e.numFmt==="bullet"?"bullet":e.numFmt,n={mode:"convert-plain",format:r,strip:"none"};if(r!=="bullet"){let a=fo(`${e.marker} x`)?.candidates?.find(i=>i.format===r)?.value;Number.isInteger(a)&&a>1&&(n.start=a)}return{type:"list-format",list:n}}function Dd(e,{policy:t,targetText:r,operationIndex:n}={}){let o=t==="error",a=o?ty:ey,i=o?`Converting a plain paragraph to a list item is not supported by text edits: the new text begins with the list marker "${e.marker}", which would be written as literal text with no list binding. Use a list-format convert-plain operation on the paragraph (capability list-format-v1), or pass listMarkers: "literal" to keep the marker as text.`:`Modified text begins with the list marker "${e.marker}", but the marker was written as literal text; no list binding was created. A list-format convert-plain operation creates the list binding.`,l=sy(e,!!Ei(r));return{code:a,severity:o?"error":"warning",message:i,listMarker:e.marker,requestedList:{kind:e.kind,format:e.numFmt},...r?{targetExcerpt:Fd(r)}:{},...Number.isInteger(n)?{operationIndex:n}:{},recovery:{action:"use_list_format_convert_plain",hint:l?'Keep the paragraph text as it is and send a list-format operation on the same target (recovery.suggestedOperation plus your target), or pass listMarkers: "literal" to write the marker as text intentionally.':'Edit the text with a redline that starts with the typed marker, then convert it with a list-format convert-plain operation (strip: "marker"), or pass listMarkers: "literal" to write the marker as text intentionally.',...l?{suggestedOperation:l}:{},field:"listMarkers",allowedValue:"literal"}}}function ly(e,t,r){let n=d=>Array.from(e.getElementsByTagNameNS("*",d)),o=(d,m)=>d?.getAttribute?.(`w:${m}`)??d?.getAttribute?.(m)??null,a=(d,m)=>Array.from(d?.childNodes||[]).find(p=>p.nodeType===1&&p.localName===m)||null,i=n("num").find(d=>String(o(d,"numId"))===String(t));if(!i)return null;let l=Array.from(i.childNodes).filter(d=>d.nodeType===1&&d.localName==="lvlOverride").find(d=>Number(o(d,"ilvl")||0)===r),s=o(a(a(l,"lvl"),"numFmt"),"val");if(s)return{numFmt:s};let c=o(a(i,"abstractNumId"),"val"),f=n("abstractNum").find(d=>String(o(d,"abstractNumId"))===String(c));if(!f)return null;let u=Array.from(f.childNodes).filter(d=>d.nodeType===1&&d.localName==="lvl").find(d=>Number(o(d,"ilvl")||0)===r);return u?{numFmt:o(a(u,"numFmt"),"val")||"decimal"}:null}function cy(e,t,r=0){if(!String(e||"").trim()||t==null)return null;let n=j(String(e));if(!n?.doc)return null;let o=ly(n.doc,t,Number(r)||0);return o?{numFmt:o.numFmt,kind:o.numFmt==="bullet"?"bullet":"numbered"}:null}function uy({requested:e,sourceLevel:t}){if(!e||!t)return null;let r=e.kind==="bullet"?"bullet":"numbered";return r!==t.kind?{requested:e,source:t}:r==="numbered"&&Al.has(e.numFmt)&&Al.has(t.numFmt)&&e.numFmt!==t.numFmt?{requested:e,source:t}:null}function Ud(e,{policy:t,numId:r,level:n,marker:o,targetText:a,operationIndex:i}={}){let l=t==="error",s=l?ny:ry,c=(p,g)=>p==="bullet"?"a bullet list":`a numbered list${g?` (${g})`:""}`,f=e.requested.kind==="bullet"?"bullet":e.requested.numFmt||e.requested.format,u=c(e.requested.kind,f),d=c(e.source.kind,e.source.numFmt),m=Al.has(f)?{type:"list-format",list:{mode:"change-format",format:f,level:Number(n)||0,scope:"list"}}:null;return{code:s,severity:l?"error":"warning",message:`${l?"Changing the list format is not supported by text edits":"The requested list format was not applied"}: the list item keeps its source numbering definition (numId ${r}, ${d}); the edit asked for ${u}${o?` ("${o}")`:""}. A list-format change-format operation changes the list's format (capability list-format-change-v1).`,requestedList:{kind:e.requested.kind,format:f},sourceList:{numId:String(r),level:Number(n)||0,kind:e.source.kind,format:e.source.numFmt},...a?{targetExcerpt:Fd(a)}:{},...Number.isInteger(i)?{operationIndex:i}:{},recovery:{action:"use_list_format_change_format",hint:m?`Text edits cannot change a list's kind or numbering format. Send recovery.suggestedOperation with a target on one item of the list as its own operation (scope "list" rebinds every item; scope "range" only a range that runs to the end of the list). Make any text edit in a separate redline without the new markers, targeting a different paragraph or a separate call. Or pass listMarkers: "literal" to accept the current result.`:`Text edits cannot change a list's kind or numbering format. Use a list-format change-format operation, or pass listMarkers: "literal" to accept the current result.`,...m?{suggestedOperation:m}:{},field:"listMarkers",allowedValue:"literal"}}}function zd(e){if(e===null)return null;if(typeof e!="object"||Array.isArray(e))return"numbering must be null (remove the list binding) or an object { numId, level }.";let t=Object.keys(e).filter(a=>a!=="numId"&&a!=="level");if(t.length>0)return`numbering has unsupported ${t.length===1?"key":"keys"}: ${t.join(", ")}. Use only numId and level.`;let r=e.numId;if(!(Number.isInteger(r)&&r>=1||typeof r=="string"&&/^[1-9]\d*$/.test(r)))return"numbering.numId must be a positive integer (numId 0 is not a list; pass numbering: null to remove the binding).";let o=e.level;return o!==void 0&&!(Number.isInteger(o)&&o>=0&&o<=8)?"numbering.level must be an integer from 0 to 8.":null}function Ri(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>!mo.includes(t))}function Xd(e){let t=e.map(r=>`"${r}"`).join(", ");return{code:oy,severity:"warning",message:`paragraph-format ignored unsupported ${e.length===1?"property":"properties"} ${t}. Supported: ${mo.join(", ")}.`,properties:e,recovery:{action:"change_request",hint:`Use only: ${mo.join(", ")}.`}}}function Rl(e){return`${e.code}: ${e.message}`}function Md(e){return String(e??"").replace(/[\s\u00a0]+/g," ").trim()}function Vd({modifiedText:e,sourceItems:t,sourceNumberingXml:r}){if(!Array.isArray(t)||t.length===0)return null;let o=String(e??"").split(/\r?\n/).filter(i=>i.trim()).map(i=>({line:i,item:Ei(i)})),a=new Set;for(let i of t){let l=Md(i.text),s=o.find((u,d)=>!a.has(d)&&Md(u.item?u.item.text:u.line)===l);if(!s||(a.add(o.indexOf(s)),!s.item))continue;let c=cy(r,i.numId,i.ilvl),f=uy({requested:s.item,sourceLevel:c});if(f)return{mismatch:f,marker:s.item.marker,numId:i.numId,level:i.ilvl,targetText:i.text}}return null}var fy=new Set(["redline","replace","format","character-format","paragraph-format","list-format","list-change","table-reconciliation","insert","restore","delete","comment","comment_reply","comment_resolve","highlight"]),jd=Object.freeze(["auto","merge-same-author","slice-cross-author","reject-input","accept-all-first","accept-all-first-keep-normalized"]);function fa(e){return jd.includes(e)}function Yt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Re(e){return typeof e=="string"&&e.trim().length>0}function dy(e){return e==="comment_reply"||e==="comment_resolve"}function my(e){let t=e?.type;return t==="insert"&&e?.target?.revisionView==="rejected"?"rejected-insert":t==="restore"?"restore":t==="comment"||t==="comment_reply"||t==="comment_resolve"||t==="highlight"?t:t==="paragraph-format"?"paragraph-format":t==="list-format"?"list-format":t==="character-format"||t==="format"&&(e?.textToFormat!=null||e?.properties!=null)?"format":"redline"}function Tn(e,t=null,r="accepted"){let n=r==="rejected"?"rejected":"accepted";return Yt(e)?{text:typeof e.exactText=="string"?e.exactText:typeof e.text=="string"?e.text:"",index:e.index??e.paragraphIndex??t??null,paragraphId:Re(e.paragraphId)?e.paragraphId.trim():null,occurrence:Number.isInteger(e.occurrence)&&e.occurrence>0?e.occurrence:null,inTable:typeof e.inTable=="boolean"?e.inTable:null,fingerprint:Re(e.fingerprint)?e.fingerprint.trim():Re(e.sourceFingerprint)?e.sourceFingerprint.trim():null,revisionView:e.revisionView==="rejected"?"rejected":e.revisionView==="accepted"?"accepted":n,captureRef:Re(e.captureRef)?e.captureRef.trim():null,select:typeof e.select=="string"?e.select:null}:{text:typeof e=="string"?e:"",index:t??null,paragraphId:null,occurrence:null,inTable:null,fingerprint:null,revisionView:n}}function St(e){let t=Yt(e)?e:{},r=my(t),n=r==="restore"?"rejected":"accepted",o=Tn(t.target,t.targetRef,n),a=t.targetEnd!=null?Tn(t.targetEnd,t.targetEndRef,n):null;return{...t,operationId:Re(t.operationId)?t.operationId.trim():null,captureKey:Re(t.captureKey)?t.captureKey.trim():null,operationKind:r,anchor:Yt(t.anchor)?{exactText:typeof t.anchor.exactText=="string"?t.anchor.exactText:"",occurrence:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0?t.anchor.occurrence:1,occurrenceExplicit:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0,offset:Number.isInteger(t.anchor.offset)?t.anchor.offset:null}:null,targetDescriptor:o,targetEndDescriptor:a,target:o.text,targetRef:o.index,targetEndRef:a?.index??t.targetEndRef??null,...t.type==="delete"&&t.modified==null?{modified:""}:{}}}function Nr(e){if(!Yt(e))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation must be an object."}};let t=e.type;if(t!=null&&t!==""&&!fy.has(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:`Unsupported operation type: "${String(t)}".`}};let r=St(e);if(Yt(e.target)&&e.target.revisionView!=null&&e.target.revisionView!=="accepted"&&e.target.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(Yt(e.targetEnd)&&e.targetEnd.revisionView!=null&&e.targetEnd.revisionView!=="accepted"&&e.targetEnd.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(e.operationId!=null&&(!Re(e.operationId)||e.operationId.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"operationId must be a non-empty string under 256 characters when provided."}};if(e.captureKey!=null&&(!Re(e.captureKey)||e.captureKey.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"captureKey must be a non-empty string under 256 characters when provided."}};if(Yt(e.target)&&e.target.captureRef!=null&&(!Re(e.target.captureRef)||e.target.captureRef.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.captureRef must be a non-empty string under 256 characters when provided."}};if(Yt(e.target)&&e.target.select!=null&&typeof e.target.select!="string")return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.select must be a string when provided."}};let n=r.targetDescriptor;if(!dy(r.operationKind)&&!Re(n.text)&&n.index==null&&!n.paragraphId&&!n.fingerprint&&!n.captureRef)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation target must provide text, a paragraph index, a paragraphId, or a captureRef."}};if(n.occurrence!=null&&!Re(n.text))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Target occurrence requires target text."}};if(r.operationKind==="redline"){let o=typeof r.modified=="string",a=r.replacements!==void 0;if(o===a)return{valid:!1,error:{code:"INVALID_OPERATION",message:'Redline operations require exactly one of string "modified" or non-empty "replacements".'}};if(a){if(t!=null&&t!==""&&!["redline","replace"].includes(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements are supported only for redline or replace operations."}};if(n.revisionView!=="accepted"||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 require one batch-start accepted-view paragraph target without captures, target occurrence, or a target range."}};let i=Ni(r.replacements);if(!i.ok)return{valid:!1,error:i.error};if(i.replacements.some(l=>/\r|\n/.test(l.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 cannot insert paragraph breaks."}};if(i.replacements.some(l=>/\r|\n/.test(l.find)))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Localized replacements v1 cannot span a line break; use one replacement per line or a full "modified" paragraph.'}};r.replacements=i.replacements}}if(r.operationKind==="rejected-insert"){if(!Re(r.modified))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require non-empty string "modified" text.'}};if(!r.anchor||!Re(r.anchor.exactText)||!Number.isInteger(r.anchor.offset)||r.anchor.offset<0||r.anchor.offset>r.anchor.exactText.length)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Rejected-view insert operations require anchor.exactText, a positive occurrence, and an offset within the anchor text."}};if(r.existingRevisions!=="slice-cross-author")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require existingRevisions: "slice-cross-author".'}}}if(r.operationKind==="restore"){let o=e.modified!==void 0,a=e.replacements!==void 0,i=Re(r.modified),l=Array.isArray(r.modified)&&r.modified.length>0&&r.modified.every(Re);if(o&&a)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations accept modified or replacements, not both."}};if(o&&!i&&!l)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore modified must be a non-empty string or non-empty string array."}};if(!o&&(n.revisionView!=="rejected"||!n.paragraphId&&!n.fingerprint||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Verbatim and localized restore require one strong batch-start rejected-view paragraph target without captures, target occurrence, or a target range."}};if(a){let s=Ni(r.replacements);if(!s.ok)return{valid:!1,error:s.error};if(s.replacements.some(c=>/\r|\n/.test(c.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized restore cannot insert paragraph breaks."}};r.replacements=s.replacements}if(r.generateRedlines===!1)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations require tracked changes and cannot set generateRedlines to false."}}}if(r.structuredContent!=null&&typeof r.structuredContent!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"structuredContent must be a boolean when provided."}};if(r.pairReplacements!=null&&typeof r.pairReplacements!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"pairReplacements must be a boolean when provided."}};if(r.listMarkers!=null&&r.listMarkers!=="literal")return{valid:!1,error:{code:"INVALID_OPERATION",message:'listMarkers must be "literal" when provided.'}};if(r.existingRevisions!=null&&!fa(r.existingRevisions))return{valid:!1,error:{code:"INVALID_OPERATION",message:`existingRevisions must be one of: ${jd.join(", ")}.`}};if(r.insertionAffinity!=null){if(!Yt(r.insertionAffinity))return{valid:!1,error:{code:"INVALID_OPERATION",message:"insertionAffinity must be an object when provided."}};let{formatting:o,hyperlink:a,revision:i,bookmark:l,comment:s}=r.insertionAffinity;if(o!=null&&!["left","right","none"].includes(o))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.formatting must be "left", "right", or "none".'}};if(a!=null&&!["inside","outside","preserve"].includes(a))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.hyperlink must be "inside", "outside", or "preserve".'}};if(i!=null&&!["coalesce_same_author","separate"].includes(i))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.revision must be "coalesce_same_author" or "separate".'}};if(l!=null&&!["inside","outside"].includes(l))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.bookmark must be "inside" or "outside".'}};if(s!=null&&!["inside","outside"].includes(s))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.comment must be "inside" or "outside".'}}}if(r.operationKind==="comment"&&!Re(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment operations require a non-empty "commentContent" field.'}};if(r.operationKind==="comment_reply"){if(!Re(String(r.parentCommentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a "parentCommentId".'}};if(!Re(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a non-empty "commentContent" field.'}}}if(r.operationKind==="comment_resolve"){if(!Re(String(r.commentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve operations require a "commentId".'}};if(r.resolved!=null&&typeof r.resolved!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve "resolved" must be a boolean when provided.'}}}if(r.operationKind==="highlight"){if(!Re(r.textToHighlight))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Highlight operations require a non-empty "textToHighlight" field.'}};if(r.color!=null&&!Re(r.color))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Highlight color must be a non-empty string when provided."}}}if(r.operationKind==="format"){if(!Re(r.textToFormat))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a non-empty "textToFormat" field.'}};if(r.textOccurrence!=null&&(!Number.isInteger(r.textOccurrence)||r.textOccurrence<1))return{valid:!1,error:{code:"INVALID_OPERATION",message:"textOccurrence must be a positive integer when provided."}};if(!Yt(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a "properties" object.'}};if(r.formattingRevisionPolicy!=null&&!["always","coalesce-own-insertion"].includes(r.formattingRevisionPolicy))return{valid:!1,error:{code:"INVALID_OPERATION",message:'formattingRevisionPolicy must be "always" or "coalesce-own-insertion".'}}}if(r.operationKind==="paragraph-format"){if(!Yt(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Paragraph-format operations require a "properties" object.'}};let o=Ri(r.properties);if(o.length>0)return{valid:!1,error:{code:"INVALID_OPERATION",message:`paragraph-format does not support ${o.length===1?"property":"properties"} ${o.map(a=>`"${a}"`).join(", ")}. Supported: ${mo.join(", ")}.`,field:`properties.${o[0]}`,properties:o,recovery:{action:"change_request",hint:`Use only: ${mo.join(", ")}.`}}};if(r.properties.numbering!==void 0){let a=zd(r.properties.numbering);if(a)return{valid:!1,error:{code:"INVALID_OPERATION",message:a,field:"properties.numbering",recovery:{action:"change_request",hint:'Pass numbering as { "numId": <existing numId from inspect>, "level": 0 } or null.'}}}}}if(r.operationKind==="list-format"){let o=Pd(r.list);if(o)return{valid:!1,error:{code:"INVALID_OPERATION",message:o.message,field:o.field,recovery:{action:"change_request",hint:'Pass list as { "mode": "convert-plain" } (optional format, kind, level, strip "marker" | "none", start with strip "none"), { "mode": "change-format", "format": ... } (optional kind, lvlText, start, level, scope "list" | "range") or { "mode": "join", "continueFrom": { "paragraphId": ... } } (optional scope).'}}};if(e.modified!==void 0||e.replacements!==void 0)return{valid:!1,error:{code:"INVALID_OPERATION",message:"list-format changes list structure only; express text changes as a separate redline operation.",field:e.modified!==void 0?"modified":"replacements"}};if(n.captureRef||n.occurrence!=null||n.revisionView!=="accepted")return{valid:!1,error:{code:"INVALID_OPERATION",message:"list-format v1 targets batch-start accepted-view paragraphs without captures or target occurrence."}}}return r.author!=null&&!Re(r.author)?{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation author must be a non-empty string when provided."}}:{valid:!0,operation:r}}function Ut(e,t,r){return Re(e?.author)?e.author.trim():Re(t)?t.trim():Re(r)?r.trim():"Author"}var Wr=class{constructor(t,r={}){if(this.originalDocumentXml=typeof t=="string"?t:"",this.currentDocumentXml=this.originalDocumentXml,this.serializer=le(),this.parseResult=j(this.originalDocumentXml,"application/xml"),this.document=this.parseResult.doc||null,this.revisionIdAllocator=null,this.initialTargetReferenceSnapshot=null,this.paragraphIndex=null,this.invalidated=!1,this.hasChanges=!1,this.documentHasChanges=!1,this.deferSerialization=r?._deferDocumentSerialization===!0,this.instrumentation=r?._sessionInstrumentation||null,this.runtimeContext=null,this.commentsXml=null,this.commentsExtendedXml=null,this.commentsXmlMode="merge",this.commentsExtendedXmlMode="merge",this.numberingXmlParts=[],this.results=[],this.executionOrder=[],this.authorsUsed=new Set,this.captureTable=new Map,this.sourceTargetRegistry=null,this.nextCaptureParaId=1,this.receiptCollector=new sa,this.document){this.instrumentation?.onDocumentParse?.(this.originalDocumentXml),this.revisionIdAllocator=r?._revisionIdAllocator instanceof De?r._revisionIdAllocator:new De,this.revisionIdAllocator._receiptCollector=this.receiptCollector,cr(this.document,this.revisionIdAllocator),Cr(this.document,this.revisionIdAllocator);let n=this.getParagraphMetadataIndex();this.initialTargetReferenceSnapshot=$s(this.document,n)}}get valid(){return!!this.document&&!this.parseResult.error}setDocumentXml(t){this.currentDocumentXml=t,this.invalidateParagraphIndex()}invalidateParagraphIndex(){this.invalidated=!0,this.paragraphIndex=null}serialize(){return this.document?(this.instrumentation?.onDocumentSerialize?.(this.document),this.serializer.serializeToString(this.document)):this.currentDocumentXml}serializeCurrent(){return this.hasChanges?this.documentHasChanges?(this.currentDocumentXml=this.serialize(),this.currentDocumentXml):this.currentDocumentXml:this.originalDocumentXml}markMutationCommitted(t=!0){this.hasChanges=!0,this.documentHasChanges=this.documentHasChanges||t,t&&this.invalidateParagraphIndex()}generateParagraphId(){return(1073741824+this.nextCaptureParaId++).toString(16).toUpperCase()}createSavepoint(){return this.document?{document:this.document.cloneNode(!0),allocatorNextId:this.revisionIdAllocator?.nextId,allocatorOccupiedIds:this.revisionIdAllocator?.occupiedIds instanceof Set?new Set(this.revisionIdAllocator.occupiedIds):null,hasChanges:this.hasChanges,documentHasChanges:this.documentHasChanges,currentDocumentXml:this.currentDocumentXml,commentsXml:this.commentsXml,commentsExtendedXml:this.commentsExtendedXml,commentsXmlMode:this.commentsXmlMode,commentsExtendedXmlMode:this.commentsExtendedXmlMode,captureTable:Wd(this.captureTable),sourceTargetRegistry:this.sourceTargetRegistry?.createSavepoint?.(this.document)||null,nextCaptureParaId:this.nextCaptureParaId,receiptCollector:this.receiptCollector?this.receiptCollector.createSavepoint():null}:null}restoreSavepoint(t){t?.document&&(this.document=t.document,this.hasChanges=t.hasChanges,this.documentHasChanges=t.documentHasChanges===!0,this.currentDocumentXml=t.currentDocumentXml,this.commentsXml=t.commentsXml,this.commentsExtendedXml=t.commentsExtendedXml,this.commentsXmlMode=t.commentsXmlMode||"merge",this.commentsExtendedXmlMode=t.commentsExtendedXmlMode||"merge",this.captureTable=t.captureTable?Wd(t.captureTable):new Map,this.sourceTargetRegistry?.restoreSavepoint?.(this.document,t.sourceTargetRegistry),typeof t.nextCaptureParaId=="number"&&(this.nextCaptureParaId=t.nextCaptureParaId),this.revisionIdAllocator&&(this.revisionIdAllocator.nextId=t.allocatorNextId,t.allocatorOccupiedIds instanceof Set&&(this.revisionIdAllocator.occupiedIds=new Set(t.allocatorOccupiedIds)),this.revisionIdAllocator._receiptCollector=this.receiptCollector,Cr(this.document,this.revisionIdAllocator)),t.receiptCollector&&this.receiptCollector&&this.receiptCollector.restoreSavepoint(t.receiptCollector),this.invalidateParagraphIndex())}getParagraphIndex(){return this.getParagraphMetadataIndex().entries}getParagraphMetadataIndex(){return this.paragraphIndex?this.paragraphIndex:(this.paragraphIndex=rr(this.document),this.invalidated=!1,this.paragraphIndex)}rollback(){return this.currentDocumentXml=this.originalDocumentXml,this.hasChanges=!1,this.documentHasChanges=!1,this.captureTable.clear(),this.sourceTargetRegistry=null,this.receiptCollector?.clear(),this.originalDocumentXml}};function Wd(e){let t=new Map;if(e instanceof Map)for(let[r,n]of e.entries())t.set(r,JSON.parse(JSON.stringify(n)));return t}function Sn(e,t={}){let r=t?._revisionIdAllocator instanceof De?t._revisionIdAllocator:new De;return t?._documentOperationSession?.receiptCollector&&(r._receiptCollector=t._documentOperationSession.receiptCollector),cr(e,r),Cr(e,r),r}function Kd(e){if(!e||typeof e!="object")return{};let t={...e};return e.listFallbackSharedNumIdByKey instanceof Map&&(t.listFallbackSharedNumIdByKey=new Map(e.listFallbackSharedNumIdByKey)),e.tableStructuralRedlineKeys instanceof Set&&(t.tableStructuralRedlineKeys=new Set(e.tableStructuralRedlineKeys)),e.numberingIdState&&typeof e.numberingIdState=="object"&&(t.numberingIdState={...e.numberingIdState,usedNumIds:e.numberingIdState.usedNumIds instanceof Set?new Set(e.numberingIdState.usedNumIds):e.numberingIdState.usedNumIds,usedAbstractNumIds:e.numberingIdState.usedAbstractNumIds instanceof Set?new Set(e.numberingIdState.usedAbstractNumIds):e.numberingIdState.usedAbstractNumIds}),e.listFallbackSequenceState&&typeof e.listFallbackSequenceState=="object"&&(t.listFallbackSequenceState={...e.listFallbackSequenceState,explicitByNumberingKey:e.listFallbackSequenceState.explicitByNumberingKey instanceof Map?new Map(e.listFallbackSequenceState.explicitByNumberingKey):e.listFallbackSequenceState.explicitByNumberingKey}),t}function Gd(e,t){if(!(!e||typeof e!="object")){if(e.listFallbackSharedNumIdByKey instanceof Map&&t.listFallbackSharedNumIdByKey instanceof Map){e.listFallbackSharedNumIdByKey.clear();for(let r of t.listFallbackSharedNumIdByKey)e.listFallbackSharedNumIdByKey.set(...r);t.listFallbackSharedNumIdByKey=e.listFallbackSharedNumIdByKey}if(e.tableStructuralRedlineKeys instanceof Set&&t.tableStructuralRedlineKeys instanceof Set){e.tableStructuralRedlineKeys.clear();for(let r of t.tableStructuralRedlineKeys)e.tableStructuralRedlineKeys.add(r);t.tableStructuralRedlineKeys=e.tableStructuralRedlineKeys}if(e.numberingIdState&&t.numberingIdState){for(let r of["usedNumIds","usedAbstractNumIds"])if(e.numberingIdState[r]instanceof Set&&t.numberingIdState[r]instanceof Set){e.numberingIdState[r].clear();for(let n of t.numberingIdState[r])e.numberingIdState[r].add(n);t.numberingIdState[r]=e.numberingIdState[r]}Object.assign(e.numberingIdState,t.numberingIdState),t.numberingIdState=e.numberingIdState}if(e.listFallbackSequenceState&&t.listFallbackSequenceState){let r=e.listFallbackSequenceState.explicitByNumberingKey,n=t.listFallbackSequenceState.explicitByNumberingKey;if(r instanceof Map&&n instanceof Map){r.clear();for(let o of n)r.set(...o);t.listFallbackSequenceState.explicitByNumberingKey=r}Object.assign(e.listFallbackSequenceState,t.listFallbackSequenceState),t.listFallbackSequenceState=e.listFallbackSequenceState}Object.assign(e,t)}}var Hd=new Set(["redline","restore","rejected-insert","list-format"]),qd=new Set(["highlight","format","paragraph-format"]),py="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Yd="LIST_FORMAT_COMPOSITION_CONFLICT",gy=new Set(["redline","replace"]);function Jd(e){let t=String(e??""),r=fo(t);return r?r.unsupported?`unsupported:${r.marker}`:t.slice(0,r.prefixLength):null}function hy(e,t){let r=e.operation;if(!gy.has(r?.type??"redline")||r.targetEnd!=null||r.targetEndRef!=null||r.anchor!=null||r.structuredContent===!0||r.part!=null||r.target?.revisionView==="rejected"||typeof r.modified!="string"||/[\r\n]/.test(r.modified))return{reason:"redline-shape",hint:"Pair a list-format only with a single-paragraph redline or replace of that paragraph: modified without line breaks, no targetEnd, anchor, part or structuredContent."};if(r.modified===t)return{reason:"redline-unchanged",hint:"The redline does not change the text; drop it and send only the list-format."};let n=Jd(t),o=Jd(r.modified);return n!==o?{reason:"marker-changed",sourceMarker:n,modifiedMarker:o,hint:'The redline adds, removes or changes the typed marker. Keep the marker text exactly as it is (the list-format strips it), and express a new label through list-format (strip "none" with format/start, or change-format).'}:null}function wy(e,t,r,n){let o=n.list?.mode;if(o!=="change-format"&&o!=="join")return[];if((n.list?.scope||"list")!=="list")return[];let a=r.sourceIds.map(l=>t.entries.get(l)?.paragraph).filter(Boolean),i=a.map(l=>Oe(l)).find(Boolean);return i?Array.from(e.getElementsByTagNameNS(py,"p")).filter(l=>a.includes(l)||kt(l)?!1:Oe(l)?.numId===i.numId):[]}function vy(e){let t={};if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="name"||r==="stack"||r==="message"||r==="code"||(t[r]=n);return{code:typeof e?.code=="string"&&e.code?e.code:"OPERATION_ERROR",message:e?.message||String(e),...t}}function yy(e,t){return!!t&&se(e).includes(t)}function by(e=[]){let t=[];for(let r of e)if(!(!r||r.nodeType!==1)){r.localName==="p"&&t.push(r);for(let n of Array.from(r.getElementsByTagNameNS?.("*","p")||[]))t.includes(n)||t.push(n)}return t}var Cl=class{constructor(t){this.document=t,this.nextId=1,this.entries=new Map,this.idsByNode=new WeakMap}register(t,r={}){let n=this.idsByNode.get(t);if(n)return n;let o=`S${this.nextId++}`;return this.entries.set(o,{sourceId:o,paragraph:t,sourceIndex:r.index||null,paragraphId:r.paragraphId||null,fingerprint:r.fingerprint||null,text:r.text||"",revisionView:r.revisionView==="rejected"?"rejected":"accepted",consumed:!1,consumedByOperation:null}),this.idsByNode.set(t,o),o}describe(t){let r=this.entries.get(t);return r?{sourceId:t,index:r.sourceIndex,paragraphId:r.paragraphId,fingerprint:r.fingerprint,text:r.text,revisionView:r.revisionView}:null}resolve(t,r=this.document){let n=this.entries.get(t);return n?n.consumed?{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} was consumed by operation ${n.consumedByOperation}.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:yy(r,n.paragraph)?{paragraph:n.paragraph,resolvedBy:"batch_source"}:{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} is no longer present in the live document.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:{error:{code:"SOURCE_TARGET_NOT_FOUND",message:`Compiled source target ${String(t)} was not found.`}}}createSavepoint(t=this.document){let r=se(t);return new Map(Array.from(this.entries,([n,o])=>[n,{paragraphIndex:r.indexOf(o.paragraph),consumed:o.consumed,consumedByOperation:o.consumedByOperation}]))}restoreSavepoint(t,r){this.document=t,this.idsByNode=new WeakMap;let n=se(t);for(let[o,a]of this.entries){let i=r instanceof Map?r.get(o):null;a.consumed=i?.consumed===!0,a.consumedByOperation=i?.consumedByOperation||null,a.paragraph=Number.isInteger(i?.paragraphIndex)&&i.paragraphIndex>=0&&n[i.paragraphIndex]||null,a.paragraph&&this.idsByNode.set(a.paragraph,o)}}previewSuccessor(t,r,n){let o=this.entries.get(t);if(!o||!o.paragraph)return null;if(!Array.isArray(r)||!r.includes(o.paragraph))return o.paragraph;let a=by(n),i=o.paragraphId?a.filter(l=>He(l)===o.paragraphId):[];return i.length===1?i[0]:a.length===1?a[0]:null}commitMutation(t,r,n,o){let a=this.entries.get(t);if(!a||!Array.isArray(r)||!r.includes(a.paragraph))return;let i=this.previewSuccessor(t,r,n);if(i){a.paragraph=i,this.idsByNode.set(i,t);return}a.paragraph=null,a.consumed=!0,a.consumedByOperation=o}};function xy(e,t){return{index:e.index,paragraphId:e.paragraphId,fingerprint:e.fingerprint,text:e.text,inTable:e.inTable,revisionView:t}}function Pl(e,t,r,n,o,a={}){let i=t?.revisionView==="rejected"?"rejected":"accepted";o[i]||(o[i]=rr(e,{revisionView:i}));let l=o[i],s=ln(e,{targetText:t.text,targetRef:t.index,targetDescriptor:t,opType:r,strictAmbiguity:n,paragraphMetadataIndex:l,metadataIndices:o,onInfo:a.onInfo,onWarn:a.onWarn}),c=l.byParagraph.get(s.paragraph);return{paragraph:s.paragraph,resolvedBy:s.resolvedBy,metadata:xy(c,i)}}function Pi(e,t,r,n,o,a={},i=null){return{code:e,message:t,operationIndexes:r.map(l=>l.index).sort((l,s)=>l-s),target:n,...a,recovery:{action:o,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1,...i?{hint:i}:{}}}}function po(e,t=[],r={}){let n=Array.isArray(t)?t:[],o=r.strictTargets!==!1,a=new Cl(e),i={accepted:rr(e,{revisionView:"accepted"}),rejected:null},l=[],s=[];for(let h=0;h<n.length;h+=1){let v=n[h],w=Nr(v),y=w.operation||St(v),b={index:h+1,operationKind:y.operationKind,operationId:y.operationId,sourceIds:[],warnings:[]},x={...v},S=y.targetDescriptor?.occurrence!=null&&!y.targetDescriptor?.paragraphId&&!y.targetDescriptor?.fingerprint,A=typeof y.targetDescriptor?.text=="string"&&/\r|\n/.test(y.targetDescriptor.text)&&!y.targetEndDescriptor&&!Array.isArray(y.replacements);if((S||A)&&(b.dynamic=!0),w.valid&&y.operationKind!=="comment_reply"&&y.operationKind!=="comment_resolve"&&!y.targetDescriptor?.captureRef&&!b.dynamic)try{let E=Pl(e,y.targetDescriptor,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:T=>b.warnings.push(String(T))}),I=a.register(E.paragraph,E.metadata);if(b.sourceIds.push(I),b.resolvedBy=E.resolvedBy,b.resolvedTarget=E.metadata,x._compiledSourceId=I,x._compiledResolvedBy=E.resolvedBy,b.warnings.length>0&&(x._compiledWarnings=b.warnings),Array.isArray(y.replacements)){let T=hd(E.metadata.text,y.replacements);if(!T.ok)throw Object.assign(new Error(T.error.message),T.error);x.modified=T.desiredText,delete x.replacements,x._localizedReplacementCompilation={sourceText:E.metadata.text,desiredText:T.desiredText,replacements:T.replacements};let N=Nr(x);if(!N.valid)throw Object.assign(new Error(N.error.message),N.error)}else if(y.operationKind==="restore"&&v.modified===void 0){x.modified=E.metadata.text;let T=Nr(x);if(!T.valid)throw Object.assign(new Error(T.error.message),T.error)}let R=y.targetEndDescriptor||(y.targetEndRef!=null?Tn(null,y.targetEndRef,y.targetDescriptor.revisionView):null);if(R){let T=Pl(e,R,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:M=>b.warnings.push(String(M))}),N=a.register(T.paragraph,T.metadata);x._compiledSourceEndId=N;let O=se(e),C=O.indexOf(E.paragraph),P=O.indexOf(T.paragraph);if(C<0||P<C)throw Object.assign(new Error("Target range is not a forward contiguous paragraph range."),{code:"TARGET_RANGE_INVALID"});for(let M of O.slice(C,P+1)){let k=(i[y.targetDescriptor.revisionView]||i.accepted).byParagraph.get(M);b.sourceIds.push(a.register(M,k||{}))}b.sourceIds=[...new Set(b.sourceIds)],b.resolvedTargetEnd=T.metadata}if(y.operationKind==="list-format"&&y.list?.continueFrom&&typeof y.list.continueFrom=="object"){let T;try{T=Pl(e,Tn(y.list.continueFrom,null,"accepted"),y.operationKind,o,i,{onInfo:r.onInfo,onWarn:N=>b.warnings.push(String(N))})}catch(N){throw Object.assign(N instanceof Error?N:new Error(String(N)),{field:"list.continueFrom"})}x._compiledContinueFromId=a.register(T.paragraph,T.metadata),b.resolvedContinueFrom=T.metadata}}catch(E){b.error=vy(E)}l.push(b),s.push(x)}let c=new Set(s.map(h=>h?.captureKey).filter(Boolean)),f=1;for(let h of l){if(h.error?.code!=="TARGET_NOT_FOUND")continue;let v=h.index-1,y=St(n[v]).targetDescriptor?.text;if(!y)continue;let b=n.flatMap((E,I)=>I===v||typeof E?.modified!="string"?[]:E.modified.split(/\r?\n/).map(T=>T.trim()).filter(Boolean).includes(y.trim())?[{candidate:E,producerIndex:I}]:[]);if(b.length!==1)continue;let[{candidate:x,producerIndex:S}]=b,A=x.captureKey||s[S].captureKey;if(!A){do A=`__batch_created_${f++}`;while(c.has(A));c.add(A),s[S].captureKey=A}s[v].target={captureRef:A,select:y},delete s[v]._compiledSourceId,delete s[v]._compiledResolvedBy,delete h.error,h.sourceIds=[],h.resolvedBy="created_content_dependency",h.createdByOperation=S+1,h.captureRef=A}let u=new Map,d=new Map;for(let h of l)if(!(h.error||h.dynamic)){for(let v of h.sourceIds)u.has(v)||u.set(v,[]),u.get(v).push(h);if(h.operationKind==="list-format"){let v=s[h.index-1];for(let w of wy(e,a,h,v)){let y=a.register(w,i.accepted.byParagraph.get(w)||{});h.sourceIds.includes(y)||((h.rebindSourceIds||(h.rebindSourceIds=[])).push(y),u.has(y)||u.set(y,[]),d.has(y)||d.set(y,[]),d.get(y).push(h))}}}let m=[],p=new Set,g=(h,v)=>{p.has(h)||(p.add(h),m.push(v))};for(let[h,v]of u){let w=d.get(h)||[],y=[...v,...w].filter(I=>Hd.has(I.operationKind)||qd.has(I.operationKind)),b=y.filter(I=>I.operationKind==="list-format"),x=y.filter(I=>I.operationKind!=="list-format");if(b.length===1&&x.length===1&&x[0].operationKind==="redline"){let[I]=b,[R]=x,T=a.describe(h),N=hy({operation:s[R.index-1]},R.resolvedTarget?.text??T?.text??"");if(N){let P=[R,I];g(`list:${P.map(M=>M.index).sort().join(",")}`,Pi(Yd,`Operations ${P.map(M=>M.index).sort((M,_)=>M-_).join(", ")} combine a redline and a list-format on the same paragraph in a way that does not compose (${N.reason}).`,P,T,"split_text_and_list_changes",{reason:N.reason,...N.sourceMarker!==void 0?{sourceMarker:N.sourceMarker,modifiedMarker:N.modifiedMarker}:{}},N.hint));continue}let O=s[I.index-1],C=new Set(O._compiledRunAfter||[]);C.add(R.index-1),O._compiledRunAfter=[...C].sort((P,M)=>P-M),I.composedWith=[...new Set([...I.composedWith||[],R.index])],R.composedWith=[...new Set([...R.composedWith||[],I.index])];continue}if(w.length>0&&y.length>1){g(`rebind:${y.map(I=>I.index).sort().join(",")}`,Pi(Yd,`Operation ${w.map(I=>I.index).join(", ")} (list-format, scope "list") rebinds this list item, and operations ${y.filter(I=>!w.includes(I)).map(I=>I.index).join(", ")} also write it.`,y,a.describe(h),"split_text_and_list_changes",{reason:"list-rebind",rebindingOperationIndexes:w.map(I=>I.index)},'A list-format with scope "list" rewrites every item of the list; in the same batch only one single-paragraph redline per item can compose with it. Send the other change in a separate apply, or use scope "range".'));continue}let S=v,A=S.filter(I=>Hd.has(I.operationKind)),E=S.filter(I=>qd.has(I.operationKind));if(A.length>1){let I=`text:${A.map(R=>R.index).sort().join(",")}`;p.has(I)||(p.add(I),m.push(Pi("OVERLAPPING_SOURCE_TARGETS",`Operations ${A.map(R=>R.index).join(", ")} contain incompatible text writes to the same batch-start source target.`,A,a.describe(h),"consolidate_operations")))}if(A.length>0&&E.length>0){let I=[...A,...E],R=`format:${I.map(T=>T.index).sort().join(",")}`;p.has(R)||(p.add(R),m.push(Pi("REVISION_ORDER_CONFLICT",`Operations ${I.map(T=>T.index).join(", ")} combine text and formatting writes on the same batch-start source target.`,I,a.describe(h),"split_or_consolidate_operations")))}}return{valid:m.length===0&&l.every(h=>!h.error),compiledOperations:s,bindings:l,conflicts:m,registry:a}}function Zd(e){return`${e?.source||""}${e?.severity||""}${e?.code||""}${e?.message||""}`}function An(e=[],t=[]){let r=new Map;for(let n of t||[]){let o=Zd(n);r.set(o,(r.get(o)||0)+1)}return(e||[]).filter(n=>{let o=Zd(n),a=r.get(o)||0;return a===0?!0:(r.set(o,a-1),!1)})}function En(e=[]){return(e||[]).filter(t=>t?.severity==="error")}var Iy="PARAGRAPH_FORMAT_REVISION_CONFLICT",Ny=new Set(["pPr","bookmarkStart","bookmarkEnd","proofErr","commentRangeStart","commentRangeEnd","permStart","permEnd"]),Ty=new Set(["rPr","t","tab","br","cr","noBreakHyphen","softHyphen","lastRenderedPageBreak"]),Sy=new Set(["rPr","t","tab","lastRenderedPageBreak"]),da=(e,t=80)=>{let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r},_l=e=>String(e?.localName||e?.nodeName||"").replace(/^.*:/,""),Ol=e=>e?.getAttribute?.("w:val")??e?.getAttribute?.("val")??null;function de(e,t,r={},n=null){return{ok:!1,error:{code:e,message:t,...r,...n?{recovery:n}:{}}}}function Ci(e){let t=String(e||"");return t.trim()&&j(t,"application/xml")?.doc||null}function kl(e,t){if(!e)return null;let r=Array.from(e.getElementsByTagNameNS("*","style")).filter(a=>(a.getAttribute("w:type")??a.getAttribute("type"))==="paragraph"),n=new Map(r.map(a=>[a.getAttribute("w:styleId")??a.getAttribute("styleId"),a])),o=t?n.get(t):r.find(a=>["1","true","on"].includes(a.getAttribute("w:default")??a.getAttribute("default")));for(let a=0;o&&a<16;a+=1){let i=et(me(o,"pPr"),"numPr"),l=Ol(et(i,"numId"));if(l!=null)return l==="0"?null:{numId:l,styleId:o.getAttribute("w:styleId")??o.getAttribute("styleId")};o=n.get(Ol(me(o,"basedOn")))}return null}function Ay(e,t,r){let n=[],o=0,a="";for(let i of Array.from(e.childNodes||[])){if(o>=t)break;if(i.nodeType!==1)continue;let l=_l(i);if($(i,"r")){let s=jt(i),c=It(s);if(c===0){if(Array.from(i.childNodes||[]).some(p=>p.nodeType===1&&!Sy.has(_l(p))))return{reason:"run-content"};continue}if(Array.from(i.childNodes||[]).filter(m=>m.nodeType===1).map(_l).some(m=>!Ty.has(m)))return{reason:"run-content"};let u=Math.min(t,o+c)-o,d=0;for(let m of s){if(d>=u)break;if(!$(m.node,"t")&&!$(m.node,"tab"))return{reason:"run-content"};d=m.end}n.push({run:i,start:o,end:o+c,pieces:s}),a+=s.map(m=>m.text).join(""),o+=c;continue}if(!Ny.has(l))return{reason:l==="ins"||l==="del"||l==="moveTo"||l==="moveFrom"?"tracked-change":"container"}}return o<t||a.slice(0,t)!==r?{reason:"text-mismatch"}:{segments:n}}function Ey(e,t,r,{author:n,generateRedlines:o,revisionIdAllocator:a}){for(let i of t){let{run:l,start:s,end:c,pieces:f}=i,u=Math.min(r,c)-s;if(u<=0)continue;let d=l.parentNode,m=me(l,"rPr");if(o){let p=$r(e,Pt(e,f,0,u,!0),m);d.insertBefore(tr(e,"del",p,n),l)}if(u<c-s){let p=$r(e,Pt(e,f,u,c-s,!1),m);o&&Ft(p,a),d.insertBefore(p,l)}d.removeChild(l)}}function Ml(e,t){return t==null?!1:Vt(e.documentElement).some(r=>Ol(r)===String(t))}function Ll(e){if(!e||typeof e!="object")return null;(!e.listFallbackSequenceState||typeof e.listFallbackSequenceState!="object")&&(e.listFallbackSequenceState={explicitByNumberingKey:new Map});let t=e.listFallbackSequenceState;return t.explicitByNumberingKey instanceof Map||(t.explicitByNumberingKey=new Map),t.explicitByNumberingKey}function Bl(e,t){if(e?.numberingIdState)return e.numberingIdState;let r=Ht(e?.numberingXml||t?.numberingXml||void 0);return e&&typeof e=="object"&&(e.numberingIdState=r),r}function Fl(e,t,r,n={}){let o=n.generateRedlines!==!1,a=n.author,i=typeof n.paragraphIndexOf=="function"?n.paragraphIndexOf:()=>null,l=Ci(n.stylesXml),s=r.strip==="none"?"none":"marker",c=[],f=[];for(let T of t){let N=i(T),O=Y(T,{revisionView:"accepted"}),C=Oe(T);if(C)return de(Td,`Paragraph ${N??""} is already a list item (numId ${C.numId}, level ${C.ilvl}); convert-plain converts plain paragraphs only.`.replace(" "," "),{paragraphIndex:N,numId:C.numId,level:C.ilvl,targetExcerpt:da(O)},{action:"use_paragraph_numbering",hint:"Narrow the range to plain paragraphs. To move a list item to another existing list or level, use paragraph-format with properties.numbering."});let P=it(T),_=P.numPr?.numId==="0"?null:kl(l,P.pStyle);if(_)return de(Ti,`Paragraph ${N??""} is numbered by its style "${_.styleId}" (numId ${_.numId}); it is already a list item through the style.`.replace(" "," "),{paragraphIndex:N,styleId:_.styleId,numId:_.numId,targetExcerpt:da(O)},{action:"convert_in_host",hint:"Style-linked numbering is not rebound by list-format-v1. Change the paragraph style or the style's numbering in the host."});if(!O.trim()){f.push({paragraph:T,paragraphIndex:N,reason:"empty"});continue}if(s==="none"){c.push({paragraph:T,paragraphIndex:N,text:O,parsed:null});continue}let k=fo(O);if(k?.unsupported){let L={multilevel:'multi-level markers such as "2.1." need a multi-level list definition',parenthesized:'parenthesized markers such as "(a)" are not supported',zero:"a marker value of 0 cannot start a Word list"}[k.unsupported];return de(ua,`The typed marker "${k.marker}" is not supported by list-format-v1: ${L}.`,{reason:k.unsupported,marker:k.marker,paragraphIndex:N,targetExcerpt:da(O)},{action:"convert_in_host",hint:"Convert this paragraph in the host, or leave the marker as literal text."})}if(!k){f.push({paragraph:T,paragraphIndex:N,reason:"no-marker"});continue}c.push({paragraph:T,paragraphIndex:N,text:O,parsed:k})}if(c.length===0)return de(Id,s==="marker"?'No target paragraph starts with a typed list marker (for example "A. ", "1. ", "iv. " or "- "), so there is nothing to strip.':"The target range has no non-empty paragraph to convert.",{targetExcerpt:da(f[0]?Y(f[0].paragraph):"")},{action:"change_request",hint:'Target the paragraphs that carry the typed markers, or pass strip: "none" with list.format to bind paragraphs whose text has no marker.',field:"list.strip",allowedValue:"none"});let u=r.format;if(s==="marker"){let T=Cd(c.map(N=>N.parsed),r.format);if(T.error){let{reason:N}=T.error;if(N==="ambiguous")return de(Nd,`The typed marker "${T.error.marker}" reads as ${T.error.formats.join(" or ")}; list-format will not guess.`,{marker:T.error.marker,formats:T.error.formats},{action:"set_list_format",hint:`Pass list.format (${T.error.formats.join(" or ")}).`,field:"list.format",allowedValues:T.error.formats});let O=N==="format-mismatch"?`The typed marker "${T.error.marker}" is not a ${T.error.requestedFormat} marker.`:`The target range mixes list markers (${[...new Set(T.error.markers)].join(", ")}); one convert-plain operation converts one list format.`;return de(ua,O,{reason:N,...T.error.marker?{marker:T.error.marker}:{},...T.error.markers?{markers:T.error.markers}:{}},{action:"change_request",hint:N==="format-mismatch"?"Omit list.format to use the typed marker, or correct it.":"Split the range into one operation per marker format."})}u=T.format}if(r.kind&&r.kind==="bullet"!=(u==="bullet"))return de(ua,`The typed markers are ${u} markers, not a ${r.kind} list.`,{reason:"format-mismatch",requestedKind:r.kind},{action:"change_request",hint:"Omit list.kind, or target paragraphs whose markers match it."});let d=s==="marker"?c[0].parsed.terminator:".",m=s==="marker"&&c[0].parsed.bulletChar||null,p=r.level||0;for(let T of c){let N=et(me(T.paragraph,"pPr"),"pPrChange"),O=N?.getAttribute("w:author")??N?.getAttribute("author")??"";if(o&&N&&O!==a)return de(Iy,`Paragraph ${T.paragraphIndex??""} already has a pending paragraph-property change by "${O||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`.replace(" "," "),{pendingAuthor:O,paragraphIndex:T.paragraphIndex},{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."});if(T.keepSnapshot=!!N,s==="marker"){let C=Ay(T.paragraph,T.parsed.prefixLength,T.text.slice(0,T.parsed.prefixLength));if(C.reason)return de(ua,`The typed marker "${T.parsed.marker}" is not plain run text (${C.reason}), so it cannot be stripped as one tracked deletion.`,{reason:"marker-shape",shape:C.reason,marker:T.parsed.marker,paragraphIndex:T.paragraphIndex,targetExcerpt:da(T.text)},{action:"convert_in_host",hint:"The marker sits inside a hyperlink, field, content control or pending revision. Resolve that markup first or convert the paragraph in the host."});T.segments=C.segments}}let g=Ll(n.runtimeContext),h=kd({format:u,level:p,terminator:d,bulletChar:m}),v=g?.get(h)||null,w=v&&Ml(e,v.numId),y=s==="none"?r.start??(w&&Number.isInteger(v.nextStartAt)?v.nextStartAt:1):null;for(let T of c)u==="bullet"?T.value=null:s==="marker"?T.value=_d(T.parsed,u):T.value=y++;let b=Bl(n.runtimeContext,n),x=Od({format:u,level:p,terminator:d,bulletChar:m}),S=[],A=[],E=null,I=null;for(let[T,N]of c.entries()){if(!(T>0&&(u==="bullet"||N.value===I+1)))if(T===0&&w&&(u==="bullet"||v.nextStartAt===N.value))E=String(v.numId);else{let P=Ho({numberingIdState:b,levels:[x],startOverrides:N.value!=null&&N.value!==1?{[p]:N.value}:void 0});if(!P)return de("NUMBERING_ID_EXHAUSTED","No numbering ids are available for a new list definition.",{},{action:"report_library_failure"});E=String(P.numId),A.push(P.numId),S.push(P.numberingXml)}N.numId=E,I=N.value}for(let T of c){let N=me(T.paragraph,"pPr");N||(N=F(e,"w:pPr"),T.paragraph.insertBefore(N,T.paragraph.firstChild)),o&&!T.keepSnapshot&&Hn(e,N,a),Kn(e,N,{numbering:{numId:T.numId,level:p}}),s==="marker"&&Ey(e,T.segments,T.parsed.prefixLength,{author:a,generateRedlines:o,revisionIdAllocator:n.revisionIdAllocator||null})}let R=c[c.length-1];return g?.set(h,{numId:R.numId,nextStartAt:R.value!=null?R.value+1:null}),{ok:!0,format:u,level:p,strip:s,items:c.map(T=>({paragraph:T.paragraph,paragraphIndex:T.paragraphIndex,marker:T.parsed?.marker??null,value:T.value,numId:T.numId})),skipped:f,numberingXml:S.length>0?vr("",S):null,allocatedNumIds:A}}var Qd="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Ry="PARAGRAPH_FORMAT_REVISION_CONFLICT",Dl=8,Ul=(e,t=80)=>{let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r},go=e=>e?.getAttribute?.("w:val")??e?.getAttribute?.("val")??null,Pn=(e,t="val")=>{let r=e?.getAttribute?.(`w:${t}`)??e?.getAttribute?.(t),n=Number.parseInt(String(r??""),10);return Number.isFinite(n)?n:null},Rn=e=>e==="bullet";function em(e){let t=String(e||""),r=t.trim()?j(t,"application/xml")?.doc:null,n=new Map,o=new Map;if(!r)return{nums:n,abstracts:o};for(let a of Array.from(r.getElementsByTagNameNS("*","abstractNum"))){let i=Pn(a,"abstractNumId");i!=null&&!o.has(String(i))&&o.set(String(i),a)}for(let a of Array.from(r.getElementsByTagNameNS("*","num"))){let i=Pn(a,"numId");if(i==null||n.has(String(i)))continue;let l=new Map,s=new Set;for(let c of Yi(a,"lvlOverride")){let f=Pn(c,"ilvl")??0,u=Pn(me(c,"startOverride"));u!=null&&l.set(f,u),me(c,"lvl")&&s.add(f)}n.set(String(i),{element:a,abstractId:String(Pn(me(a,"abstractNumId"))??""),startOverrides:l,levelOverrides:s})}return{nums:n,abstracts:o}}function Py(e,t){let r=e.nums.get(String(t));if(!r)return{reason:"missing"};let n=e.abstracts.get(r.abstractId);if(!n)return{reason:"missing"};let o=new Map;for(let l of Yi(n,"lvl")){let s=Pn(l,"ilvl")??0;o.set(s,{numFmt:go(me(l,"numFmt"))||"decimal",lvlText:go(me(l,"lvlText"))??"",start:Pn(me(l,"start"))??0,restart:!!me(l,"lvlRestart"),pStyle:go(me(l,"pStyle"))})}let a=go(me(n,"numStyleLink"))||go(me(n,"styleLink")),i=[...o.values()].map(l=>l.pStyle).filter(Boolean);return{numId:String(t),num:r,abstract:n,abstractId:r.abstractId,levels:o,styleLink:a||null,levelStyles:i,startOf:l=>r.startOverrides.has(l)?r.startOverrides.get(l):o.get(l)?.start??0}}function Cy(e,t){if(!e)return[];let r=[];for(let n of Array.from(e.getElementsByTagNameNS("*","style"))){let o=go(et(et(me(n,"pPr"),"numPr"),"numId"));o!=null&&t.has(String(o))&&r.push(n.getAttribute("w:styleId")??n.getAttribute("styleId"))}return r}function Vl(e,t){let r=[];for(let n of Array.from(e.getElementsByTagNameNS(Qd,"p"))){let o=Oe(n);!o||o.numId!==String(t)||r.push({paragraph:n,ilvl:o.ilvl,deleted:kt(n),inTextbox:_y(n,"txbxContent")})}return r}function _y(e,t){for(let r=e?.parentNode;r&&r.nodeType===1;r=r.parentNode)if(r.localName===t)return!0;return!1}function Oy(e,t,r){return[...t.nums.entries()].filter(([o,a])=>o!==r.numId&&a.abstractId===r.abstractId).map(([o])=>o).filter(o=>Vl(e,o).some(a=>!a.deleted))}function $l(e,t,r=[]){let n=Array.from({length:Dl+1},(a,i)=>r[i]??null),o=[];for(let a of e){for(let i=0;i<a;i+=1)n[i]==null&&(n[i]=t(i));n[a]=n[a]==null?t(a):n[a]+1;for(let i=a+1;i<=Dl;i+=1)n[i]=null;o.push(n.slice(0,a+1))}return{values:o,counters:n}}function tm(e,{stylesDoc:t,indexOf:r,mode:n}){let o=[],a=[],i=[];for(let s of e){let c=r(s);if(kt(s)){a.push({paragraph:s,paragraphIndex:c,reason:"tracked-deleted"});continue}let f=Oe(s);if(f){o.push({paragraph:s,paragraphIndex:c,ilvl:f.ilvl,numId:f.numId});continue}let u=it(s),d=u.numPr?.numId==="0"?null:kl(t,u.pStyle);if(d)return de(Ti,`Paragraph ${c??""} is numbered by its style "${d.styleId}" (numId ${d.numId}), not by a direct list binding; ${n} rebinds direct list items only.`.replace(" "," "),{paragraphIndex:c,styleId:d.styleId,numId:d.numId,targetExcerpt:Ul(Y(s))},{action:"convert_in_host",hint:"Style-linked numbering is not rebound by list-format. Change the style's numbering in the host."});i.push({paragraph:s,paragraphIndex:c})}if(o.length===0)return de(Sd,`The target range has no list item; ${n} changes existing lists.`,{paragraphIndexes:i.map(s=>s.paragraphIndex),targetExcerpt:Ul(i[0]?Y(i[0].paragraph):"")},{action:"use_list_format_convert_plain",hint:"To turn plain paragraphs into a list use list-format convert-plain (typed markers) or paragraph-format numbering (an existing list)."});if(i.length>0)return de(Si,`The target range mixes list items and paragraphs that are not list items (paragraphs ${i.map(s=>s.paragraphIndex).join(", ")}).`,{reason:"non-list",paragraphIndexes:i.map(s=>s.paragraphIndex)},{action:"narrow_range",hint:'Target only list items: one paragraph of the list is enough with scope "list".'});let l=[...new Set(o.map(s=>s.numId))];return l.length>1?de(Si,`The target range spans ${l.length} lists (numIds ${l.join(", ")}); one ${n} operation changes one list.`,{reason:"several-lists",numIds:l,paragraphIndexes:o.filter(s=>s.numId!==o[0].numId).map(s=>s.paragraphIndex)},{action:"narrow_range",hint:"Send one operation per list."}):{ok:!0,numId:l[0],items:o,skipped:a}}function zl(e,t,r,{stylesDoc:n,role:o}){let a=Py(t,r);if(a.reason==="missing")return de(Nn,`numId ${r} (${o}) has no numbering definition in the numbering part, so its levels cannot be read.`,{reason:"missing",numId:String(r)},{action:"inspect_numbering",hint:"Bare document.xml callers must pass the package's word/numbering.xml as numberingXml."});if(a.num.levelOverrides.size>0)return de(Nn,`numId ${r} (${o}) redefines level ${[...a.num.levelOverrides].join(", ")} inside its w:num (w:lvlOverride/w:lvl); list-format does not rebind such instance-level definitions.`,{reason:"level-override",numId:String(r),levels:[...a.num.levelOverrides]},{action:"convert_in_host",hint:"Change this list in the host."});let i=Cy(n,new Set([String(r),...[...t.nums.entries()].filter(([,s])=>s.abstractId===a.abstractId).map(([s])=>s)]));if(a.styleLink||a.levelStyles.length>0||i.length>0){let s=[...new Set([a.styleLink,...a.levelStyles,...i].filter(Boolean))];return de(Ad,`numId ${r} (${o}) is style-linked (${s.map(c=>`"${c}"`).join(", ")}): paragraphs can join it through a style without a direct binding, so rebinding the direct items would split the list unpredictably.`,{numId:String(r),styleIds:s},{action:"convert_in_host",hint:"Style-linked lists (heading numbering, list styles) are not changed by list-format. Change the numbering of the style in the host."})}let l=Oy(e,t,a);return l.length>0?de(uo,`numId ${r} (${o}) shares its abstract definition ${a.abstractId} with numIds ${l.join(", ")}, which Word numbers as one continuous list; rebinding one of them would renumber the others.`,{reason:"shared-definition",numId:String(r),sharedNumIds:l},{action:"convert_in_host",hint:"Change these lists together in the host, or restart the other list first."}):a.num.element&&[...a.levels.keys()].length===0?de(Nn,`numId ${r} (${o}) has no levels.`,{reason:"undefined-level",numId:String(r)},{action:"convert_in_host"}):{ok:!0,definition:a}}function rm(e,t,r,n,o,a){let l=Vl(e,t).filter(d=>!d.deleted),s=l.find(d=>d.inTextbox);if(s)return de(uo,`numId ${t} has a list item inside a text box (paragraph ${o(s.paragraph)??"?"}); list-format changes body lists only.`,{reason:"textbox-member",numId:String(t)},{action:"convert_in_host",hint:"Change this list in the host."});let c=new Set(r.map(d=>d.paragraph));if(n==="list")return{ok:!0,rebind:l.map(d=>({...d,paragraphIndex:o(d.paragraph),inTarget:c.has(d.paragraph)})),preceding:[]};let f=l.findIndex(d=>c.has(d.paragraph)),u=l.slice(f).filter(d=>!c.has(d.paragraph));if(u.length>0){let d=o(l[l.length-1].paragraph);return de(uo,`scope "range" would split numId ${t} mid-sequence: ${u.length} later item(s) of the list (paragraphs ${u.map(m=>o(m.paragraph)).join(", ")}) would stay on the source list and renumber.`,{reason:"mid-sequence",numId:String(t),followingParagraphIndexes:u.map(m=>o(m.paragraph)),lastListParagraphIndex:d},{action:"extend_range_or_use_list_scope",hint:`Extend targetEnd to the last item of the list (paragraph ${d}), or use scope "list" to ${a==="join"?"join":"change"} the whole list.`})}return{ok:!0,rebind:l.slice(f).map(d=>({...d,paragraphIndex:o(d.paragraph),inTarget:!0})),preceding:l.slice(0,f)}}function nm(e,{author:t,generateRedlines:r}){let n=e.filter(o=>!o.inTarget);if(!r&&n.length>0)return de("INVALID_OPERATION",`An untracked (generateRedlines: false) list-format would rebind ${n.length} paragraph(s) outside the target (paragraphs ${n.map(o=>o.paragraphIndex).join(", ")}); untracked edits stay inside their target.`,{field:"generateRedlines",paragraphIndexes:n.map(o=>o.paragraphIndex)},{action:"change_request",hint:"Keep tracking on, or target the whole list with target..targetEnd."});for(let o of e){let a=et(me(o.paragraph,"pPr"),"pPrChange"),i=a?.getAttribute("w:author")??a?.getAttribute("author")??"";if(r&&a&&i!==t)return de(Ry,`Paragraph ${o.paragraphIndex??""} of the list already has a pending paragraph-property change by "${i||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`.replace(" "," "),{pendingAuthor:i,paragraphIndex:o.paragraphIndex},{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."});o.keepSnapshot=!!a}return{ok:!0}}function om(e,t,r,{author:n,generateRedlines:o}){for(let a of t){let i=me(a.paragraph,"pPr");i||(i=F(e,"w:pPr"),a.paragraph.insertBefore(i,a.paragraph.firstChild)),o&&!a.keepSnapshot&&Hn(e,i,n),Kn(e,i,{numbering:{numId:r,level:a.ilvl}}),a.numId=String(r)}}var Xl=(e,t={})=>({ok:!0,unchanged:!0,message:e,...t});function am(e,t,r,n={}){let o=n.generateRedlines!==!1,a=n.author,i=typeof n.paragraphIndexOf=="function"?n.paragraphIndexOf:()=>null,l=Ci(n.stylesXml),s=em(n.numberingXml),c=r.scope==="range"?"range":"list",f=tm(t,{stylesDoc:l,indexOf:i,mode:"change-format"});if(!f.ok)return f;let u=zl(e,s,f.numId,{stylesDoc:l,role:"the target list"});if(!u.ok)return u;let{definition:d}=u,m=[...new Set(f.items.map(O=>O.ilvl))].sort((O,C)=>O-C);if(r.explicitLevel==null&&m.length>1)return de(Si,`The target paragraphs use list levels ${m.join(", ")}; change-format redefines one level per operation.`,{reason:"levels",levels:m},{action:"set_list_level",hint:"Pass list.level, or target paragraphs of one level.",field:"list.level",allowedValues:m});let p=r.explicitLevel??m[0],g=d.levels.get(p);if(!g)return de(Nn,`numId ${f.numId} does not define list level ${p}.`,{reason:"undefined-level",numId:f.numId,level:p},{action:"set_list_level",field:"list.level",allowedValues:[...d.levels.keys()]});let h=r.format??(r.kind==="bullet"?"bullet":g.numFmt),v=Rn(g.numFmt)!==Rn(h),w=r.lvlText??(v?Rn(h)?"\u2022":`%${p+1}.`:g.lvlText),y=Tl(w,{bullet:Rn(h),level:p});if(y)return de("INVALID_OPERATION",`${y} (level ${p}, format ${h})`,{field:"list.lvlText"},{action:"change_request",hint:Rn(h)?"Pass the bullet character as list.lvlText.":`Pass list.lvlText with %${p+1}, for example "%${p+1}."`});let b=rm(e,f.numId,f.items,c,i,"change-format");if(!b.ok)return b;let x=O=>d.levels.get(O)?.start??0,S=new Map;for(let O=0;O<=Dl;O+=1)S.set(O,d.startOf(O));if(c==="range"&&b.preceding.length>0){if([...b.preceding,...b.rebind].some(L=>d.levels.get(L.ilvl)?.restart))return de(Nn,`numId ${f.numId} uses w:lvlRestart, so the count a split would continue cannot be computed exactly.`,{reason:"level-restart",numId:f.numId},{action:"extend_range_or_use_list_scope",hint:'Use scope "list".'});let C=$l(b.preceding.map(L=>L.ilvl),d.startOf),P=b.rebind[0].ilvl;for(let L=0;L<P;L+=1)S.set(L,C.counters[L]??d.startOf(L));S.set(P,C.counters[P]==null?d.startOf(P):C.counters[P]+1);let M=$l(b.rebind.map(L=>L.ilvl),d.startOf,C.counters).values,k=$l(b.rebind.map(L=>L.ilvl),L=>S.get(L)).values.findIndex((L,D)=>JSON.stringify(L)!==JSON.stringify(M[D]));if(k>=0)return de(uo,`scope "range" cannot continue the count of numId ${f.numId} exactly: a level whose start must change restarts inside the range (paragraph ${b.rebind[k].paragraphIndex??"?"}), and Word applies a level start again on every restart.`,{reason:"nested-restart",numId:f.numId,paragraphIndex:b.rebind[k].paragraphIndex},{action:"extend_range_or_use_list_scope",hint:'Start the range at a top-level item of the list, or use scope "list".'})}if(r.start!=null&&S.set(p,r.start),!b.rebind.some(O=>O.ilvl===p))return Xl(`No paragraph of the ${c==="list"?"list":"range"} uses level ${p}; nothing would change.`,{level:p,sourceNumId:f.numId});let A=r.start!=null&&r.start!==d.startOf(p);if(h===g.numFmt&&w===g.lvlText&&!A)return Xl(`numId ${f.numId} level ${p} already has format ${h} with level text "${w}".`,{level:p,sourceNumId:f.numId});let E=nm(b.rebind,{author:a,generateRedlines:o});if(!E.ok)return E;let I={};for(let[O,C]of S)C!==x(O)&&(I[O]=C);let R=new Map(Object.entries(I).map(([O,C])=>[Number(O),{ilvl:Number(O),start:C}]));R.set(p,{...R.get(p)||{},ilvl:p,numFmt:h,lvlText:w,...h!==g.numFmt?{dropChildren:v&&!Rn(h)?["isLgl","lvlPicBulletId","legacy"]:["isLgl"]}:{},...v&&!Rn(h)?{dropRunFonts:!0}:{}});let T=Bl(n.runtimeContext,n),N=Ho({numberingIdState:T,sourceNumberingXml:n.numberingXml,sourceNumId:f.numId,levels:[...R.values()]});return N?(om(e,b.rebind,N.numId,{author:a,generateRedlines:o}),{ok:!0,mode:"change-format",scope:c,format:h,level:p,lvlText:w,sourceNumId:f.numId,numId:String(N.numId),levelStarts:I,items:b.rebind.map(O=>({paragraph:O.paragraph,paragraphIndex:O.paragraphIndex,level:O.ilvl,numId:O.numId,sourceNumId:f.numId,inTarget:O.inTarget})),skipped:f.skipped,numberingXml:vr("",[N.numberingXml]),allocatedNumIds:[N.numId]}):de("NUMBERING_ID_EXHAUSTED","No numbering ids are available for a new list definition.",{},{action:"report_library_failure"})}function im(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=o.author,l=typeof o.paragraphIndexOf=="function"?o.paragraphIndexOf:()=>null,s=Ci(o.stylesXml),c=em(o.numberingXml),f=n.scope==="range"?"range":"list",u=l(r),d=Oe(r);if(!d||kt(r))return de(Ai,`list.continueFrom (paragraph ${u??"?"}) is ${d?"a tracked-deleted paragraph":"not a list item"}; join continues an existing list.`,{reason:d?"deleted":"not-a-list",paragraphIndex:u,targetExcerpt:Ul(Y(r))},{action:"change_request",hint:"Point list.continueFrom at a live item of the list the target should continue.",field:"list.continueFrom"});if(t.includes(r))return de(Ai,"list.continueFrom is inside the target range; it must be an item of an earlier list.",{reason:"inside-target",paragraphIndex:u},{action:"change_request",field:"list.continueFrom"});let m=tm(t,{stylesDoc:s,indexOf:l,mode:"join"});if(!m.ok)return m;if(m.numId===d.numId)return Xl(`The target already belongs to the list of list.continueFrom (numId ${m.numId}).`,{sourceNumId:m.numId});let p=zl(e,c,m.numId,{stylesDoc:s,role:"the target list"});if(!p.ok)return p;let g=zl(e,c,d.numId,{stylesDoc:s,role:"the list.continueFrom list"});if(!g.ok)return g;let h=rm(e,m.numId,m.items,f,l,"join");if(!h.ok)return h;let v=Array.from(e.getElementsByTagNameNS(Qd,"p")),w=v.indexOf(h.rebind[0].paragraph),b=Vl(e,d.numId).filter(A=>!A.deleted).filter(A=>v.indexOf(A.paragraph)>w);if(b.length>0){let A=v.indexOf(r)>w?"after-target":"interleaved";return de(A==="after-target"?Ai:uo,A==="after-target"?"list.continueFrom comes after the target; join continues an earlier list.":`The list of list.continueFrom (numId ${d.numId}) has items after the joined paragraphs (paragraphs ${b.map(E=>l(E.paragraph)).join(", ")}); they would renumber.`,{reason:A,numId:d.numId,paragraphIndexes:b.map(E=>l(E.paragraph))},{action:"change_request",hint:"Join a list to the list that immediately precedes it.",field:"list.continueFrom"})}let x=h.rebind.find(A=>!g.definition.levels.has(A.ilvl));if(x)return de(Nn,`numId ${d.numId} (the list.continueFrom list) does not define level ${x.ilvl}, which paragraph ${x.paragraphIndex??"?"} uses.`,{reason:"undefined-level",numId:d.numId,level:x.ilvl},{action:"convert_in_host"});let S=nm(h.rebind,{author:i,generateRedlines:a});return S.ok?(om(e,h.rebind,d.numId,{author:i,generateRedlines:a}),{ok:!0,mode:"join",scope:f,sourceNumId:m.numId,numId:d.numId,continueFrom:{paragraphIndex:u,numId:d.numId},items:h.rebind.map(A=>({paragraph:A.paragraph,paragraphIndex:A.paragraphIndex,level:A.ilvl,numId:A.numId,sourceNumId:m.numId,inTarget:A.inTarget})),skipped:m.skipped,numberingXml:null,allocatedNumIds:[]}):S}var ky=/^(\s*)((?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|[ivxlcIVXLC]+\.|[-*+\u2022]))\s+(.*)$/,sm=/(?:^|\s)(?:\d+(?:\.\d+)*\.?|[A-Za-z]\.|[ivxlcIVXLC]+\.)\s+/g;function My(e){let t=String(e||"").trim();if(!/^\d+(?:\.\d+)+\.?$/.test(t))return null;let r=t.replace(/\.$/,"").split(".");return Math.max(0,r.length-1)}function Ly(e){let t=String(e||"").split(/\r?\n/g).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);if(t.length<2)return null;let r=[];for(let n of t){let o=n.match(ky);if(!o)return null;let a=o[2],i=/^[-*+\u2022]$/.test(a)?"bullet":"numbered";r.push({marker:a,markerType:i,level:Math.floor((o[1]||"").length/2),outlineLevel:i==="numbered"?My(a):null,text:un(o[3])})}return r.length>=2?r:null}function lm(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=Ly(t);if(!r)return null;let n=e.map(d=>q(_e(d))),o=r.map(d=>q(d.text));if(n.some(d=>!d)||o.some(d=>!d))return null;let a=e.map(d=>Oe(d));if(a.some(d=>!d||!d.numId))return null;let i=String(a[0].numId);if(a.some(d=>String(d.numId)!==i))return null;let l=[],s=0;for(let d=0;d<o.length&&s<n.length;d+=1)o[d]===n[s]&&(l.push({originalIndex:s,modifiedIndex:d}),s+=1);if(s!==n.length)return null;let c=new Set(l.map(d=>d.modifiedIndex)),f=[];for(let d=0;d<r.length;d+=1)c.has(d)||f.push(d);if(f.length===0)return null;let u=r[0]?.level||0;return f.map(d=>{let m=l.find(b=>b.modifiedIndex>d)||null,p=[...l].reverse().find(b=>b.modifiedIndex<d)||null,g=m||p;if(!g)return null;let h=a[g.originalIndex]||a[0];if(!h)return null;let v=r[d],w=Math.max(0,v.level-u),y=Number.isInteger(v.outlineLevel)?v.outlineLevel:null;return{text:v.text,markerType:v.markerType,ilvl:y??Math.max(0,(h.ilvl||0)+w),numId:String(h.numId),insertBeforeOriginalIndex:m?m.originalIndex:null}}).filter(Boolean)}function By(e){return String(e||"").trim().split(/\s+/).filter(Boolean).length}function Fy(e){let t=String(e||"");if(!t)return!1;let r=0,n=new RegExp(sm.source,sm.flags);for(;n.exec(t);)if(r+=1,r>=2)return!0;return!1}function cm(e,t){let r=String(e||"").trim(),n=String(t||"").trim();if(!r||!n||n===r||n.includes(`
218
+ `))return null;let o=q(r),a=s=>un(String(s||"").trim()).trim(),i=(s,c)=>{let f=a(c),u=q(f);return!f||f===r||By(f)<6||Fy(f)||o&&u.includes(o)?null:{position:s,text:f}};if(n.endsWith(r)){let s=i("before",n.slice(0,-r.length));if(s)return s}if(n.startsWith(r)){let s=i("after",n.slice(r.length));if(s)return s}let l=q(n);if(!o||o===l)return null;if(l.endsWith(o)){let s=i("before",l.slice(0,-o.length));if(s)return s}if(l.startsWith(o)){let s=i("after",l.slice(o.length));if(s)return s}return null}function um(e,t){let r=String(e||"").trim(),n=String(t||"");if(!r||!n||!n.includes(`
219
+ `))return null;let o=n.split(/\r?\n/g).map(l=>String(l||"").trim()).filter(Boolean);if(o.length<2)return null;let a=l=>q(String(l||"")),i=a(r);if(a(o[o.length-1])===i){let l=o.slice(0,-1).filter(Boolean);if(l.length>0)return{position:"before",paragraphs:l}}if(a(o[0])===i){let l=o.slice(1).filter(Boolean);if(l.length>0)return{position:"after",paragraphs:l}}return null}function fm(e){let t=String(e||"").split(/\r?\n/g).map(a=>a.trimEnd()).filter(a=>a.trim().length>0);if(t.length<3||t.findIndex(a=>a.trim().startsWith("|"))!==1)return null;let n=t.slice(1);if(!n.every(a=>a.trim().startsWith("|")))return null;let o=n[1].replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(o)?{paragraphMarkdown:t[0].trim(),tableText:n.join(`
220
+ `)}:null}function Tr(e,t){let r=new Error(t);return r.code=e,r}function dm(e,t,r){let n=[],o=!1,a=!1;for(let m of r||[])m&&(m.localName==="tbl"?(o=!0,n.push(...Array.from(m.getElementsByTagNameNS(B,"p")))):m.localName==="p"&&(it(m).numPr&&(a=!0),n.push(m)));let i=o?"table":a?"list":n.length>1?"range":"paragraph",l=[],s=[],c=[],f=[],u=e.document,d=se(u);for(let m of n){let p=He(m)||"";l.push(p);let g=Y(m);c.push(g);let h=d.indexOf(m)+1;s.push(Ot(m,{text:g,paragraphId:p||null,index:h>0?h:void 0,inTable:o||!!ut(m,"tbl")}));let v=m.parentNode?.localName||"body";f.push(`${v}/${m.localName}`)}return{captureKey:t.captureKey,operationIndex:typeof t.index=="number"?t.index:0,kind:i,generatedParagraphIds:l,fingerprints:s,expectedText:c,structuralPathHints:f,stale:!1}}function mm(e,t){if(!e||!(e instanceof Map)||!Array.isArray(t)||t.length===0)return;let r=new Set;for(let n of t)if(n){if(n.localName==="p"){let o=He(n);o&&r.add(o)}else if(typeof n.getElementsByTagNameNS=="function")for(let o of Array.from(n.getElementsByTagNameNS(B,"p"))){let a=He(o);a&&r.add(a)}}if(r.size!==0)for(let[,n]of e)n.stale||n.generatedParagraphIds.some(o=>o&&r.has(o))&&(n.stale=!0)}function pm(e,t,r,n="redline",o={}){let a=r?.captureRef;if(!a)throw Tr("INVALID_OPERATION","Operation target is missing captureRef.");if(!t||!t.captureTable||!t.captureTable.has(a))throw Tr("CAPTURE_NOT_FOUND",`Capture "${a}" was not found in the session capture table.`);let i=t.captureTable.get(a);if(i.stale)throw Tr("CAPTURE_STALE",`Capture "${a}" is stale; the captured content was modified or removed.`);let l=t.getParagraphMetadataIndex(),s=[];for(let d=0;d<i.expectedText.length;d++){let m=i.generatedParagraphIds[d],p=i.expectedText[d],g=null;if(m&&l.byId.has(m)&&(g=l.byId.get(m).paragraph),!g){let v=l.entries.find(w=>w.text===p||w.fingerprint===i.fingerprints[d]);v&&(g=v.paragraph)}if(!g||!g.parentNode)throw i.stale=!0,Tr("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} was removed from the document.`);let h=Y(g);if(h!==p)throw i.stale=!0,Tr("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} content drifted from "${p}" to "${h}".`);s.push(g)}if(s.length===0)throw i.stale=!0,Tr("CAPTURE_STALE",`Capture "${a}" is stale; no live paragraphs found.`);let c=r.select;if(c==null||c===""){if(s.length===1)return{paragraph:s[0],resolvedBy:"capture"};throw Tr("AMBIGUOUS_CAPTURE_SELECTION",`Capture "${a}" contains ${s.length} paragraphs; target.select is required to disambiguate.`)}let f=[],u=String(c).trim();if(u===":first"||u==="first")f=[s[0]];else if(u===":last"||u==="last")f=[s[s.length-1]];else if(/^\d+$/.test(u)){let d=parseInt(u,10);d>=1&&d<=s.length&&(f=[s[d-1]])}else{let d=s.filter(m=>Y(m).trim()===u);d.length>0?f=d:f=s.filter(m=>Y(m).includes(u))}if(f.length===0)throw Tr("TARGET_NOT_FOUND",`Target selection "${c}" was not found in capture "${a}".`);if(f.length>1)throw Tr("AMBIGUOUS_CAPTURE_SELECTION",`Target selection "${c}" matched ${f.length} paragraphs in capture "${a}".`);return{paragraph:f[0],resolvedBy:"capture"}}var ce="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ma="http://schemas.microsoft.com/office/word/2010/wordml";function gm(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.(ce,r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function hm(e,t){return!t||typeof t!="object"?[]:e.map(r=>t[r]).filter(Boolean)}function Kr(e,t={}){let r=t?._documentOperationSession||null;return r?.valid&&r.document?{xmlDoc:r.document,serializer:r.serializer,operationSession:r}:{xmlDoc:j(e,"application/xml").doc,serializer:le(),operationSession:null}}function ot(e,t,r,n){return n?r:t.serializeToString(e)}async function wo(e,t,r,n={}){let o=await $o(e,t,r,n);return o?.useNativeApi&&typeof o?.oxml!="string"?Ce({...o,oxml:e,hasChanges:!1,warnings:[...Array.isArray(o?.warnings)?o.warnings:[],"Standalone mode cannot execute native Word API fallback for this operation."]}):o}async function $y(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=bt(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await wo(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}function ho(e){return _e(e)}function wm(e,t=96){let r=String(e??"");return(r.length>t?`${r.slice(0,t)}\u2026`:r).replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\u00a0/g,"\\u00A0").replace(/\u202f/g,"\\u202F").replace(/\u2060/g,"\\u2060")}function _i(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function Dy(e,t){let r=String(e??""),n=String(t??"");if(r===n)return{mode:"exact"};let o=[],a=Math.min(r.length,n.length);for(let l=0;l<a&&o.length<8;l++)r[l]!==n[l]&&o.push({offset:l,sourceCodePoint:_i(r,l),requestedCodePoint:_i(n,l)});return r.length!==n.length&&o.length<8&&o.push({offset:a,sourceCodePoint:_i(r,a),requestedCodePoint:_i(n,a)}),{mode:r.length===n.length&&r.replace(/\u00a0/g," ")===n.replace(/\u00a0/g," ")?"space_equivalent":"normalized",differences:o,sourceExcerpt:wm(r),requestedExcerpt:wm(n)}}function jl(e,t,r,n,o){let a=o?.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",i=r?.revisionView===a?r:null,l=i?.index??se(e).indexOf(t)+1,s=i?.paragraphId??He(t),c=i?.inTable??!!ut(t,"tbl"),f=i?.text??Y(t,{revisionView:a}),u=i?.fingerprint??Ot(t,{text:f,index:l,paragraphId:s,inTable:c,revisionView:a});return{index:l,paragraphId:s,text:f,fingerprint:u,revisionView:a,inTable:c,targetTextMatch:Dy(f,o?.targetDescriptor?.text??o?.targetDescriptor?.exactText??n)}}function At(e,t,r,n,o=null,a={}){let i=typeof a?.onInfo=="function"?a.onInfo:()=>{},l=typeof a?.onWarn=="function"?a.onWarn:()=>{},s=a?._documentOperationSession||null,c=s?.getParagraphMetadataIndex?.()||null;if(a?._compiledSourceId&&a?._sourceTargetRegistry){let u=a._sourceTargetRegistry.resolve(a._compiledSourceId,e);if(u?.error||!u?.paragraph)return u;if(u.resolvedBy=a._compiledResolvedBy||u.resolvedBy,a?._resolutionCapture){let d=u.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:u.resolvedBy,resolvedTarget:jl(e,d,m,t,a)})}return u}if(a?.targetDescriptor?.captureRef)try{let u=pm(e,s,a.targetDescriptor,n,a);if(a?._resolutionCapture&&u?.paragraph){let d=u.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:u.resolvedBy,resolvedTarget:jl(e,d,m,t,a)})}return u}catch(u){return{error:{code:typeof u?.code=="string"&&u.code?u.code:"TARGET_NOT_FOUND",message:u?.message||String(u)}}}let f=Jn(e,{targetText:t,targetRef:r,opType:n,targetRefSnapshot:o?.targetRefSnapshot||null,targetDescriptor:a?.targetDescriptor||null,strictAmbiguity:a?.strictTargets===!0,paragraphMetadataIndex:c,onInfo:i,onWarn:l});if(a?._resolutionCapture&&f?.paragraph){let u=f.paragraph,d=c?.byParagraph?.get(u)||null;Object.assign(a._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:jl(e,u,d,t,a)})}return f}function Nm(e,t,r,n,o,a={}){let i={...a,_resolutionCapture:null,onInfo:()=>{},onWarn:()=>{}},l=m=>{if(!m)return null;let p=se(e).indexOf(m);return p>=0?p:null},s;try{s=At(e,t,r,"redline",o,i)}catch{return null}let c=l(s?.paragraph);if(c===null)return null;let f=a.targetEndDescriptor||null,u=null;if(a._compiledSourceEndId&&a._sourceTargetRegistry)u=a._sourceTargetRegistry.resolve(a._compiledSourceEndId,e)?.paragraph||null;else if(f)u=At(e,f.text||"",f.index,"redline",o,{...i,targetDescriptor:f,_compiledSourceId:null})?.paragraph||null;else if(n)u=Jn(e,{targetRef:n,opType:"redline",targetRefSnapshot:o?.targetRefSnapshot||null,onInfo:()=>{},onWarn:()=>{}})?.paragraph||null;else return{from:c,to:c};let d=l(u);return d!==null&&d>=c?{from:c,to:d}:null}function Sr(e){return hl(e)}function Uy(e,t){if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||!t.includes("Paragraph expanded to list fragment"))return e;let r=e[e.length-1];return!r||r.localName!=="p"||Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.localName!=="pPr")?e:e.slice(0,-1)}function at(e){hi(e)}function zy(e){for(let t of Array.from(e?.getElementsByTagNameNS?.(ce,"proofErr")||[]))t.parentNode?.removeChild(t)}function Xy(e){e&&zy(e)}function be(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI===ce&&r.localName===t)||null}function Vy(e,t){if(!e||!t)return null;let n=Array.from(e.getElementsByTagNameNS(ce,"tbl")).indexOf(t);return n>=0?n+1:null}function jy(e){return String(e||"").replace(/\r\n/g,`
220
221
  `).split(`
221
222
  `).map(t=>t.trim()).filter(Boolean).join(`
222
- `)}function Hg(e,t,r){let n=jg(e,t);if(!Number.isInteger(n)||n<1)return null;let o=Kg(r);return o?`table:${n}|payload:${o}`:null}function Gg(e,t,r,n){let o=tt(t,"pPr");o||(o=D(e,"w:pPr"),t.insertBefore(o,t.firstChild));let a=tt(o,"numPr");a||(a=D(e,"w:numPr"),o.appendChild(a));let i=tt(a,"ilvl");i||(i=D(e,"w:ilvl"),a.appendChild(i)),i.setAttribute("w:val",String(Math.max(0,Number.parseInt(r,10)||0)));let s=tt(a,"numId");s||(s=D(e,"w:numId"),a.appendChild(s)),s.setAttribute("w:val",String(n))}function hs(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,s=D(e,"w:p"),l=tt(t,"pPr");l&&s.appendChild(ct(l)),Gg(e,s,r.ilvl,r.numId),i&&Or(e,s,o);let c=D(e,"w:r"),u=Array.from(t.getElementsByTagNameNS(ae,"r"))[0]||null,f=u?tt(u,"rPr"):null;f&&c.appendChild(ct(f));let d=D(e,"w:t"),m=String(r.text||"").trim();if(/^\s|\s$/.test(m)&&d.setAttribute("xml:space","preserve"),d.textContent=m,c.appendChild(d),i){let p=n||ie(o,e),g=D(e,"w:ins");g.setAttribute("w:id",String(p.id)),g.setAttribute("w:author",p.author),g.setAttribute("w:date",p.date),g.appendChild(c),s.appendChild(g)}else s.appendChild(c);return s}function gs(e,t){let r=(e||[]).map(n=>t.serializeToString(n)).join("");return`<w:document xmlns:w="${ae}"><w:body>${r}</w:body></w:document>`}function qg({xmlDoc:e,explicitRangeParagraphs:t,insertionEntries:r,generateRedlines:n,author:o}){if(!Array.isArray(t)||t.length===0||!Array.isArray(r)||r.length===0)return!1;let a=t[0].parentNode;if(!a||t.some(s=>s.parentNode!==a))return!1;let i=t[t.length-1].nextSibling;for(let s of r){let l=s.insertBeforeOriginalIndex!=null?t[s.insertBeforeOriginalIndex]:t[t.length-1];if(!l)return!1;let c=hs(e,l,{ilvl:s.ilvl,markerType:s.markerType,numId:s.numId,text:s.text},n?ie(o,e):null,o,{generateRedlines:n});s.insertBeforeOriginalIndex!=null?a.insertBefore(c,l):a.insertBefore(c,i)}return lt(e),!0}function Yg(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=D(e,"w:p"),s=D(e,"w:r"),l=D(e,"w:t"),c=String(t||"");if(/^\s|\s$/.test(c)&&l.setAttribute("xml:space","preserve"),l.textContent=c,s.appendChild(l),a){o.trackParagraphMark===!0&&Or(e,i,n);let u=r||ie(n,e,"ins"),f=D(e,"w:ins");f.setAttribute("w:id",String(u.id)),f.setAttribute("w:author",u.author),f.setAttribute("w:date",u.date),f.appendChild(s),i.appendChild(f)}else i.appendChild(s);return i}function Zg(e,t){let r=D(e,"w:p"),n=tt(t,"pPr");n&&r.appendChild(ct(n));let o=D(e,"w:r"),a=Array.from(t.getElementsByTagNameNS(ae,"r"))[0]||null,i=a?tt(a,"rPr"):null;i&&o.appendChild(ct(i));let s=D(e,"w:t");return s.textContent="",o.appendChild(s),r.appendChild(o),r}function ju(e,t,r,n,o={}){let a=D(e,"w:p"),i=o.sanitizeParagraphProperties===!0?Ku(e,t):ct(tt(t,"pPr"));i&&a.appendChild(i),o.paragraphId&&a.setAttributeNS(vs,"w14:paraId",o.paragraphId),o.trackParagraphMark===!0&&Or(e,a,n);let s=D(e,"w:ins"),l=r||ie(n,e,"ins");s.setAttribute("w:id",String(l.id)),s.setAttribute("w:author",l.author),s.setAttribute("w:date",l.date);for(let c of Array.from(t.childNodes||[]))c?.nodeType===1&&c.namespaceURI===ae&&c.localName==="pPr"||s.appendChild(c.cloneNode(!0));return a.appendChild(s),a}async function Jg(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,s=oe(),l=Zg(e,t),c=s.serializeToString(l),u=await Rn(c,"",String(r||""),{author:o,generateRedlines:!1}),f=null;return typeof u?.oxml=="string"&&(f=(or(u.oxml).replacementNodes||[]).find(m=>m&&m.nodeType===1&&m.namespaceURI===ae&&m.localName==="p")||null),f?i?ju(e,f,n,o,a):f:Yg(e,r,n,o,{...a,generateRedlines:i})}function xs(e){let t=new Set;for(let r of e||[]){let n=Array.from(r?.getElementsByTagNameNS?.("*","numId")||[]);for(let o of n){let a=o.getAttribute("w:val")||o.getAttribute("val");a!=null&&a!==""&&t.add(String(a))}}return Array.from(t)}function Xu(e){return Array.from(e?.childNodes||[]).reduce((t,r)=>t+(r?.nodeType===1&&r.namespaceURI===ae&&r.localName==="r"?Ht(r).map(n=>n.text).join(""):""),"")}function Qg(e,t,r){let n=0,o=-1;for(let a=0;a<r;a++){if(o=e.indexOf(t,n),o<0)return-1;n=o+Math.max(t.length,1)}return o}function eh(e,t){if(!t)return 0;let r=0,n=0;for(;n<=e.length;){let o=e.indexOf(t,n);if(o<0)break;r+=1,n=o+t.length}return r}function th(e,t){let r=new Set(["commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"]);if(Array.from(e.getElementsByTagName?.("*")||[]).some(n=>r.has(n.localName)))return!0;for(let n of Array.from(t?.childNodes||[]))if(n.nodeType===1){if(!(n.namespaceURI===ae&&n.localName==="r"))return!0;for(let o of Array.from(n.childNodes||[]))if(!(o.nodeType!==1||o.namespaceURI!==ae)&&!["rPr","delText","t","tab","br","cr","noBreakHyphen","softHyphen"].includes(o.localName))return!0}return!1}function rh(e,t){let r=0;for(let n of Array.from(e?.childNodes||[])){if(!(n?.nodeType===1&&n.namespaceURI===ae&&n.localName==="r"))continue;let o=yt(Ht(n));if(t<=r+o)return ct(tt(n,"rPr"));r+=o}return null}var nh=new Set(["pStyle","numPr","ind","jc","spacing","tabs","keepNext","keepLines","outlineLvl","contextualSpacing"]);function ws(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Vu(e){return String(e||"").trim().toLowerCase()}function oh(e,t="nextSibling"){let r=e?.[t]||null;for(;r;){if(r.nodeType===1&&r.namespaceURI===ae&&r.localName==="p")return r;r=r[t]||null}return null}function Ku(e,t){let r=tt(t,"pPr"),n=D(e,"w:pPr");if(!r)return n;for(let o of Array.from(r.childNodes||[]))o.nodeType!==1||o.namespaceURI!==ae||nh.has(o.localName)&&n.appendChild(e.importNode(o,!0));return n}function ah(e){let t=[],r=new Set;for(let o of Array.from(e?.getElementsByTagNameNS?.(ae,"bookmarkStart")||[])){let a=ws(o,"name")||"(unnamed)";r.add(a)}for(let o of r)t.push(`RESTORATION_DROPPED_BOOKMARK:${o}`);let n=new Set;for(let o of["commentRangeStart","commentRangeEnd","commentReference"])for(let a of Array.from(e?.getElementsByTagNameNS?.(ae,o)||[])){let i=ws(a,"id");i!==""&&n.add(i)}for(let o of n)t.push(`RESTORATION_DROPPED_COMMENT:${o}`);return t}function ih(e){let t=["bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference"];for(let r of t)for(let n of Array.from(e?.getElementsByTagNameNS?.(ae,r)||[]))n.parentNode?.removeChild(n);for(let r of Array.from(e?.getElementsByTagNameNS?.(ae,"r")||[]))Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.namespaceURI===ae&&o.localName!=="rPr")||r.parentNode?.removeChild(r)}function sh(e,t,r){let n=yr(r.serializeToString(t),{allAuthors:!0}),a=W(n.oxml,"application/xml").doc?.getElementsByTagNameNS?.(ae,"p")?.[0]||null;if(!a)return null;let i=D(e,"w:p");i.appendChild(Ku(e,t));for(let s of Array.from(a.childNodes||[]))s.nodeType===1&&s.namespaceURI===ae&&s.localName==="pPr"||i.appendChild(e.importNode(s,!0));return ih(i),i}async function lh(e,t,r,n,o){let a=te(t);if(a===r)return t;let i=await Rn(o.serializeToString(t),a,r,{author:n,generateRedlines:!1,structuredContent:!1});if(i?.status==="error"||typeof i?.oxml!="string")return null;let l=(or(i.oxml).replacementNodes||[]).find(c=>c?.nodeType===1&&c.namespaceURI===ae&&c.localName==="p");return l?e.importNode(l,!0):null}function ch(e,t){let r=new Set(le(e).map(o=>o.getAttributeNS?.(vs,"paraId")||o.getAttribute?.("w14:paraId")||"").filter(Boolean).map(o=>o.toUpperCase())),n=null;do n=t?.generateParagraphId?.()||(1073741824+r.size+1).toString(16).toUpperCase();while(r.has(n.toUpperCase()));return n}function uh(e,t,r,n){let o=e.documentElement;return o&&!o.getAttribute("xmlns:w14")&&o.setAttribute("xmlns:w14",vs),ju(e,t,null,r,{paragraphId:ch(e,n),sanitizeParagraphProperties:!0,trackParagraphMark:!0})}function fh(e,t){let r=tt(e,"pPr"),n=tt(r,"rPr"),o=tt(n,"ins");return!!o&&Vu(ws(o,"author"))===Vu(t)}function dh(e,t){let r=[],n=e;for(let o=0;o<t;o++){if(n=oh(n,"nextSibling"),!n)return[];r.push(n)}return r}function ys(e){let t=W(e,"application/xml");return t.error||!t.doc?null:le(t.doc).map(r=>te(r))}function mh(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>r===t[n])}function La(e,t){let r=t==="accept"?Br(e,{allAuthors:!0}):yr(e,{allAuthors:!0});return ys(r.oxml)}function ph(e,t,r,n){let o=W(e,"application/xml");if(o.error||!o.doc)return null;let a=o.doc,i=le(a),s=i[t+n.length-1]||null;if(!s?.parentNode)return null;for(let c of[...r].sort((u,f)=>f-u)){let u=i[c];u?.parentNode?.removeChild(u)}let l=s.nextSibling;for(let c of n)s.parentNode.insertBefore(a.importNode(c,!0),l);return oe().serializeToString(a)}function gh(e,t,r,n,o,a=[]){let i=pt(e),s=pt(t),l=Zr(s.issues,i.issues),c=a.flatMap(m=>pt(oe().serializeToString(m)).issues.filter(p=>p.severity==="error")),u=Jr(l);if(u.length>0||c.length>0)return{valid:!1,stage:"validation",code:"GENERATED_OOXML_INVALID",generatedIssues:l,envelopeIssues:c,message:[...u,...c].map(m=>m.message).join(" ")};let f=ph(e,r,n,o);if(!f)return{valid:!1,stage:"expected-document",message:"Could not construct the restoration lifecycle oracle."};let d=[["current",ys(f),ys(t)],["accept-all",La(f,"accept"),La(t,"accept")],["reject-all",La(e,"reject"),La(t,"reject")]];for(let[m,p,g]of d)if(!mh(p,g))return{valid:!1,stage:m,expected:p,actual:g,message:`Paragraph restoration ${m} lifecycle text did not match the expected body-scoped paragraph sequence.`};return{valid:!0}}async function Hu(e,t,r,n,o,a=null,i=null,s={}){let{serializer:l,xmlDoc:c,operationSession:u}=Qr(e,s);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let f=nr(c,t,a,"insert",i,s);if(f?.error||!f?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:f?.error||{code:"TARGET_NOT_FOUND",message:"Rejected-view insertion target was not found."}};let d=f.paragraph;if(!vr(d,o).matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"REJECTED_INSERTION_STATE_REQUIRED",message:"Rejected-view insertion requires a wholly deleted paragraph owned by another author."}};let p=Fr(d,{requireFollowingParagraph:!1});if(p)return{documentXml:e,hasChanges:!1,status:"error",error:p};if(/\r|\n/.test(n))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Rejected-view insertion supports run-level text only; use restore for paragraph boundaries."}};let g=te(d,{revisionView:"rejected"});if(!r.occurrenceExplicit&&eh(g,r.exactText)>1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"AMBIGUOUS_ANCHOR",message:"The rejected-view insertion anchor is repeated; provide anchor.occurrence explicitly."}};let h=Qg(g,r.exactText,r.occurrence);if(h<0)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"ANCHOR_NOT_FOUND",message:"The rejected-view insertion anchor was not found at the requested occurrence."}};let y=h+r.offset,w=Array.from(d.childNodes||[]).filter(R=>R?.nodeType===1&&R.namespaceURI===ae&&R.localName==="del");if(w.some(R=>th(d,R)))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_BOUNDARY",message:"The rejected-view insertion boundary contains comments, bookmarks, fields, hyperlinks, moves, or non-text run markup that cannot be split safely."}};let v=0,b=null,x=0;for(let R of w){let M=Xu(R).length;if(y>=v&&y<=v+M){b=R,x=y-v;break}v+=M}if(!b||w.map(Xu).join("")!==g)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"The rejected-view anchor is not contained in a supported direct deletion carrier."}};let T=rh(b,x),{leftCarrier:I,rightCarrier:N}=Vo(c,b,x,s._revisionIdAllocator||null),A=D(c,"w:ins"),S=ie(o,s._revisionIdAllocator||c,"ins");A.setAttribute("w:id",String(S.id)),A.setAttribute("w:author",S.author),A.setAttribute("w:date",S.date);let O=D(c,"w:r");T&&O.appendChild(T);let E=D(c,"w:t");/^\s|\s$/.test(n)&&E.setAttribute("xml:space","preserve"),E.textContent=n,O.appendChild(E),A.appendChild(O);let k=b.parentNode;I&&k.insertBefore(I,b),k.insertBefore(A,b),N&&k.insertBefore(N,b),s?._mutationRemovedNodes?.push(b),k.removeChild(b),s?._mutationLiveNodes?.push(d,A),u?.invalidateParagraphMetadata?.();let C=l.serializeToString(c),P=te(d,{revisionView:"rejected"}),_=te(d,{revisionView:"accepted"});return P!==g||!_.includes(n)?{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Rejected-view insertion did not preserve the deleted source and expose the requested inserted text."}}:{documentXml:C,hasChanges:!0,status:"ok"}}async function Gu(e,t,r,n,o=null,a=null,i=null,s={}){let{serializer:l,xmlDoc:c,operationSession:u}=Qr(e,s);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let f=nr(c,t,o,"restore",i,s);if(f?.error||!f?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:f?.error||{code:"TARGET_NOT_FOUND",message:"Restoration target paragraph not found."}};let d=f.paragraph,m=[d];if(s._compiledSourceEndId){let k=nr(c,s.targetEndDescriptor?.text||"",a,"restore",i,{...s,_compiledSourceId:s._compiledSourceEndId}),C=k?.paragraph?le(c):[],P=C.indexOf(d),_=C.indexOf(k?.paragraph);m=P>=0&&_>=P?C.slice(P,_+1):null}else if(a)m=fn(c,o,a,{opType:"restore",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:s.onInfo,onWarn:s.onWarn});else if(s.targetEndDescriptor){let k=nr(c,s.targetEndDescriptor.text,s.targetEndDescriptor.index,"restore",i,{...s,targetDescriptor:s.targetEndDescriptor,_compiledSourceId:s._compiledSourceEndId||null}),C=k?.paragraph?le(c):[],P=C.indexOf(d),_=C.indexOf(k?.paragraph);m=P>=0&&_>=P?C.slice(P,_+1):null}if(!Array.isArray(m)||m.length===0||m[0]!==d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:"The restoration range could not be resolved as a contiguous paragraph block."}};let p=Array.isArray(r)?r.map(String):[String(r||"")];if(p.length!==m.length||p.some(k=>k.length===0))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:`Restoration requires exactly one non-empty replacement per source paragraph (${m.length} expected, ${p.length} received).`}};let g=d.parentNode;if(!g||m.some(k=>k.parentNode!==g))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Restoration source paragraphs must be a contiguous block in one structural container."}};for(let k of m){let C=Fr(k);if(C?.code==="UNSUPPORTED_MOVE_REVISION")return{documentXml:e,hasChanges:!1,status:"error",error:C};let P=vr(k,n);if(!P.matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_STATE_REQUIRED",message:P.hasParagraphMarkDeletion&&!P.foreignParagraphMarkDeletion?"Explicit cross-author restoration does not apply to a paragraph deleted by the current author; use merge-same-author.":"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...P.ownerAuthor?{ownerAuthor:P.ownerAuthor}:{}}};let _=C||Fr(k);if(_)return{documentXml:e,hasChanges:!1,status:"error",error:_}}let h=m[m.length-1],y=dh(h,m.length),w=y.length===m.length&&y.every(k=>fh(k,n));if(w&&y.every((k,C)=>te(k)===p[C]))return{documentXml:e,hasChanges:!1,status:"no-op",warnings:["An identical same-author paragraph restoration already exists."]};let v=l.serializeToString(c),b=le(c),x=b.indexOf(d),T=w?y.map(k=>b.indexOf(k)):[],I=[],N=[];for(let k=0;k<m.length;k++){let C=m[k];N.push(...ah(C));let P=sh(c,C,l),_=P?await lh(c,P,p[k],n,l):null;if(!_)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:`Could not reconstruct restoration paragraph ${k+1} from its rejected revision view.`}};I.push(_)}let A=I.map(k=>{let C=c.importNode(k,!0);return uh(c,C,n,u)}),S=h.nextSibling;for(let k of A)g.insertBefore(k,S);if(w)for(let k of y)s?._mutationRemovedNodes?.push(k),k.parentNode?.removeChild(k);s?._mutationLiveNodes?.push(...A),lt(c);let O=l.serializeToString(c),E=gh(v,O,x,T,I,A);return E.valid?{documentXml:st(c,l,e,u),hasChanges:!0,status:"ok",numberingXml:null,...N.length>0?{warnings:[...new Set(N)]}:{}}:{documentXml:e,hasChanges:!1,status:"error",error:{code:E.code||"PATCH_ROUNDTRIP_MISMATCH",message:E.message,stage:E.stage,...E.generatedIssues?{generatedIssues:E.generatedIssues}:{},...E.envelopeIssues?{envelopeIssues:E.envelopeIssues}:{},...E.expected?{expected:E.expected}:{},...E.actual?{actual:E.actual}:{}}}}async function hh({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:s,runtimeContext:l,revisionIdAllocator:c,generateRedlines:u=!0,onInfo:f=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=pn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p||p.numberingKey!=="numbered:decimal:single"||!Number.isInteger(p.startAt)||p.startAt<1)return null;let g=Mi(p.listInput||i);if(!g)return null;f("[List] Applying explicit numeric header conversion with direct list binding.");let h=await Rn(t.serializeToString(o),a,g,{author:s,generateRedlines:u,_revisionIdAllocator:c});if(!h?.hasChanges||typeof h?.oxml!="string")return null;let w=or(h.oxml).replacementNodes,v=aa(p,l?.listFallbackSequenceState||null),b=p.startAt,x=l?.numberingIdState||null,T=null,I=null;if(v.type==="explicitReuse"&&v.numId)T=String(v.numId),f(`[List] Reusing explicit-start list sequence (${v.numberingKey} -> numId ${T}, next ${b+1}).`);else{let A=ca(x);if(!A)return null;T=String(A.numId),I=da(A.numId,A.abstractNumId,b),v.type==="explicitStartNew"&&f(`[List] Started explicit-start list sequence (${v.numberingKey} -> numId ${T}).`),f(`[List] Using isolated explicit-start numbering (start ${b}, numId ${T}, abstractNumId ${A.abstractNumId}).`)}p.numberingKey&&l?.listFallbackSharedNumIdByKey instanceof Map&&l.listFallbackSharedNumIdByKey.delete(p.numberingKey),v.type==="explicitStartNew"||v.type==="explicitReuse"?ia(l?.listFallbackSequenceState||null,v.numberingKey||p.numberingKey,T,b):eo(l?.listFallbackSequenceState||null,v.numberingKey||p.numberingKey),sa(w,{numId:T,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0});let N=o.parentNode;if(!N)return null;for(let A of w){let S=e.importNode(A,!0);let O=N.insertBefore(S,o);d?._mutationLiveNodes?.push(O)}if(d?._mutationRemovedNodes?.push(o),N.removeChild(o),lt(e),n?.receiptCollector&&I){let A=xs(d?._mutationLiveNodes);for(let S of A)n.receiptCollector.recordNumbering(S)}return{documentXml:st(e,t,r,n),hasChanges:!0,numberingXml:I}}async function wh({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:s,runtimeContext:l,revisionIdAllocator:c,generateRedlines:u=!0,onInfo:f=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=pn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p)return null;f("[List] No textual diff but list marker detected; forcing structural list conversion fallback.");let g=await gn(p,{author:s,generateRedlines:u,revisionIdAllocator:c,setAbstractStartOverride:!1});if(!g?.hasChanges||!g?.oxml)return f("[List] Structural list fallback produced no valid OOXML payload."),null;let h=or(g.oxml),y=h.replacementNodes,w=h.numberingXml||g?.numberingXml||null,v=Number.isInteger(p?.startAt)&&p.startAt>0,b=g?.listStructuralFallbackKey||p?.numberingKey||null,x=aa(p,l?.listFallbackSequenceState||null);if(v){let I=p.startAt,N=null,A=l?.numberingIdState||null;if(x.type==="explicitReuse"&&x.numId)N=String(x.numId),w=null,f(`[List] Reusing explicit-start list sequence (${x.numberingKey} -> numId ${N}, next ${I+1}).`);else if(A){let S=ca(A);if(!S)return null;ua(y,S.numId),N=String(S.numId),w=da(S.numId,S.abstractNumId,I),x.type==="explicitStartNew"&&f(`[List] Started explicit-start list sequence (${x.numberingKey} -> numId ${S.numId}).`),f(`[List] Using isolated explicit-start numbering (start ${I}, numId ${S.numId}, abstractNumId ${S.abstractNumId}).`)}else{let S=fa(y);N=S?String(S):null,f(`[List] Using isolated list numbering with explicit start ${I}${S?` (numId ${S})`:""}.`)}b&&l?.listFallbackSharedNumIdByKey instanceof Map&&l.listFallbackSharedNumIdByKey.delete(b),x.type==="explicitStartNew"||x.type==="explicitReuse"?ia(l?.listFallbackSequenceState||null,x.numberingKey||b,N,I):eo(l?.listFallbackSequenceState||null,x.numberingKey||b),N&&sa(y,{numId:N,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0})}else{if(w&&l?.numberingIdState){let I=yn(w,y,l.numberingIdState);y=I.replacementNodes,w=I.numberingXml}eo(l?.listFallbackSequenceState||null,x.numberingKey||b)}if(!v&&l?.listFallbackSharedNumIdByKey instanceof Map){let I=b?l.listFallbackSharedNumIdByKey.get(b):null;if(I)ua(y,I),w=null,f(`[List] Reusing shared list numbering (${b} -> numId ${I}).`);else if(b){let N=fa(y);N&&(l.listFallbackSharedNumIdByKey.set(b,N),f(`[List] Captured shared list numbering (${b} -> numId ${N}).`))}}let T=o.parentNode;if(!T)return null;for(let I of y){let N=e.importNode(I,!0);let A=T.insertBefore(N,o);d?._mutationLiveNodes?.push(A)}if(d?._mutationRemovedNodes?.push(o),T.removeChild(o),lt(e),n?.receiptCollector&&w){let I=xs(d?._mutationLiveNodes);for(let N of I)n.receiptCollector.recordNumbering(N)}return{documentXml:st(e,t,r,n),hasChanges:!0,numberingXml:w}}async function qu(e,t,r,n,o=null,a=null,i=null,s={}){let l=s.generateRedlines!==!1,c=typeof s?.onInfo=="function"?s.onInfo:()=>{},u=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=Qr(e,s);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||An(d,s),g=nr(d,t,o,"redline",i,{...s,onInfo:c,onWarn:u});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph;if(typeof r=="string"&&r.length>0){let L=vr(h,n);if(L.matches){let j=L.ownerAuthor||"unattributed";return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${j}). Use explicit paragraph restoration when supported.`,ownerAuthor:j}}}}Wg(h);let y=xo(h);if(r===""){let L=$u(h);if(L.length>0){let j=Uu(L,s._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:L,...j.length>0?{comments:j}:{}}}}}let w=ta(h,r,s);if(!w.valid)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:w.code,message:w.message}};let v=mr(h),b=s.existingRevisions||"merge-same-author";if(v&&b!=="accept-all-first"&&b!=="accept-all-first-keep-normalized")if(b==="merge-same-author"||b==="slice-cross-author"){let L=Rr(h),j=String(n||"").trim().toLowerCase(),J=L.length>0&&L.every(Ze=>Ze.trim().toLowerCase()===j);if(!J&&b==="merge-same-author")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${L.length?L.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:L,currentPolicy:b}};let we=J?$u(h):[];if(we.length>0){let Ze=Uu(we,s._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:we,...Ze.length>0?{comments:Ze}:{}}}}if(!J&&(h.getElementsByTagNameNS(ae,"moveFrom").length>0||h.getElementsByTagNameNS(ae,"moveTo").length>0))return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}}}else{let L=h.getElementsByTagNameNS(ae,"del").length>0,j=h.getElementsByTagNameNS(ae,"moveFrom").length>0||h.getElementsByTagNameNS(ae,"moveTo").length>0;return L?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}}:j?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}}:{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}}if(r===""&&y===""&&!(v&&b==="merge-same-author"))return l?(_r(d,h,n,ie(n,d)),s?._mutationLiveNodes?.push(h)):(s?._mutationRemovedNodes?.push(h),h.parentNode?.removeChild(h)),lt(d),{documentXml:st(d,f,e,m),hasChanges:!0,numberingXml:null};let x=He(h,"tbl"),I=!!x&&!a&&typeof r=="string"&&r.includes(`
223
- `)&&!Ur(r)?Hg(d,x,r):null,N=i?.tableStructuralRedlineKeys instanceof Set?i.tableStructuralRedlineKeys:null;if(I&&N?.has(I))return c("[Table] Skipping duplicate table-structural redline for the same table/payload in this turn."),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:["Skipped duplicate table-structural redline in the same turn."]};let S=(x?Fi(h,r,{tableElement:x,currentParagraphText:y,onInfo:c,onWarn:u}):null)||r,O=!!x&&Ur(S),E=Ur(S),k=a?fn(d,o,a,{opType:"redline",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:c,onWarn:u}):typeof t=="string"&&/\r?\n/.test(t)?Wo(d,t):null,C=Array.isArray(k)&&k.length>0;if(!O&&C){let L=_u(k,S);if(L&&L.length>0){c(`[List] Applying explicit-range insertion-only heuristic (${L.length} new item(s)).`);for(let J of L)c(`[List] Explicit-range insertion: ilvl=${J.ilvl}, markerType=${J.markerType}, text="${String(J.text||"").slice(0,80)}${String(J.text||"").length>80?"\u2026":""}"`);if(qg({xmlDoc:d,explicitRangeParagraphs:k,insertionEntries:L,generateRedlines:l,author:n}))return{documentXml:st(d,f,e,m),hasChanges:!0,numberingXml:null}}}let P=null;!k&&!O&&E&&(P=Di(h,{getParagraphText:xo}),P?.length>1&&c(`[Table] Heuristic range expansion selected ${P.length} paragraph(s) for replacement.`));let _=mt(h);if(_&&typeof S=="string"&&!S.includes(`
224
- `)){let L=Xr(S);L&&L!==S.trim()&&(c("[List] Stripped redundant manual list marker prefix from single-line list item edit."),S=L)}O&&c("[Table] Markdown table edit detected in table cell target; applying reconciliation at table scope.");let R=s.explicitStructuredContent===!0,M=!R&&!O&&!C&&_?ku(y,S):null;if(M){c(`[List] Applying single-paragraph list adjacency insertion heuristic (${M.position}).`);let L=h.parentNode;if(!L)throw new Error("Target paragraph has no parent for adjacency list insertion");let j=hs(d,h,{ilvl:_.ilvl,numId:_.numId,markerType:"numbered",text:M.text},l?ie(n,d):null,n,{generateRedlines:l}),J=M.position==="before"?h:h.nextSibling;return L.insertBefore(j,J),s?._mutationLiveNodes?.push(j),lt(d),{documentXml:st(d,f,e,m),hasChanges:!0,numberingXml:null}}let U=!O&&!C&&!_&&!x&&!a?Lu(S):null,X=U?We(U.paragraphMarkdown):null;if(U&&q(X.cleanText)===q(y)){let L=rt(U.tableText);if(L.headers.length>0||L.rows.length>0){c("[Table] Applying retained-paragraph table append heuristic.");let j=h.parentNode;if(!j)throw new Error("Target paragraph has no parent for table append");let J=h.nextSibling;if(X.formatHints.length>0){let Be=await Rn(f.serializeToString(h),y||t,U.paragraphMarkdown,{author:n,generateRedlines:l,existingRevisions:s.existingRevisions||"merge-same-author",structuredContent:!1,_revisionIdAllocator:p});if(Be?.status==="error")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:Be.error};if(Be?.hasChanges){if(typeof Be.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed paragraph format");for(let Ut of or(Be.oxml).replacementNodes){let zt=d.importNode(Ut,!0);s?._mutationLiveNodes?.push(j.insertBefore(zt,h))}s?._mutationRemovedNodes?.push(h),j.removeChild(h)}}let we=Kt(L,{generateRedlines:l,author:n,revisionIdAllocator:p,trackAsBlock:!0});for(let Be of or(we).replacementNodes)s?._mutationLiveNodes?.push(j.insertBefore(d.importNode(Be,!0),J));if(!J||J.nodeType===1&&J.namespaceURI===ae&&J.localName==="sectPr"){let Be=D(d,"w:p"),Ut=ct(tt(h,"pPr"));if(Ut){for(let zt of Array.from(Ut.childNodes))zt.nodeType===1&&["sectPr","numPr"].includes(zt.localName)&&Ut.removeChild(zt);Be.appendChild(Ut)}l&&Or(d,Be,n),s?._mutationLiveNodes?.push(j.insertBefore(Be,J))}return lt(d),{documentXml:st(d,f,e,m),hasChanges:!0,numberingXml:null}}}let z=!R&&!O&&!C&&!_?Mu(y,S):null;if(z){c(`[Text] Applying single-paragraph plain adjacency insertion heuristic (${z.position}, count=${z.paragraphs.length}).`);let L=h.parentNode;if(!L)throw new Error("Target paragraph has no parent for plain adjacency insertion");let j=z.position==="before"?h:h.nextSibling;for(let J of z.paragraphs){let we=await Jg(d,h,J,l?ie(n,d):null,n,{generateRedlines:l,trackParagraphMark:!0}),Ze=d.importNode(we,!0);let Be=L.insertBefore(Ze,j);s?._mutationLiveNodes?.push(Be)}return lt(d),{documentXml:st(d,f,e,m),hasChanges:!0,numberingXml:null}}let H=!R&&!O&&!C?_i(h,S,{currentParagraphText:y,onInfo:c,onWarn:u}):null;if(H&&H.entries.length>0){c(`[List] Applying insertion-only list redline heuristic (${H.entries.length} new item(s)).`);for(let J of H.entries)c(`[List] Insertion entry resolved: ilvl=${J.ilvl}, markerType=${J.markerType}, text="${String(J.text||"").slice(0,80)}${String(J.text||"").length>80?"\u2026":""}"`);let L=h.parentNode;if(!L)throw new Error("Target paragraph has no parent for list insertion");let j=h.nextSibling;for(let J of H.entries){let we=hs(d,h,{...J,numId:H.numId},l?ie(n,d):null,n,{generateRedlines:l});L.insertBefore(we,j),s?._mutationLiveNodes?.push(we)}return lt(d),{documentXml:st(d,f,e,m),hasChanges:!0,numberingXml:null}}let se=!R&&!O&&!C?Oi(h,S,{currentParagraphText:y,onInfo:c,onWarn:u}):null,ue=!!se&&Array.isArray(se.paragraphs)&&se.paragraphs.length>0;if(ue&&(S=se.modifiedText),!R&&!O&&!ue&&!C){let L=await hh({xmlDoc:d,serializer:f,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:y,modifiedText:S,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:l,onInfo:c,options:s});if(L)return L;let j=await wh({xmlDoc:d,serializer:f,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:y,modifiedText:S,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:l,onInfo:c,options:s});if(j)return j}let Y=ue?se.originalText:k?k.map(L=>xo(L)).join(`
225
- `):P?P.map(L=>xo(L)).join(`
226
- `):y||t,G=O?f.serializeToString(x):ue?gs(se.paragraphs,f):k?gs(k,f):P?gs(P,f):f.serializeToString(h),ee=E?await Ug(G,Y,S,{author:n,generateRedlines:l,existingRevisions:s.existingRevisions||"merge-same-author",structuredContent:s.structuredContent!==!1,explicitStructuredContent:s.explicitStructuredContent===!0,_revisionIdAllocator:p,_isolatedTableCell:O}):await Rn(G,Y,S,{author:n,generateRedlines:l,existingRevisions:s.existingRevisions||"merge-same-author",structuredContent:s.structuredContent!==!1,explicitStructuredContent:s.explicitStructuredContent===!0,pairReplacements:s.pairReplacements===!0,insertionAffinity:s.insertionAffinity||null,literalTextEdit:s.literalTextEdit===!0,_revisionIdAllocator:p,_isolatedTableCell:O});if(!ee?.hasChanges)return{documentXml:e,hasChanges:!1,numberingXml:null,status:ee?.status||"no-op",error:ee?.error};if(ee.useNativeApi&&!ee.oxml){let L="Format-only fallback requires native Word API; browser demo skipped this operation.";return u(`[WARN] ${L}`),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:[L]}}if(typeof ee.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed redline operation");let xe=or(ee.oxml),me=Xg(xe.replacementNodes,ee.warnings),pe=xe.numberingXml;if(pe&&i?.numberingIdState&&!O){let L=ue?se.paragraphs:k||[h],j=Bc(pe,me,L,i.numberingIdState);j&&(me=j.replacementNodes,pe=null)}if(pe&&i?.numberingIdState){let L=yn(pe,me,i.numberingIdState);me=L.replacementNodes,pe=L.numberingXml}let be=O?[x]:ue?se.paragraphs:k||P||[h],Tt=be[0],K=Tt.parentNode;for(let L of me){let j=d.importNode(L,!0);let J=K.insertBefore(j,Tt);s?._mutationLiveNodes?.push(J)}for(let L of be)L&&L.parentNode===K&&(s?._mutationRemovedNodes?.push(L),K.removeChild(L));if(lt(d),I&&N&&(O||x)&&N.add(I),m?.receiptCollector&&pe){let L=xs(s?._mutationLiveNodes);for(let j of L)m.receiptCollector.recordNumbering(j)}return{documentXml:st(d,f,e,m),hasChanges:!0,numberingXml:pe,status:"ok",...Array.isArray(ee.warnings)&&ee.warnings.length>0?{warnings:ee.warnings}:{}}}async function Yu(e,t,r,n,o,a=null,i=null,s={}){let l=s.generateRedlines!==!1,c=typeof s?.onInfo=="function"?s.onInfo:()=>{},u=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=Qr(e,s);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||An(d,s),g=nr(d,t,a,"highlight",i,{...s,onInfo:c,onWarn:u});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,y=f.serializeToString(h),w=Zi(y,r,n,{generateRedlines:l,author:o,_revisionIdAllocator:p});if(!w||w===y)return{documentXml:e,hasChanges:!1};let{replacementNodes:v}=or(w),b=h.parentNode;for(let x of v){let T=d.importNode(x,!0);let I=b.insertBefore(T,h);s?._mutationLiveNodes?.push(I)}return s?._mutationRemovedNodes?.push(h),b.removeChild(h),lt(d),{documentXml:st(d,f,e,m),hasChanges:!0}}async function Zu(e,t,r,n,o,a=null,i=null,s={}){let l=typeof s?.onInfo=="function"?s.onInfo:()=>{},c=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:u,xmlDoc:f,operationSession:d}=Qr(e,s);if(!f)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||An(f,s);let m=nr(f,t,a,"comment",i,{...s,onInfo:l,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=u.serializeToString(p),h=typeof r=="string"&&r.length>0?r:xo(p),y=qi(g,[{paragraphIndex:1,textToFind:h,commentContent:n}],{author:o,commentIdAllocator:s.commentIdAllocator});if(y.status==="error"||y.error||!y.commentsApplied)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:y.error||{code:"ANCHOR_INSERTION_FAILED",message:"The comment anchor was not applied to the resolved paragraph."},warnings:y.warnings||[]};let{replacementNodes:w}=or(y.oxml),v=p.parentNode;for(let b of w){let x=f.importNode(b,!0);let T=v.insertBefore(x,p);s?._mutationLiveNodes?.push(T)}if(s?._mutationRemovedNodes?.push(p),v.removeChild(p),lt(f),d?.receiptCollector&&Array.isArray(y.placedComments))for(let b of y.placedComments)d.receiptCollector.recordComment(b.id);return{documentXml:st(f,u,e,d),hasChanges:!0,commentsXml:y.commentsXml||null,warnings:y.warnings||[],resolvedAnchor:y.resolvedAnchors?.[0]||null}}function Wu(e,t,r,n){let o=t.cloneNode(!0),a=t.cloneNode(!0);Lt(a,n);let i=d=>{if(d.nodeType!==1)return!1;let m=d.localName||d.nodeName.replace(/^w:/,"");return["t","tab","br","noBreakHyphen","delText"].includes(m)};Array.from(o.childNodes).forEach(d=>{i(d)&&o.removeChild(d)}),Array.from(a.childNodes).forEach(d=>{i(d)&&a.removeChild(d)});let s="";for(let d of Array.from(t.childNodes)){if(d.nodeType!==1)continue;let m=d.localName||d.nodeName.replace(/^w:/,"");m==="t"?s+=d.textContent||"":m==="tab"?s+=" ":m==="br"?s+=`
227
- `:m==="noBreakHyphen"&&(s+="\u2011")}let l=s.slice(0,r),c=s.slice(r),u=(d,m)=>{let p=m.split(/(\t|\n|\u2011)/);for(let g of p)if(g)if(g===" ")d.appendChild(D(e,"w:tab"));else if(g===`
228
- `)d.appendChild(D(e,"w:br"));else if(g==="\u2011")d.appendChild(D(e,"w:noBreakHyphen"));else{let h=D(e,"w:t");/^\s|\s$/.test(g)&&h.setAttribute("xml:space","preserve"),h.textContent=g,d.appendChild(h)}};u(o,l),u(a,c);let f=t.parentNode;return f.insertBefore(o,t),f.insertBefore(a,t),f.removeChild(t),[o,a]}async function Ju(e,t,r,n={},o,a=null,i=null,s={}){let l=s.generateRedlines!==!1,c=typeof s?.onInfo=="function"?s.onInfo:()=>{},u=typeof s?.onWarn=="function"?s.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=Qr(e,s);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||An(d,s),g=nr(d,t,a,"format",i,{...s,onInfo:c,onWarn:u});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,w=(()=>{let C=[],P=Array.from(h.getElementsByTagNameNS(ae,"r"));for(let _ of P){let R=_.parentNode,M=!1;for(;R&&R!==h;){if(R.nodeType===1&&(R.localName==="del"||R.nodeName==="w:del")){M=!0;break}R=R.parentNode}if(M)continue;let U="";for(let X of Array.from(_.childNodes)){if(X.nodeType!==1)continue;let z=X.localName||X.nodeName.replace(/^w:/,"");z==="t"?U+=X.textContent||"":z==="tab"?U+=" ":z==="br"?U+=`
229
- `:z==="noBreakHyphen"&&(U+="\u2011")}U.length>0&&C.push({run:_,text:U})}return C})(),v="",b=[];for(let C of w){let P=v.length;v+=C.text;let _=v.length;b.push({...C,start:P,end:_})}let x=s.targetDescriptor,T=Number.isInteger(s.textOccurrence)&&s.textOccurrence>0?s.textOccurrence:null,I=T??x?.occurrence??null,N=-1;if(I!=null&&I>0){let C=0,P=0;for(;P<=v.length-r.length;){let _=v.indexOf(r,P);if(_===-1)break;if(C++,C===I){N=_;break}P=_+1}}else N=v.indexOf(r);if(N===-1&&T!=null&&v.includes(r))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_SOURCE_NOT_FOUND",message:`Occurrence ${T} of text to format was not found in target paragraph: "${r}".`}};if(N===-1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:`Text to format was not found in target paragraph: "${r}".`}};let A=N+r.length,S=[];for(let C of b)if(C.start<N&&C.end>N){let P=N-C.start,[_,R]=Wu(d,C.run,P,p);S.push({run:_,start:C.start,end:N,text:C.text.slice(0,P)}),S.push({run:R,start:N,end:C.end,text:C.text.slice(P)})}else S.push(C);let O=[];for(let C of S)if(C.start<A&&C.end>A){let P=A-C.start,[_,R]=Wu(d,C.run,P,p);O.push({run:_,start:C.start,end:A,text:C.text.slice(0,P)}),O.push({run:R,start:A,end:C.end,text:C.text.slice(P)})}else O.push(C);let E=O.filter(C=>C.start>=N&&C.end<=A),k=!1;for(let C of E){let P=C.run.getElementsByTagNameNS(ae,"rPr")[0]||null;if(El(P,n)){k=!0;break}}if(!k)return{documentXml:e,hasChanges:!1,status:"no-op"};for(let C of E){let P=C.run,_=P.getElementsByTagNameNS(ae,"rPr")[0];_||(_=D(d,"w:rPr"),P.insertBefore(_,P.firstChild));let R=P.parentNode,M=!1;for(;R&&R!==h;){if(R.nodeType===1&&(R.localName==="ins"||R.nodeName==="w:ins")){(R.getAttribute("w:author")||R.getAttributeNS(ae,"author"))===(o||re())&&(M=!0);break}R=R.parentNode}let U=M&&s.formattingRevisionPolicy==="coalesce-own-insertion";l&&!U&&Xn(d,_,o||re()),Rl(d,_,n)}return lt(d),s?._mutationLiveNodes?.push(h),{documentXml:st(d,f,e,m),hasChanges:!0,status:"ok"}}async function Qu(e,t,r={},n,o=null,a=null,i={}){let s=i.generateRedlines!==!1,l=typeof i?.onInfo=="function"?i.onInfo:()=>{},c=typeof i?.onWarn=="function"?i.onWarn:()=>{},{serializer:u,xmlDoc:f,operationSession:d}=Qr(e,i);if(!f)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||An(f,i);let m=nr(f,t,o,"paragraph-format",a,{...i,onInfo:l,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=p.getElementsByTagNameNS(ae,"pPr")[0];return g||(g=D(f,"w:pPr"),p.insertBefore(g,p.firstChild)),Pl(g,r)?(s&&Dl(f,g,n||re()),Cl(f,g,r),lt(f),i?._mutationLiveNodes?.push(p),{documentXml:st(f,u,e,d),hasChanges:!0,status:"ok"}):{documentXml:e,hasChanges:!1,status:"no-op"}}function Re(e,t={}){return et(e,t)}async function bs(e,t,r,n=null,o={}){let a=typeof o._operationIndex=="number"?o._operationIndex:1,i={operationIndex:a,...typeof t?.operationId=="string"?{operationId:t.operationId}:{}},s=tr(t);if(!s.valid){let h=Nt(t,r,re());return{documentXml:e,hasChanges:!1,status:"error",error:Re(s.error,i),operationType:it(t).operationKind,authorUsed:h,receipt:Le(a,t?.operationId,h,"refused")}}let l=s.operation||it(t),c=Nt(l,r,re());if(l.operationKind!=="comment_reply"&&l.operationKind!=="comment_resolve"&&l.operationKind!=="rejected-insert"&&l.operationKind!=="restore"&&(l.targetDescriptor?.revisionView==="rejected"||l.targetEndDescriptor?.revisionView==="rejected"))return{documentXml:e,hasChanges:!1,status:"error",error:Re({code:"UNSUPPORTED_REVISION_VIEW_MUTATION",message:"Targeting rejected revision view for mutation is not supported yet."},i),operationType:l.operationKind,authorUsed:c,receipt:Le(a,l.operationId,c,"refused")};if(!o?._documentOperationSession&&o?.expectedRevision){let h=Kr(o.expectedRevision);if(!h.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Re({code:h.error?.code||"INVALID_REVISION_TOKEN",message:h.error?.message||"Invalid revision token."},i),operationType:l.operationKind,authorUsed:c,receipt:Le(a,l.operationId,c,"refused")};if(o.expectedRevision.scope!=="document-parts")return{documentXml:e,hasChanges:!1,status:"error",error:Re({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`},i),operationType:l.operationKind,authorUsed:c,receipt:Le(a,l.operationId,c,"refused")};let y=await so({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!Hr(y.value,o.expectedRevision.value))return{documentXml:e,hasChanges:!1,status:"error",error:Re({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${y.value}'.`,expectedRevision:o.expectedRevision,currentRevision:y},i),operationType:l.operationKind,authorUsed:c,receipt:Le(a,l.operationId,c,"refused")}}let u=o?._documentOperationSession instanceof Tr?o._documentOperationSession:new Tr(e,o);if(!u.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Re(u.parseResult.error,i),warnings:u.parseResult.warnings,operationType:l.operationKind,authorUsed:c,receipt:Le(a,l.operationId,c,"refused")};if(Array.isArray(l.replacements)||l.operationKind==="restore"&&t?.modified===void 0){let h=En(u.document,[t],{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn}),y=h.bindings[0]?.error||h.conflicts[0]||null;if(y)return{documentXml:e,hasChanges:!1,status:"error",error:Re(y,i),operationType:l.operationKind,authorUsed:c,receipt:Le(a,l.operationId,c,"refused")};let w=tr(h.compiledOperations[0]);if(!w.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Re(w.error,i),operationType:l.operationKind,authorUsed:c,receipt:Le(a,l.operationId,c,"refused")};u.sourceTargetRegistry=h.registry,l=w.operation}let f={},d=null,m=u.createSavepoint();u.receiptCollector?.beginOperation(a,l.operationId,c);let p=Array.isArray(l._compiledWarnings)?[...l._compiledWarnings]:[],g={...o,...typeof l.generateRedlines=="boolean"?{generateRedlines:l.generateRedlines}:{},...l.existingRevisions?{existingRevisions:l.existingRevisions}:{},structuredContent:typeof l.structuredContent=="boolean"?l.structuredContent:o.structuredContent!==!1,explicitStructuredContent:l.structuredContent===!0,...l._localizedReplacementCompilation&&l.structuredContent!==!0?{literalTextEdit:!0}:{},pairReplacements:typeof l.pairReplacements=="boolean"?l.pairReplacements:o.pairReplacements!==!1,...l.insertionAffinity?{insertionAffinity:l.insertionAffinity}:{},...l.formattingRevisionPolicy?{formattingRevisionPolicy:l.formattingRevisionPolicy}:{},...l.operationKind==="format"&&Number.isInteger(l.textOccurrence)?{textOccurrence:l.textOccurrence}:{},targetDescriptor:l.targetDescriptor,targetEndDescriptor:l.targetEndDescriptor,_compiledSourceId:l._compiledSourceId||null,_compiledSourceEndId:l._compiledSourceEndId||null,_compiledResolvedBy:l._compiledResolvedBy||null,_sourceTargetRegistry:u.sourceTargetRegistry||null,_resolutionCapture:f,_revisionIdAllocator:u.revisionIdAllocator,_documentOperationSession:u,_mutationLiveNodes:[],_mutationRemovedNodes:[],onInfo:h=>{typeof o?.onInfo=="function"&&o.onInfo(h)},onWarn:h=>{p.push(String(h)),typeof o?.onWarn=="function"&&o.onWarn(h)}};try{let h;if(l.operationKind==="comment_reply"){let v=u.commentsXml||n?.commentsXml||o.commentsXml,b=u.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,x=typeof o.commentIdAllocator=="function"?o.commentIdAllocator():null;if(x==null&&v){let T=[...v.matchAll(/<(?:w:)?comment\b[^>]*\b(?:w:)?id=["'](\d+)["']/g)].map(I=>Number(I[1]));x=(T.length?Math.max(...T):-1)+1}x==null?h={documentXml:e,hasChanges:!1,status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing comments part."}}:(h=Yi({commentsXml:v,commentsExtendedXml:b,documentXml:e,parentCommentId:l.parentCommentId,commentId:x,commentContent:l.commentContent,author:c,date:l.date||new Date().toISOString()}),h.documentXml=e,h.status!=="error"&&h.hasChanges&&(!u.document||!Wc(u.document,h.threadCommentIds,x)?h={documentXml:e,hasChanges:!1,status:"error",error:{code:"PARENT_ANCHOR_NOT_FOUND",message:`Comment '${l.parentCommentId}' has no anchor in the document body, so a reply cannot be placed.`}}:u.receiptCollector&&u.receiptCollector.recordComment(x)))}else if(l.operationKind==="comment_resolve"){let v=ya({commentsXml:u.commentsXml||n?.commentsXml||o.commentsXml,commentsExtendedXml:u.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,commentId:l.commentId,resolved:l.resolved!==!1});h=v.status==="error"?{documentXml:e,hasChanges:!1,status:"error",error:v.error}:{documentXml:e,hasChanges:v.hasChanges,...v.commentsXml?{commentsXml:v.commentsXml,commentsXmlMode:"replace"}:{},...v.commentsExtendedXml?{commentsExtendedXml:v.commentsExtendedXml,commentsExtendedXmlMode:"replace"}:{},resolved:v.resolved,threadRootId:v.threadRootId,commentIds:v.commentIds}}else l.operationKind==="highlight"?h=await Yu(e,l.target,l.textToHighlight,l.color,c,l.targetRef,n,g):l.operationKind==="comment"?h=await Zu(e,l.target,l.textToComment,l.commentContent,c,l.targetRef,n,g):l.operationKind==="format"?h=await Ju(e,l.target,l.textToFormat,l.properties,c,l.targetRef,n,g):l.operationKind==="paragraph-format"?h=await Qu(e,l.target,l.properties,c,l.targetRef,n,g):l.operationKind==="rejected-insert"?h=await Hu(e,l.target,l.anchor,l.modified,c,l.targetRef,n,g):l.operationKind==="restore"?h=await Gu(e,l.target,l.modified,c,l.targetRef,l.targetEndRef,n,g):h=await qu(e,l.target,l.modified,c,l.targetRef,l.targetEndRef,n,g);if((l.operationKind==="comment"||l.operationKind==="comment_reply")&&h?.hasChanges!==!0&&h?.status!=="error"&&!h?.error&&(h={...h,status:"error",error:{code:"COMMENT_NOT_APPLIED",message:"The comment operation completed without placing a comment."}}),p.length>0&&h){let v=Array.from(new Set([...Array.isArray(h.warnings)?h.warnings:[],...p]));h.warnings=v}let y=h?.status==="error"||!!h?.error,w=null;if(y||h?.hasChanges!==!0){u.restoreSavepoint(m);let v=y?"refused":"no_change";if(w=Le(a,l.operationId,c,v),Array.isArray(h?.warnings))for(let b of h.warnings)w.warnings.push(String(b))}else{let v=pt(m.document),b=pt(u.document),x=Zr(b.issues,v.issues),T=Jr(x);if(T.length>0){u.restoreSavepoint(m),w=Le(a,l.operationId,c,"refused");let I=[...new Set(T.map(N=>N.code))].join(", ");return{documentXml:e,hasChanges:!1,status:"error",error:Re({code:"GENERATED_OOXML_INVALID",stage:"validation",message:`Operation introduced invalid OOXML (${I}).`,generatedIssues:T},i),operationType:l.operationKind,authorUsed:c,receipt:w,...f}}if(u.markMutationCommitted(!0),l._compiledSourceId&&u.sourceTargetRegistry&&u.sourceTargetRegistry.commitMutation(l._compiledSourceId,g._mutationRemovedNodes,g._mutationLiveNodes,a),l._localizedReplacementCompilation){let I=null;if(l.operationKind==="restore"){let N=g._mutationLiveNodes.find(A=>A?.localName==="p");N&&(I=te(N,{revisionView:"accepted"}))}else if(l._compiledSourceId&&u.sourceTargetRegistry){let N=u.sourceTargetRegistry.resolve(l._compiledSourceId,u.document);N.paragraph&&(I=te(N.paragraph,{revisionView:"accepted"}))}d=Iu(l._localizedReplacementCompilation,I,f.resolvedTarget||{},l._speculativeContext||null)}if(l.captureKey&&u.captureTable&&u.captureTable.set(l.captureKey,Bu(u,l,g._mutationLiveNodes)),g._mutationRemovedNodes?.length>0&&u.captureTable&&Du(u.captureTable,g._mutationRemovedNodes),f.resolvedTarget&&u.receiptCollector?.recordAffectedTarget(f.resolvedTarget),Array.isArray(h.warnings))for(let I of h.warnings)u.receiptCollector?.recordWarning(I);if(w=u.receiptCollector?.commitOperation("applied"),h.documentXml=u.deferSerialization?u.currentDocumentXml:u.serializeCurrent(),!u.deferSerialization&&w){let I=wo({documentXml:h.documentXml,commentsXml:h.commentsXml||null,numberingXml:h.numberingXml||null},[w]);if(!I.valid)return u.restoreSavepoint(m),w.finalDisposition="rolled_back",w.committed=!1,{documentXml:e,hasChanges:!1,status:"error",error:Re(I.error,i),warnings:[I.error.message],operationType:l.operationKind,authorUsed:c,receipt:w,...f}}}return h?.error&&(h.error=Re(h.error,i)),{...h,operationType:l.operationKind,authorUsed:c,receipt:w,...d?{change:d}:{},...f}}catch(h){u.restoreSavepoint(m);let y=Re(h,i),w=Le(a,l.operationId,c,"refused");return w.warnings.push(y.message),{documentXml:e,hasChanges:!1,status:"error",error:y,warnings:[y.message],operationType:l.operationKind,authorUsed:c,receipt:w,...f}}}var ef="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function tf(e){return e?.type==="comment"||e?.type==="comment_reply"||e?.type==="comment_resolve"?0:1}function Ba(e=[]){let t=Array.isArray(e)?e:[],r=new Map;for(let c=0;c<t.length;c++){let u=t[c],f=u?.captureKey??u?.targetDescriptor?.captureKey;if(f!=null){if(typeof f!="string"||!f.trim()||f.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} declared an invalid captureKey: must be a non-empty string under 256 characters.`}};let d=f.trim();if(r.has(d)){let m=r.get(d);return{valid:!1,error:{code:"DUPLICATE_CAPTURE_KEY",message:`Duplicate capture key "${d}" declared by operations at indices ${m+1} and ${c+1}.`}}}r.set(d,c)}}let n=new Array(t.length).fill(0),o=Array.from({length:t.length},()=>new Set),a=Array.from({length:t.length},()=>new Set),i=new Map;for(let c=0;c<t.length;c++){let u=t[c],f=u?.target?.captureRef??u?.targetDescriptor?.captureRef;if(f!=null){if(typeof f!="string"||!f.trim()||f.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} referenced an invalid captureRef: must be a non-empty string under 256 characters.`}};let d=f.trim();if(!r.has(d))return{valid:!1,error:{code:"CAPTURE_NOT_FOUND",message:`Capture "${d}" referenced by operation ${c+1} was not found in the batch.`}};let m=r.get(d);if(m===c)return{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:`Capture dependency cycle detected: operation ${c+1} references its own capture "${d}".`}};a[c].has(m)||(a[c].add(m),o[m].add(c),n[c]++);let p=it(u).operationKind;p!=="comment"&&p!=="comment_reply"&&p!=="comment_resolve"&&(i.has(d)||i.set(d,[]),i.get(d).push({index:c,select:u?.target?.select??u?.targetDescriptor?.select??null}))}}for(let[c,u]of i){if(u.length<2)continue;let f=u.map(m=>m.select),d=new Set(f);if(!(f.every(m=>typeof m=="string"&&m.length>0)&&d.size===f.length))return{valid:!1,error:{code:"CAPTURE_FANOUT_CONFLICT",message:`Capture "${c}" has overlapping or unscoped mutating consumers at operation indices ${u.map(m=>m.index+1).join(", ")}.`,operationIndexes:u.map(m=>m.index+1),captureRef:c}}}let s=[];for(let c=0;c<t.length;c++)n[c]===0&&s.push({operation:t[c],index:c});let l=[];for(;s.length>0;){s.sort((u,f)=>tf(u.operation)-tf(f.operation)||u.index-f.index);let c=s.shift();l.push(c);for(let u of o[c.index])n[u]--,n[u]===0&&s.push({operation:t[u],index:u})}return l.length<t.length?{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:"Capture dependency cycle detected among batch operations."}}:{valid:!0,scheduled:l,captureProducers:r}}function yh(e,t){if(!t)return e;if(!e)return t;let r=W(e,"application/xml")?.doc,n=W(t,"application/xml")?.doc;if(!r||!n)return e;let o=oe(),a=r.documentElement,i=new Set(Array.from(r.getElementsByTagNameNS(ef,"comment")).map(s=>s.getAttribute("w:id")||s.getAttribute("id")).filter(Boolean));for(let s of Array.from(n.getElementsByTagNameNS(ef,"comment"))){let l=s.getAttribute("w:id")||s.getAttribute("id");l&&i.has(l)||(a.appendChild(r.importNode(s,!0)),l&&i.add(l))}return o.serializeToString(r)}async function Da(e,t,r,n=null,o={}){let a=Array.isArray(t)?t:[],i=re(),s=()=>a.map((E,k)=>Le(k+1,E?.operationId,Nt(E,r,i),"not_attempted")),l=(E,k={})=>{let C=s();return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:[],receipts:C,executionOrder:[],authorsUsed:[],...o.atomic===!0?{rolledBack:!0}:{},status:"error",error:Re(E),retryPlan:er({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:[],receipts:C,operationCount:a.length}),...k}};if(o.existingRevisions!=null&&!vo(o.existingRevisions))return l({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(o.existingRevisions)}".`,field:"existingRevisions"});if(o?.expectedRevision){let E=Kr(o.expectedRevision);if(!E.valid)return l({code:E.error?.code||"INVALID_REVISION_TOKEN",message:E.error?.message||"Invalid revision token."});if(o.expectedRevision.scope!=="document-parts")return l({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`,expectedScope:"document-parts",actualScope:o.expectedRevision.scope});let k=await so({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!Hr(k.value,o.expectedRevision.value))return l({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${k.value}'.`,expectedRevision:o.expectedRevision,currentRevision:k})}let c=o?._documentOperationSession instanceof Tr?o._documentOperationSession:new Tr(e,{...o,_deferDocumentSerialization:!0});if(!c.valid)return l(c.parseResult.error,{warnings:c.parseResult.warnings});let u=En(c.document,a,{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn});if(c.sourceTargetRegistry=u.registry,u.conflicts.length>0){let E=new Map;for(let P of u.conflicts)for(let _ of P.operationIndexes)E.has(_)||E.set(_,P);let k=Array.from(E,([P,_])=>{let R=a[P-1],M=Nt(R,r,i),U=Re(_,{operationIndex:P,...R?.operationId?{operationId:R.operationId}:{}});return{index:P,type:R?.type||"redline",operationType:it(R).operationKind,status:"error",authorUsed:M,error:U,receipt:Le(P,R?.operationId,M,"refused")}}).sort((P,_)=>P.index-_.index),C=a.map((P,_)=>k.find(M=>M.index===_+1)?.receipt||Le(_+1,P?.operationId,Nt(P,r,i),"not_attempted"));return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:k,receipts:C,executionOrder:[],authorsUsed:[],rolledBack:o.atomic===!0,status:"error",error:Re(u.conflicts[0]),conflicts:u.conflicts.map(P=>Re(P)),retryPlan:er({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:k,receipts:C,operationCount:a.length})}}let f=u.compiledOperations,d=Ba(f);if(!d.valid)return l(d.error);let m=d.scheduled,p=o.atomic===!0,g=o.continueOnError!==!1;n&&typeof n=="object"&&!n.numberingIdState&&typeof n.numberingXml=="string"&&n.numberingXml.trim()&&(n.numberingIdState=xr(n.numberingXml));let h=Au(n);h.targetRefSnapshot instanceof Map||(h.targetRefSnapshot=c.initialTargetReferenceSnapshot),c.runtimeContext=h,a.some(E=>E?.type==="comment_reply"||E?.type==="comment_resolve")&&(c.commentsXml=h.commentsXml||o.commentsXml||null,c.commentsExtendedXml=h.commentsExtendedXml||o.commentsExtendedXml||null,c.commentsXmlMode="replace",c.commentsExtendedXmlMode="replace");let y=!1,w=c.results,v=c.executionOrder,b=c.authorsUsed,x=!1;for(let{operation:E,index:k}of m){v.push(k+1);let C=u.bindings[k];if(C?.error){x=!0;let P=Nt(E,r,i),_=Le(k+1,E?.operationId,P,"refused"),R=Re(C.error,{operationIndex:k+1,...E?.operationId?{operationId:E.operationId}:{}});if(_.warnings.push(R.message),w.push({index:k+1,type:E?.type||"redline",status:"error",operationType:it(E).operationKind,authorUsed:P,warnings:[R.message],error:R,receipt:_}),!g)break;continue}try{let P=await bs(c.currentDocumentXml,E,r,h,{...o,_documentOperationSession:c,_deferDocumentSerialization:!0,_operationIndex:k+1});y=y||P.hasChanges===!0,c.commentsXml=P.commentsXmlMode==="replace"?P.commentsXml||c.commentsXml:yh(c.commentsXml,P.commentsXml||null),c.commentsExtendedXml=(P.commentsExtendedXmlMode==="replace",P.commentsExtendedXml||c.commentsExtendedXml),P.commentsXmlMode==="replace"&&(c.commentsXmlMode="replace"),P.commentsExtendedXmlMode==="replace"&&(c.commentsExtendedXmlMode="replace"),P.numberingXml&&c.numberingXmlParts.push(P.numberingXml);let _=P.status==="error"||!!P.error;if(x=x||_,!_&&P.hasChanges&&P.authorUsed&&b.add(P.authorUsed),w.push({index:k+1,type:E?.type||"redline",status:_?"error":P.hasChanges?"applied":"no_change",operationType:P.operationType||"redline",authorUsed:P.authorUsed,...P.resolvedBy?{resolvedBy:P.resolvedBy}:{},...P.resolvedTarget?{resolvedTarget:P.resolvedTarget}:{},...P.resolvedAnchor?{resolvedAnchor:P.resolvedAnchor}:{},...P.change?{change:P.change}:{},...P.operationType==="comment_resolve"&&!_?{resolved:P.resolved,threadRootId:P.threadRootId,commentIds:P.commentIds}:{},...Array.isArray(P.warnings)&&P.warnings.length>0?{warnings:P.warnings}:{},...P.error?{error:P.error}:{},...P.receipt?{receipt:P.receipt}:{}}),_&&!g)break}catch(P){let _=Re(P,{operationIndex:k+1,...E?.operationId?{operationId:E.operationId}:{}});x=!0;let R=Nt(E,r,re()),M=Le(k+1,E?.operationId,R,"refused");if(M.warnings.push(_.message),w.push({index:k+1,type:E?.type||"redline",status:"error",operationType:it(E).operationKind,authorUsed:R,warnings:[_.message],error:_,receipt:M}),!g)break}}w.sort((E,k)=>E.index-k.index);let T=[];for(let E=0;E<a.length;E++){let k=E+1,C=w.find(P=>P.index===k);if(C?.receipt)T.push(C.receipt);else{let P=Le(k,a[E]?.operationId,Nt(a[E],r,i),"not_attempted");T.push(P)}}let I=p&&x,N=e,A=null;if(!I&&y)try{N=c.serializeCurrent()}catch(E){A=Re(E),I=!0}let S=null;if(!I&&y){let E=wo({documentXml:N,commentsXml:c.commentsXml,commentsExtendedXml:c.commentsExtendedXml,numberingXmlParts:c.numberingXmlParts},T);E.valid||(S=E.error,p&&(I=!0))}if(I){for(let E of w)E.receipt&&E.receipt.attemptedDisposition==="applied"&&(E.receipt.finalDisposition="rolled_back",E.receipt.committed=!1),E.change&&(E.change.finalDisposition="rolled_back",E.change.committed=!1);for(let E of T)E.attemptedDisposition==="applied"&&(E.finalDisposition="rolled_back",E.committed=!1)}else{for(let E of w)E.receipt&&E.receipt.attemptedDisposition==="applied"&&(E.receipt.committed=!0,E.receipt.finalDisposition="applied"),E.change&&(E.change.finalDisposition="applied",E.change.committed=!0);for(let E of T)E.attemptedDisposition==="applied"&&(E.committed=!0,E.finalDisposition="applied")}I||Eu(n,h);let O={documentXml:I?c.rollback():N,hasChanges:I?!1:y,commentsXml:I?null:c.commentsXml,commentsExtendedXml:I?null:c.commentsExtendedXml,commentsXmlMode:c.commentsXmlMode,commentsExtendedXmlMode:c.commentsExtendedXmlMode,numberingXmlParts:I?[]:c.numberingXmlParts,results:[...w].sort((E,k)=>(E.index||0)-(k.index||0)),receipts:T.sort((E,k)=>E.operationIndex-k.operationIndex),executionOrder:v,authorsUsed:I?[]:Array.from(b),...I?{rolledBack:!0,status:"error",error:Re({code:S?S.code:A?"DOCUMENT_SERIALIZATION_FAILED":"BATCH_OPERATION_FAILED",message:S?.message||A?.message||"Atomic batch rolled back because one or more operations failed."})}:S?{status:"error",error:Re(S)}:x?{status:y?"partial":"error",error:Re({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed."})}:{status:"ok"}};return(O.status==="error"||O.status==="partial")&&(O.retryPlan=er({atomic:p,rolledBack:I,results:O.results,receipts:O.receipts,operationCount:a.length})),O}function Pn(e,t={}){return et(e,t)}function vh(e){return e.operationKind!=="redline"||typeof e.modified!="string"?!1:e.modified.split(/\r?\n/).some(t=>/^\s*(?:[-+*]|\d+[.)])\s+/.test(t))}function xh(e,t,r,n,o=null,a="accepted"){let i=o?.byParagraph?.get(t)||null,s=i?null:le(e),l=i?.text??te(t,{revisionView:a}),c=q(n||""),u=q(l);return{resolvedBy:r,resolvedTarget:{index:i?.index??s.indexOf(t)+1,paragraphId:i?.paragraphId??Xe(t),text:l,fingerprint:i?.fingerprint??dt(t,{text:l,revisionView:a}),inTable:i?.inTable??!!He(t,"tbl"),revisionView:a},matchDiagnostics:{exactTextMatch:typeof n=="string"&&n===l,normalizedTextMatch:!!c&&c===u,suppliedText:n||"",actualText:l,revisionView:a}}}function rf(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.("*",r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Fa(e,t,r,n={}){if(n.existingRevisions!=null&&!vo(n.existingRevisions))return{valid:!1,status:"error",error:Pn({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(n.existingRevisions)}".`}),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let o=W(e,"application/xml");if(o.error||!o.doc)return{valid:!1,status:"error",error:Pn(o.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let a=o.doc,i={accepted:Dt(a,{revisionView:"accepted"}),rejected:null},s=Array.isArray(t)?t:[],l=En(a,s,{strictTargets:n.strictTargets!==!1,onInfo:n.onInfo,onWarn:n.onWarn}),c=Ba(l.compiledOperations);if(!c.valid)return{valid:!1,status:"error",error:Pn(c.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let u=n.strictTargets!==!1,f=[],d=new Set,m=!1,p=!1;for(let v=0;v<s.length;v++){let b=s[v],x=l.bindings[v],T=l.compiledOperations[v],I=!x?.error&&T?._localizedReplacementCompilation?T:b,N=tr(I),A=it(b),S=N.operation||A,O=Nt(S,r,re());if(d.add(O),!N.valid){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"error",authorUsed:O,error:N.error});continue}if(m=m||S.operationKind==="comment"||S.operationKind==="comment_reply",p=p||vh(S),S.operationKind==="comment_resolve"){let C=String(S.commentId);f.push(n._existingCommentDetails?.[C]?{index:v+1,type:b.type,operationType:S.operationKind,status:"ready",authorUsed:O,resolvedBy:"comment_id",commentId:C}:{index:v+1,type:b.type,operationType:S.operationKind,status:"error",authorUsed:O,error:{code:"COMMENT_NOT_FOUND",message:`Comment '${C}' was not found.`}});continue}if(S.operationKind==="comment_reply"){let C=String(S.parentCommentId),P=n._existingCommentDetails?.[C];f.push(P?{index:v+1,type:b.type,operationType:S.operationKind,status:"ready",authorUsed:O,resolvedBy:"parent_comment",parentCommentId:C}:{index:v+1,type:b.type,operationType:S.operationKind,status:"error",authorUsed:O,error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${C}' was not found.`}});continue}if(S.targetDescriptor?.captureRef){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"deferred",authorUsed:O,resolvedBy:"capture",captureRef:S.targetDescriptor.captureRef,...S.targetDescriptor.select?{select:S.targetDescriptor.select}:{}});continue}if(x?.error){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"error",authorUsed:O,error:x.error});continue}if(x?.createdByOperation){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"deferred",authorUsed:O,resolvedBy:"created_content_dependency",captureRef:x.captureRef,select:S.targetDescriptor.text,createdByOperation:x.createdByOperation});continue}let E=S.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",k=E==="rejected"?i.rejected||(i.rejected=Dt(a,{revisionView:"rejected"})):i.accepted;try{let C;if(x.dynamic)C=zr(a,{targetText:S.target,targetRef:S.targetRef,targetDescriptor:S.targetDescriptor,opType:S.operationKind,strictAmbiguity:u,paragraphMetadataIndex:k,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn});else{let G=l.registry.resolve(x.sourceIds[0],a);if(G.error)throw Object.assign(new Error(G.error.message),G.error);C={paragraph:G.paragraph,resolvedBy:x.resolvedBy,warnings:x.warnings}}let P=C.paragraph,_=xh(a,P,C.resolvedBy,S.target,k,E),R=_.resolvedTarget.text,M=S.operationKind==="comment"?S.textToComment||R:S.operationKind==="highlight"?S.textToHighlight:S.operationKind==="format"?S.textToFormat:null,U=S.operationKind==="comment"&&M!=null?uo(bn(P,{revisionView:E}),M):null,X=M==null||(U?U.found:R.includes(M)),z=mr(P),H=S.existingRevisions||n.existingRevisions||"merge-same-author",ue=S.operationKind==="redline"&&S.modified===""?rf(P):[],Y=null;if(S.operationKind==="restore"){let G=S.targetEndRef?fn(a,S.targetRef,S.targetEndRef,{opType:"restore",targetRefSnapshot:n.targetRefSnapshot||null,onInfo:n.onInfo,onWarn:n.onWarn}):[P];if(!S.targetEndRef&&S.targetEndDescriptor){let xe=zr(a,{targetText:S.targetEndDescriptor.text,targetRef:S.targetEndDescriptor.index,targetDescriptor:S.targetEndDescriptor,opType:"restore",strictAmbiguity:u,paragraphMetadataIndex:k,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn}),me=le(a),pe=me.indexOf(P),be=me.indexOf(xe?.paragraph);G=pe>=0&&be>=pe?me.slice(pe,be+1):null}let ee=Array.isArray(S.modified)?S.modified:[S.modified];if(!G||G[0]!==P||ee.length!==G.length)Y={code:"RESTORATION_COUNT_MISMATCH",message:"Restoration requires one replacement for every paragraph in a contiguous resolved range."};else for(let xe of G){let me=Fr(xe);if(me?.code==="UNSUPPORTED_MOVE_REVISION"){Y=me;break}let pe=vr(xe,O),be=pe.matches?me||Fr(xe):null;if(!pe.matches){Y={code:"RESTORATION_STATE_REQUIRED",message:"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...pe.ownerAuthor?{ownerAuthor:pe.ownerAuthor}:{}};break}if(be){Y=be;break}}}else if(!X)Y=U?.error||{code:"ANCHOR_NOT_FOUND",message:`Anchor text was not found in target paragraph: "${M}".`};else if(ue.length>0){let G=ue.map(ee=>n._existingCommentDetails?.[ee]).filter(Boolean);Y={code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:ue,...G.length>0?{comments:G}:{}}}else if(S.operationKind==="redline"&&z&&H!=="accept-all-first"&&H!=="accept-all-first-keep-normalized")if(H==="merge-same-author"||H==="slice-cross-author"){let G=Rr(P),ee=String(O||"").trim().toLowerCase(),xe=G.length>0&&G.every(me=>me.trim().toLowerCase()===ee);if(!xe&&H==="merge-same-author")Y={code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${G.length?G.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:G,currentPolicy:H};else if(xe){let me=rf(P);if(me.length>0){let pe=me.map(be=>n._existingCommentDetails?.[be]).filter(Boolean);Y={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:me,...pe.length>0?{comments:pe}:{}}}}else(P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0)&&(Y={code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."})}else{let G=P.getElementsByTagNameNS(B,"del").length>0,ee=P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0;G?Y={code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}:ee?Y={code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}:Y={code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}if(!Y&&S.operationKind==="redline"){let G=ta(P,S.modified,n);G.valid||(Y={code:G.code,message:G.message})}f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:Y?"error":"ready",authorUsed:O,..._,anchor:M==null?null:{text:M,found:X,...U?.found?{resolvedBy:U.resolvedBy,start:U.start,end:U.end}:{},...!U?.found&&Array.isArray(U?.error?.candidates)?{candidates:U.error.candidates}:{}},hasRevisions:z,existingRevisions:H,...C?.warnings?.length?{warnings:C.warnings}:{},...Y?{error:Y}:{}})}catch(C){f.push({index:v+1,type:b?.type||"redline",operationType:S.operationKind,status:"error",authorUsed:O,error:Pn(C)})}}let g=l.conflicts,h=f.map(v=>v.error?{...v,error:Pn(v.error,{operationIndex:v.index,...s[v.index-1]?.operationId?{operationId:s[v.index-1].operationId}:{}})}:v),y=g.map(v=>Pn(v)),w=h.some(v=>v.status==="error");return{valid:!w&&y.length===0,status:!w&&y.length===0?"ok":"error",results:h,conflicts:y,authorsUsed:Array.from(d),requiredArtifacts:{comments:m,numbering:p}}}var Ye=Uint8Array,gt=Uint16Array,Ps=Int32Array,$a=new Ye([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ua=new Ye([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ss=new Ye([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),sf=function(e,t){for(var r=new gt(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var o=new Ps(r[30]),n=1;n<30;++n)for(var a=r[n];a<r[n+1];++a)o[a]=a-r[n]<<5|n;return{b:r,r:o}},lf=sf($a,2),cf=lf.b,As=lf.r;cf[28]=258,As[258]=28;var uf=sf(Ua,0),bh=uf.b,nf=uf.r,Es=new gt(32768);for(fe=0;fe<32768;++fe)ar=(fe&43690)>>1|(fe&21845)<<1,ar=(ar&52428)>>2|(ar&13107)<<2,ar=(ar&61680)>>4|(ar&3855)<<4,Es[fe]=((ar&65280)>>8|(ar&255)<<8)>>1;var ar,fe,Ft=(function(e,t,r){for(var n=e.length,o=0,a=new gt(t);o<n;++o)e[o]&&++a[e[o]-1];var i=new gt(t);for(o=1;o<t;++o)i[o]=i[o-1]+a[o-1]<<1;var s;if(r){s=new gt(1<<t);var l=15-t;for(o=0;o<n;++o)if(e[o])for(var c=o<<4|e[o],u=t-e[o],f=i[e[o]-1]++<<u,d=f|(1<<u)-1;f<=d;++f)s[Es[f]>>l]=c}else for(s=new gt(n),o=0;o<n;++o)e[o]&&(s[o]=Es[i[e[o]-1]++]>>15-e[o]);return s}),Sr=new Ye(288);for(fe=0;fe<144;++fe)Sr[fe]=8;var fe;for(fe=144;fe<256;++fe)Sr[fe]=9;var fe;for(fe=256;fe<280;++fe)Sr[fe]=7;var fe;for(fe=280;fe<288;++fe)Sr[fe]=8;var fe,Io=new Ye(32);for(fe=0;fe<32;++fe)Io[fe]=5;var fe,Nh=Ft(Sr,9,0),Ih=Ft(Sr,9,1),Th=Ft(Io,5,0),Sh=Ft(Io,5,1),Ns=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Ot=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},Is=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},Cs=function(e){return(e+7)/8|0},ff=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new Ye(e.subarray(t,r))};var Ah=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],sr=function(e,t,r){var n=new Error(t||Ah[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,sr),!r)throw n;return n},Eh=function(e,t,r,n){var o=e.length,a=n?n.length:0;if(!o||t.f&&!t.l)return r||new Ye(0);var i=!r,s=i||t.i!=2,l=t.i;i&&(r=new Ye(o*3));var c=function(be){var Tt=r.length;if(be>Tt){var K=new Ye(Math.max(Tt*2,be));K.set(r),r=K}},u=t.f||0,f=t.p||0,d=t.b||0,m=t.l,p=t.d,g=t.m,h=t.n,y=o*8;do{if(!m){u=Ot(e,f,1);var w=Ot(e,f+1,3);if(f+=3,w)if(w==1)m=Ih,p=Sh,g=9,h=5;else if(w==2){var T=Ot(e,f,31)+257,I=Ot(e,f+10,15)+4,N=T+Ot(e,f+5,31)+1;f+=14;for(var A=new Ye(N),S=new Ye(19),O=0;O<I;++O)S[Ss[O]]=Ot(e,f+O*3,7);f+=I*3;for(var E=Ns(S),k=(1<<E)-1,C=Ft(S,E,1),O=0;O<N;){var P=C[Ot(e,f,k)];f+=P&15;var v=P>>4;if(v<16)A[O++]=v;else{var _=0,R=0;for(v==16?(R=3+Ot(e,f,3),f+=2,_=A[O-1]):v==17?(R=3+Ot(e,f,7),f+=3):v==18&&(R=11+Ot(e,f,127),f+=7);R--;)A[O++]=_}}var M=A.subarray(0,T),U=A.subarray(T);g=Ns(M),h=Ns(U),m=Ft(M,g,1),p=Ft(U,h,1)}else sr(1);else{var v=Cs(f)+4,b=e[v-4]|e[v-3]<<8,x=v+b;if(x>o){l&&sr(0);break}s&&c(d+b),r.set(e.subarray(v,x),d),t.b=d+=b,t.p=f=x*8,t.f=u;continue}if(f>y){l&&sr(0);break}}s&&c(d+131072);for(var X=(1<<g)-1,z=(1<<h)-1,H=f;;H=f){var _=m[Is(e,f)&X],se=_>>4;if(f+=_&15,f>y){l&&sr(0);break}if(_||sr(2),se<256)r[d++]=se;else if(se==256){H=f,m=null;break}else{var ue=se-254;if(se>264){var O=se-257,Y=$a[O];ue=Ot(e,f,(1<<Y)-1)+cf[O],f+=Y}var G=p[Is(e,f)&z],ee=G>>4;G||sr(3),f+=G&15;var U=bh[ee];if(ee>3){var Y=Ua[ee];U+=Is(e,f)&(1<<Y)-1,f+=Y}if(f>y){l&&sr(0);break}s&&c(d+131072);var xe=d+ue;if(d<U){var me=a-U,pe=Math.min(U,xe);for(me+d<0&&sr(3);d<pe;++d)r[d]=n[me+d]}for(;d<xe;++d)r[d]=r[d-U]}}t.l=m,t.p=H,t.b=d,t.f=u,m&&(u=1,t.m=g,t.d=p,t.n=h)}while(!u);return d!=r.length&&i?ff(r,0,d):r.subarray(0,d)},ir=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},bo=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},Ts=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var o=r.length,a=r.slice();if(!o)return{t:mf,l:0};if(o==1){var i=new Ye(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(x,T){return x.f-T.f}),r.push({s:-1,f:25001});var s=r[0],l=r[1],c=0,u=1,f=2;for(r[0]={s:-1,f:s.f+l.f,l:s,r:l};u!=o-1;)s=r[r[c].f<r[f].f?c++:f++],l=r[c!=u&&r[c].f<r[f].f?c++:f++],r[u++]={s:-1,f:s.f+l.f,l:s,r:l};for(var d=a[0].s,n=1;n<o;++n)a[n].s>d&&(d=a[n].s);var m=new gt(d+1),p=Rs(r[u-1],m,0);if(p>t){var n=0,g=0,h=p-t,y=1<<h;for(a.sort(function(T,I){return m[I.s]-m[T.s]||T.f-I.f});n<o;++n){var w=a[n].s;if(m[w]>t)g+=y-(1<<p-m[w]),m[w]=t;else break}for(g>>=h;g>0;){var v=a[n].s;m[v]<t?g-=1<<t-m[v]++-1:++n}for(;n>=0&&g;--n){var b=a[n].s;m[b]==t&&(--m[b],++g)}p=t}return{t:new Ye(m),l:p}},Rs=function(e,t,r){return e.s==-1?Math.max(Rs(e.l,t,r+1),Rs(e.r,t,r+1)):t[e.s]=r},of=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new gt(++t),n=0,o=e[0],a=1,i=function(l){r[n++]=l},s=1;s<=t;++s)if(e[s]==o&&s!=t)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=e[s]}return{c:r.subarray(0,n),n:t}},No=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},df=function(e,t,r){var n=r.length,o=Cs(t+2);e[o]=n&255,e[o+1]=n>>8,e[o+2]=e[o]^255,e[o+3]=e[o+1]^255;for(var a=0;a<n;++a)e[o+a+4]=r[a];return(o+4+n)*8},af=function(e,t,r,n,o,a,i,s,l,c,u){ir(t,u++,r),++o[256];for(var f=Ts(o,15),d=f.t,m=f.l,p=Ts(a,15),g=p.t,h=p.l,y=of(d),w=y.c,v=y.n,b=of(g),x=b.c,T=b.n,I=new gt(19),N=0;N<w.length;++N)++I[w[N]&31];for(var N=0;N<x.length;++N)++I[x[N]&31];for(var A=Ts(I,7),S=A.t,O=A.l,E=19;E>4&&!S[Ss[E-1]];--E);var k=c+5<<3,C=No(o,Sr)+No(a,Io)+i,P=No(o,d)+No(a,g)+i+14+3*E+No(I,S)+2*I[16]+3*I[17]+7*I[18];if(l>=0&&k<=C&&k<=P)return df(t,u,e.subarray(l,l+c));var _,R,M,U;if(ir(t,u,1+(P<C)),u+=2,P<C){_=Ft(d,m,0),R=d,M=Ft(g,h,0),U=g;var X=Ft(S,O,0);ir(t,u,v-257),ir(t,u+5,T-1),ir(t,u+10,E-4),u+=14;for(var N=0;N<E;++N)ir(t,u+3*N,S[Ss[N]]);u+=3*E;for(var z=[w,x],H=0;H<2;++H)for(var se=z[H],N=0;N<se.length;++N){var ue=se[N]&31;ir(t,u,X[ue]),u+=S[ue],ue>15&&(ir(t,u,se[N]>>5&127),u+=se[N]>>12)}}else _=Nh,R=Sr,M=Th,U=Io;for(var N=0;N<s;++N){var Y=n[N];if(Y>255){var ue=Y>>18&31;bo(t,u,_[ue+257]),u+=R[ue+257],ue>7&&(ir(t,u,Y>>23&31),u+=$a[ue]);var G=Y&31;bo(t,u,M[G]),u+=U[G],G>3&&(bo(t,u,Y>>5&8191),u+=Ua[G])}else bo(t,u,_[Y]),u+=R[Y]}return bo(t,u,_[256]),u+R[256]},Rh=new Ps([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),mf=new Ye(0),Ph=function(e,t,r,n,o,a){var i=a.z||e.length,s=new Ye(n+i+5*(1+Math.ceil(i/7e3))+o),l=s.subarray(n,s.length-o),c=a.l,u=(a.r||0)&7;if(t){u&&(l[0]=a.r>>3);for(var f=Rh[t-1],d=f>>13,m=f&8191,p=(1<<r)-1,g=a.p||new gt(32768),h=a.h||new gt(p+1),y=Math.ceil(r/3),w=2*y,v=function(L){return(e[L]^e[L+1]<<y^e[L+2]<<w)&p},b=new Ps(25e3),x=new gt(288),T=new gt(32),I=0,N=0,A=a.i||0,S=0,O=a.w||0,E=0;A+2<i;++A){var k=v(A),C=A&32767,P=h[k];if(g[C]=P,h[k]=C,O<=A){var _=i-A;if((I>7e3||S>24576)&&(_>423||!c)){u=af(e,l,0,b,x,T,N,S,E,A-E,u),S=I=N=0,E=A;for(var R=0;R<286;++R)x[R]=0;for(var R=0;R<30;++R)T[R]=0}var M=2,U=0,X=m,z=C-P&32767;if(_>2&&k==v(A-z))for(var H=Math.min(d,_)-1,se=Math.min(32767,A),ue=Math.min(258,_);z<=se&&--X&&C!=P;){if(e[A+M]==e[A+M-z]){for(var Y=0;Y<ue&&e[A+Y]==e[A+Y-z];++Y);if(Y>M){if(M=Y,U=z,Y>H)break;for(var G=Math.min(z,Y-2),ee=0,R=0;R<G;++R){var xe=A-z+R&32767,me=g[xe],pe=xe-me&32767;pe>ee&&(ee=pe,P=xe)}}}C=P,P=g[C],z+=C-P&32767}if(U){b[S++]=268435456|As[M]<<18|nf[U];var be=As[M]&31,Tt=nf[U]&31;N+=$a[be]+Ua[Tt],++x[257+be],++T[Tt],O=A+M,++I}else b[S++]=e[A],++x[e[A]]}}for(A=Math.max(A,O);A<i;++A)b[S++]=e[A],++x[e[A]];u=af(e,l,c,b,x,T,N,S,E,A-E,u),c||(a.r=u&7|l[u/8|0]<<3,u-=7,a.h=h,a.p=g,a.i=A,a.w=O)}else{for(var A=a.w||0;A<i+c;A+=65535){var K=A+65535;K>=i&&(l[u/8|0]=c,K=i),u=df(l,u+1,e.subarray(A,K))}a.i=i}return ff(s,0,n+Cs(u)+o)};var Ch=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),i=new Ye(a.length+e.length);i.set(a),i.set(e,a.length),e=i,o.w=a.length}return Ph(e,t.level==null?6:t.level,t.mem==null?o.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,o)};function pf(e,t){return Ch(e,t||{},0,0)}function gf(e,t){return Eh(e,{i:2},t&&t.out,t&&t.dictionary)}var Oh=typeof TextDecoder<"u"&&new TextDecoder,_h=0;try{Oh.decode(mf,{stream:!0}),_h=1}catch{}var wf=new TextEncoder,yf=new TextDecoder("utf-8"),kh=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function Mh(e){let t=4294967295;for(let r=0;r<e.length;r++)t=kh[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function Cn(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof e=="string")return wf.encode(e);throw new TypeError("Invalid binary input: expected Uint8Array, Buffer, or ArrayBuffer.")}function hf(e){let t=0;for(let o=0;o<e.length;o++)t+=e[o].length;let r=new Uint8Array(t),n=0;for(let o=0;o<e.length;o++)r.set(e[o],n),n+=e[o].length;return r}function On(e){let t=Cn(e);if(t.length<22)throw new Error("Invalid DOCX: ZIP end record not found.");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=-1,o=Math.max(0,t.length-65535-22);for(let c=t.length-22;c>=o;c--)if(r.getUint32(c,!0)===101010256){n=c;break}if(n<0)throw new Error("Invalid DOCX: ZIP end record not found.");let a=r.getUint16(n+10,!0),i=r.getUint32(n+16,!0);if(a===65535||i===4294967295)throw new Error("Unsupported DOCX: ZIP64 archives are not supported.");let s=new Map,l=i;for(let c=0;c<a;c++){if(l+46>t.length||r.getUint32(l,!0)!==33639248)throw new Error("Invalid DOCX: central directory is corrupt.");let u=r.getUint16(l+8,!0),f=r.getUint16(l+10,!0);if(u&1)throw new Error("Unsupported DOCX: encrypted ZIP entries are not supported.");let d=r.getUint32(l+20,!0),m=r.getUint16(l+28,!0),p=r.getUint16(l+30,!0),g=r.getUint16(l+32,!0),h=r.getUint32(l+42,!0);if(l+46+m>t.length)throw new Error("Invalid DOCX: central directory entry name extends beyond bounds.");let y=yf.decode(t.subarray(l+46,l+46+m));if(h+30>t.length||r.getUint32(h,!0)!==67324752)throw new Error("Invalid DOCX: local entry is corrupt.");let w=r.getUint16(h+26,!0),v=r.getUint16(h+28,!0),b=h+30+w+v;if(b+d>t.length)throw new Error("Invalid DOCX: local entry data extends beyond archive bounds.");let x=t.subarray(b,b+d);if(f!==0&&f!==8)throw new Error(`Unsupported DOCX compression method: ${f}.`);let T=f===8?gf(x):new Uint8Array(x);s.set(y,T),l+=46+m+p+g}return s}function vf(e){let t=e instanceof Map?Array.from(e.entries()):Symbol.iterator in Object(e)?Array.from(e):Object.entries(e||{}),r=[],n=[],o=0;for(let[l,c]of t){let u=wf.encode(l),f=Cn(c),d=pf(f,{level:9}),m=d.length<f.length?8:0,p=m===8?d:f,g=Mh(f),h=new Uint8Array(30),y=new DataView(h.buffer,h.byteOffset,30);y.setUint32(0,67324752,!0),y.setUint16(4,20,!0),y.setUint16(8,m,!0),y.setUint16(12,23585,!0),y.setUint32(14,g,!0),y.setUint32(18,p.length,!0),y.setUint32(22,f.length,!0),y.setUint16(26,u.length,!0),y.setUint16(28,0,!0),r.push(h,u,p);let w=new Uint8Array(46),v=new DataView(w.buffer,w.byteOffset,46);v.setUint32(0,33639248,!0),v.setUint16(4,20,!0),v.setUint16(6,20,!0),v.setUint16(10,m,!0),v.setUint16(14,23585,!0),v.setUint32(16,g,!0),v.setUint32(20,p.length,!0),v.setUint32(24,f.length,!0),v.setUint16(28,u.length,!0),v.setUint16(30,0,!0),v.setUint16(32,0,!0),v.setUint32(42,o,!0),n.push(w,u),o+=h.length+u.length+p.length}let a=hf(n),i=new Uint8Array(22),s=new DataView(i.buffer,i.byteOffset,22);return s.setUint32(0,101010256,!0),s.setUint16(8,t.length,!0),s.setUint16(10,t.length,!0),s.setUint32(12,a.length,!0),s.setUint32(16,o,!0),hf([...r,a,i])}var lr=class{constructor(t){this.entries=t instanceof Map?t:new Map(Object.entries(t||{}))}file(t,r){if(r!==void 0)return this.entries.set(t,Cn(r)),this;let n=this.entries.get(t);return n?{async:async o=>o==="string"?yf.decode(n):new Uint8Array(n)}:null}};var $t=new TextEncoder,Tf=new TextDecoder("utf-8"),ne=(e,t)=>{let r=e.get(t);return r?typeof r=="string"?r:Tf.decode(r):null};function xf(e){let t=jc({commentsXml:ne(e,"word/comments.xml"),commentsIdsXml:ne(e,"word/commentsIds.xml"),commentsExtensibleXml:ne(e,"word/commentsExtensible.xml")});t.commentsIdsXml&&e.set("word/commentsIds.xml",$t.encode(t.commentsIdsXml)),t.commentsExtensibleXml&&e.set("word/commentsExtensible.xml",$t.encode(t.commentsExtensibleXml))}var _n=e=>new Map([...e].map(([t,r])=>[t,new Uint8Array(r)]));function ce(e){return typeof Buffer<"u"&&typeof Buffer.from=="function"?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function To(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function bf(e,t){let r=i=>!i||typeof i!="object"?i:i.attemptedDisposition!=="applied"&&i.committed!==!0?{...i}:{...i,committed:!1,finalDisposition:"rolled_back"},n=(e?.receipts||[]).map(r),o=new Map(n.map(i=>[i.operationIndex,i])),a=(e?.results||[]).map(i=>({...i,...i.receipt?{receipt:o.get(i.index)||r(i.receipt)}:{}}));return{results:a,receipts:n,executionOrder:e?.executionOrder||[],authorsUsed:[],rolledBack:!0,retryPlan:er({atomic:!0,rolledBack:!0,results:a,receipts:n,operationCount:t})}}function Os(e){let t;if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer?.(e))t=On(e);else if(e instanceof Map)t=e;else if(e?.entries instanceof Map)t=e.entries;else if(typeof e?.toUint8Array=="function")t=On(e.toUint8Array());else if(typeof e?.toBuffer=="function")t=On(e.toBuffer());else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=On(Cn(e));else throw new TypeError("computePackageRevisionToken requires a Uint8Array, Buffer, Map of entries, or DocxDocument.");return io({scope:"package",entries:t})}var Nf=new Set(["comment","comment_reply","comment_resolve"]);function Lh(e){let r=(`${ne(e,"word/document.xml")||""} ${ne(e,"word/comments.xml")||""}`.match(/(?:w:)?id=["'](\d+)["']/g)||[]).reduce((n,o)=>Math.max(n,Number(o.match(/\d+/)?.[0]||0)),0)+1;return()=>r++}function If(e){let t=ne(e,"word/comments.xml");if(!t)return{};let r=W(t,"application/xml");if(!r.doc||r.error)return{};let n={};for(let o of Array.from(r.doc.getElementsByTagNameNS("*","comment"))){let a=o.getAttribute("w:id")||o.getAttribute("id");a!==""&&(n[a]={id:a,author:o.getAttribute("w:author")||o.getAttribute("author")||"",text:String(o.textContent||"").trim(),paraId:at(o)||null})}return n}function It(e,t,r){let n=ce(e);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,error:et({code:t,message:r}),retryPlan:er({atomic:!0,rolledBack:!0}),artifactsChanged:[],uint8Array:e,toUint8Array:()=>new Uint8Array(e),buffer:n,toBuffer:()=>ce(e)}}var za=class{constructor(t){this.originalBytes=Cn(t),this.entries=On(this.originalBytes)}get originalBuffer(){return ce(this.originalBytes)}inspect(t={}){let r=t.digestFn||(o=>ao(o)),n=ba({documentXml:ne(this.entries,"word/document.xml"),commentsXml:ne(this.entries,"word/comments.xml"),commentsExtendedXml:ne(this.entries,"word/commentsExtended.xml"),numberingXml:ne(this.entries,"word/numbering.xml"),stylesXml:ne(this.entries,"word/styles.xml")},{...t,digestFn:r});return n.status==="error"?n:{...n,headersFooters:this.inspectHeadersFooters()}}inspectHeadersFooters(){return us({documentXml:ne(this.entries,"word/document.xml"),relsXml:ne(this.entries,"word/_rels/document.xml.rels"),settingsXml:ne(this.entries,"word/settings.xml")}).map(t=>{let r=ne(this.entries,t.path)||"",n=r?ba({documentXml:r}):{paragraphs:[]};return{...t,hasFields:/<w:fldChar\b|<w:fldSimple\b/.test(r),paragraphs:(n.paragraphs||[]).map(o=>({index:o.index,text:o.text}))}})}getRevisionToken(){return Os(this.entries)}get revisionToken(){return this.getRevisionToken()}preflight(t,r=re(),n={}){let o=Array.isArray(t)?t:[],a=p=>Fa(ne(this.entries,"word/document.xml"),p,r||re(),{...n,_existingCommentDetails:If(this.entries)});if(!o.some(p=>p&&typeof p=="object"&&p.part!=null))return a(t);let i=this.inspectHeadersFooters(),s=[],l=[],c=[],u=new Set,f=!0;o.forEach((p,g)=>{if(!p||typeof p!="object"||p.part==null){s.push({operation:p,origIndex:g});return}let h=fs(i,p.part),y=Nf.has(p.type)?{code:"COMMENT_IN_HEADER_FOOTER",message:"Word does not support comments in headers or footers."}:h.error;if(y){f=!1,l.push({index:g+1,type:p.type||"redline",status:"error",error:et({...y,operationIndex:g+1})});return}let{part:w,...v}=p,b=Fa(ne(this.entries,h.part.path),[v],r||re(),{...n,_existingCommentDetails:{}});f=f&&b.valid;for(let x of b.results||[])l.push({...x,index:g+1,part:h.part.path});c.push(...b.conflicts||[]);for(let x of b.authorsUsed||[])u.add(x)});let d={comments:!1,numbering:!1};if(s.length){let p=a(s.map(g=>g.operation));f=f&&p.valid;for(let g of p.results||[])l.push({...g,index:s[g.index-1].origIndex+1});c.push(...p.conflicts||[]);for(let g of p.authorsUsed||[])u.add(g);d=p.requiredArtifacts||d}l.sort((p,g)=>p.index-g.index);let m=f&&c.length===0;return{valid:m,status:m?"ok":"error",results:l,conflicts:c,authorsUsed:[...u],requiredArtifacts:d}}toUint8Array(){return vf(this.entries)}toBuffer(){return ce(this.toUint8Array())}async applyOperations(t,r={}){let n=Array.isArray(t)?t:[];return n.some(o=>o&&typeof o=="object"&&o.part!=null)?this.applyOperationsWithParts(n,r):this.applyBodyOperations(t,r)}async applyOperationsWithParts(t,r={}){let n=r.author||re(),o=r.atomic===!0,a=this.entries,i=this.originalBytes,s=t.length,l=()=>{this.entries=a,this.originalBytes=i},c=()=>({uint8Array:i,toUint8Array:()=>new Uint8Array(i),buffer:ce(i),toBuffer:()=>ce(i)}),u=(R,M=[],U=[],X={})=>({status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:M,receipts:U,executionOrder:[],authorsUsed:[],artifactsChanged:[],error:et(R),retryPlan:er({atomic:!0,rolledBack:!0,results:M,receipts:U,operationCount:s}),validation:{originalIssues:[],generatedIssues:[]},...X,...c()});if(r.expectedRevision){let R=await this.applyBodyOperations([],{expectedRevision:r.expectedRevision});if(R.status==="error")return R}let f=us({documentXml:ne(this.entries,"word/document.xml"),relsXml:ne(this.entries,"word/_rels/document.xml.rels"),settingsXml:ne(this.entries,"word/settings.xml")}),d=[],m=[];for(let R=0;R<t.length;R++){let M=t[R];if(!M||typeof M!="object"||M.part==null){d.push({operation:M,origIndex:R});continue}if(Nf.has(M.type))return u({code:"COMMENT_IN_HEADER_FOOTER",message:`Operation ${R+1}: Word does not support comments in headers or footers.`,operationIndex:R+1});let U=fs(f,M.part);if(U.error)return u({...U.error,message:`Operation ${R+1}: ${U.error.message}`,operationIndex:R+1});let{part:X,...z}=M;m.push({operation:z,origIndex:R,part:U.part})}let p=[],g=[],h=[],y=new Set,w=[],v=!1,b=!1,x=null;if(d.length){x=await this.applyBodyOperations(d.map(M=>M.operation),{...r,expectedRevision:void 0});let R=M=>d[M-1]?.origIndex+1;for(let M of x.results||[])p.push({...M,index:R(M.index),...M.receipt?{receipt:{...M.receipt,operationIndex:R(M.receipt.operationIndex)}}:{}});for(let M of x.receipts||[])g.push({...M,operationIndex:R(M.operationIndex)});for(let M of x.executionOrder||[])h.push(R(M));for(let M of x.authorsUsed||[])y.add(M);if(w.push(...x.validation?.originalIssues||[]),(x.status==="error"||x.rolledBack)&&(b=!0,o))return l(),{...x,results:p,receipts:g,executionOrder:h,written:!1,artifactsChanged:[],rolledBack:!0,...c()};v=x.hasChanges===!0}let T=_n(this.entries),I=new lr(T),N=new Set,{expectedRevision:A,...S}=r,O=(R,M)=>{b=!0;let U=et({...M,operationIndex:R.origIndex+1});p.push({index:R.origIndex+1,type:R.operation.type||"redline",status:"error",authorUsed:n,part:R.part.path,error:U})};for(let R of m){let M=R.part.path,U=ne(T,M);if(!U){if(O(R,{code:"PART_NOT_FOUND",message:`Part '${M}' is referenced but missing from the package.`}),o)break;continue}let X=ne(T,"word/numbering.xml"),z=await Da(U,[R.operation],n,{numberingIdState:xr(X||void 0)},{...S,atomic:!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:{}}),H=z.results?.[0];if(z.rolledBack||z.status==="error"){if(O(R,H?.error||z.error||{code:"OPERATION_FAILED",message:"Operation failed."}),o)break;continue}if(!z.hasChanges){p.push({...H,index:R.origIndex+1,part:M});continue}if(ds(z.documentXml)>ds(U)){if(O(R,{code:"FIELD_EDIT_REFUSED",message:`The edit would change a field (for example PAGE or NUMPAGES) in ${M}. Word recomputes fields; edit the text around them instead.`}),o)break;continue}let se=new Set;for(let[G,ee]of T)if(!(G===M||!(G==="word/document.xml"||yu(G))))for(let xe of vu(Tf.decode(ee)))se.add(xe);let ue=xu(z.documentXml,se);T.set(M,$t.encode(ue.xml));let Y=G=>G?.revisionItems?{...G,revisionItems:G.revisionItems.map(ee=>({...ee,id:ue.idMap.get(String(ee.id))??ee.id,partName:M}))}:G;z.numberingXmlParts?.length&&await Aa(I,z.numberingXmlParts,{mergeNumberingXml:ma}),N.add(M),v=!0,p.push({...H,index:R.origIndex+1,part:M,partSections:R.part.appliesToSections,...H?.receipt?{receipt:{...Y(H.receipt),operationIndex:R.origIndex+1}}:{}}),z.receipts?.[0]&&g.push({...Y(z.receipts[0]),operationIndex:R.origIndex+1}),h.push(R.origIndex+1);for(let G of z.authorsUsed||[])y.add(G)}let E=[];if(!(o&&b)){for(let R of N){let M=pt(ne(this.entries,R)).issues.map(X=>({source:R,...X})),U=pt(ne(T,R)).issues.map(X=>({source:R,...X}));E.push(...Jr(Zr(U,M)))}if(r.validate!==!1&&N.size)try{await Ir(I)}catch(R){E.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:R.message})}}if(o&&b||E.length){l();let R=E.length?{code:"PACKAGE_OPERATION_FAILED",message:`Applied operations introduced invalid markup (${[...new Set(E.map(X=>X.code))].join(", ")}).`,issues:E}:{code:"BATCH_OPERATION_FAILED",message:"Atomic batch rolled back because one or more operations failed."},M=p.map(X=>X.receipt?{...X,receipt:{...X.receipt,committed:!1,finalDisposition:"rolled_back"}}:X).sort((X,z)=>X.index-z.index),U=g.map(X=>({...X,committed:!1,finalDisposition:"rolled_back"}));return u(R,M,U,{validation:{originalIssues:w,generatedIssues:E},issues:E})}p.sort((R,M)=>R.index-M.index),g.sort((R,M)=>R.operationIndex-M.operationIndex);let k=b?v?"partial":"error":"ok",C=b?{error:et({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed; the others were applied."})}:{};if(!N.size){let R=ce(this.originalBytes);return{...x||{},results:p,receipts:g,executionOrder:h,authorsUsed:[...y],status:k,hasChanges:v,written:x?.written===!0,artifactsChanged:x?.artifactsChanged||[],validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:R,toBuffer:()=>ce(this.originalBytes)}}this.entries=T;let P=this.toUint8Array();this.originalBytes=P;let _=[...T].filter(([R,M])=>!a.has(R)||!To(M,a.get(R))).map(([R])=>R);return{...x||{},status:k,hasChanges:!0,written:!0,results:p,receipts:g,executionOrder:h,authorsUsed:[...y],artifactsChanged:_,validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:P,toUint8Array:()=>new Uint8Array(P),buffer:ce(P),inspection:this.inspect(),toBuffer:()=>ce(P)}}async applyBodyOperations(t,r={}){let n=u=>{let f=[],d=[],m=ce(this.originalBytes);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:f,receipts:d,artifactsChanged:[],error:et(u),retryPlan:er({atomic:!0,rolledBack:!0,results:f,receipts:d,operationCount:Array.isArray(t)?t.length:0}),validation:{originalIssues:[],generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>ce(this.originalBytes)}};if(r?.expectedRevision){let u=Kr(r.expectedRevision);if(!u.valid)return n({code:u.error?.code||"INVALID_REVISION_TOKEN",message:u.error?.message||"Invalid revision token."});if(r.expectedRevision.scope!=="package")return n({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'package', got '${r.expectedRevision.scope}'.`,expectedScope:"package",actualScope:r.expectedRevision.scope});let f=Os(this.entries);if(!Hr(f.value,r.expectedRevision.value))return n({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${r.expectedRevision.value}', current is '${f.value}'.`,expectedRevision:r.expectedRevision,currentRevision:f})}let o=this.entries,a=_n(o),i=new lr(a),s=ne(a,"word/document.xml"),l=[],c=null;try{if(!s)throw new Error("Missing word/document.xml.");l=pt(s).issues.map(T=>({source:"word/document.xml",...T}));try{await Ir(new lr(_n(o)))}catch(T){l.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:T.message})}let f={numberingIdState:xr(ne(a,"word/numbering.xml")||void 0),commentsXml:ne(a,"word/comments.xml"),commentsExtendedXml:ne(a,"word/commentsExtended.xml")},{expectedRevision:d,...m}=r,p=r.author||re(),g=c=await Da(s,t,p,f,{...m,atomic:r.atomic===!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:If(a),commentIdAllocator:Lh(a)});if(g.rolledBack||g.status==="error"){let T=ce(this.originalBytes);return{...g,...bf(g,Array.isArray(t)?t.length:0),written:!1,artifactsChanged:[],validation:{originalIssues:l,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:T,toBuffer:()=>ce(this.originalBytes)}}if(!g.hasChanges){let T=ce(this.originalBytes);return{...g,status:g.status||"ok",written:!1,artifactsChanged:[],validation:{originalIssues:l,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:T,toBuffer:()=>ce(this.originalBytes)}}(g.results||[]).some(T=>T?.status!=="error"&&T?.operationType!=="comment_resolve")&&a.set("word/document.xml",$t.encode(g.documentXml)),await Aa(i,g.numberingXmlParts,{mergeNumberingXml:ma});let y=ne(a,"word/comments.xml"),w=g.commentsXml||y;if(await cs(i,w,{replaceExisting:g.commentsXmlMode==="replace"||!g.commentsXml&&!!y}),g.commentsExtendedXml&&await Ea(i,g.commentsExtendedXml,{replaceExisting:g.commentsExtendedXmlMode==="replace"}),await Tn(i),xf(a),r.validate!==!1){let I=pt(g.documentXml).issues.map(S=>({source:"word/document.xml",...S}));try{await Ir(i)}catch(S){I.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:S.message})}let N=Zr(I,l),A=Jr(N);if(A.length){let S=[...new Set(A.map(O=>O.code))].join(", ");throw Object.assign(new Error(`Applied operations introduced invalid revision markup (${S}); these are generated-output issues, not pre-existing input issues.`),{issues:A})}}this.entries=a;let v=this.toUint8Array();this.originalBytes=v;let b=ce(v),x=[...a].filter(([T,I])=>!o.has(T)||!To(I,o.get(T))).map(([T])=>T);return{...g,status:g.status||"ok",written:!0,artifactsChanged:x,validation:{originalIssues:l,generatedIssues:[]},uint8Array:v,toUint8Array:()=>new Uint8Array(v),buffer:b,inspection:this.inspect(),toBuffer:()=>ce(v)}}catch(u){this.entries=o;let f=u.issues||[{source:"package",code:"PACKAGE_OPERATION_FAILED",severity:"error",message:u.message}],d=bf(c,Array.isArray(t)?t.length:0),m=ce(this.originalBytes);return{...d,status:"error",hasChanges:!1,written:!1,artifactsChanged:[],error:et({code:"PACKAGE_OPERATION_FAILED",message:u.message,stage:"package",issues:f}),validation:{originalIssues:l,generatedIssues:f},issues:f,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>ce(this.originalBytes)}}}async resolveRevisions(t,r={}){let n=t==="accept"?Br:t==="reject"?yr:null;if(!n)return It(this.originalBytes,"INVALID_ACTION",`Unknown revision action: ${t}`);let o=this.originalBytes,a=this.entries,i=_n(this.entries),s=new lr(i),l=n(ne(i,"word/document.xml"),{author:r.author,allAuthors:r.allAuthors===!0});if(l.status==="error"||l.error)return It(o,l.error?.code||"REVISION_OPERATION_FAILED",l.error?.message||"Revision operation failed.");let c=new Map;for(let m of this.inspectHeadersFooters()){let p=ne(i,m.path);if(!p)continue;let g=n(p,{author:r.author,allAuthors:r.allAuthors===!0});if(g.status==="error"||g.error)return It(o,g.error?.code||"REVISION_OPERATION_FAILED",`${m.path}: ${g.error?.message||"Revision operation failed."}`);g.hasChanges&&c.set(m.path,g.oxml)}if(!(l.hasChanges||c.size>0)){let m=ce(o);return{...l,status:"ok",written:!1,artifactsChanged:[],uint8Array:o,toUint8Array:()=>new Uint8Array(o),buffer:m,toBuffer:()=>ce(o)}}l.hasChanges&&i.set("word/document.xml",$t.encode(l.oxml));for(let[m,p]of c)i.set(m,$t.encode(p));try{await Tn(s),r.validate!==!1&&await Ir(s)}catch(m){return It(o,"PACKAGE_VALIDATION",m.message)}this.entries=i;let f=this.toUint8Array();this.originalBytes=f;let d=ce(f);return{...l,status:"ok",written:!0,hasChanges:!0,artifactsChanged:[...i].filter(([m,p])=>!a.has(m)||!To(p,a.get(m))).map(([m])=>m),uint8Array:f,toUint8Array:()=>new Uint8Array(f),buffer:d,toBuffer:()=>ce(f)}}async resolveComment(t,r={}){let n=this.originalBytes,o=_n(this.entries),a=r.resolved!==!1,i=f=>{let d=ce(n);return{status:"ok",hasChanges:!1,written:!1,artifactsChanged:[],...f,uint8Array:n,toUint8Array:()=>new Uint8Array(n),buffer:d,toBuffer:()=>ce(n)}},s=ya({commentsXml:ne(o,"word/comments.xml"),commentsExtendedXml:ne(o,"word/commentsExtended.xml"),commentId:t,resolved:a});if(s.status==="error")return It(n,s.error.code,s.error.message);if(!s.hasChanges)return i({resolved:a,threadRootId:s.threadRootId,commentIds:s.commentIds});let l=new lr(o);try{s.commentsXml&&o.set("word/comments.xml",$t.encode(s.commentsXml)),await Ea(l,s.commentsExtendedXml,{replaceExisting:!0}),await Tn(l),r.validate!==!1&&await Ir(l)}catch(f){return It(n,"PACKAGE_VALIDATION",f.message)}let c=[...o].filter(([f,d])=>!this.entries.has(f)||!To(d,this.entries.get(f))).map(([f])=>f);this.entries=o;let u=this.toUint8Array();return this.originalBytes=u,{status:"ok",hasChanges:!0,written:!0,resolved:a,threadRootId:s.threadRootId,commentIds:s.commentIds,artifactsChanged:c,uint8Array:u,toUint8Array:()=>new Uint8Array(u),buffer:ce(u),toBuffer:()=>ce(u)}}async deleteComments(t={}){let r=this.originalBytes,n=_n(this.entries),o=ne(n,"word/comments.xml"),a=ce(r);if(!o)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>ce(r)};let i=W(o,"application/xml");if(!i.doc||i.error)return It(r,"PARSE_ERROR",i.error?.message||"Could not parse comments.xml.");let s=Array.isArray(t.ids)?new Set(t.ids.map(String)):null;if(s){let x=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).map(I=>I.getAttribute("w:id")||I.getAttribute("id"))),T=[...s].filter(I=>!x.has(I));if(T.length)return It(r,"COMMENT_NOT_FOUND",`Comment id(s) not found: ${T.join(", ")}.`)}let l=x=>s?s.has(x.getAttribute("w:id")||x.getAttribute("id")):t.allAuthors===!0||(x.getAttribute("w:author")||x.getAttribute("author"))===t.author,c=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).filter(l).map(x=>x.getAttribute("w:id")||x.getAttribute("id")).filter(Boolean));if(!c.size)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>ce(r)};let u=ne(n,"word/commentsExtended.xml"),f=null,d=new Set;if(u){if(f=W(u,"application/xml"),!f.doc||f.error)return It(r,"PARSE_ERROR",f.error?.message||"Could not parse commentsExtended.xml.");let x=new Map;for(let I of Array.from(i.doc.getElementsByTagNameNS("*","comment"))){let N=I.getAttribute("w:id")||I.getAttribute("id"),A=at(I);A&&x.set(A,N)}for(let[I,N]of x)c.has(N)&&d.add(I);let T=!0;for(;T;){T=!1;for(let I of Array.from(f.doc.getElementsByTagNameNS("*","commentEx"))){let N=(I.getAttribute("w15:paraId")||I.getAttribute("paraId")||"").toUpperCase(),A=(I.getAttribute("w15:paraIdParent")||I.getAttribute("paraIdParent")||"").toUpperCase();A&&d.has(A)&&!d.has(N)&&(d.add(N),x.has(N)&&c.add(x.get(N)),T=!0)}}}let m=s?o:Ti(o,{author:t.author,allAuthors:t.allAuthors===!0}).oxml,p=W(m,"application/xml");if(!p.doc||p.error)return It(r,"PARSE_ERROR",p.error?.message||"Could not parse updated comments.xml.");for(let x of Array.from(p.doc.getElementsByTagNameNS("*","comment"))){let T=x.getAttribute("w:id")||x.getAttribute("id");c.has(T)&&x.parentNode?.removeChild(x)}let g=W(ne(n,"word/document.xml"),"application/xml");if(!g.doc||g.error)return It(r,"PARSE_ERROR",g.error?.message||"Could not parse document.xml.");let h=0;for(let x of["commentRangeStart","commentRangeEnd","commentReference"])for(let T of Array.from(g.doc.getElementsByTagNameNS("*",x))){let I=T.getAttribute("w:id")||T.getAttribute("id");if(!c.has(I)||!T.parentNode)continue;let N=T.parentNode;N.removeChild(T),h+=1,x==="commentReference"&&N.localName==="r"&&!Array.from(N.childNodes||[]).some(A=>A.nodeType===1&&A.localName!=="rPr")&&N.parentNode?.removeChild(N)}let y=oe();if(n.set("word/comments.xml",$t.encode(y.serializeToString(p.doc))),f?.doc){for(let x of Array.from(f.doc.getElementsByTagNameNS("*","commentEx"))){let T=(x.getAttribute("w15:paraId")||x.getAttribute("paraId")||"").toUpperCase();d.has(T)&&x.parentNode?.removeChild(x)}n.set("word/commentsExtended.xml",$t.encode(y.serializeToString(f.doc)))}n.set("word/document.xml",$t.encode(y.serializeToString(g.doc)));try{xf(n);let x=new lr(n);await Tn(x),t.validate!==!1&&await Ir(x)}catch(x){return It(r,"PACKAGE_VALIDATION",x.message)}let w=[...n].filter(([x,T])=>!this.entries.has(x)||!To(T,this.entries.get(x))).map(([x])=>x);this.entries=n;let v=this.toUint8Array();this.originalBytes=v;let b=ce(v);return{status:"ok",hasChanges:!0,written:!0,commentsRemoved:c.size,referencesRemoved:h,artifactsChanged:w,uint8Array:v,toUint8Array:()=>new Uint8Array(v),buffer:b,toBuffer:()=>ce(v)}}};function Bh(e){return new za(e)}function Dh(e,t){let r=typeof t?.numberingXml=="string"&&t.numberingXml.trim()?t.numberingXml:null,n=t?.numberingIdState&&typeof t.numberingIdState=="object"?t.numberingIdState:r?xr(r):null;if(!n||!e?.hasChanges||typeof e.oxml!="string"||!e.oxml.includes("/word/numbering.xml"))return e;let o=ft(e.oxml),a=Array.from(o.getElementsByTagNameNS("*","part")),i=d=>{let p=a.find(g=>(g.getAttribute("pkg:name")||g.getAttribute("name"))===d)?.getElementsByTagNameNS("*","xmlData")[0];return p&&Array.from(p.childNodes).find(g=>g.nodeType===1)||null},s=i("/word/numbering.xml"),l=i("/word/document.xml")?.getElementsByTagNameNS("*","body")[0];if(!s||!l)return e;let c=Array.from(l.childNodes).filter(d=>d.nodeType===1&&d.localName!=="sectPr"),u=yn(Yt(s),c,n),f=o.importNode(ft(u.numberingXml).documentElement,!0);return s.parentNode.replaceChild(f,s),c.forEach((d,m)=>l.replaceChild(u.replacementNodes[m],d)),{...e,oxml:Yt(o)}}async function Sf(e,t,r,n={}){let o=await Gn(e,t,r,n),a=Dh(o,n);if(a?.useNativeApi&&typeof a?.oxml!="string"){let i=Array.isArray(a?.warnings)?a.warnings:[];return Ne({...a,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return a}async function eS(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=rt(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await Sf(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function tS(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,a=n.sanitizeInput===!0?Ei(r):r,i=a!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],s=pn({oxml:e,originalText:t,modifiedText:a,allowExistingList:o}),l=n.preferListStructuralFallback!==!1,c=[];if(s&&l){let g=await gn(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(g?.hasChanges&&g?.oxml){let h=dr(g.oxml,{includeNumbering:g.includeNumbering??!0,numberingXml:g.numberingXml}),y=Array.isArray(g?.warnings)?g.warnings:[];return Ne({oxml:h,hasChanges:!0,warnings:[...i,...y],listStructuralFallbackApplied:!0,listStructuralFallbackKey:g.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:g.numberingXml||null})}c=Array.isArray(g?.warnings)?g.warnings:[]}let u=await Sf(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 gn(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let g=Array.isArray(u?.warnings)?u.warnings:[],h=Array.isArray(f?.warnings)?f.warnings:[];return{...u,warnings:[...g,...h],listStructuralFallbackApplied:!1}}let d=dr(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),m=Array.isArray(u?.warnings)?u.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return Ne({...u,oxml:d,hasChanges:!0,warnings:[...m,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{tn as ContainerKind,js as ContentType,ht as DiffOp,za as DocxDocument,B as NS_W,jt as NumberingService,ho as ReceiptCollector,Un as ReconciliationPipeline,Sn as RoutePlanKind,Z as RunKind,Oe as WORD_MAIN_NS,Br as acceptTrackedChangesInOoxml,Lo as analyzeStructuredContent,Yi as applyCommentReplyToParts,rg as applyFormattingRemovalToOoxml,Zi as applyHighlightToOoxml,Sf as applyRedlineToOxml,tS as applyRedlineToOxmlWithListFallback,Hr as areRevisionTokensEqual,oo as buildCommentElement,Xi as buildCommentsPartXml,da as buildExplicitDecimalMultilevelNumberingXml,fp as buildListMarkdown,dg as buildReconciliationPlan,Hi as buildRevisionTokenFraming,pn as buildSingleLineListStructuralFallbackPlan,Ci as buildTargetReferenceSnapshot,eo as clearSingleLineListFallbackExplicitSequence,Ac as collectContiguousListParagraphBlock,so as computeDocumentPartsRevisionToken,Os as computePackageRevisionToken,Hc as computeRevisionToken,io as computeRevisionTokenSync,Lf as configureLogger,Ff as configureXmlProvider,mr as containsTrackedChanges,xr as createDynamicNumberingIdState,Le as createEmptyReceipt,dt as createParagraphFingerprint,Ti as deleteCommentsByAuthorInOoxml,sa as enforceListBindingOnParagraphNodes,cs as ensureCommentsArtifactsInZip,Ea as ensureCommentsExtendedArtifactsInZip,Aa as ensureNumberingArtifactsInZip,je as escapeXml,gn as executeSingleLineListStructuralFallback,te as extractCanonicalParagraphText,va as extractDocumentPartsEntries,fa as extractFirstParagraphNumId,mg as extractParagraphIdFromOoxml,Uo as extractParagraphRevisionSegments,is as extractReplacementNodesFromOoxml,He as findContainingWordElement,Ri as findParagraphByBestTextMatch,Nc as findParagraphByReference,Qo as findParagraphByStrictText,ea as findStrictTargetCandidates,Kt as generateTableOoxml,as as getBodyElementFromDocument,re as getDefaultAuthor,le as getDocumentParagraphNodes,ts as getPackagePartName,Xe as getParagraphId,mt as getParagraphListInfo,Ie as getParagraphText,ja as getPlatform,Rr as getTrackedChangeAuthors,ki as hasListItems,kn as inferNumberingStyleFromMarker,Di as inferTableReplacementParagraphBlock,on as ingestOoxml,$p as ingestWordOoxmlToMarkdown,Xc as ingestWordOoxmlToMarkdownResult,Fp as ingestWordOoxmlToPlainText,zc as ingestWordOoxmlToPlainTextResult,qi as injectCommentsIntoOoxml,eg as injectCommentsIntoPackage,cg as insertBodyElementBeforeSectPr,ba as inspectDocumentParts,Dc as isLikelyStructuredTableSourceParagraph,Ur as isMarkdownTableText,kr as isNodeVisibleInRevisionView,ma as mergeNumberingXmlBySchemaOrder,Sa as normalizeBodySectionOrderStandalone,hu as normalizeContentEscapesForRouting,dp as normalizeListItemsWithLevels,Kc as normalizeOpcEntryName,q as normalizeWhitespaceForTargeting,Bh as openDocx,ua as overwriteParagraphNumIds,Qn as parseMarkdownListContent,ft as parseOoxml,W as parseOoxmlSafe,Pi as parseParagraphReference,_i as planListInsertionOnlyEdit,Hd as planStructuredReplacement,We as preprocessMarkdown,Mr as readCanonicalRunText,eS as reconcileMarkdownTableOoxml,wo as reconcileReceiptsAgainstOutput,ia as recordSingleLineListFallbackExplicitSequence,yr as rejectTrackedChangesInOoxml,yn as remapNumberingPayloadForDocument,au as removeFormattingFromRPr,Tn as repairKnownContentTypes,to as reserveNextNumberingId,ca as reserveNextNumberingIdPair,fn as resolveParagraphRangeByRefs,aa as resolveSingleLineListFallbackNumberingAction,zr as resolveTargetParagraph,Yn as resolveTargetParagraphWithSnapshot,Ei as sanitizeAiResponse,ug as sanitizeNestedParagraphsInTables,Yt as serializeOoxml,wt as serializeToOoxml,Vf as setDefaultAuthor,Wf as setPlatform,op as splitLeadingParagraphMarker,np as stripLeadingParagraphMarker,Xr as stripRedundantLeadingListMarkers,Mi as stripSingleLineListMarkerPrefix,Oi as synthesizeExpandedListScopeEdit,Fi as synthesizeTableMarkdownFromMultilineCellEdit,Ir as validateDocxPackage,pt as validateRedlineOoxml,Kr as validateRevisionToken,dr as wrapInDocumentFragment};
223
+ `)}function Wy(e,t,r){let n=Vy(e,t);if(!Number.isInteger(n)||n<1)return null;let o=jy(r);return o?`table:${n}|payload:${o}`:null}function Ky(e,t,r,n){let o=be(t,"pPr");o||(o=F(e,"w:pPr"),t.insertBefore(o,t.firstChild));let a=be(o,"numPr");a||(a=F(e,"w:numPr"),o.appendChild(a));let i=be(a,"ilvl");i||(i=F(e,"w:ilvl"),a.appendChild(i)),i.setAttribute("w:val",String(Math.max(0,Number.parseInt(r,10)||0)));let l=be(a,"numId");l||(l=F(e,"w:numId"),a.appendChild(l)),l.setAttribute("w:val",String(n))}function Gl(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,l=F(e,"w:p"),s=be(t,"pPr");s&&l.appendChild(gt(s)),Ky(e,l,r.ilvl,r.numId),i&&Zr(l,{author:o});let c=F(e,"w:r"),f=Array.from(t.getElementsByTagNameNS(ce,"r"))[0]||null,u=f?be(f,"rPr"):null;u&&c.appendChild(gt(u));let d=F(e,"w:t"),m=String(r.text||"").trim();if(/^\s|\s$/.test(m)&&d.setAttribute("xml:space","preserve"),d.textContent=m,c.appendChild(d),i){let p=n||ue(o,e),g=F(e,"w:ins");g.setAttribute("w:id",String(p.id)),g.setAttribute("w:author",p.author),g.setAttribute("w:date",p.date),g.appendChild(c),l.appendChild(g)}else l.appendChild(c);return l}function Wl(e,t){let r=(e||[]).map(n=>t.serializeToString(n)).join("");return`<w:document xmlns:w="${ce}"><w:body>${r}</w:body></w:document>`}function Gy({xmlDoc:e,explicitRangeParagraphs:t,insertionEntries:r,generateRedlines:n,author:o}){if(!Array.isArray(t)||t.length===0||!Array.isArray(r)||r.length===0)return!1;let a=t[0].parentNode;if(!a||t.some(l=>l.parentNode!==a))return!1;let i=t[t.length-1].nextSibling;for(let l of r){let s=l.insertBeforeOriginalIndex!=null?t[l.insertBeforeOriginalIndex]:t[t.length-1];if(!s)return!1;let c=Gl(e,s,{ilvl:l.ilvl,markerType:l.markerType,numId:l.numId,text:l.text},n?ue(o,e):null,o,{generateRedlines:n});l.insertBeforeOriginalIndex!=null?a.insertBefore(c,s):a.insertBefore(c,i)}return at(e),!0}function Hy(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=F(e,"w:p"),l=F(e,"w:r"),s=F(e,"w:t"),c=String(t||"");if(/^\s|\s$/.test(c)&&s.setAttribute("xml:space","preserve"),s.textContent=c,l.appendChild(s),a){o.trackParagraphMark===!0&&Zr(i,{author:n});let f=r||ue(n,e,"ins"),u=F(e,"w:ins");u.setAttribute("w:id",String(f.id)),u.setAttribute("w:author",f.author),u.setAttribute("w:date",f.date),u.appendChild(l),i.appendChild(u)}else i.appendChild(l);return i}function qy(e,t){let r=F(e,"w:p"),n=be(t,"pPr");n&&r.appendChild(gt(n));let o=F(e,"w:r"),a=Array.from(t.getElementsByTagNameNS(ce,"r"))[0]||null,i=a?be(a,"rPr"):null;i&&o.appendChild(gt(i));let l=F(e,"w:t");return l.textContent="",o.appendChild(l),r.appendChild(o),r}function Tm(e,t,r,n,o={}){let a=F(e,"w:p"),i=o.sanitizeParagraphProperties===!0?Sm(e,t):gt(be(t,"pPr"));i&&a.appendChild(i),o.paragraphId&&a.setAttributeNS(ma,"w14:paraId",o.paragraphId),o.trackParagraphMark===!0&&Zr(a,{author:n});let l=F(e,"w:ins"),s=r||ue(n,e,"ins");l.setAttribute("w:id",String(s.id)),l.setAttribute("w:author",s.author),l.setAttribute("w:date",s.date);for(let c of Array.from(t.childNodes||[]))c?.nodeType===1&&c.namespaceURI===ce&&c.localName==="pPr"||l.appendChild(c.cloneNode(!0));return a.appendChild(l),a}async function Yy(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,l=le(),s=qy(e,t),c=l.serializeToString(s),f=await wo(c,"",String(r||""),{author:o,generateRedlines:!1}),u=null;return typeof f?.oxml=="string"&&(u=(Sr(f.oxml).replacementNodes||[]).find(m=>m&&m.nodeType===1&&m.namespaceURI===ce&&m.localName==="p")||null),u?i?Tm(e,u,n,o,a):u:Hy(e,r,n,o,{...a,generateRedlines:i})}function Yl(e){let t=new Set;for(let r of e||[])for(let n of Bn(r)){let o=n.getAttribute("w:val")||n.getAttribute("val");o!=null&&o!==""&&t.add(String(o))}return Array.from(t)}function vm(e){return Array.from(e?.childNodes||[]).reduce((t,r)=>t+(r?.nodeType===1&&r.namespaceURI===ce&&r.localName==="r"?jt(r).map(n=>n.text).join(""):""),"")}function Jy(e,t,r){let n=0,o=-1;for(let a=0;a<r;a++){if(o=e.indexOf(t,n),o<0)return-1;n=o+Math.max(t.length,1)}return o}function Zy(e,t){if(!t)return 0;let r=0,n=0;for(;n<=e.length;){let o=e.indexOf(t,n);if(o<0)break;r+=1,n=o+t.length}return r}function Qy(e,t){let r=new Set(["commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"]);if(Array.from(e.getElementsByTagName?.("*")||[]).some(n=>r.has(n.localName)))return!0;for(let n of Array.from(t?.childNodes||[]))if(n.nodeType===1){if(!(n.namespaceURI===ce&&n.localName==="r"))return!0;for(let o of Array.from(n.childNodes||[]))if(!(o.nodeType!==1||o.namespaceURI!==ce)&&!["rPr","delText","t","tab","br","cr","noBreakHyphen","softHyphen"].includes(o.localName))return!0}return!1}function eb(e,t){let r=0;for(let n of Array.from(e?.childNodes||[])){if(!(n?.nodeType===1&&n.namespaceURI===ce&&n.localName==="r"))continue;let o=It(jt(n));if(t<=r+o)return gt(be(n,"rPr"));r+=o}return null}var tb=new Set(["pStyle","numPr","ind","jc","spacing","tabs","keepNext","keepLines","outlineLvl","contextualSpacing"]);function Hl(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function ym(e){return String(e||"").trim().toLowerCase()}function rb(e,t="nextSibling"){let r=e?.[t]||null;for(;r;){if(r.nodeType===1&&r.namespaceURI===ce&&r.localName==="p")return r;r=r[t]||null}return null}function Sm(e,t){let r=be(t,"pPr"),n=F(e,"w:pPr");if(!r)return n;for(let o of Array.from(r.childNodes||[]))o.nodeType!==1||o.namespaceURI!==ce||tb.has(o.localName)&&n.appendChild(e.importNode(o,!0));return n}function nb(e){let t=[],r=new Set;for(let o of Array.from(e?.getElementsByTagNameNS?.(ce,"bookmarkStart")||[])){let a=Hl(o,"name")||"(unnamed)";r.add(a)}for(let o of r)t.push(`RESTORATION_DROPPED_BOOKMARK:${o}`);let n=new Set;for(let o of["commentRangeStart","commentRangeEnd","commentReference"])for(let a of Array.from(e?.getElementsByTagNameNS?.(ce,o)||[])){let i=Hl(a,"id");i!==""&&n.add(i)}for(let o of n)t.push(`RESTORATION_DROPPED_COMMENT:${o}`);return t}function ob(e){let t=["bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference"];for(let r of t)for(let n of Array.from(e?.getElementsByTagNameNS?.(ce,r)||[]))n.parentNode?.removeChild(n);for(let r of Array.from(e?.getElementsByTagNameNS?.(ce,"r")||[]))Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.namespaceURI===ce&&o.localName!=="rPr")||r.parentNode?.removeChild(r)}function ab(e,t,r){let n=Ur(r.serializeToString(t),{allAuthors:!0}),a=j(n.oxml,"application/xml").doc?.getElementsByTagNameNS?.(ce,"p")?.[0]||null;if(!a)return null;let i=F(e,"w:p");i.appendChild(Sm(e,t));for(let l of Array.from(a.childNodes||[]))l.nodeType===1&&l.namespaceURI===ce&&l.localName==="pPr"||i.appendChild(e.importNode(l,!0));return ob(i),i}async function ib(e,t,r,n,o){let a=Y(t);if(a===r)return t;let i=await wo(o.serializeToString(t),a,r,{author:n,generateRedlines:!1,structuredContent:!1});if(i?.status==="error"||typeof i?.oxml!="string")return null;let s=(Sr(i.oxml).replacementNodes||[]).find(c=>c?.nodeType===1&&c.namespaceURI===ce&&c.localName==="p");return s?e.importNode(s,!0):null}function sb(e,t){let r=new Set(se(e).map(o=>o.getAttributeNS?.(ma,"paraId")||o.getAttribute?.("w14:paraId")||"").filter(Boolean).map(o=>o.toUpperCase())),n=null;do n=t?.generateParagraphId?.()||(1073741824+r.size+1).toString(16).toUpperCase();while(r.has(n.toUpperCase()));return n}function lb(e,t,r,n){let o=e.documentElement;return o&&!o.getAttribute("xmlns:w14")&&o.setAttribute("xmlns:w14",ma),Tm(e,t,null,r,{paragraphId:sb(e,n),sanitizeParagraphProperties:!0,trackParagraphMark:!0})}function cb(e,t){let r=be(e,"pPr"),n=be(r,"rPr"),o=be(n,"ins");return!!o&&ym(Hl(o,"author"))===ym(t)}function ub(e,t){let r=[],n=e;for(let o=0;o<t;o++){if(n=rb(n,"nextSibling"),!n)return[];r.push(n)}return r}function ql(e){let t=j(e,"application/xml");return t.error||!t.doc?null:se(t.doc).map(r=>Y(r))}function fb(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>r===t[n])}function Oi(e,t){let r=t==="accept"?nn(e,{allAuthors:!0}):Ur(e,{allAuthors:!0});return ql(r.oxml)}function db(e,t,r,n){let o=j(e,"application/xml");if(o.error||!o.doc)return null;let a=o.doc,i=se(a),l=i[t+n.length-1]||null;if(!l?.parentNode)return null;for(let c of[...r].sort((f,u)=>u-f)){let f=i[c];f?.parentNode?.removeChild(f)}let s=l.nextSibling;for(let c of n)l.parentNode.insertBefore(a.importNode(c,!0),s);return le().serializeToString(a)}function mb(e,t,r,n,o,a=[]){let i=Mt(e),l=Mt(t),s=An(l.issues,i.issues),c=a.flatMap(m=>Mt(le().serializeToString(m)).issues.filter(p=>p.severity==="error")),f=En(s);if(f.length>0||c.length>0)return{valid:!1,stage:"validation",code:"GENERATED_OOXML_INVALID",generatedIssues:s,envelopeIssues:c,message:[...f,...c].map(m=>m.message).join(" ")};let u=db(e,r,n,o);if(!u)return{valid:!1,stage:"expected-document",message:"Could not construct the restoration lifecycle oracle."};let d=[["current",ql(u),ql(t)],["accept-all",Oi(u,"accept"),Oi(t,"accept")],["reject-all",Oi(e,"reject"),Oi(t,"reject")]];for(let[m,p,g]of d)if(!fb(p,g))return{valid:!1,stage:m,expected:p,actual:g,message:`Paragraph restoration ${m} lifecycle text did not match the expected body-scoped paragraph sequence.`};return{valid:!0}}async function Am(e,t,r,n,o,a=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:f}=Kr(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let u=At(c,t,a,"insert",i,l);if(u?.error||!u?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:u?.error||{code:"TARGET_NOT_FOUND",message:"Rejected-view insertion target was not found."}};let d=u.paragraph;if(!zr(d,o).matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"REJECTED_INSERTION_STATE_REQUIRED",message:"Rejected-view insertion requires a wholly deleted paragraph owned by another author."}};let p=an(d,{requireFollowingParagraph:!1});if(p)return{documentXml:e,hasChanges:!1,status:"error",error:p};if(/\r|\n/.test(n))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Rejected-view insertion supports run-level text only; use restore for paragraph boundaries."}};let g=Y(d,{revisionView:"rejected"});if(!r.occurrenceExplicit&&Zy(g,r.exactText)>1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"AMBIGUOUS_ANCHOR",message:"The rejected-view insertion anchor is repeated; provide anchor.occurrence explicitly."}};let h=Jy(g,r.exactText,r.occurrence);if(h<0)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"ANCHOR_NOT_FOUND",message:"The rejected-view insertion anchor was not found at the requested occurrence."}};let v=h+r.offset,w=Array.from(d.childNodes||[]).filter(_=>_?.nodeType===1&&_.namespaceURI===ce&&_.localName==="del");if(w.some(_=>Qy(d,_)))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_BOUNDARY",message:"The rejected-view insertion boundary contains comments, bookmarks, fields, hyperlinks, moves, or non-text run markup that cannot be split safely."}};let y=0,b=null,x=0;for(let _ of w){let k=vm(_).length;if(v>=y&&v<=y+k){b=_,x=v-y;break}y+=k}if(!b||w.map(vm).join("")!==g)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"The rejected-view anchor is not contained in a supported direct deletion carrier."}};let S=eb(b,x),{leftCarrier:A,rightCarrier:E}=La(c,b,x,l._revisionIdAllocator||null),I=F(c,"w:ins"),R=ue(o,l._revisionIdAllocator||c,"ins");I.setAttribute("w:id",String(R.id)),I.setAttribute("w:author",R.author),I.setAttribute("w:date",R.date);let T=F(c,"w:r");S&&T.appendChild(S);let N=F(c,"w:t");/^\s|\s$/.test(n)&&N.setAttribute("xml:space","preserve"),N.textContent=n,T.appendChild(N),I.appendChild(T);let O=b.parentNode;A&&O.insertBefore(A,b),O.insertBefore(I,b),E&&O.insertBefore(E,b),l?._mutationRemovedNodes?.push(b),O.removeChild(b),l?._mutationLiveNodes?.push(d,I),f?.invalidateParagraphMetadata?.();let C=s.serializeToString(c),P=Y(d,{revisionView:"rejected"}),M=Y(d,{revisionView:"accepted"});return P!==g||!M.includes(n)?{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Rejected-view insertion did not preserve the deleted source and expose the requested inserted text."}}:{documentXml:C,hasChanges:!0,status:"ok"}}async function Em(e,t,r,n,o=null,a=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:f}=Kr(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let u=At(c,t,o,"restore",i,l);if(u?.error||!u?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:u?.error||{code:"TARGET_NOT_FOUND",message:"Restoration target paragraph not found."}};let d=u.paragraph,m=[d];if(l._compiledSourceEndId){let O=At(c,l.targetEndDescriptor?.text||"",a,"restore",i,{...l,_compiledSourceId:l._compiledSourceEndId}),C=O?.paragraph?se(c):[],P=C.indexOf(d),M=C.indexOf(O?.paragraph);m=P>=0&&M>=P?C.slice(P,M+1):null}else if(a)m=cn(c,o,a,{opType:"restore",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:l.onInfo,onWarn:l.onWarn});else if(l.targetEndDescriptor){let O=At(c,l.targetEndDescriptor.text,l.targetEndDescriptor.index,"restore",i,{...l,targetDescriptor:l.targetEndDescriptor,_compiledSourceId:l._compiledSourceEndId||null}),C=O?.paragraph?se(c):[],P=C.indexOf(d),M=C.indexOf(O?.paragraph);m=P>=0&&M>=P?C.slice(P,M+1):null}if(!Array.isArray(m)||m.length===0||m[0]!==d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:"The restoration range could not be resolved as a contiguous paragraph block."}};let p=Array.isArray(r)?r.map(String):[String(r||"")];if(p.length!==m.length||p.some(O=>O.length===0))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:`Restoration requires exactly one non-empty replacement per source paragraph (${m.length} expected, ${p.length} received).`}};let g=d.parentNode;if(!g||m.some(O=>O.parentNode!==g))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Restoration source paragraphs must be a contiguous block in one structural container."}};for(let O of m){let C=an(O);if(C?.code==="UNSUPPORTED_MOVE_REVISION")return{documentXml:e,hasChanges:!1,status:"error",error:C};let P=zr(O,n);if(!P.matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_STATE_REQUIRED",message:P.hasParagraphMarkDeletion&&!P.foreignParagraphMarkDeletion?"Explicit cross-author restoration does not apply to a paragraph deleted by the current author; use merge-same-author.":"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...P.ownerAuthor?{ownerAuthor:P.ownerAuthor}:{}}};let M=C||an(O);if(M)return{documentXml:e,hasChanges:!1,status:"error",error:M}}let h=m[m.length-1],v=ub(h,m.length),w=v.length===m.length&&v.every(O=>cb(O,n));if(w&&v.every((O,C)=>Y(O)===p[C]))return{documentXml:e,hasChanges:!1,status:"no-op",warnings:["An identical same-author paragraph restoration already exists."]};let y=s.serializeToString(c),b=se(c),x=b.indexOf(d),S=w?v.map(O=>b.indexOf(O)):[],A=[],E=[];for(let O=0;O<m.length;O++){let C=m[O];E.push(...nb(C));let P=ab(c,C,s),M=P?await ib(c,P,p[O],n,s):null;if(!M)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:`Could not reconstruct restoration paragraph ${O+1} from its rejected revision view.`}};A.push(M)}let I=A.map(O=>{let C=c.importNode(O,!0);return lb(c,C,n,f)}),R=h.nextSibling;for(let O of I)g.insertBefore(O,R);if(w)for(let O of v)l?._mutationRemovedNodes?.push(O),O.parentNode?.removeChild(O);l?._mutationLiveNodes?.push(...I),at(c);let T=s.serializeToString(c),N=mb(y,T,x,S,A,I);return N.valid?{documentXml:ot(c,s,e,f),hasChanges:!0,status:"ok",numberingXml:null,...E.length>0?{warnings:[...new Set(E)]}:{}}:{documentXml:e,hasChanges:!1,status:"error",error:{code:N.code||"PATCH_ROUNDTRIP_MISMATCH",message:N.message,stage:N.stage,...N.generatedIssues?{generatedIssues:N.generatedIssues}:{},...N.envelopeIssues?{envelopeIssues:N.envelopeIssues}:{},...N.expected?{expected:N.expected}:{},...N.actual?{actual:N.actual}:{}}}}async function pb({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=dn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p||p.numberingKey!=="numbered:decimal:single"||!Number.isInteger(p.startAt)||p.startAt<1)return null;let g=Xs(p.listInput||i);if(!g)return null;u("[List] Applying explicit numeric header conversion with direct list binding.");let h=Za(p,s?.listFallbackSequenceState||null),v=p.startAt,w=s?.numberingIdState||null,y=null,b=null;if(h.type==="explicitReuse"&&h.numId)y=String(h.numId),u(`[List] Reusing explicit-start list sequence (${h.numberingKey} -> numId ${y}, next ${v+1}).`);else{let I=to(w);if(!I)return null;y=String(I.numId),b=ni(I.numId,I.abstractNumId,v),h.type==="explicitStartNew"&&u(`[List] Started explicit-start list sequence (${h.numberingKey} -> numId ${y}).`),u(`[List] Using isolated explicit-start numbering (start ${v}, numId ${y}, abstractNumId ${I.abstractNumId}).`)}let x=await wo(t.serializeToString(o),a,g,{author:l,generateRedlines:f,_revisionIdAllocator:c});if(!x?.hasChanges||typeof x?.oxml!="string")return null;let A=Sr(x.oxml).replacementNodes;p.numberingKey&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(p.numberingKey),h.type==="explicitStartNew"||h.type==="explicitReuse"?Qa(s?.listFallbackSequenceState||null,h.numberingKey||p.numberingKey,y,v):Vo(s?.listFallbackSequenceState||null,h.numberingKey||p.numberingKey),ei(A,{numId:y,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0,trackPropertyChange:f?{author:l,revisionIdAllocator:c}:null});let E=o.parentNode;if(!E)return null;for(let I of A){let R=e.importNode(I,!0);let T=E.insertBefore(R,o);d?._mutationLiveNodes?.push(T)}if(d?._mutationRemovedNodes?.push(o),E.removeChild(o),at(e),n?.receiptCollector&&b){let I=Yl(d?._mutationLiveNodes);for(let R of I)n.receiptCollector.recordNumbering(R)}return{documentXml:ot(e,t,r,n),hasChanges:!0,numberingXml:b}}var gb=Object.freeze({upperAlpha:"upperLetter",lowerAlpha:"lowerLetter",upperRoman:"upperRoman",lowerRoman:"lowerRoman",bullet:"bullet"});function hb({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o||Oe(o)||q(a)!==q(i))return null;let m=dn({oxml:t.serializeToString(o),originalText:a,modifiedText:i,allowExistingList:!1}),p=m?gb[m.numberingStyle]:null;if(!p)return null;let g=se(e),h=Fl(e,[o],Sl({mode:"convert-plain",format:p,strip:"marker"}),{author:l||ae(),generateRedlines:f,revisionIdAllocator:c,runtimeContext:s,stylesXml:s?.stylesXml||d.stylesXml||null,numberingXml:s?.numberingXml||d.numberingXml||null,paragraphIndexOf:v=>g.indexOf(v)+1});if(!h.ok)return u(`[List] In-place marker conversion declined (${h.error.code}); using the structural fallback.`),null;u(`[List] Converted typed ${p} marker in place (numId ${h.items[0].numId}).`),d?._mutationLiveNodes?.push(o);for(let v of h.allocatedNumIds)n?.receiptCollector?.recordNumbering(v);return at(e),{documentXml:ot(e,t,r,n),hasChanges:!0,numberingXml:h.numberingXml}}var bm=["pStyle","keepNext","keepLines","pageBreakBefore","framePr","widowControl","numPr","suppressLineNumbers","pBdr","shd","tabs","suppressAutoHyphens","kinsoku","wordWrap","overflowPunct","topLinePunct","autoSpaceDE","autoSpaceDN","bidi","adjustRightInd","snapToGrid","spacing","ind","contextualSpacing","mirrorIndents","suppressOverlap","jc","textDirection","textAlignment","textboxTightWrap","outlineLvl","divId","cnfStyle","rPr","sectPr","pPrChange"],wb=new Set(["pStyle","numPr","rPr","sectPr","pPrChange"]);function vb(e,t,r){let n=t.filter(s=>s?.nodeType===1&&s.localName==="p"),o=(s,c)=>{let f=be(be(s,"pPr"),"rPr");return!!f&&!!be(f,c)},a=n.find(s=>o(s,"del")),i=n.find(s=>!o(s,"del")),l=be(r,"pPr");if(a&&l){let s=e.importNode(l,!0),c=be(be(a,"pPr"),"rPr"),f=c&&be(c,"del");if(f){let u=be(s,"rPr");if(!u){u=F(e,"w:rPr");let d=be(s,"sectPr")||be(s,"pPrChange");s.insertBefore(u,d||null)}Array.from(u.childNodes).forEach(d=>{d.nodeType===1&&(d.localName==="ins"||d.localName==="del")&&u.removeChild(d)}),u.appendChild(e.importNode(f,!0)),a.replaceChild(s,be(a,"pPr"))}}if(i&&l){let s=be(i,"pPr");s||(s=F(e,"w:pPr"),i.insertBefore(s,i.firstChild||null));for(let c of Array.from(l.childNodes)){if(c.nodeType!==1||wb.has(c.localName)||be(s,c.localName))continue;let f=bm.indexOf(c.localName),u=Array.from(s.childNodes).find(d=>d.nodeType===1&&bm.indexOf(d.localName)>f);s.insertBefore(e.importNode(c,!0),u||null)}}if(i)for(let s of["paraId","textId"]){let c=r.getAttributeNS?.(ma,s)||r.getAttribute?.(`w14:${s}`);c&&i.setAttributeNS(ma,`w14:${s}`,c)}}async function yb({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=dn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p)return null;u("[List] No textual diff but list marker detected; forcing structural list conversion fallback.");let g=await Qn(p,{author:l,generateRedlines:f,revisionIdAllocator:c,setAbstractStartOverride:!1});if(!g?.hasChanges||!g?.oxml)return u("[List] Structural list fallback produced no valid OOXML payload."),null;let h=Sr(g.oxml),v=h.replacementNodes,w=h.numberingXml||g?.numberingXml||null,y=Number.isInteger(p?.startAt)&&p.startAt>0,b=y&&p?.numberingStyle==="decimal",x=y&&!b,S=g?.listStructuralFallbackKey||p?.numberingKey||null,A=Za(p,s?.listFallbackSequenceState||null);if(b){let I=p.startAt,R=null,T=s?.numberingIdState||null;if(A.type==="explicitReuse"&&A.numId)R=String(A.numId),w=null,u(`[List] Reusing explicit-start list sequence (${A.numberingKey} -> numId ${R}, next ${I+1}).`);else if(T){let N=to(T);if(!N)return null;ti(v,N.numId),R=String(N.numId),w=ni(N.numId,N.abstractNumId,I),A.type==="explicitStartNew"&&u(`[List] Started explicit-start list sequence (${A.numberingKey} -> numId ${N.numId}).`),u(`[List] Using isolated explicit-start numbering (start ${I}, numId ${N.numId}, abstractNumId ${N.abstractNumId}).`)}else{let N=ri(v);R=N?String(N):null,u(`[List] Using isolated list numbering with explicit start ${I}${N?` (numId ${N})`:""}.`)}S&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(S),A.type==="explicitStartNew"||A.type==="explicitReuse"?Qa(s?.listFallbackSequenceState||null,A.numberingKey||S,R,I):Vo(s?.listFallbackSequenceState||null,A.numberingKey||S),R&&ei(v,{numId:R,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0,trackPropertyChange:f?{author:l,revisionIdAllocator:c}:null})}else{if(w&&s?.numberingIdState){let I=mn(w,v,s.numberingIdState);v=I.replacementNodes,w=I.numberingXml}Vo(s?.listFallbackSequenceState||null,A.numberingKey||S)}if(!b&&w&&s){let I=Rf({numberingXml:w,replacementNodes:v,sequence:Ll(s),isNumIdLive:R=>Ml(e,R)});I&&(v=I.replacementNodes,w=null,u(`[List] Continuing batch list numbering (numId ${I.numId}).`))}if(!b&&!x&&s?.listFallbackSharedNumIdByKey instanceof Map){let I=S?s.listFallbackSharedNumIdByKey.get(S):null;if(I)ti(v,I),w=null,u(`[List] Reusing shared list numbering (${S} -> numId ${I}).`);else if(S){let R=ri(v);R&&(s.listFallbackSharedNumIdByKey.set(S,R),u(`[List] Captured shared list numbering (${S} -> numId ${R}).`))}}let E=o.parentNode;if(!E)return null;f&&vb(e,v,o);for(let I of v){let R=e.importNode(I,!0);let T=E.insertBefore(R,o);d?._mutationLiveNodes?.push(T)}if(d?._mutationRemovedNodes?.push(o),E.removeChild(o),at(e),n?.receiptCollector&&w){let I=Yl(d?._mutationLiveNodes);for(let R of I)n.receiptCollector.recordNumbering(R)}return{documentXml:ot(e,t,r,n),hasChanges:!0,numberingXml:w}}function Kl(e,t){let{severity:r,...n}=t;return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:n}}function ki(e){return e.length>0?{diagnostics:e,warnings:e.map(Rl)}:{}}function xm({sourceParagraphs:e,modifiedText:t,runtimeContext:r,options:n}){let o=El(n);if(o==="off")return null;let a=r?.numberingIdState?.sourceNumberingXml;if(!a)return null;let i=[];for(let s of e||[]){let c=Oe(s);c&&i.push({text:ho(s),numId:c.numId,ilvl:c.ilvl})}let l=Vd({modifiedText:t,sourceItems:i,sourceNumberingXml:a});return l?Ud(l.mismatch,{policy:o,numId:l.numId,level:l.level,marker:l.marker,targetText:l.targetText,operationIndex:n?._operationIndex}):null}async function Rm(e,t,r,n,o=null,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=At(d,t,o,"redline",i,{...l,onInfo:c,onWarn:f});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph;if(typeof r=="string"&&r.length>0){let X=zr(h,n);if(X.matches){let Q=X.ownerAuthor||"unattributed";return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${Q}). Use explicit paragraph restoration when supported.`,ownerAuthor:Q}}}}Xy(h);let v=ho(h);if(r===""){let X=gm(h);if(X.length>0){let Q=hm(X,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:X,...Q.length>0?{comments:Q}:{}}}}}let w=Ha(h,r,l);if(!w.valid)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:w.code,message:w.message}};let y=l.existingRevisions==="auto";y&&(l={...l,existingRevisions:Lr("auto",h,n)});let b=fr(h),x=l.existingRevisions||"merge-same-author";if(b&&x!=="accept-all-first"&&x!=="accept-all-first-keep-normalized")if(x==="merge-same-author"||x==="slice-cross-author"){let X=Mr(h),Q=String(n||"").trim().toLowerCase(),Te=X.length>0&&!dr(h)&&X.every(Ae=>Ae.trim().toLowerCase()===Q);if(!Te&&x==="merge-same-author")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${[...X,...dr(h)?["unattributed"]:[]].join(", ")}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:X,currentPolicy:x}};let Se=Te?gm(h):[];if(Se.length>0){let Ae=hm(Se,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:Se,...Ae.length>0?{comments:Ae}:{}}}}if(!Te&&(h.getElementsByTagNameNS(ce,"moveFrom").length>0||h.getElementsByTagNameNS(ce,"moveTo").length>0))return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}}}else{let X=h.getElementsByTagNameNS(ce,"del").length>0,Q=h.getElementsByTagNameNS(ce,"moveFrom").length>0||h.getElementsByTagNameNS(ce,"moveTo").length>0;return X?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}}:Q?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}}:{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}}if(r===""&&v===""&&!(b&&x==="merge-same-author"))return s?(Qr(h,{author:n}),l?._mutationLiveNodes?.push(h)):(l?._mutationRemovedNodes?.push(h),h.parentNode?.removeChild(h)),at(d),{documentXml:ot(d,u,e,m),hasChanges:!0,numberingXml:null};let S=ut(h,"tbl"),E=!!S&&!a&&typeof r=="string"&&r.includes(`
224
+ `)&&!sn(r)?Wy(d,S,r):null,I=i?.tableStructuralRedlineKeys instanceof Set?i.tableStructuralRedlineKeys:null;if(E&&I?.has(E))return c("[Table] Skipping duplicate table-structural redline for the same table/payload in this turn."),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:["Skipped duplicate table-structural redline in the same turn."]};let T=(S?Ws(h,r,{tableElement:S,currentParagraphText:v,onInfo:c,onWarn:f}):null)||r,N=!!S&&sn(T),O=sn(T),C=null;if(!a&&(l._compiledSourceEndId||l.targetEndDescriptor)){let X=km(d,t,o,a,"redline",i,{...l,_resolutionCapture:null});if(X.error)return{documentXml:e,hasChanges:!1,status:"error",error:X.error};if(X.paragraphs.length>1){let Q=X.paragraphs[0].parentNode;if(X.paragraphs.some(Te=>Te.parentNode!==Q))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_RANGE_INVALID",message:"A redline target range must stay inside one container (body, table cell, header, ...); it spans a table or other container boundary. Edit the paragraphs on each side separately."}};C=X.paragraphs}}let P=C||(a?cn(d,o,a,{opType:"redline",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:c,onWarn:f}):typeof t=="string"&&/\r?\n/.test(t)?Ba(d,t):null),M=Array.isArray(P)&&P.length>0;if(y&&M&&(l={...l,existingRevisions:Lr("auto",P,n)}),!N&&M){let X=lm(P,T);if(X&&X.length>0){c(`[List] Applying explicit-range insertion-only heuristic (${X.length} new item(s)).`);for(let Se of X)c(`[List] Explicit-range insertion: ilvl=${Se.ilvl}, markerType=${Se.markerType}, text="${String(Se.text||"").slice(0,80)}${String(Se.text||"").length>80?"\u2026":""}"`);let Q=xm({sourceParagraphs:P,modifiedText:T,runtimeContext:i,options:l});if(Q?.severity==="error")return Kl(e,Q);if(Gy({xmlDoc:d,explicitRangeParagraphs:P,insertionEntries:X,generateRedlines:s,author:n}))return{documentXml:ot(d,u,e,m),hasChanges:!0,numberingXml:null,...ki(Q?[Q]:[])}}}let _=null;!P&&!N&&O&&(_=js(h,{getParagraphText:ho}),_?.length>1&&c(`[Table] Heuristic range expansion selected ${_.length} paragraph(s) for replacement.`));let k=Oe(h);if(k&&typeof T=="string"&&!T.includes(`
225
+ `)){let X=un(T);X&&X!==T.trim()&&(c("[List] Stripped redundant manual list marker prefix from single-line list item edit."),T=X)}N&&c("[Table] Markdown table edit detected in table cell target; applying reconciliation at table scope.");let L=l.explicitStructuredContent===!0,D=!L&&!N&&!M&&k?cm(v,T):null;if(D){c(`[List] Applying single-paragraph list adjacency insertion heuristic (${D.position}).`);let X=h.parentNode;if(!X)throw new Error("Target paragraph has no parent for adjacency list insertion");let Q=Gl(d,h,{ilvl:k.ilvl,numId:k.numId,markerType:"numbered",text:D.text},s?ue(n,d):null,n,{generateRedlines:s}),Te=D.position==="before"?h:h.nextSibling;return X.insertBefore(Q,Te),l?._mutationLiveNodes?.push(Q),at(d),{documentXml:ot(d,u,e,m),hasChanges:!0,numberingXml:null}}let z=!N&&!M&&!k&&!S&&!a?fm(T):null,G=z?qe(z.paragraphMarkdown):null;if(z&&q(G.cleanText)===q(v)){let X=bt(z.tableText);if(X.headers.length>0||X.rows.length>0){c("[Table] Applying retained-paragraph table append heuristic.");let Q=h.parentNode;if(!Q)throw new Error("Target paragraph has no parent for table append");let Te=h.nextSibling;if(G.formatHints.length>0){let Je=await wo(u.serializeToString(h),v||t,z.paragraphMarkdown,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:!1,_revisionIdAllocator:p});if(Je?.status==="error")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:Je.error};if(Je?.hasChanges){if(typeof Je.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed paragraph format");for(let On of Sr(Je.oxml).replacementNodes){let kn=d.importNode(On,!0);l?._mutationLiveNodes?.push(Q.insertBefore(kn,h))}l?._mutationRemovedNodes?.push(h),Q.removeChild(h)}}let Se=mr(X,{generateRedlines:s,author:n,revisionIdAllocator:p,trackAsBlock:!0});for(let Je of Sr(Se).replacementNodes)l?._mutationLiveNodes?.push(Q.insertBefore(d.importNode(Je,!0),Te));let Ae=Te;for(;Ae&&Ae.nodeType!==1;)Ae=Ae.nextSibling;if(!Ae||Ae.namespaceURI===ce&&Ae.localName==="sectPr"){let Je=F(d,"w:p"),On=gt(be(h,"pPr"));if(On){for(let kn of Array.from(On.childNodes))kn.nodeType===1&&["sectPr","numPr"].includes(kn.localName)&&On.removeChild(kn);Je.appendChild(On)}s&&Zr(Je,{author:n}),l?._mutationLiveNodes?.push(Q.insertBefore(Je,Te))}return at(d),{documentXml:ot(d,u,e,m),hasChanges:!0,numberingXml:null}}}let ee=!L&&!N&&!M&&!k?um(v,T):null;if(ee){c(`[Text] Applying single-paragraph plain adjacency insertion heuristic (${ee.position}, count=${ee.paragraphs.length}).`);let X=h.parentNode;if(!X)throw new Error("Target paragraph has no parent for plain adjacency insertion");let Q=ee.position==="before"?h:h.nextSibling;for(let Te of ee.paragraphs){let Se=await Yy(d,h,Te,s?ue(n,d):null,n,{generateRedlines:s,trackParagraphMark:!0}),Ae=d.importNode(Se,!0);let zi=X.insertBefore(Ae,Q);l?._mutationLiveNodes?.push(zi)}return at(d),{documentXml:ot(d,u,e,m),hasChanges:!0,numberingXml:null}}let J=!L&&!N&&!M?Us(h,T,{currentParagraphText:v,onInfo:c,onWarn:f}):null;if(J&&J.entries.length>0){let X=xm({sourceParagraphs:[h],modifiedText:T,runtimeContext:i,options:l});if(X?.severity==="error")return Kl(e,X);c(`[List] Applying insertion-only list redline heuristic (${J.entries.length} new item(s)).`);for(let Se of J.entries)c(`[List] Insertion entry resolved: ilvl=${Se.ilvl}, markerType=${Se.markerType}, text="${String(Se.text||"").slice(0,80)}${String(Se.text||"").length>80?"\u2026":""}"`);let Q=h.parentNode;if(!Q)throw new Error("Target paragraph has no parent for list insertion");let Te=h.nextSibling;for(let Se of J.entries){let Ae=Gl(d,h,{...Se,numId:J.numId},s?ue(n,d):null,n,{generateRedlines:s});Q.insertBefore(Ae,Te),l?._mutationLiveNodes?.push(Ae)}return at(d),{documentXml:ot(d,u,e,m),hasChanges:!0,numberingXml:null,...ki(X?[X]:[])}}let Z=!L&&!N&&!M?Ds(h,T,{currentParagraphText:v,onInfo:c,onWarn:f}):null,ie=!!Z&&Array.isArray(Z.paragraphs)&&Z.paragraphs.length>0;ie&&(T=Z.modifiedText);let ne=null;if(!L&&!N&&!ie&&!M){let X=await pb({xmlDoc:d,serializer:u,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:v,modifiedText:T,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if(X)return X;let Q=hb({xmlDoc:d,serializer:u,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:v,modifiedText:T,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if(Q)return Q;let Te=await yb({xmlDoc:d,serializer:u,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:v,modifiedText:T,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if(Te)return Te;let Se=El(l);if(Se!=="off"&&!k){let Ae=$d({originalText:v,modifiedText:T,targetIsListItem:!1});if(Ae&&(ne=Dd(Ae,{policy:Se,targetText:v,operationIndex:l?._operationIndex}),Se==="error"))return Kl(e,ne)}}let re=ie?Z.originalText:P?P.map(X=>ho(X)).join(`
226
+ `):_?_.map(X=>ho(X)).join(`
227
+ `):v||t,je=N?u.serializeToString(S):ie?Wl(Z.paragraphs,u):P?Wl(P,u):_?Wl(_,u):u.serializeToString(h),ge=O?await $y(je,re,T,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:l.structuredContent!==!1,explicitStructuredContent:l.explicitStructuredContent===!0,_revisionIdAllocator:p,_isolatedTableCell:N}):await wo(je,re,T,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:l.structuredContent!==!1,explicitStructuredContent:l.explicitStructuredContent===!0,pairReplacements:l.pairReplacements===!0,insertionAffinity:l.insertionAffinity||null,literalTextEdit:l.literalTextEdit===!0,plainTextContent:l.plainTextContent===!0,_revisionIdAllocator:p,_isolatedTableCell:N});if(!ge?.hasChanges)return{documentXml:e,hasChanges:!1,numberingXml:null,status:ge?.status||"no-op",error:ge?.error};if(ge.useNativeApi&&!ge.oxml){let X="Format-only fallback requires native Word API; browser demo skipped this operation.";return f(`[WARN] ${X}`),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:[X]}}if(typeof ge.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed redline operation");let he=Sr(ge.oxml),Me=Uy(he.replacementNodes,ge.warnings),K=he.numberingXml;if(K&&i?.numberingIdState){let X=Hs({numberingXml:K,replacementNodes:Me,sourceParagraphs:ie?Z.paragraphs:P||[h],numberingIdState:i.numberingIdState,allowContinueSource:!N});Me=X.replacementNodes,K=X.numberingXml}let V=N?[S]:ie?Z.paragraphs:P||_||[h],ye=V[0],Pe=ye.parentNode;for(let X of Me){let Q=d.importNode(X,!0);let Te=Pe.insertBefore(Q,ye);l?._mutationLiveNodes?.push(Te)}for(let X of V)X&&X.parentNode===Pe&&(l?._mutationRemovedNodes?.push(X),Pe.removeChild(X));if(at(d),E&&I&&(N||S)&&I.add(E),m?.receiptCollector&&K){let X=Yl(l?._mutationLiveNodes);for(let Q of X)m.receiptCollector.recordNumbering(Q)}return{documentXml:ot(d,u,e,m),hasChanges:!0,numberingXml:K,status:"ok",...ne?{diagnostics:[ne],warnings:[...Array.isArray(ge.warnings)?ge.warnings:[],Rl(ne)]}:Array.isArray(ge.warnings)&&ge.warnings.length>0?{warnings:ge.warnings}:{}}}async function Pm(e,t,r,n,o,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=At(d,t,a,"highlight",i,{...l,onInfo:c,onWarn:f});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,v=u.serializeToString(h),w=sl(v,r,n,{generateRedlines:s,author:o,_revisionIdAllocator:p});if(!w||w===v)return{documentXml:e,hasChanges:!1};let{replacementNodes:y}=Sr(w),b=h.parentNode;for(let x of y){let S=d.importNode(x,!0);let A=b.insertBefore(S,h);l?._mutationLiveNodes?.push(A)}return l?._mutationRemovedNodes?.push(h),b.removeChild(h),at(d),{documentXml:ot(d,u,e,m),hasChanges:!0}}async function Cm(e,t,r,n,o,a=null,i=null,l={}){let s=typeof l?.onInfo=="function"?l.onInfo:()=>{},c=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:f,xmlDoc:u,operationSession:d}=Kr(e,l);if(!u)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||Sn(u,l);let m=At(u,t,a,"comment",i,{...l,onInfo:s,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=f.serializeToString(p),h=typeof r=="string"&&r.length>0?r:ho(p),v=al(g,[{paragraphIndex:1,textToFind:h,commentContent:n}],{author:o,commentIdAllocator:l.commentIdAllocator});if(v.status==="error"||v.error||!v.commentsApplied)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:v.error||{code:"ANCHOR_INSERTION_FAILED",message:"The comment anchor was not applied to the resolved paragraph."},warnings:v.warnings||[]};let{replacementNodes:w}=Sr(v.oxml),y=p.parentNode;for(let b of w){let x=u.importNode(b,!0);let S=y.insertBefore(x,p);l?._mutationLiveNodes?.push(S)}if(l?._mutationRemovedNodes?.push(p),y.removeChild(p),at(u),d?.receiptCollector&&Array.isArray(v.placedComments))for(let b of v.placedComments)d.receiptCollector.recordComment(b.id);return{documentXml:ot(u,f,e,d),hasChanges:!0,commentsXml:v.commentsXml||null,warnings:v.warnings||[],resolvedAnchor:v.resolvedAnchors?.[0]||null}}function Im(e,t,r,n){let o=t.cloneNode(!0),a=t.cloneNode(!0);Ft(a,n);let i=d=>{if(d.nodeType!==1)return!1;let m=d.localName||d.nodeName.replace(/^w:/,"");return["t","tab","br","noBreakHyphen","delText"].includes(m)};Array.from(o.childNodes).forEach(d=>{i(d)&&o.removeChild(d)}),Array.from(a.childNodes).forEach(d=>{i(d)&&a.removeChild(d)});let l="";for(let d of Array.from(t.childNodes)){if(d.nodeType!==1)continue;let m=d.localName||d.nodeName.replace(/^w:/,"");m==="t"?l+=d.textContent||"":m==="tab"?l+=" ":m==="br"?l+=`
228
+ `:m==="noBreakHyphen"&&(l+="\u2011")}let s=l.slice(0,r),c=l.slice(r),f=(d,m)=>{let p=m.split(/(\t|\n|\u2011)/);for(let g of p)if(g)if(g===" ")d.appendChild(F(e,"w:tab"));else if(g===`
229
+ `)d.appendChild(F(e,"w:br"));else if(g==="\u2011")d.appendChild(F(e,"w:noBreakHyphen"));else{let h=F(e,"w:t");/^\s|\s$/.test(g)&&h.setAttribute("xml:space","preserve"),h.textContent=g,d.appendChild(h)}};f(o,s),f(a,c);let u=t.parentNode;return u.insertBefore(o,t),u.insertBefore(a,t),u.removeChild(t),[o,a]}async function _m(e,t,r,n={},o,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=At(d,t,a,"format",i,{...l,onInfo:c,onWarn:f});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,w=(()=>{let C=[],P=Array.from(h.getElementsByTagNameNS(ce,"r"));for(let M of P){let _=M.parentNode,k=!1;for(;_&&_!==h;){if(_.nodeType===1&&(_.localName==="del"||_.nodeName==="w:del")){k=!0;break}_=_.parentNode}if(k)continue;let L="";for(let D of Array.from(M.childNodes)){if(D.nodeType!==1)continue;let z=D.localName||D.nodeName.replace(/^w:/,"");z==="t"?L+=D.textContent||"":z==="tab"?L+=" ":z==="br"?L+=`
230
+ `:z==="noBreakHyphen"&&(L+="\u2011")}L.length>0&&C.push({run:M,text:L})}return C})(),y="",b=[];for(let C of w){let P=y.length;y+=C.text;let M=y.length;b.push({...C,start:P,end:M})}let x=l.targetDescriptor,S=Number.isInteger(l.textOccurrence)&&l.textOccurrence>0?l.textOccurrence:null,A=S??x?.occurrence??null,E=-1;if(A!=null&&A>0){let C=0,P=0;for(;P<=y.length-r.length;){let M=y.indexOf(r,P);if(M===-1)break;if(C++,C===A){E=M;break}P=M+1}}else E=y.indexOf(r);if(E===-1&&S!=null&&y.includes(r))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_SOURCE_NOT_FOUND",message:`Occurrence ${S} of text to format was not found in target paragraph: "${r}".`}};if(E===-1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:`Text to format was not found in target paragraph: "${r}".`}};let I=E+r.length,R=[];for(let C of b)if(C.start<E&&C.end>E){let P=E-C.start,[M,_]=Im(d,C.run,P,p);R.push({run:M,start:C.start,end:E,text:C.text.slice(0,P)}),R.push({run:_,start:E,end:C.end,text:C.text.slice(P)})}else R.push(C);let T=[];for(let C of R)if(C.start<I&&C.end>I){let P=I-C.start,[M,_]=Im(d,C.run,P,p);T.push({run:M,start:C.start,end:I,text:C.text.slice(0,P)}),T.push({run:_,start:I,end:C.end,text:C.text.slice(P)})}else T.push(C);let N=T.filter(C=>C.start>=E&&C.end<=I),O=!1;for(let C of N){let P=C.run.getElementsByTagNameNS(ce,"rPr")[0]||null;if(yu(P,n)){O=!0;break}}if(!O)return{documentXml:e,hasChanges:!1,status:"no-op"};for(let C of N){let P=C.run,M=P.getElementsByTagNameNS(ce,"rPr")[0];M||(M=F(d,"w:rPr"),P.insertBefore(M,P.firstChild));let _=P.parentNode,k=!1;for(;_&&_!==h;){if(_.nodeType===1&&(_.localName==="ins"||_.nodeName==="w:ins")){(_.getAttribute("w:author")||_.getAttributeNS(ce,"author"))===(o||ae())&&(k=!0);break}_=_.parentNode}let L=k&&l.formattingRevisionPolicy==="coalesce-own-insertion";s&&!L&&ko(d,M,o||ae()),bu(d,M,n)}return at(d),l?._mutationLiveNodes?.push(h),{documentXml:ot(d,u,e,m),hasChanges:!0,status:"ok"}}async function Om(e,t,r={},n,o=null,a=null,i={}){let l=i.generateRedlines!==!1,s=typeof i?.onInfo=="function"?i.onInfo:()=>{},c=typeof i?.onWarn=="function"?i.onWarn:()=>{},{serializer:f,xmlDoc:u,operationSession:d}=Kr(e,i);if(!u)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||Sn(u,i);let m=At(u,t,o,"paragraph-format",a,{...i,onInfo:s,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=p.getElementsByTagNameNS(ce,"pPr")[0];g||(g=F(u,"w:pPr"),p.insertBefore(g,p.firstChild));let h=Ri(r),v=h.length>0?[Xd(h)]:[];if(r?.numbering){let y=Cf(a?.numberingIdState,r.numbering.numId,Number(r.numbering.level)||0);if(!y.ok)return{documentXml:e,hasChanges:!1,status:"error",error:{code:Ld,message:`${y.message} paragraph-format.numbering binds to an existing list; it never creates one.`,field:"properties.numbering",numId:Number(r.numbering.numId),level:Number(r.numbering.level)||0,reason:y.reason,recovery:{action:"inspect_numbering",hint:"Inspect a paragraph already in the target list and pass its list.numId and list.level. To start a new list, use a list-change/redline operation."}}}}if(!xu(g,r))return{documentXml:e,hasChanges:!1,status:"no-op",...ki(v)};if(l){let y=n||ae(),b=et(g,"pPrChange"),x=b?.getAttribute("w:author")??b?.getAttribute("author")??"";if(b&&x!==y)return{documentXml:e,hasChanges:!1,status:"error",error:{code:Bd,message:`Target paragraph already has a pending paragraph-property change by "${x||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`,pendingAuthor:x,recovery:{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."}}};b||Hn(u,g,y)}return Kn(u,g,r),at(u),i?._mutationLiveNodes?.push(p),{documentXml:ot(u,f,e,d),hasChanges:!0,status:"ok",...ki(v)}}function km(e,t,r,n,o,a,i){let l=At(e,t,r,o,a,i);if(l?.error||!l?.paragraph)return{error:l?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let s=l.paragraph;if(!(i._compiledSourceEndId||n!=null||i.targetEndDescriptor))return{paragraphs:[s]};let f=null;if(i._compiledSourceEndId||i.targetEndDescriptor){let u=At(e,i.targetEndDescriptor?.text||"",i._compiledSourceEndId?n:i.targetEndDescriptor?.index??n,o,a,{...i,...i.targetEndDescriptor?{targetDescriptor:i.targetEndDescriptor}:{},_compiledSourceId:i._compiledSourceEndId||null,_resolutionCapture:null});if(u?.error)return{error:u.error};let d=u?.paragraph?se(e):[],m=d.indexOf(s),p=d.indexOf(u?.paragraph);f=m>=0&&p>=m?d.slice(m,p+1):null}else f=cn(e,r,n,{opType:o,targetRefSnapshot:a?.targetRefSnapshot||null,onInfo:i.onInfo,onWarn:i.onWarn});return!Array.isArray(f)||f.length===0||f[0]!==s?{error:{code:"TARGET_RANGE_INVALID",message:"targetEnd must resolve to the target paragraph or a paragraph after it."}}:{paragraphs:f}}async function Mm(e,t,r,n,o=null,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=km(d,t,o,a,"list-format",i,{...l,onInfo:c,onWarn:f});if(g.error)return{documentXml:e,hasChanges:!1,status:"error",error:g.error};let h=g.paragraphs;if(h.some(b=>b.parentNode!==h[0].parentNode))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_RANGE_INVALID",message:"A list-format range must stay inside one container (the body, or one table cell)."}};let v=se(d),w=Sl(r);if(w.mode==="change-format"||w.mode==="join")return bb(d,h,w,{documentXml:e,serializer:u,operationSession:m,runtimeContext:i,options:l,author:n,generateRedlines:s,onInfo:c,onWarn:f,paragraphIndexOf:b=>{let x=v.indexOf(b);return x>=0?x+1:null}});let y=Fl(d,h,w,{author:n||ae(),generateRedlines:s,revisionIdAllocator:p,runtimeContext:i,stylesXml:i?.stylesXml||l.stylesXml||null,numberingXml:i?.numberingXml||l.numberingXml||null,paragraphIndexOf:b=>v.indexOf(b)+1});if(!y.ok)return{documentXml:e,hasChanges:!1,status:"error",error:y.error};for(let b of y.items)b.paragraph,l?._mutationLiveNodes?.push(b.paragraph);for(let b of y.allocatedNumIds)m?.receiptCollector?.recordNumbering(b);return at(d),c(`[List] list-format convert-plain bound ${y.items.length} paragraph(s) as ${y.format} (numId ${[...new Set(y.items.map(b=>b.numId))].join(", ")}).`),{documentXml:ot(d,u,e,m),hasChanges:!0,status:"ok",numberingXml:y.numberingXml,list:{mode:"convert-plain",format:y.format,level:y.level,strip:y.strip,items:y.items.map(b=>({paragraphIndex:b.paragraphIndex,paragraphId:He(b.paragraph),marker:b.marker,value:b.value,numId:b.numId})),skipped:y.skipped.map(b=>({paragraphIndex:b.paragraphIndex,reason:b.reason}))}}}function bb(e,t,r,n){let{documentXml:o,serializer:a,operationSession:i,runtimeContext:l,options:s,author:c,generateRedlines:f,onInfo:u,paragraphIndexOf:d}=n,m=b=>({documentXml:o,hasChanges:!1,status:"error",error:b}),p=l?.numberingIdState?.sourceNumberingXml||l?.numberingXml||s.numberingXml||"",g=Array.isArray(i?.numberingXmlParts)?i.numberingXmlParts:[],h=g.length>0?vr(p,g):p,v={author:c||ae(),generateRedlines:f,runtimeContext:l,stylesXml:l?.stylesXml||s.stylesXml||null,numberingXml:h,paragraphIndexOf:d},w;if(r.mode==="join"){let b=s.continueFromDescriptor||null,x=b?At(e,b.text||"",b.index??null,"list-format",l,{...s,targetDescriptor:b,_compiledSourceId:s._compiledContinueFromId||null,_compiledResolvedBy:null,_resolutionCapture:null}):null;if(!x?.paragraph)return m({code:x?.error?.code||"TARGET_NOT_FOUND",message:`list.continueFrom: ${x?.error?.message||"paragraph not found."}`,field:"list.continueFrom"});w=im(e,t,x.paragraph,r,v)}else w=am(e,t,r,v);if(!w.ok)return m(w.error);if(w.unchanged){let b=`${Ed}: ${w.message}`;return n.onWarn?.(b),{documentXml:o,hasChanges:!1,status:"ok",warnings:[b]}}for(let b of w.items)b.paragraph,s?._mutationLiveNodes?.push(b.paragraph);for(let b of w.allocatedNumIds)i?.receiptCollector?.recordNumbering(b);at(e);let y=w.items.filter(b=>!b.inTarget).length;return u(`[List] list-format ${w.mode} (${w.scope}) rebound ${w.items.length} paragraph(s) from numId ${w.sourceNumId} to numId ${w.numId}${y?` (${y} outside the target range)`:""}.`),{documentXml:ot(e,a,o,i),hasChanges:!0,status:"ok",numberingXml:w.numberingXml,list:{mode:w.mode,scope:w.scope,sourceNumId:w.sourceNumId,numId:w.numId,...w.mode==="change-format"?{format:w.format,level:w.level,lvlText:w.lvlText,levelStarts:w.levelStarts}:{continueFrom:w.continueFrom},items:w.items.map(b=>({paragraphIndex:b.paragraphIndex,paragraphId:He(b.paragraph),level:b.level,numId:b.numId,sourceNumId:b.sourceNumId,inTarget:b.inTarget})),skipped:w.skipped.map(b=>({paragraphIndex:b.paragraphIndex,reason:b.reason}))}}}var xb=new Set(["body","tc","txbxContent","footnote","endnote","comment","hdr","ftr"]),Ib=new Set(["hyperlink","fldSimple","sdt","smartTag","customXml"]),Nb=new Set(["rPr","pPrChange","sectPr"]),Rt=e=>{let t=e?.localName;return t?t.indexOf(":")<0?t:t.replace(/^.*:/,""):String(e?.nodeName||"").replace(/^.*:/,"")},vo=e=>e?.nodeType===1&&(!e.namespaceURI||e.namespaceURI===B),Gr=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Bm(e,t){let r=[];if(!e)return r;let n=[];for(let o=e.lastChild;o;o=o.previousSibling)n.push(o);for(;n.length;){let o=n.pop();if(o.nodeType===1){o.namespaceURI===B&&o.localName===t&&r.push(o);for(let a=o.lastChild;a;a=a.previousSibling)n.push(a)}}return r}function Et(e,t){for(let r=e?.firstChild;r;r=r.nextSibling)if(vo(r)&&Rt(r)===t)return r;return null}function Tb(e){let t=Et(Et(e,"pPr"),"rPr");if(!t)return null;for(let r=t.firstChild;r;r=r.nextSibling){if(!vo(r))continue;let n=Rt(r);if(n==="ins"||n==="moveTo")return"ins";if(n==="del"||n==="moveFrom")return"del"}return null}function Sb(e){for(let t=e.parentNode;t;t=t.parentNode)if(xb.has(Rt(t)))return t;return null}function Ab(e,t){let r=t==="rejected"?"ins":"del";for(let n=e.parentNode;n;n=n.parentNode){let o=Rt(n);if(o==="tr"){if(Et(Et(n,"trPr"),r))return!0}else if(o==="tc"){let a=t==="rejected"?"cellIns":"cellDel";if(Et(Et(n,"tcPr"),a))return!0}else if(o==="body")break}return!1}function Fm(e){let t=Array.from(e.attributes||[]).filter(n=>!/^xmlns(:|$)/.test(n.name)&&!/(^|:)(rsid\w*|paraId|textId)$/.test(n.name)).map(n=>`${n.name.replace(/^.*:/,"")}=${n.value}`).sort(),r=Array.from(e.childNodes||[]).filter(vo).map(Fm).sort();return`${Rt(e)}[${t.join(",")}]{${r.join("")}}`}function Eb(e,t){let r=Et(e,"pPr"),n=r;if(t==="rejected"){let i=Et(r,"pPrChange");i&&(n=Et(i,"pPr"))}let o=null,a=[];for(let i of Array.from(n?.childNodes||[]))if(!(!vo(i)||Nb.has(Rt(i)))){if(Rt(i)==="numPr"){o={numId:Gr(Et(i,"numId"),"val")||null,ilvl:Gr(Et(i,"ilvl"),"val")||"0"};continue}a.push(Fm(i))}return{props:a.sort().join(""),numPr:o}}function Rb(e){let t=Rt(e);if(t==="hyperlink")return`hyperlink:${e.getAttribute?.("r:id")||Gr(e,"anchor")||""}`;if(t==="fldSimple")return`fldSimple:${Gr(e,"instr").trim()}`;if(t==="sdt"){let r=Et(e,"sdtPr");return`sdt:${Gr(Et(r,"id"),"val")}:${Gr(Et(r,"tag"),"val")}`}return`${t}:${Gr(e,"element")||Gr(e,"uri")}`}function Pb(e,t){let r="",n=[],o=(a,i)=>{for(let l=a.firstChild;l;l=l.nextSibling){if(!vo(l))continue;let s=Rt(l);if(s!=="pPr"&&!(t==="rejected"&&(s==="ins"||s==="moveTo"))&&!(t==="accepted"&&(s==="del"||s==="moveFrom"))){if(s==="r"){let c=r.length;if(r+=gr(l,{revisionView:t,boundary:e}),r.length>c)for(let f of i)n.push({key:f,start:c,end:r.length});continue}o(l,Ib.has(s)?[...i,Rb(l)]:i)}}};return o(e,[]),{text:r,spans:n}}function Cb(e){let t=new Map;for(let r of e){let n=t.get(r.key)||[],o=n[n.length-1];o&&o.end>=r.start?o.end=Math.max(o.end,r.end):n.push({...r}),t.set(r.key,n)}return[...t.values()].flat().sort((r,n)=>r.start-n.start||r.end-n.end||(r.key<n.key?-1:1)).map(r=>`${r.key}@${r.start}-${r.end}`)}function Jl(e,t="rejected"){if(t!=="rejected"&&t!=="accepted")throw new Error(`Unknown revision view '${t}'.`);let r=Bm(e,"p"),n=t==="rejected"?"ins":"del",o=[],a=new Map;r.forEach((i,l)=>{if(Ab(i,t))return;let s=Sb(i),c=a.get(s)||null;a.delete(s);let{text:f,spans:u}=Pb(i,t),d=c?c.text.length:0,m={text:(c?.text||"")+f,spans:[...c?.spans||[],...u.map(p=>({...p,start:p.start+d,end:p.end+d}))]};if(Tb(i)===n){a.set(s,{...m,paragraph:i,sourceIndex:l});return}o.push(Lm(i,m,t,s,l))});for(let[i,l]of a)!(t==="rejected"&&Rt(i)==="tc")&&l.text.length===0||o.push(Lm(l.paragraph,l,t,i,l.sourceIndex));return o.sort((i,l)=>i.sourceIndex-l.sourceIndex),_b(e,r,o),o}function _b(e,t,r){let n=Rt(e)==="body"?[e]:Bm(e,"body");for(let o of n){let a=Array.from(o.childNodes||[]).filter(l=>vo(l)&&Rt(l)!=="sectPr"),i=a[a.length-1];!i||Rt(i)!=="tbl"||r.push({text:"",props:"",numPr:null,wrappers:[],container:"body",sourceIndex:t.length,implicit:!0})}}function Lm(e,t,r,n,o){let{props:a,numPr:i}=Eb(e,r);return{text:t.text,props:a,numPr:i,wrappers:Cb(t.spans),container:n?Rt(n):"root",sourceIndex:o}}var $m=Object.freeze(["enforce","warn","off"]),Xm="enforce",Zl=5,Dm=120,Cn=Object.freeze({REJECT_PARAGRAPH_COUNT:{explanation:"Reject All of the output has a different number of paragraphs than the source: a paragraph was created or removed without a tracked paragraph mark.",retry:"Target one paragraph at a time; add new paragraphs with a separate insertion instead of folding them into a replacement; do not merge or split paragraphs in the same operation as a text edit."},REJECT_PARAGRAPH_TEXT:{explanation:"Reject All of the output shows different paragraph text than the source: text, a tab or a manual line break changed without being tracked, or was reordered.",retry:"Use replacements (find/replace) for a small literal change, keep manual line breaks and tabs where they are, and retry with the exact current paragraph text from a fresh extraction."},REJECT_PARAGRAPH_PROPS:{explanation:"Reject All of the output shows different paragraph properties (style, alignment, spacing, indentation) than the source: a property changed without a tracked w:pPrChange.",retry:"Change paragraph formatting with a separate paragraph-format operation and keep the text edit free of style or list changes."},REJECT_NUMBERING_REFS:{explanation:"Reject All of the output puts a source paragraph in a different list or list level (numId/ilvl) than the source, so the restored document would number differently.",retry:"Edit list item text without changing list markers or indentation, and make list membership or level changes in their own operation."},ACCEPT_NEIGHBORS:{explanation:"An untracked edit changed a paragraph outside its target, so the change could not be reviewed or undone.",retry:"Re-extract the target and retry against exactly that paragraph; if the edit must span several paragraphs, use a tracked operation with an explicit targetEnd range."},UNTRACKED_CREATED_REVISION:{explanation:"An untracked edit (generateRedlines: false) created a tracked revision (w:ins, w:del, a move, a property change or a paragraph-mark revision) that was not in the source, so the edit is not the plain change the caller asked for.",retry:"Retry the same edit against the current extraction; if it is refused again the untracked path wrote a tracked revision, so report the operation instead of working around it, or make the edit tracked (generateRedlines: true) if a reviewable change is acceptable."},ACCEPT_INTENT:{explanation:"Accept All of the target of the operation would not read as the complete replacement text the operation declared: content was lost, duplicated or left out of the accepted result.",retry:"Re-extract the target paragraph(s) and retry with the exact current text as the basis; for a small literal change use replacements instead of complete modified text, and keep list, table and Markdown structure out of a plain-text edit."},REJECT_WRAPPERS:{explanation:"Reject All of the output moves text into or out of a hyperlink, field or content control compared with the source.",retry:"Keep the change entirely inside or entirely outside the hyperlink, field or content control, for example with replacements that do not cross its boundary."}});function yo(e){if(e==null)return null;let t=typeof e=="string"?e:JSON.stringify(e);return t.length>Dm?`${t.slice(0,Dm-3)}...`:t}function bo(e){return e?{sourceParagraphIndex:e.sourceIndex+1,container:e.container,text:yo(e.text)}:null}function Ql(e){return{document:e,accepted:null,rejected:null,revisionSignatures:null,numberingRefs:null}}function _n(e,t,r){return e?e[r]||(e[r]=Jl(t,r)):Jl(t,r)}function Vm({before:e,after:t,baselineView:r="rejected",acceptedScope:n=null,beforeViews:o=null,afterViews:a=null}){let i=Array.isArray(t)?t:_n(a,t,"rejected"),l=Array.isArray(e)?e:_n(o,e,"rejected"),s=r==="accepted"&&!Array.isArray(e)?Fb(l,_n(o,e,"accepted"),i,n):l,c=[],f=(u,d,m,p,g,h)=>{c.push({invariant:u,paragraph:d,expected:yo(m),actual:yo(p),explanation:Cn[u].explanation,source:bo(g),output:bo(h)})};if(s.length!==i.length){let u=0;for(;u<s.length&&u<i.length&&ga(s[u],i[u]);)u++;return f("REJECT_PARAGRAPH_COUNT",u+1,`${s.length} paragraphs`,`${i.length} paragraphs`,s[u]||s[s.length-1],i[u]||i[i.length-1]),{ok:!1,violations:c,afterProjection:i}}for(let u=0;u<s.length&&c.length<Zl;u++){let d=s[u],m=i[u],p=u+1;d.container!==m.container?f("REJECT_PARAGRAPH_COUNT",p,`paragraph in ${d.container}`,`paragraph in ${m.container}`,d,m):d.text!==m.text?f("REJECT_PARAGRAPH_TEXT",p,d.text,m.text,d,m):(d.numPr?.numId??null)!==(m.numPr?.numId??null)||(d.numPr?.ilvl??null)!==(m.numPr?.ilvl??null)?f("REJECT_NUMBERING_REFS",p,d.numPr,m.numPr,d,m):d.props!==m.props?f("REJECT_PARAGRAPH_PROPS",p,d.props,m.props,d,m):d.wrappers.join("|")!==m.wrappers.join("|")&&f("REJECT_WRAPPERS",p,d.wrappers,m.wrappers,d,m)}return c.length?{ok:!1,violations:c,afterProjection:i}:{ok:!0,afterProjection:i}}var ga=(e,t)=>e.text===t.text&&e.props===t.props&&e.container===t.container&&(e.numPr?.numId??null)===(t.numPr?.numId??null)&&(e.numPr?.ilvl??null)===(t.numPr?.ilvl??null)&&e.wrappers.join("|")===t.wrappers.join("|");function jm({before:e,after:t,targetSourceIndex:r,beforeViews:n=null,afterViews:o=null}){let a=[];for(let i of["accepted","rejected"]){let l=_n(n,e,i),s=_n(o,t,i),c=l.findIndex(m=>m.sourceIndex>=r);if(c<0)continue;let f=l.length-c-1,u=0;for(;u<c&&u<s.length&&ga(l[u],s[u]);)u++;let d=0;for(;d<f&&d<s.length-u&&ga(l[l.length-1-d],s[s.length-1-d]);)d++;if(u<c)a.push(zm(u+1,l[u],s[u],i));else if(d<f){let m=l.length-1-d;a.push(zm(m+1,l[m],s[s.length-1-d],i))}if(a.length)break}return a.length?{ok:!1,violations:a}:{ok:!0}}var pa=new Map,Ob=8;function kb(e){let t=pa.get(e);if(t)return t;let r=new Map;for(let a of e.matchAll(/<(?:\w+:)?abstractNum\b([^>]*)>([\s\S]*?)<\/(?:\w+:)?abstractNum>/g)){let i=/abstractNumId="([^"]*)"/.exec(a[1])?.[1];if(i==null)continue;let l=r.get(i)||new Set;for(let s of a[2].matchAll(/<(?:\w+:)?lvl\b[^>]*?ilvl="([^"]*)"/g))l.add(s[1]);r.set(i,l)}let n=new Map;for(let a of e.matchAll(/<(?:\w+:)?num\b([^>]*)>([\s\S]*?)<\/(?:\w+:)?num>/g)){let i=/numId="([^"]*)"/.exec(a[1])?.[1],l=/abstractNumId[^>]*?val="([^"]*)"/.exec(a[2])?.[1];i!=null&&l!=null&&n.set(i,l)}let o={abstractLevels:r,numToAbstract:n};return pa.size>=Ob&&pa.delete(pa.keys().next().value),pa.set(e,o),o}function Wm({before:e,after:t,numberingXmls:r}){let n=c=>{let f=new Map;for(let u of Bn(c)){let d=u.getAttribute("w:val");if(d===null||d===""||d==="0")continue;let p=Array.from(u.parentNode?.childNodes||[]).find(g=>g.nodeType===1&&Mi(g)==="ilvl")?.getAttribute("w:val")||"0";f.has(d)||f.set(d,new Set),f.get(d).add(p)}return f},o=n(t);if(o.size===0)return{ok:!0};let a=n(e),{abstractLevels:i,numToAbstract:l}=kb((r||[]).filter(Boolean).join(`
231
+ `)),s=[];for(let[c,f]of o){if(a.has(c))continue;let u=l.get(c),d=u!=null?i.get(u):null,m=null;if(u==null)m=`numId ${c} has no w:num in the output numbering`;else if(!d)m=`numId ${c} points at missing w:abstractNum ${u}`;else{let p=[...f].find(g=>!d.has(g));p!==void 0&&(m=`numId ${c} level ${p} is not defined by w:abstractNum ${u}`)}if(m!==null&&(s.push({invariant:"REJECT_NUMBERING_REFS",paragraph:null,expected:`numId ${c} defined in the output numbering`,actual:m,explanation:"The output (or what Reject All restores) references a list numId that no numbering definition in the output provides, so Word would drop or renumber the list.",source:null,output:null}),s.length>=Zl))break}return s.length?{ok:!1,violations:s}:{ok:!0}}var Mb=/\+\+|==|[*_#>`|~\[\]\\]/,Lb=/^\s*(?:[-+•●]|[A-Za-z0-9]{1,5}[.)]|\d[0-9.]*[.)]?|\(\w{1,4}\))\s/m;function Km(e){return typeof e=="string"&&e.length>0&&!Mb.test(e)&&!Lb.test(e)}function Gm({before:e,after:t,range:r,modified:n,beforeViews:o=null,afterViews:a=null}){let i=_n(o,e,"accepted"),l=_n(a,t,"accepted"),s=i.filter(p=>p.sourceIndex<r.from).length,c=i.filter(p=>p.sourceIndex>r.to).length,f=i.filter(p=>p.sourceIndex>=r.from&&p.sourceIndex<=r.to);if(f.length!==r.to-r.from+1||f.some(p=>p.container!=="body"))return{ok:!0,skipped:"target not positionally comparable"};let u=l.slice(s,Math.max(s,l.length-c)),d=u.map(p=>p.text).join(`
232
+ `),m=p=>p.replace(/\r?\n/g,"");return d===n||m(d)===m(n)?{ok:!0}:{ok:!1,violations:[{invariant:"ACCEPT_INTENT",paragraph:null,expected:n,actual:d,explanation:Cn.ACCEPT_INTENT.explanation,source:f[0]?bo(f[0]):null,output:u[0]?bo(u[0]):null}]}}var Bb=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tblPrExChange","trPrChange","tcPrChange","numberingChange","cellIns","cellDel","cellMerge"]),Mi=e=>e.localName||String(e.nodeName).replace(/^.*:/,"");function Um(e){let t=new Map,r=[e];for(;r.length;){let n=r.pop();if(n.nodeType===1&&Bb.has(Mi(n))){let o=n.getAttribute("w:id");o!==null&&!t.has(o)&&t.set(o,n)}for(let o=n.firstChild;o;o=o.nextSibling)r.push(o)}return t}function Hm({before:e,after:t,beforeViews:r=null,afterViews:n=null}){let o=f=>`${Mi(f)}|${f.getAttribute("w:author")}|${f.getAttribute("w:date")}`,a=f=>new Map([...f].map(([u,d])=>[u,o(d)])),i=r?.revisionSignatures;i||(i=a(Um(e)),r&&(r.revisionSignatures=i));let l=Um(t);n&&(n.revisionSignatures=a(l));let s=new Set(i.values()),c=[];for(let[f,u]of l){if(i.has(f)||s.has(o(u)))continue;let d=Mi(u),m=u.getAttribute("w:author"),p=yo(u.textContent||"");if(c.push({invariant:"UNTRACKED_CREATED_REVISION",paragraph:null,expected:"no new revisions",actual:`w:${d} w:id=${f}${m?` by ${m}`:""}${p?` ("${p}")`:""}`,explanation:Cn.UNTRACKED_CREATED_REVISION.explanation,source:null,output:null}),c.length>=Zl)break}return c.length?{ok:!1,violations:c}:{ok:!0}}function zm(e,t,r,n){return{invariant:"ACCEPT_NEIGHBORS",paragraph:e,view:n,expected:yo(t?.text??null),actual:yo(r?.text??null),explanation:Cn.ACCEPT_NEIGHBORS.explanation,source:bo(t),output:bo(r)}}function Fb(e,t,r,n){if(n&&Number.isInteger(n.from)&&Number.isInteger(n.to)){let c=f=>f.sourceIndex>=n.from&&f.sourceIndex<=n.to;return[...e.filter(f=>!c(f)),...t.filter(c)].sort((f,u)=>f.sourceIndex-u.sourceIndex)}let o=0;for(;o<e.length&&o<r.length&&ga(e[o],r[o]);)o++;let a=0;for(;a<e.length-o&&a<r.length-o&&ga(e[e.length-1-a],r[r.length-1-a]);)a++;if(o+a===e.length&&o+a===r.length)return e;let i=o>0?e[o-1].sourceIndex:-1,l=a>0?e[e.length-a].sourceIndex:1/0,s=t.filter(c=>c.sourceIndex>i&&c.sourceIndex<l);return[...e.slice(0,o),...s,...e.slice(e.length-a)]}function ec(e,t={}){let r=e[0],n=r.source?`source paragraph ${r.source.sourceParagraphIndex}${r.source.text?` ("${r.source.text}")`:""}`:`paragraph ${r.paragraph} of the Reject All view`,o=[...new Set(e.map(i=>i.invariant))],a=t.mode||Xm;return{code:"REVISION_FIDELITY_VIOLATION",stage:"verification",message:`${a==="warn"?"Applied with a fidelity warning":"Refused, document unchanged"}: `+(r.invariant==="UNTRACKED_CREATED_REVISION"?`this untracked operation created a tracked revision (${r.invariant}: `:r.invariant==="ACCEPT_NEIGHBORS"?`this untracked operation changed a paragraph outside its target (${r.invariant} in the ${r.view} view at ${n}: `:r.invariant==="ACCEPT_INTENT"?`Accept All of this operation's target would not read as the requested text (${r.invariant} at ${n}: `:`Reject All of this operation's output would not restore the source (${r.invariant} at ${n}: `)+(r.invariant==="UNTRACKED_CREATED_REVISION"?`found ${r.actual}). `:`expected ${JSON.stringify(r.expected)}, got ${JSON.stringify(r.actual)}). `)+`${r.explanation} Retry: ${Cn[r.invariant].retry}`,violations:e,invariants:o,verificationMode:a,...t.baselineView==="accepted"?{baselineView:"accepted"}:{},recovery:{hint:Cn[r.invariant].retry,retryGuidance:o.map(i=>({invariant:i,retry:Cn[i].retry})),reportIfNarrowRetryFails:"If a narrower operation on the same paragraph is also refused, the shape is unsupported: report the violations with the operation; do not disable verification to force it through."}}}function tc(e){return String(e||"").startsWith("accept-all-first")?"accepted":"rejected"}function rc(e){if($m.includes(e))return e;let t=globalThis.process?.env?.DOCX_REDLINE_REVISION_FIDELITY;return $m.includes(t)?t:Xm}function Ne(e,t={}){return yt(e,t)}async function nc(e,t,r,n=null,o={}){let a=typeof o._operationIndex=="number"?o._operationIndex:1,i={operationIndex:a,...typeof t?.operationId=="string"?{operationId:t.operationId}:{}},l=Nr(t);if(!l.valid){let I=Ut(t,r,ae());return{documentXml:e,hasChanges:!1,status:"error",error:Ne(l.error,i),operationType:St(t).operationKind,authorUsed:I,receipt:ke(a,t?.operationId,I,"refused")}}let s=l.operation||St(t),c=Ut(s,r,ae());if(s.operationKind!=="comment_reply"&&s.operationKind!=="comment_resolve"&&s.operationKind!=="rejected-insert"&&s.operationKind!=="restore"&&(s.targetDescriptor?.revisionView==="rejected"||s.targetEndDescriptor?.revisionView==="rejected"))return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"UNSUPPORTED_REVISION_VIEW_MUTATION",message:"Targeting rejected revision view for mutation is not supported yet."},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};if(!o?._documentOperationSession&&o?.expectedRevision){let I=vn(o.expectedRevision);if(!I.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:I.error?.code||"INVALID_REVISION_TOKEN",message:I.error?.message||"Invalid revision token."},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};if(o.expectedRevision.scope!=="document-parts")return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};let R=await Qo({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!yn(R.value,o.expectedRevision.value))return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${R.value}'.`,expectedRevision:o.expectedRevision,currentRevision:R},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")}}let f=o?._documentOperationSession instanceof Wr?o._documentOperationSession:new Wr(e,o);if(!f.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(f.parseResult.error,i),warnings:f.parseResult.warnings,operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};if(Array.isArray(s.replacements)||s.operationKind==="restore"&&t?.modified===void 0){let I=po(f.document,[t],{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn}),R=I.bindings[0]?.error||I.conflicts[0]||null;if(R)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(R,i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};let T=Nr(I.compiledOperations[0]);if(!T.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(T.error,i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};f.sourceTargetRegistry=I.registry,s=T.operation}if(Array.isArray(s.replacements)&&!s._localizedReplacementCompilation)return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"PATCH_ROUNDTRIP_MISMATCH",stage:"validation",message:"Localized replacements were not compiled against a batch-start paragraph target, so they were refused instead of applied."},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};let u={},d=null,m=f.createSavepoint(),p=f._fidelityViews?.document===f.document?f._fidelityViews:null;f._fidelityViews=null;let g={...p||Ql(null),document:m.document},h=Ql(f.document);f.receiptCollector?.beginOperation(a,s.operationId,c);let v=Array.isArray(s._compiledWarnings)?[...s._compiledWarnings]:[],w={...o,...typeof s.generateRedlines=="boolean"?{generateRedlines:s.generateRedlines}:{},...s.existingRevisions?{existingRevisions:s.existingRevisions}:{},structuredContent:typeof s.structuredContent=="boolean"?s.structuredContent:o.structuredContent!==!1,explicitStructuredContent:s.structuredContent===!0,plainTextContent:s.structuredContent===!1||s.structuredContent==null&&o.structuredContent===!1,...s._localizedReplacementCompilation&&s.structuredContent!==!0?{literalTextEdit:!0}:{},pairReplacements:typeof s.pairReplacements=="boolean"?s.pairReplacements:o.pairReplacements!==!1,...s.insertionAffinity?{insertionAffinity:s.insertionAffinity}:{},...s.listMarkers?{listMarkers:s.listMarkers}:{},...s.formattingRevisionPolicy?{formattingRevisionPolicy:s.formattingRevisionPolicy}:{},...s.operationKind==="format"&&Number.isInteger(s.textOccurrence)?{textOccurrence:s.textOccurrence}:{},targetDescriptor:s.targetDescriptor,targetEndDescriptor:s.targetEndDescriptor,_compiledSourceId:s._compiledSourceId||null,_compiledSourceEndId:s._compiledSourceEndId||null,...s.operationKind==="list-format"&&s.list?.continueFrom&&typeof s.list.continueFrom=="object"?{continueFromDescriptor:Tn(s.list.continueFrom,null,"accepted"),_compiledContinueFromId:s._compiledContinueFromId||null}:{},_compiledResolvedBy:s._compiledResolvedBy||null,_sourceTargetRegistry:f.sourceTargetRegistry||null,_resolutionCapture:u,_revisionIdAllocator:f.revisionIdAllocator,_documentOperationSession:f,_mutationLiveNodes:[],_mutationRemovedNodes:[],onInfo:I=>{typeof o?.onInfo=="function"&&o.onInfo(I)},onWarn:I=>{v.push(String(I)),typeof o?.onWarn=="function"&&o.onWarn(I)}},y=!!(s.targetEndDescriptor||s.targetEndRef),b=rc(o.verifyRevisionFidelity),x=tc(w.existingRevisions)==="accepted",S=s.operationKind==="redline"&&w.generateRedlines!==!1&&!s._localizedReplacementCompilation&&s.structuredContent!==!0&&Km(s.modified)&&!/\r?\n/.test(String(s.targetDescriptor?.exactText??s.targetDescriptor?.text??(typeof s.target=="string"?s.target:""))),A=b!=="off"&&f.document&&(y&&x||S)?Nm(f.document,s.target,s.targetRef,s.targetEndRef,n,w):null,E=A?A.to:null;try{let I;if(s.operationKind==="comment_reply"){let N=f.commentsXml||n?.commentsXml||o.commentsXml,O=f.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,C=typeof o.commentIdAllocator=="function"?o.commentIdAllocator():null;if(C==null&&N){let P=[...N.matchAll(/<(?:w:)?comment\b[^>]*\b(?:w:)?id=["'](\d+)["']/g)].map(M=>Number(M[1]));C=(P.length?Math.max(...P):-1)+1}C==null?I={documentXml:e,hasChanges:!1,status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing comments part."}}:(I=il({commentsXml:N,commentsExtendedXml:O,documentXml:e,parentCommentId:s.parentCommentId,commentId:C,commentContent:s.commentContent,author:c,date:s.date||new Date().toISOString()}),I.documentXml=e,I.status!=="error"&&I.hasChanges&&(!f.document||!Ff(f.document,I.threadCommentIds,C)?I={documentXml:e,hasChanges:!1,status:"error",error:{code:"PARENT_ANCHOR_NOT_FOUND",message:`Comment '${s.parentCommentId}' has no anchor in the document body, so a reply cannot be placed.`}}:f.receiptCollector&&f.receiptCollector.recordComment(C)))}else if(s.operationKind==="comment_resolve"){let N=ci({commentsXml:f.commentsXml||n?.commentsXml||o.commentsXml,commentsExtendedXml:f.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,commentId:s.commentId,resolved:s.resolved!==!1});I=N.status==="error"?{documentXml:e,hasChanges:!1,status:"error",error:N.error}:{documentXml:e,hasChanges:N.hasChanges,...N.commentsXml?{commentsXml:N.commentsXml,commentsXmlMode:"replace"}:{},...N.commentsExtendedXml?{commentsExtendedXml:N.commentsExtendedXml,commentsExtendedXmlMode:"replace"}:{},resolved:N.resolved,threadRootId:N.threadRootId,commentIds:N.commentIds}}else s.operationKind==="highlight"?I=await Pm(e,s.target,s.textToHighlight,s.color,c,s.targetRef,n,w):s.operationKind==="comment"?I=await Cm(e,s.target,s.textToComment,s.commentContent,c,s.targetRef,n,w):s.operationKind==="format"?I=await _m(e,s.target,s.textToFormat,s.properties,c,s.targetRef,n,w):s.operationKind==="paragraph-format"?I=await Om(e,s.target,s.properties,c,s.targetRef,n,w):s.operationKind==="list-format"?I=await Mm(e,s.target,s.list,c,s.targetRef,s.targetEndRef,n,w):s.operationKind==="rejected-insert"?I=await Am(e,s.target,s.anchor,s.modified,c,s.targetRef,n,w):s.operationKind==="restore"?I=await Em(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,w):I=await Rm(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,w);if((s.operationKind==="comment"||s.operationKind==="comment_reply")&&I?.hasChanges!==!0&&I?.status!=="error"&&!I?.error&&(I={...I,status:"error",error:{code:"COMMENT_NOT_APPLIED",message:"The comment operation completed without placing a comment."}}),v.length>0&&I){let N=Array.from(new Set([...Array.isArray(I.warnings)?I.warnings:[],...v]));I.warnings=N}let R=I?.status==="error"||!!I?.error,T=null;if(R||I?.hasChanges!==!0){f.restoreSavepoint(m);let N=R?"refused":"no_change";if(T=ke(a,s.operationId,c,N),Array.isArray(I?.warnings))for(let O of I.warnings)T.warnings.push(String(O))}else{let N=Mt(m.document),O=Mt(f.document),C=An(O.issues,N.issues),P=En(C);if(P.length>0){f.restoreSavepoint(m),T=ke(a,s.operationId,c,"refused");let L=[...new Set(P.map(D=>D.code))].join(", ");return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"GENERATED_OOXML_INVALID",stage:"validation",message:`Operation introduced invalid OOXML (${L}).`,generatedIssues:P},i),operationType:s.operationKind,authorUsed:c,receipt:T,...u}}if(s._localizedReplacementCompilation&&s.structuredContent!==!0){let L=null;if(s.operationKind==="restore"){let D=w._mutationLiveNodes.find(z=>z?.localName==="p");D&&(L=Y(D,{revisionView:"accepted"}))}else if(s._compiledSourceId&&f.sourceTargetRegistry){let D=f.sourceTargetRegistry.previewSuccessor(s._compiledSourceId,w._mutationRemovedNodes,w._mutationLiveNodes);D&&(L=Y(D,{revisionView:"accepted"}))}if(L!==s._localizedReplacementCompilation.desiredText){f.restoreSavepoint(m);let D="The localized replacement did not produce the compiled accepted text, so it was refused before commit to avoid losing content. Re-extract the paragraph and retry with its current text.",z=ke(a,s.operationId,c,"refused");return z.warnings.push(D),{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"PATCH_ROUNDTRIP_MISMATCH",stage:"validation",message:D},i),warnings:[D],operationType:s.operationKind,authorUsed:c,receipt:z,...u}}}let M=rc(o.verifyRevisionFidelity),_=!s.targetEndDescriptor&&!s.targetEndRef?u.resolvedTarget?.index:null,k=M==="off"?null:w.generateRedlines!==!1?"tracked":Number.isInteger(_)?"untracked":null;if(k==="tracked"){let L=tc(w.existingRevisions),D=u.resolvedTarget?.index,z=Number.isInteger(D)?y?Number.isInteger(E)&&E>=D-1?{from:D-1,to:E}:null:{from:D-1,to:D-1}:null,G=Vm({before:m.document,after:f.document,baselineView:L,acceptedScope:z,beforeViews:g,afterViews:h}),ee=Wm({before:m.document,after:f.document,numberingXmls:[n?.numberingXml||o.numberingXml,...f.numberingXmlParts||[],I.numberingXml],beforeViews:g,afterViews:h});if(ee.ok||(G.ok=!1,G.violations=[...G.violations||[],...ee.violations]),S&&A){let J=Gm({before:m.document,after:f.document,range:A,modified:s.modified,beforeViews:g,afterViews:h});J.ok||(G.ok=!1,G.violations=[...G.violations||[],...J.violations])}if(!G.ok){let J=ec(G.violations,{mode:M,baselineView:L}),Z=`${J.code} (operation ${a}${s.operationId?` "${s.operationId}"`:""}): ${J.message}`;if(typeof o?.onWarn=="function"&&o.onWarn(Z),M==="enforce"){f.restoreSavepoint(m),f._fidelityViews=g;let ie=ke(a,s.operationId,c,"refused");return ie.warnings.push(Z),{documentXml:e,hasChanges:!1,status:"error",error:Ne(J,i),warnings:[Z],operationType:s.operationKind,authorUsed:c,receipt:ie,...u}}I.warnings=[...Array.isArray(I.warnings)?I.warnings:[],Z],I.revisionFidelityViolations=G.violations}}else{let L=k==="untracked"?jm({before:m.document,after:f.document,targetSourceIndex:_-1,beforeViews:g,afterViews:h}):{ok:!0};if(L.ok&&M!=="off"&&w.generateRedlines===!1&&(L=Hm({before:m.document,after:f.document,beforeViews:g,afterViews:h})),!L.ok){let D=ec(L.violations,{mode:M}),z=`${D.code} (operation ${a}${s.operationId?` "${s.operationId}"`:""}): ${D.message}`;if(typeof o?.onWarn=="function"&&o.onWarn(z),M==="enforce"){f.restoreSavepoint(m),f._fidelityViews=g;let G=ke(a,s.operationId,c,"refused");return G.warnings.push(z),{documentXml:e,hasChanges:!1,status:"error",error:Ne(D,i),warnings:[z],operationType:s.operationKind,authorUsed:c,receipt:G,...u}}I.warnings=[...Array.isArray(I.warnings)?I.warnings:[],z],I.revisionFidelityViolations=L.violations}}if((k==="tracked"||k==="untracked")&&(f._fidelityViews=h),f.markMutationCommitted(!0),s._compiledSourceId&&f.sourceTargetRegistry&&f.sourceTargetRegistry.commitMutation(s._compiledSourceId,w._mutationRemovedNodes,w._mutationLiveNodes,a),s._localizedReplacementCompilation){let L=null;if(s.operationKind==="restore"){let D=w._mutationLiveNodes.find(z=>z?.localName==="p");D&&(L=Y(D,{revisionView:"accepted"}))}else if(s._compiledSourceId&&f.sourceTargetRegistry){let D=f.sourceTargetRegistry.resolve(s._compiledSourceId,f.document);D.paragraph&&(L=Y(D.paragraph,{revisionView:"accepted"}))}d=wd(s._localizedReplacementCompilation,L,u.resolvedTarget||{},s._speculativeContext||null)}if(s.captureKey&&f.captureTable&&f.captureTable.set(s.captureKey,dm(f,s,w._mutationLiveNodes)),w._mutationRemovedNodes?.length>0&&f.captureTable&&mm(f.captureTable,w._mutationRemovedNodes),u.resolvedTarget&&f.receiptCollector?.recordAffectedTarget(u.resolvedTarget),Array.isArray(I.warnings))for(let L of I.warnings)f.receiptCollector?.recordWarning(L);if(T=f.receiptCollector?.commitOperation("applied"),I.documentXml=f.deferSerialization?f.currentDocumentXml:f.serializeCurrent(),!f.deferSerialization&&T){let L=la({documentXml:I.documentXml,commentsXml:I.commentsXml||null,numberingXml:I.numberingXml||null},[T]);if(!L.valid)return f.restoreSavepoint(m),T.finalDisposition="rolled_back",T.committed=!1,{documentXml:e,hasChanges:!1,status:"error",error:Ne(L.error,i),warnings:[L.error.message],operationType:s.operationKind,authorUsed:c,receipt:T,...u}}}return I?.error&&(I.error=Ne(I.error,i)),{...I,operationType:s.operationKind,authorUsed:c,receipt:T,...d?{change:d}:{},...u}}catch(I){f.restoreSavepoint(m);let R=Ne(I,i),T=ke(a,s.operationId,c,"refused");return T.warnings.push(R.message),{documentXml:e,hasChanges:!1,status:"error",error:R,warnings:[R.message],operationType:s.operationKind,authorUsed:c,receipt:T,...u}}}var qm="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Ym(e){return e?.type==="comment"||e?.type==="comment_reply"||e?.type==="comment_resolve"?0:1}function Li(e=[]){let t=Array.isArray(e)?e:[],r=new Map;for(let c=0;c<t.length;c++){let f=t[c],u=f?.captureKey??f?.targetDescriptor?.captureKey;if(u!=null){if(typeof u!="string"||!u.trim()||u.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} declared an invalid captureKey: must be a non-empty string under 256 characters.`}};let d=u.trim();if(r.has(d)){let m=r.get(d);return{valid:!1,error:{code:"DUPLICATE_CAPTURE_KEY",message:`Duplicate capture key "${d}" declared by operations at indices ${m+1} and ${c+1}.`}}}r.set(d,c)}}let n=new Array(t.length).fill(0),o=Array.from({length:t.length},()=>new Set),a=Array.from({length:t.length},()=>new Set),i=new Map;for(let c=0;c<t.length;c++){let f=t[c],u=f?.target?.captureRef??f?.targetDescriptor?.captureRef;if(u!=null){if(typeof u!="string"||!u.trim()||u.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} referenced an invalid captureRef: must be a non-empty string under 256 characters.`}};let d=u.trim();if(!r.has(d))return{valid:!1,error:{code:"CAPTURE_NOT_FOUND",message:`Capture "${d}" referenced by operation ${c+1} was not found in the batch.`}};let m=r.get(d);if(m===c)return{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:`Capture dependency cycle detected: operation ${c+1} references its own capture "${d}".`}};a[c].has(m)||(a[c].add(m),o[m].add(c),n[c]++);let p=St(f).operationKind;p!=="comment"&&p!=="comment_reply"&&p!=="comment_resolve"&&(i.has(d)||i.set(d,[]),i.get(d).push({index:c,select:f?.target?.select??f?.targetDescriptor?.select??null}))}}for(let c=0;c<t.length;c++){let f=Array.isArray(t[c]?._compiledRunAfter)?t[c]._compiledRunAfter:[];for(let u of f)!Number.isInteger(u)||u<0||u>=t.length||u===c||a[c].has(u)||(a[c].add(u),o[u].add(c),n[c]++)}for(let[c,f]of i){if(f.length<2)continue;let u=f.map(m=>m.select),d=new Set(u);if(!(u.every(m=>typeof m=="string"&&m.length>0)&&d.size===u.length))return{valid:!1,error:{code:"CAPTURE_FANOUT_CONFLICT",message:`Capture "${c}" has overlapping or unscoped mutating consumers at operation indices ${f.map(m=>m.index+1).join(", ")}.`,operationIndexes:f.map(m=>m.index+1),captureRef:c}}}let l=[];for(let c=0;c<t.length;c++)n[c]===0&&l.push({operation:t[c],index:c});let s=[];for(;l.length>0;){l.sort((f,u)=>Ym(f.operation)-Ym(u.operation)||f.index-u.index);let c=l.shift();s.push(c);for(let f of o[c.index])n[f]--,n[f]===0&&l.push({operation:t[f],index:f})}return s.length<t.length?{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:"Capture dependency cycle detected among batch operations."}}:{valid:!0,scheduled:s,captureProducers:r}}function $b(e,t){if(!t)return e;if(!e)return t;let r=j(e,"application/xml")?.doc,n=j(t,"application/xml")?.doc;if(!r||!n)return e;let o=le(),a=r.documentElement,i=new Set(Array.from(r.getElementsByTagNameNS(qm,"comment")).map(l=>l.getAttribute("w:id")||l.getAttribute("id")).filter(Boolean));for(let l of Array.from(n.getElementsByTagNameNS(qm,"comment"))){let s=l.getAttribute("w:id")||l.getAttribute("id");s&&i.has(s)||(a.appendChild(r.importNode(l,!0)),s&&i.add(s))}return o.serializeToString(r)}async function Bi(e,t,r,n=null,o={}){let a=Array.isArray(t)?t:[],i=ae(),l=()=>a.map((N,O)=>ke(O+1,N?.operationId,Ut(N,r,i),"not_attempted")),s=(N,O={})=>{let C=l();return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:[],receipts:C,executionOrder:[],authorsUsed:[],...o.atomic===!0?{rolledBack:!0}:{},status:"error",error:Ne(N),retryPlan:Ir({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:[],receipts:C,operationCount:a.length}),...O}};if(o.existingRevisions!=null&&!fa(o.existingRevisions))return s({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(o.existingRevisions)}".`,field:"existingRevisions"});if(o?.expectedRevision){let N=vn(o.expectedRevision);if(!N.valid)return s({code:N.error?.code||"INVALID_REVISION_TOKEN",message:N.error?.message||"Invalid revision token."});if(o.expectedRevision.scope!=="document-parts")return s({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`,expectedScope:"document-parts",actualScope:o.expectedRevision.scope});let O=await Qo({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!yn(O.value,o.expectedRevision.value))return s({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${O.value}'.`,expectedRevision:o.expectedRevision,currentRevision:O})}let c=o?._documentOperationSession instanceof Wr?o._documentOperationSession:new Wr(e,{...o,_deferDocumentSerialization:!0});if(!c.valid)return s(c.parseResult.error,{warnings:c.parseResult.warnings});let f=po(c.document,a,{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn});if(c.sourceTargetRegistry=f.registry,f.conflicts.length>0){let N=new Map;for(let P of f.conflicts)for(let M of P.operationIndexes)N.has(M)||N.set(M,P);let O=Array.from(N,([P,M])=>{let _=a[P-1],k=Ut(_,r,i),L=Ne(M,{operationIndex:P,..._?.operationId?{operationId:_.operationId}:{}});return{index:P,type:_?.type||"redline",operationType:St(_).operationKind,status:"error",authorUsed:k,error:L,receipt:ke(P,_?.operationId,k,"refused")}}).sort((P,M)=>P.index-M.index),C=a.map((P,M)=>O.find(k=>k.index===M+1)?.receipt||ke(M+1,P?.operationId,Ut(P,r,i),"not_attempted"));return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:O,receipts:C,executionOrder:[],authorsUsed:[],rolledBack:o.atomic===!0,status:"error",error:Ne(f.conflicts[0]),conflicts:f.conflicts.map(P=>Ne(P)),retryPlan:Ir({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:O,receipts:C,operationCount:a.length})}}let u=f.compiledOperations,d=Li(u);if(!d.valid)return s(d.error);let m=d.scheduled,p=o.atomic===!0,g=o.continueOnError!==!1;if(n&&typeof n=="object"&&!n.numberingIdState){let N=typeof n.numberingXml=="string"&&n.numberingXml.trim()?n.numberingXml:void 0;n.numberingIdState=Ht(N)}let h=Kd(n);h.numberingIdState||(h.numberingIdState=Ht(void 0)),h.targetRefSnapshot instanceof Map||(h.targetRefSnapshot=c.initialTargetReferenceSnapshot),c.runtimeContext=h,a.some(N=>N?.type==="comment_reply"||N?.type==="comment_resolve")&&(c.commentsXml=h.commentsXml||o.commentsXml||null,c.commentsExtendedXml=h.commentsExtendedXml||o.commentsExtendedXml||null,c.commentsXmlMode="replace",c.commentsExtendedXmlMode="replace");let v=!1,w=c.results,y=c.executionOrder,b=c.authorsUsed,x=!1;for(let{operation:N,index:O}of m){y.push(O+1);let C=f.bindings[O];if(C?.error){x=!0;let P=Ut(N,r,i),M=ke(O+1,N?.operationId,P,"refused"),_=Ne(C.error,{operationIndex:O+1,...N?.operationId?{operationId:N.operationId}:{}});if(M.warnings.push(_.message),w.push({index:O+1,type:N?.type||"redline",status:"error",operationType:St(N).operationKind,authorUsed:P,warnings:[_.message],error:_,receipt:M}),!g)break;continue}try{let P=await nc(c.currentDocumentXml,N,r,h,{...o,_documentOperationSession:c,_deferDocumentSerialization:!0,_operationIndex:O+1});v=v||P.hasChanges===!0,c.commentsXml=P.commentsXmlMode==="replace"?P.commentsXml||c.commentsXml:$b(c.commentsXml,P.commentsXml||null),c.commentsExtendedXml=(P.commentsExtendedXmlMode==="replace",P.commentsExtendedXml||c.commentsExtendedXml),P.commentsXmlMode==="replace"&&(c.commentsXmlMode="replace"),P.commentsExtendedXmlMode==="replace"&&(c.commentsExtendedXmlMode="replace"),P.numberingXml&&c.numberingXmlParts.push(P.numberingXml);let M=P.status==="error"||!!P.error;if(x=x||M,!M&&P.hasChanges&&P.authorUsed&&b.add(P.authorUsed),w.push({index:O+1,type:N?.type||"redline",status:M?"error":P.hasChanges?"applied":"no_change",operationType:P.operationType||"redline",authorUsed:P.authorUsed,...P.resolvedBy?{resolvedBy:P.resolvedBy}:{},...P.resolvedTarget?{resolvedTarget:P.resolvedTarget}:{},...P.resolvedAnchor?{resolvedAnchor:P.resolvedAnchor}:{},...P.change?{change:P.change}:{},...P.list&&!M?{list:P.list}:{},...P.operationType==="comment_resolve"&&!M?{resolved:P.resolved,threadRootId:P.threadRootId,commentIds:P.commentIds}:{},...Array.isArray(P.warnings)&&P.warnings.length>0?{warnings:P.warnings}:{},...Array.isArray(P.diagnostics)&&P.diagnostics.length>0?{diagnostics:P.diagnostics}:{},...P.error?{error:P.error}:{},...P.receipt?{receipt:P.receipt}:{}}),M&&!g)break}catch(P){let M=Ne(P,{operationIndex:O+1,...N?.operationId?{operationId:N.operationId}:{}});x=!0;let _=Ut(N,r,ae()),k=ke(O+1,N?.operationId,_,"refused");if(k.warnings.push(M.message),w.push({index:O+1,type:N?.type||"redline",status:"error",operationType:St(N).operationKind,authorUsed:_,warnings:[M.message],error:M,receipt:k}),!g)break}}w.sort((N,O)=>N.index-O.index);let S=[];for(let N=0;N<a.length;N++){let O=N+1,C=w.find(P=>P.index===O);if(C?.receipt)S.push(C.receipt);else{let P=ke(O,a[N]?.operationId,Ut(a[N],r,i),"not_attempted");S.push(P)}}let A=p&&x,E=e,I=null;if(!A&&v)try{E=c.serializeCurrent()}catch(N){I=Ne(N),A=!0}let R=null;if(!A&&v){let N=la({documentXml:E,commentsXml:c.commentsXml,commentsExtendedXml:c.commentsExtendedXml,numberingXmlParts:c.numberingXmlParts},S);N.valid||(R=N.error,p&&(A=!0))}if(A){for(let N of w)N.receipt&&N.receipt.attemptedDisposition==="applied"&&(N.receipt.finalDisposition="rolled_back",N.receipt.committed=!1),N.change&&(N.change.finalDisposition="rolled_back",N.change.committed=!1);for(let N of S)N.attemptedDisposition==="applied"&&(N.finalDisposition="rolled_back",N.committed=!1)}else{for(let N of w)N.receipt&&N.receipt.attemptedDisposition==="applied"&&(N.receipt.committed=!0,N.receipt.finalDisposition="applied"),N.change&&(N.change.finalDisposition="applied",N.change.committed=!0);for(let N of S)N.attemptedDisposition==="applied"&&(N.committed=!0,N.finalDisposition="applied")}A||Gd(n,h);let T={documentXml:A?c.rollback():E,hasChanges:A?!1:v,commentsXml:A?null:c.commentsXml,commentsExtendedXml:A?null:c.commentsExtendedXml,commentsXmlMode:c.commentsXmlMode,commentsExtendedXmlMode:c.commentsExtendedXmlMode,numberingXmlParts:A?[]:c.numberingXmlParts,results:[...w].sort((N,O)=>(N.index||0)-(O.index||0)),receipts:S.sort((N,O)=>N.operationIndex-O.operationIndex),executionOrder:y,authorsUsed:A?[]:Array.from(b),...A?{rolledBack:!0,status:"error",error:Ne({code:R?R.code:I?"DOCUMENT_SERIALIZATION_FAILED":"BATCH_OPERATION_FAILED",message:R?.message||I?.message||"Atomic batch rolled back because one or more operations failed."})}:R?{status:"error",error:Ne(R)}:x?{status:v?"partial":"error",error:Ne({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed."})}:{status:"ok"}};return(T.status==="error"||T.status==="partial")&&(T.retryPlan=Ir({atomic:p,rolledBack:A,results:T.results,receipts:T.receipts,operationCount:a.length})),T}function xo(e,t={}){return yt(e,t)}function Db(e){return e.operationKind==="list-format"?!0:e.operationKind!=="redline"||typeof e.modified!="string"?!1:e.modified.split(/\r?\n/).some(t=>/^\s*(?:[-+*]|\d+[.)])\s+/.test(t))}function Ub(e,t,r,n,o=null,a="accepted"){let i=o?.byParagraph?.get(t)||null,l=i?null:se(e),s=i?.text??Y(t,{revisionView:a}),c=q(n||""),f=q(s);return{resolvedBy:r,resolvedTarget:{index:i?.index??l.indexOf(t)+1,paragraphId:i?.paragraphId??He(t),text:s,fingerprint:i?.fingerprint??Ot(t,{text:s,revisionView:a}),inTable:i?.inTable??!!ut(t,"tbl"),revisionView:a},matchDiagnostics:{exactTextMatch:typeof n=="string"&&n===s,normalizedTextMatch:!!c&&c===f,suppliedText:n||"",actualText:s,revisionView:a}}}function Jm(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.("*",r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Fi(e,t,r,n={}){if(n.existingRevisions!=null&&!fa(n.existingRevisions))return{valid:!1,status:"error",error:xo({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(n.existingRevisions)}".`}),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let o=j(e,"application/xml");if(o.error||!o.doc)return{valid:!1,status:"error",error:xo(o.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let a=o.doc,i={accepted:rr(a,{revisionView:"accepted"}),rejected:null},l=Array.isArray(t)?t:[],s=po(a,l,{strictTargets:n.strictTargets!==!1,onInfo:n.onInfo,onWarn:n.onWarn}),c=Li(s.compiledOperations);if(!c.valid)return{valid:!1,status:"error",error:xo(c.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let f=n.strictTargets!==!1,u=[],d=new Set,m=!1,p=!1;for(let y=0;y<l.length;y++){let b=l[y],x=s.bindings[y],S=s.compiledOperations[y],A=!x?.error&&S?._localizedReplacementCompilation?S:b,E=Nr(A),I=St(b),R=E.operation||I,T=Ut(R,r,ae());if(d.add(T),!E.valid){u.push({index:y+1,type:b?.type||"redline",operationType:R.operationKind,status:"error",authorUsed:T,error:E.error});continue}if(m=m||R.operationKind==="comment"||R.operationKind==="comment_reply",p=p||Db(R),R.operationKind==="comment_resolve"){let C=String(R.commentId);u.push(n._existingCommentDetails?.[C]?{index:y+1,type:b.type,operationType:R.operationKind,status:"ready",authorUsed:T,resolvedBy:"comment_id",commentId:C}:{index:y+1,type:b.type,operationType:R.operationKind,status:"error",authorUsed:T,error:{code:"COMMENT_NOT_FOUND",message:`Comment '${C}' was not found.`}});continue}if(R.operationKind==="comment_reply"){let C=String(R.parentCommentId),P=n._existingCommentDetails?.[C];u.push(P?{index:y+1,type:b.type,operationType:R.operationKind,status:"ready",authorUsed:T,resolvedBy:"parent_comment",parentCommentId:C}:{index:y+1,type:b.type,operationType:R.operationKind,status:"error",authorUsed:T,error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${C}' was not found.`}});continue}if(R.targetDescriptor?.captureRef){u.push({index:y+1,type:b?.type||"redline",operationType:R.operationKind,status:"deferred",authorUsed:T,resolvedBy:"capture",captureRef:R.targetDescriptor.captureRef,...R.targetDescriptor.select?{select:R.targetDescriptor.select}:{}});continue}if(x?.error){u.push({index:y+1,type:b?.type||"redline",operationType:R.operationKind,status:"error",authorUsed:T,error:x.error});continue}if(x?.createdByOperation){u.push({index:y+1,type:b?.type||"redline",operationType:R.operationKind,status:"deferred",authorUsed:T,resolvedBy:"created_content_dependency",captureRef:x.captureRef,select:R.targetDescriptor.text,createdByOperation:x.createdByOperation});continue}let N=R.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",O=N==="rejected"?i.rejected||(i.rejected=rr(a,{revisionView:"rejected"})):i.accepted;try{let C;if(x.dynamic)C=ln(a,{targetText:R.target,targetRef:R.targetRef,targetDescriptor:R.targetDescriptor,opType:R.operationKind,strictAmbiguity:f,paragraphMetadataIndex:O,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn});else{let re=s.registry.resolve(x.sourceIds[0],a);if(re.error)throw Object.assign(new Error(re.error.message),re.error);C={paragraph:re.paragraph,resolvedBy:x.resolvedBy,warnings:x.warnings}}let P=C.paragraph,M=Ub(a,P,C.resolvedBy,R.target,O,N),_=M.resolvedTarget.text,k=R.operationKind==="comment"?R.textToComment||_:R.operationKind==="highlight"?R.textToHighlight:R.operationKind==="format"?R.textToFormat:null,L=R.operationKind==="comment"&&k!=null?ra(ao(P,{revisionView:N}),k):null,D=k==null||(L?L.found:_.includes(k)),z=re=>{if(R.targetEndRef)return cn(a,R.targetRef,R.targetEndRef,{opType:re,targetRefSnapshot:n.targetRefSnapshot||null,onInfo:n.onInfo,onWarn:n.onWarn});if(!R.targetEndDescriptor)return[P];let je=ln(a,{targetText:R.targetEndDescriptor.text,targetRef:R.targetEndDescriptor.index,targetDescriptor:R.targetEndDescriptor,opType:re,strictAmbiguity:f,paragraphMetadataIndex:O,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn}),ge=se(a),he=ge.indexOf(P),Me=ge.indexOf(je?.paragraph);return he>=0&&Me>=he?ge.slice(he,Me+1):null},G=fr(P),ee=R.existingRevisions||n.existingRevisions||"merge-same-author",J=Lr(ee,ee==="auto"&&R.operationKind==="redline"&&(R.targetEndRef||R.targetEndDescriptor)&&z("redline")||P,T),ie=R.operationKind==="redline"&&R.modified===""?Jm(P):[],ne=null;if(R.operationKind==="restore"){let re=z("restore"),je=Array.isArray(R.modified)?R.modified:[R.modified];if(!re||re[0]!==P||je.length!==re.length)ne={code:"RESTORATION_COUNT_MISMATCH",message:"Restoration requires one replacement for every paragraph in a contiguous resolved range."};else for(let ge of re){let he=an(ge);if(he?.code==="UNSUPPORTED_MOVE_REVISION"){ne=he;break}let Me=zr(ge,T),K=Me.matches?he||an(ge):null;if(!Me.matches){ne={code:"RESTORATION_STATE_REQUIRED",message:"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...Me.ownerAuthor?{ownerAuthor:Me.ownerAuthor}:{}};break}if(K){ne=K;break}}}else if(!D)ne=L?.error||{code:"ANCHOR_NOT_FOUND",message:`Anchor text was not found in target paragraph: "${k}".`};else if(ie.length>0){let re=ie.map(je=>n._existingCommentDetails?.[je]).filter(Boolean);ne={code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:ie,...re.length>0?{comments:re}:{}}}else if(R.operationKind==="redline"&&G&&J!=="accept-all-first"&&J!=="accept-all-first-keep-normalized")if(J==="merge-same-author"||J==="slice-cross-author"){let re=Mr(P),je=String(T||"").trim().toLowerCase(),ge=re.length>0&&!dr(P)&&re.every(he=>he.trim().toLowerCase()===je);if(!ge&&J==="merge-same-author")ne={code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${[...re,...dr(P)?["unattributed"]:[]].join(", ")}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:re,currentPolicy:J};else if(ge){let he=Jm(P);if(he.length>0){let Me=he.map(K=>n._existingCommentDetails?.[K]).filter(Boolean);ne={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:he,...Me.length>0?{comments:Me}:{}}}}else(P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0)&&(ne={code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."})}else{let re=P.getElementsByTagNameNS(B,"del").length>0,je=P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0;re?ne={code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}:je?ne={code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}:ne={code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}if(!ne&&R.operationKind==="redline"){let re=Ha(P,R.modified,n);re.valid||(ne={code:re.code,message:re.message})}u.push({index:y+1,type:b?.type||"redline",operationType:R.operationKind,status:ne?"error":"ready",authorUsed:T,...M,anchor:k==null?null:{text:k,found:D,...L?.found?{resolvedBy:L.resolvedBy,start:L.start,end:L.end}:{},...!L?.found&&Array.isArray(L?.error?.candidates)?{candidates:L.error.candidates}:{}},hasRevisions:G,existingRevisions:J,...C?.warnings?.length?{warnings:C.warnings}:{},...ne?{error:ne}:{}})}catch(C){u.push({index:y+1,type:b?.type||"redline",operationType:R.operationKind,status:"error",authorUsed:T,error:xo(C)})}}let g=s.conflicts,h=u.map(y=>y.error?{...y,error:xo(y.error,{operationIndex:y.index,...l[y.index-1]?.operationId?{operationId:l[y.index-1].operationId}:{}})}:y),v=g.map(y=>xo(y)),w=h.some(y=>y.status==="error");return{valid:!w&&v.length===0,status:!w&&v.length===0?"ok":"error",results:h,conflicts:v,authorsUsed:Array.from(d),requiredArtifacts:{comments:m,numbering:p}}}var pt=Uint8Array,Lt=Uint16Array,fc=Int32Array,$i=new pt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Di=new pt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),sc=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tp=function(e,t){for(var r=new Lt(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var o=new fc(r[30]),n=1;n<30;++n)for(var a=r[n];a<r[n+1];++a)o[a]=a-r[n]<<5|n;return{b:r,r:o}},rp=tp($i,2),np=rp.b,lc=rp.r;np[28]=258,lc[258]=28;var op=tp(Di,0),zb=op.b,Zm=op.r,cc=new Lt(32768);for(we=0;we<32768;++we)Ar=(we&43690)>>1|(we&21845)<<1,Ar=(Ar&52428)>>2|(Ar&13107)<<2,Ar=(Ar&61680)>>4|(Ar&3855)<<4,cc[we]=((Ar&65280)>>8|(Ar&255)<<8)>>1;var Ar,we,or=(function(e,t,r){for(var n=e.length,o=0,a=new Lt(t);o<n;++o)e[o]&&++a[e[o]-1];var i=new Lt(t);for(o=1;o<t;++o)i[o]=i[o-1]+a[o-1]<<1;var l;if(r){l=new Lt(1<<t);var s=15-t;for(o=0;o<n;++o)if(e[o])for(var c=o<<4|e[o],f=t-e[o],u=i[e[o]-1]++<<f,d=u|(1<<f)-1;u<=d;++u)l[cc[u]>>s]=c}else for(l=new Lt(n),o=0;o<n;++o)e[o]&&(l[o]=cc[i[e[o]-1]++]>>15-e[o]);return l}),Hr=new pt(288);for(we=0;we<144;++we)Hr[we]=8;var we;for(we=144;we<256;++we)Hr[we]=9;var we;for(we=256;we<280;++we)Hr[we]=7;var we;for(we=280;we<288;++we)Hr[we]=8;var we,va=new pt(32);for(we=0;we<32;++we)va[we]=5;var we,Xb=or(Hr,9,0),Vb=or(Hr,9,1),jb=or(va,5,0),Wb=or(va,5,1),oc=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Jt=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},ac=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},dc=function(e){return(e+7)/8|0},ap=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new pt(e.subarray(t,r))};var Kb=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Rr=function(e,t,r){var n=new Error(t||Kb[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Rr),!r)throw n;return n},Gb=function(e,t,r,n){var o=e.length,a=n?n.length:0;if(!o||t.f&&!t.l)return r||new pt(0);var i=!r,l=i||t.i!=2,s=t.i;i&&(r=new pt(o*3));var c=function(he){var Me=r.length;if(he>Me){var K=new pt(Math.max(Me*2,he));K.set(r),r=K}},f=t.f||0,u=t.p||0,d=t.b||0,m=t.l,p=t.d,g=t.m,h=t.n,v=o*8;do{if(!m){f=Jt(e,u,1);var w=Jt(e,u+1,3);if(u+=3,w)if(w==1)m=Vb,p=Wb,g=9,h=5;else if(w==2){var S=Jt(e,u,31)+257,A=Jt(e,u+10,15)+4,E=S+Jt(e,u+5,31)+1;u+=14;for(var I=new pt(E),R=new pt(19),T=0;T<A;++T)R[sc[T]]=Jt(e,u+T*3,7);u+=A*3;for(var N=oc(R),O=(1<<N)-1,C=or(R,N,1),T=0;T<E;){var P=C[Jt(e,u,O)];u+=P&15;var y=P>>4;if(y<16)I[T++]=y;else{var M=0,_=0;for(y==16?(_=3+Jt(e,u,3),u+=2,M=I[T-1]):y==17?(_=3+Jt(e,u,7),u+=3):y==18&&(_=11+Jt(e,u,127),u+=7);_--;)I[T++]=M}}var k=I.subarray(0,S),L=I.subarray(S);g=oc(k),h=oc(L),m=or(k,g,1),p=or(L,h,1)}else Rr(1);else{var y=dc(u)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>o){s&&Rr(0);break}l&&c(d+b),r.set(e.subarray(y,x),d),t.b=d+=b,t.p=u=x*8,t.f=f;continue}if(u>v){s&&Rr(0);break}}l&&c(d+131072);for(var D=(1<<g)-1,z=(1<<h)-1,G=u;;G=u){var M=m[ac(e,u)&D],ee=M>>4;if(u+=M&15,u>v){s&&Rr(0);break}if(M||Rr(2),ee<256)r[d++]=ee;else if(ee==256){G=u,m=null;break}else{var J=ee-254;if(ee>264){var T=ee-257,Z=$i[T];J=Jt(e,u,(1<<Z)-1)+np[T],u+=Z}var ie=p[ac(e,u)&z],ne=ie>>4;ie||Rr(3),u+=ie&15;var L=zb[ne];if(ne>3){var Z=Di[ne];L+=ac(e,u)&(1<<Z)-1,u+=Z}if(u>v){s&&Rr(0);break}l&&c(d+131072);var re=d+J;if(d<L){var je=a-L,ge=Math.min(L,re);for(je+d<0&&Rr(3);d<ge;++d)r[d]=n[je+d]}for(;d<re;++d)r[d]=r[d-L]}}t.l=m,t.p=G,t.b=d,t.f=f,m&&(f=1,t.m=g,t.d=p,t.n=h)}while(!f);return d!=r.length&&i?ap(r,0,d):r.subarray(0,d)},Er=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},ha=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},ic=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var o=r.length,a=r.slice();if(!o)return{t:sp,l:0};if(o==1){var i=new pt(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(x,S){return x.f-S.f}),r.push({s:-1,f:25001});var l=r[0],s=r[1],c=0,f=1,u=2;for(r[0]={s:-1,f:l.f+s.f,l,r:s};f!=o-1;)l=r[r[c].f<r[u].f?c++:u++],s=r[c!=f&&r[c].f<r[u].f?c++:u++],r[f++]={s:-1,f:l.f+s.f,l,r:s};for(var d=a[0].s,n=1;n<o;++n)a[n].s>d&&(d=a[n].s);var m=new Lt(d+1),p=uc(r[f-1],m,0);if(p>t){var n=0,g=0,h=p-t,v=1<<h;for(a.sort(function(S,A){return m[A.s]-m[S.s]||S.f-A.f});n<o;++n){var w=a[n].s;if(m[w]>t)g+=v-(1<<p-m[w]),m[w]=t;else break}for(g>>=h;g>0;){var y=a[n].s;m[y]<t?g-=1<<t-m[y]++-1:++n}for(;n>=0&&g;--n){var b=a[n].s;m[b]==t&&(--m[b],++g)}p=t}return{t:new pt(m),l:p}},uc=function(e,t,r){return e.s==-1?Math.max(uc(e.l,t,r+1),uc(e.r,t,r+1)):t[e.s]=r},Qm=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Lt(++t),n=0,o=e[0],a=1,i=function(s){r[n++]=s},l=1;l<=t;++l)if(e[l]==o&&l!=t)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=e[l]}return{c:r.subarray(0,n),n:t}},wa=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},ip=function(e,t,r){var n=r.length,o=dc(t+2);e[o]=n&255,e[o+1]=n>>8,e[o+2]=e[o]^255,e[o+3]=e[o+1]^255;for(var a=0;a<n;++a)e[o+a+4]=r[a];return(o+4+n)*8},ep=function(e,t,r,n,o,a,i,l,s,c,f){Er(t,f++,r),++o[256];for(var u=ic(o,15),d=u.t,m=u.l,p=ic(a,15),g=p.t,h=p.l,v=Qm(d),w=v.c,y=v.n,b=Qm(g),x=b.c,S=b.n,A=new Lt(19),E=0;E<w.length;++E)++A[w[E]&31];for(var E=0;E<x.length;++E)++A[x[E]&31];for(var I=ic(A,7),R=I.t,T=I.l,N=19;N>4&&!R[sc[N-1]];--N);var O=c+5<<3,C=wa(o,Hr)+wa(a,va)+i,P=wa(o,d)+wa(a,g)+i+14+3*N+wa(A,R)+2*A[16]+3*A[17]+7*A[18];if(s>=0&&O<=C&&O<=P)return ip(t,f,e.subarray(s,s+c));var M,_,k,L;if(Er(t,f,1+(P<C)),f+=2,P<C){M=or(d,m,0),_=d,k=or(g,h,0),L=g;var D=or(R,T,0);Er(t,f,y-257),Er(t,f+5,S-1),Er(t,f+10,N-4),f+=14;for(var E=0;E<N;++E)Er(t,f+3*E,R[sc[E]]);f+=3*N;for(var z=[w,x],G=0;G<2;++G)for(var ee=z[G],E=0;E<ee.length;++E){var J=ee[E]&31;Er(t,f,D[J]),f+=R[J],J>15&&(Er(t,f,ee[E]>>5&127),f+=ee[E]>>12)}}else M=Xb,_=Hr,k=jb,L=va;for(var E=0;E<l;++E){var Z=n[E];if(Z>255){var J=Z>>18&31;ha(t,f,M[J+257]),f+=_[J+257],J>7&&(Er(t,f,Z>>23&31),f+=$i[J]);var ie=Z&31;ha(t,f,k[ie]),f+=L[ie],ie>3&&(ha(t,f,Z>>5&8191),f+=Di[ie])}else ha(t,f,M[Z]),f+=_[Z]}return ha(t,f,M[256]),f+_[256]},Hb=new fc([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),sp=new pt(0),qb=function(e,t,r,n,o,a){var i=a.z||e.length,l=new pt(n+i+5*(1+Math.ceil(i/7e3))+o),s=l.subarray(n,l.length-o),c=a.l,f=(a.r||0)&7;if(t){f&&(s[0]=a.r>>3);for(var u=Hb[t-1],d=u>>13,m=u&8191,p=(1<<r)-1,g=a.p||new Lt(32768),h=a.h||new Lt(p+1),v=Math.ceil(r/3),w=2*v,y=function(V){return(e[V]^e[V+1]<<v^e[V+2]<<w)&p},b=new fc(25e3),x=new Lt(288),S=new Lt(32),A=0,E=0,I=a.i||0,R=0,T=a.w||0,N=0;I+2<i;++I){var O=y(I),C=I&32767,P=h[O];if(g[C]=P,h[O]=C,T<=I){var M=i-I;if((A>7e3||R>24576)&&(M>423||!c)){f=ep(e,s,0,b,x,S,E,R,N,I-N,f),R=A=E=0,N=I;for(var _=0;_<286;++_)x[_]=0;for(var _=0;_<30;++_)S[_]=0}var k=2,L=0,D=m,z=C-P&32767;if(M>2&&O==y(I-z))for(var G=Math.min(d,M)-1,ee=Math.min(32767,I),J=Math.min(258,M);z<=ee&&--D&&C!=P;){if(e[I+k]==e[I+k-z]){for(var Z=0;Z<J&&e[I+Z]==e[I+Z-z];++Z);if(Z>k){if(k=Z,L=z,Z>G)break;for(var ie=Math.min(z,Z-2),ne=0,_=0;_<ie;++_){var re=I-z+_&32767,je=g[re],ge=re-je&32767;ge>ne&&(ne=ge,P=re)}}}C=P,P=g[C],z+=C-P&32767}if(L){b[R++]=268435456|lc[k]<<18|Zm[L];var he=lc[k]&31,Me=Zm[L]&31;E+=$i[he]+Di[Me],++x[257+he],++S[Me],T=I+k,++A}else b[R++]=e[I],++x[e[I]]}}for(I=Math.max(I,T);I<i;++I)b[R++]=e[I],++x[e[I]];f=ep(e,s,c,b,x,S,E,R,N,I-N,f),c||(a.r=f&7|s[f/8|0]<<3,f-=7,a.h=h,a.p=g,a.i=I,a.w=T)}else{for(var I=a.w||0;I<i+c;I+=65535){var K=I+65535;K>=i&&(s[f/8|0]=c,K=i),f=ip(s,f+1,e.subarray(I,K))}a.i=i}return ap(l,0,n+dc(f)+o)};var Yb=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),i=new pt(a.length+e.length);i.set(a),i.set(e,a.length),e=i,o.w=a.length}return qb(e,t.level==null?6:t.level,t.mem==null?o.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,o)};function lp(e,t){return Yb(e,t||{},0,0)}function cp(e,t){return Gb(e,{i:2},t&&t.out,t&&t.dictionary)}var Jb=typeof TextDecoder<"u"&&new TextDecoder,Zb=0;try{Jb.decode(sp,{stream:!0}),Zb=1}catch{}var fp=new TextEncoder,dp=new TextDecoder("utf-8"),Qb=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function ex(e){let t=4294967295;for(let r=0;r<e.length;r++)t=Qb[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function Io(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof e=="string")return fp.encode(e);throw new TypeError("Invalid binary input: expected Uint8Array, Buffer, or ArrayBuffer.")}function up(e){let t=0;for(let o=0;o<e.length;o++)t+=e[o].length;let r=new Uint8Array(t),n=0;for(let o=0;o<e.length;o++)r.set(e[o],n),n+=e[o].length;return r}function No(e){let t=Io(e);if(t.length<22)throw new Error("Invalid DOCX: ZIP end record not found.");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=-1,o=Math.max(0,t.length-65535-22);for(let c=t.length-22;c>=o;c--)if(r.getUint32(c,!0)===101010256){n=c;break}if(n<0)throw new Error("Invalid DOCX: ZIP end record not found.");let a=r.getUint16(n+10,!0),i=r.getUint32(n+16,!0);if(a===65535||i===4294967295)throw new Error("Unsupported DOCX: ZIP64 archives are not supported.");let l=new Map,s=i;for(let c=0;c<a;c++){if(s+46>t.length||r.getUint32(s,!0)!==33639248)throw new Error("Invalid DOCX: central directory is corrupt.");let f=r.getUint16(s+8,!0),u=r.getUint16(s+10,!0);if(f&1)throw new Error("Unsupported DOCX: encrypted ZIP entries are not supported.");let d=r.getUint32(s+20,!0),m=r.getUint16(s+28,!0),p=r.getUint16(s+30,!0),g=r.getUint16(s+32,!0),h=r.getUint32(s+42,!0);if(s+46+m>t.length)throw new Error("Invalid DOCX: central directory entry name extends beyond bounds.");let v=dp.decode(t.subarray(s+46,s+46+m));if(h+30>t.length||r.getUint32(h,!0)!==67324752)throw new Error("Invalid DOCX: local entry is corrupt.");let w=r.getUint16(h+26,!0),y=r.getUint16(h+28,!0),b=h+30+w+y;if(b+d>t.length)throw new Error("Invalid DOCX: local entry data extends beyond archive bounds.");let x=t.subarray(b,b+d);if(u!==0&&u!==8)throw new Error(`Unsupported DOCX compression method: ${u}.`);let S=u===8?cp(x):new Uint8Array(x);l.set(v,S),s+=46+m+p+g}return l}function mp(e){let t=e instanceof Map?Array.from(e.entries()):Symbol.iterator in Object(e)?Array.from(e):Object.entries(e||{}),r=[],n=[],o=0;for(let[s,c]of t){let f=fp.encode(s),u=Io(c),d=lp(u,{level:9}),m=d.length<u.length?8:0,p=m===8?d:u,g=ex(u),h=new Uint8Array(30),v=new DataView(h.buffer,h.byteOffset,30);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint16(8,m,!0),v.setUint16(12,23585,!0),v.setUint32(14,g,!0),v.setUint32(18,p.length,!0),v.setUint32(22,u.length,!0),v.setUint16(26,f.length,!0),v.setUint16(28,0,!0),r.push(h,f,p);let w=new Uint8Array(46),y=new DataView(w.buffer,w.byteOffset,46);y.setUint32(0,33639248,!0),y.setUint16(4,20,!0),y.setUint16(6,20,!0),y.setUint16(10,m,!0),y.setUint16(14,23585,!0),y.setUint32(16,g,!0),y.setUint32(20,p.length,!0),y.setUint32(24,u.length,!0),y.setUint16(28,f.length,!0),y.setUint16(30,0,!0),y.setUint16(32,0,!0),y.setUint32(42,o,!0),n.push(w,f),o+=h.length+f.length+p.length}let a=up(n),i=new Uint8Array(22),l=new DataView(i.buffer,i.byteOffset,22);return l.setUint32(0,101010256,!0),l.setUint16(8,t.length,!0),l.setUint16(10,t.length,!0),l.setUint32(12,a.length,!0),l.setUint32(16,o,!0),up([...r,a,i])}var Pr=class{constructor(t){this.entries=t instanceof Map?t:new Map(Object.entries(t||{}))}file(t,r){if(r!==void 0)return this.entries.set(t,Io(r)),this;let n=this.entries.get(t);return n?{async:async o=>o==="string"?dp.decode(n):new Uint8Array(n)}:null}};var ar=new TextEncoder,vp=new TextDecoder("utf-8"),te=(e,t)=>{let r=e.get(t);return r?typeof r=="string"?r:vp.decode(r):null};function pp(e){let t=$f({commentsXml:te(e,"word/comments.xml"),commentsIdsXml:te(e,"word/commentsIds.xml"),commentsExtensibleXml:te(e,"word/commentsExtensible.xml")});t.commentsIdsXml&&e.set("word/commentsIds.xml",ar.encode(t.commentsIdsXml)),t.commentsExtensibleXml&&e.set("word/commentsExtensible.xml",ar.encode(t.commentsExtensibleXml))}var To=e=>new Map([...e].map(([t,r])=>[t,new Uint8Array(r)]));function pe(e){return typeof Buffer<"u"&&typeof Buffer.from=="function"?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function ya(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function gp(e,t){let r=i=>!i||typeof i!="object"?i:i.attemptedDisposition!=="applied"&&i.committed!==!0?{...i}:{...i,committed:!1,finalDisposition:"rolled_back"},n=(e?.receipts||[]).map(r),o=new Map(n.map(i=>[i.operationIndex,i])),a=(e?.results||[]).map(i=>({...i,...i.receipt?{receipt:o.get(i.index)||r(i.receipt)}:{}}));return{results:a,receipts:n,executionOrder:e?.executionOrder||[],authorsUsed:[],rolledBack:!0,retryPlan:Ir({atomic:!0,rolledBack:!0,results:a,receipts:n,operationCount:t})}}function mc(e){let t;if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer?.(e))t=No(e);else if(e instanceof Map)t=e;else if(e?.entries instanceof Map)t=e.entries;else if(typeof e?.toUint8Array=="function")t=No(e.toUint8Array());else if(typeof e?.toBuffer=="function")t=No(e.toBuffer());else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=No(Io(e));else throw new TypeError("computePackageRevisionToken requires a Uint8Array, Buffer, Map of entries, or DocxDocument.");return Zo({scope:"package",entries:t})}var hp=new Set(["comment","comment_reply","comment_resolve"]);function tx(e){let r=(`${te(e,"word/document.xml")||""} ${te(e,"word/comments.xml")||""}`.match(/(?:w:)?id=["'](\d+)["']/g)||[]).reduce((n,o)=>Math.max(n,Number(o.match(/\d+/)?.[0]||0)),0)+1;return()=>r++}function wp(e){let t=te(e,"word/comments.xml");if(!t)return{};let r=j(t,"application/xml");if(!r.doc||r.error)return{};let n={};for(let o of Array.from(r.doc.getElementsByTagNameNS("*","comment"))){let a=o.getAttribute("w:id")||o.getAttribute("id");a!==""&&(n[a]={id:a,author:o.getAttribute("w:author")||o.getAttribute("author")||"",text:String(o.textContent||"").trim(),paraId:Tt(o)||null})}return n}function zt(e,t,r){let n=pe(e);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,error:yt({code:t,message:r}),retryPlan:Ir({atomic:!0,rolledBack:!0}),artifactsChanged:[],uint8Array:e,toUint8Array:()=>new Uint8Array(e),buffer:n,toBuffer:()=>pe(e)}}var Ui=class{constructor(t){this.originalBytes=Io(t),this.entries=No(this.originalBytes)}get originalBuffer(){return pe(this.originalBytes)}inspect(t={}){let r=t.digestFn||(o=>Jo(o)),n=di({documentXml:te(this.entries,"word/document.xml"),commentsXml:te(this.entries,"word/comments.xml"),commentsExtendedXml:te(this.entries,"word/commentsExtended.xml"),numberingXml:te(this.entries,"word/numbering.xml"),stylesXml:te(this.entries,"word/styles.xml")},{...t,digestFn:r});return n.status==="error"?n:{...n,headersFooters:this.inspectHeadersFooters()}}inspectHeadersFooters(){return bl({documentXml:te(this.entries,"word/document.xml"),relsXml:te(this.entries,"word/_rels/document.xml.rels"),settingsXml:te(this.entries,"word/settings.xml")}).map(t=>{let r=te(this.entries,t.path)||"",n=r?di({documentXml:r}):{paragraphs:[]};return{...t,hasFields:/<w:fldChar\b|<w:fldSimple\b/.test(r),paragraphs:(n.paragraphs||[]).map(o=>({index:o.index,text:o.text}))}})}getRevisionToken(){return mc(this.entries)}get revisionToken(){return this.getRevisionToken()}preflight(t,r=ae(),n={}){let o=Array.isArray(t)?t:[],a=p=>Fi(te(this.entries,"word/document.xml"),p,r||ae(),{...n,_existingCommentDetails:wp(this.entries)});if(!o.some(p=>p&&typeof p=="object"&&p.part!=null))return a(t);let i=this.inspectHeadersFooters(),l=[],s=[],c=[],f=new Set,u=!0;o.forEach((p,g)=>{if(!p||typeof p!="object"||p.part==null){l.push({operation:p,origIndex:g});return}let h=xl(i,p.part),v=hp.has(p.type)?{code:"COMMENT_IN_HEADER_FOOTER",message:"Word does not support comments in headers or footers."}:h.error;if(v){u=!1,s.push({index:g+1,type:p.type||"redline",status:"error",error:yt({...v,operationIndex:g+1})});return}let{part:w,...y}=p,b=Fi(te(this.entries,h.part.path),[y],r||ae(),{...n,_existingCommentDetails:{}});u=u&&b.valid;for(let x of b.results||[])s.push({...x,index:g+1,part:h.part.path});c.push(...b.conflicts||[]);for(let x of b.authorsUsed||[])f.add(x)});let d={comments:!1,numbering:!1};if(l.length){let p=a(l.map(g=>g.operation));u=u&&p.valid;for(let g of p.results||[])s.push({...g,index:l[g.index-1].origIndex+1});c.push(...p.conflicts||[]);for(let g of p.authorsUsed||[])f.add(g);d=p.requiredArtifacts||d}s.sort((p,g)=>p.index-g.index);let m=u&&c.length===0;return{valid:m,status:m?"ok":"error",results:s,conflicts:c,authorsUsed:[...f],requiredArtifacts:d}}toUint8Array(){return mp(this.entries)}toBuffer(){return pe(this.toUint8Array())}async applyOperations(t,r={}){let n=Array.isArray(t)?t:[];return n.some(o=>o&&typeof o=="object"&&o.part!=null)?this.applyOperationsWithParts(n,r):this.applyBodyOperations(t,r)}async applyOperationsWithParts(t,r={}){let n=r.author||ae(),o=r.atomic===!0,a=this.entries,i=this.originalBytes,l=t.length,s=()=>{this.entries=a,this.originalBytes=i},c=()=>({uint8Array:i,toUint8Array:()=>new Uint8Array(i),buffer:pe(i),toBuffer:()=>pe(i)}),f=(_,k=[],L=[],D={})=>({status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:k,receipts:L,executionOrder:[],authorsUsed:[],artifactsChanged:[],error:yt(_),retryPlan:Ir({atomic:!0,rolledBack:!0,results:k,receipts:L,operationCount:l}),validation:{originalIssues:[],generatedIssues:[]},...D,...c()});if(r.expectedRevision){let _=await this.applyBodyOperations([],{expectedRevision:r.expectedRevision});if(_.status==="error")return _}let u=bl({documentXml:te(this.entries,"word/document.xml"),relsXml:te(this.entries,"word/_rels/document.xml.rels"),settingsXml:te(this.entries,"word/settings.xml")}),d=[],m=[];for(let _=0;_<t.length;_++){let k=t[_];if(!k||typeof k!="object"||k.part==null){d.push({operation:k,origIndex:_});continue}if(hp.has(k.type))return f({code:"COMMENT_IN_HEADER_FOOTER",message:`Operation ${_+1}: Word does not support comments in headers or footers.`,operationIndex:_+1});if(k.type==="list-format")return f({code:"INVALID_OPERATION",field:"part",message:`Operation ${_+1}: list-format is body-only in list-format-v1; headers and footers are not supported.`,operationIndex:_+1});let L=xl(u,k.part);if(L.error)return f({...L.error,message:`Operation ${_+1}: ${L.error.message}`,operationIndex:_+1});let{part:D,...z}=k;m.push({operation:z,origIndex:_,part:L.part})}let p=[],g=[],h=[],v=new Set,w=[],y=!1,b=!1,x=null;if(d.length){x=await this.applyBodyOperations(d.map(k=>k.operation),{...r,expectedRevision:void 0});let _=k=>d[k-1]?.origIndex+1;for(let k of x.results||[])p.push({...k,index:_(k.index),...k.receipt?{receipt:{...k.receipt,operationIndex:_(k.receipt.operationIndex)}}:{}});for(let k of x.receipts||[])g.push({...k,operationIndex:_(k.operationIndex)});for(let k of x.executionOrder||[])h.push(_(k));for(let k of x.authorsUsed||[])v.add(k);if(w.push(...x.validation?.originalIssues||[]),(x.status==="error"||x.rolledBack)&&(b=!0,o))return s(),{...x,results:p,receipts:g,executionOrder:h,written:!1,artifactsChanged:[],rolledBack:!0,...c()};y=x.hasChanges===!0}let S=To(this.entries),A=new Pr(S),E=new Set,{expectedRevision:I,...R}=r,T=(_,k)=>{b=!0;let L=yt({...k,operationIndex:_.origIndex+1});p.push({index:_.origIndex+1,type:_.operation.type||"redline",status:"error",authorUsed:n,part:_.part.path,error:L})};for(let _ of m){let k=_.part.path,L=te(S,k);if(!L){if(T(_,{code:"PART_NOT_FOUND",message:`Part '${k}' is referenced but missing from the package.`}),o)break;continue}let D=te(S,"word/numbering.xml"),z=await Bi(L,[_.operation],n,{numberingIdState:Ht(D||void 0)},{...R,atomic:!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:{}}),G=z.results?.[0];if(z.rolledBack||z.status==="error"){if(T(_,G?.error||z.error||{code:"OPERATION_FAILED",message:"Operation failed."}),o)break;continue}if(!z.hasChanges){p.push({...G,index:_.origIndex+1,part:k});continue}if(Il(z.documentXml)>Il(L)){if(T(_,{code:"FIELD_EDIT_REFUSED",message:`The edit would change a field (for example PAGE or NUMPAGES) in ${k}. Word recomputes fields; edit the text around them instead.`}),o)break;continue}let ee=new Set;for(let[ie,ne]of S)if(!(ie===k||!(ie==="word/document.xml"||dd(ie))))for(let re of md(vp.decode(ne)))ee.add(re);let J=pd(z.documentXml,ee);S.set(k,ar.encode(J.xml));let Z=ie=>ie?.revisionItems?{...ie,revisionItems:ie.revisionItems.map(ne=>({...ne,id:J.idMap.get(String(ne.id))??ne.id,partName:k}))}:ie;z.numberingXmlParts?.length&&await wi(A,z.numberingXmlParts),E.add(k),y=!0,p.push({...G,index:_.origIndex+1,part:k,partSections:_.part.appliesToSections,...G?.receipt?{receipt:{...Z(G.receipt),operationIndex:_.origIndex+1}}:{}}),z.receipts?.[0]&&g.push({...Z(z.receipts[0]),operationIndex:_.origIndex+1}),h.push(_.origIndex+1);for(let ie of z.authorsUsed||[])v.add(ie)}let N=[];if(!(o&&b)){for(let _ of E){let k=Mt(te(this.entries,_)).issues.map(D=>({source:_,...D})),L=Mt(te(S,_)).issues.map(D=>({source:_,...D}));k.push(...ro(te(this.entries,_),te(this.entries,"word/numbering.xml")).map(D=>({source:_,...D}))),L.push(...ro(te(S,_),te(S,"word/numbering.xml")).map(D=>({source:_,...D}))),N.push(...En(An(L,k)))}if(r.validate!==!1&&E.size)try{await Vr(A)}catch(_){N.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:_.message})}}if(o&&b||N.length){s();let _=N.length?{code:"PACKAGE_OPERATION_FAILED",message:`Applied operations introduced invalid markup (${[...new Set(N.map(D=>D.code))].join(", ")}).`,issues:N}:{code:"BATCH_OPERATION_FAILED",message:"Atomic batch rolled back because one or more operations failed."},k=p.map(D=>D.receipt?{...D,receipt:{...D.receipt,committed:!1,finalDisposition:"rolled_back"}}:D).sort((D,z)=>D.index-z.index),L=g.map(D=>({...D,committed:!1,finalDisposition:"rolled_back"}));return f(_,k,L,{validation:{originalIssues:w,generatedIssues:N},issues:N})}p.sort((_,k)=>_.index-k.index),g.sort((_,k)=>_.operationIndex-k.operationIndex);let O=b?y?"partial":"error":"ok",C=b?{error:yt({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed; the others were applied."})}:{};if(!E.size){let _=pe(this.originalBytes);return{...x||{},results:p,receipts:g,executionOrder:h,authorsUsed:[...v],status:O,hasChanges:y,written:x?.written===!0,artifactsChanged:x?.artifactsChanged||[],validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:_,toBuffer:()=>pe(this.originalBytes)}}this.entries=S;let P=this.toUint8Array();this.originalBytes=P;let M=[...S].filter(([_,k])=>!a.has(_)||!ya(k,a.get(_))).map(([_])=>_);return{...x||{},status:O,hasChanges:!0,written:!0,results:p,receipts:g,executionOrder:h,authorsUsed:[...v],artifactsChanged:M,validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:P,toUint8Array:()=>new Uint8Array(P),buffer:pe(P),inspection:this.inspect(),toBuffer:()=>pe(P)}}async applyBodyOperations(t,r={}){let n=f=>{let u=[],d=[],m=pe(this.originalBytes);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:u,receipts:d,artifactsChanged:[],error:yt(f),retryPlan:Ir({atomic:!0,rolledBack:!0,results:u,receipts:d,operationCount:Array.isArray(t)?t.length:0}),validation:{originalIssues:[],generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>pe(this.originalBytes)}};if(r?.expectedRevision){let f=vn(r.expectedRevision);if(!f.valid)return n({code:f.error?.code||"INVALID_REVISION_TOKEN",message:f.error?.message||"Invalid revision token."});if(r.expectedRevision.scope!=="package")return n({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'package', got '${r.expectedRevision.scope}'.`,expectedScope:"package",actualScope:r.expectedRevision.scope});let u=mc(this.entries);if(!yn(u.value,r.expectedRevision.value))return n({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${r.expectedRevision.value}', current is '${u.value}'.`,expectedRevision:r.expectedRevision,currentRevision:u})}let o=this.entries,a=To(o),i=new Pr(a),l=te(a,"word/document.xml"),s=[],c=null;try{if(!l)throw new Error("Missing word/document.xml.");s=Mt(l).issues.map(S=>({source:"word/document.xml",...S})),s.push(...ro(l,te(a,"word/numbering.xml")).map(S=>({source:"word/numbering.xml",...S})));try{await Vr(new Pr(To(o)))}catch(S){s.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:S.message})}let u={numberingIdState:Ht(te(a,"word/numbering.xml")||void 0),stylesXml:te(a,"word/styles.xml"),commentsXml:te(a,"word/comments.xml"),commentsExtendedXml:te(a,"word/commentsExtended.xml")},{expectedRevision:d,...m}=r,p=r.author||ae(),g=c=await Bi(l,t,p,u,{...m,atomic:r.atomic===!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:wp(a),commentIdAllocator:tx(a)});if(g.rolledBack||g.status==="error"){let S=pe(this.originalBytes);return{...g,...gp(g,Array.isArray(t)?t.length:0),written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:S,toBuffer:()=>pe(this.originalBytes)}}if(!g.hasChanges){let S=pe(this.originalBytes);return{...g,status:g.status||"ok",written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:S,toBuffer:()=>pe(this.originalBytes)}}(g.results||[]).some(S=>S?.status!=="error"&&S?.operationType!=="comment_resolve")&&a.set("word/document.xml",ar.encode(g.documentXml)),await wi(i,g.numberingXmlParts);let v=te(a,"word/comments.xml"),w=g.commentsXml||v;if(await yl(i,w,{replaceExisting:g.commentsXmlMode==="replace"||!g.commentsXml&&!!v}),g.commentsExtendedXml&&await vi(i,g.commentsExtendedXml,{replaceExisting:g.commentsExtendedXmlMode==="replace"}),await lo(i),pp(a),r.validate!==!1){let A=Mt(g.documentXml).issues.map(R=>({source:"word/document.xml",...R}));A.push(...ro(g.documentXml,te(a,"word/numbering.xml")).map(R=>({source:"word/numbering.xml",...R})));try{await Vr(i)}catch(R){A.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:R.message})}let E=An(A,s),I=En(E);if(I.length){let R=[...new Set(I.map(T=>T.code))].join(", ");throw Object.assign(new Error(`Applied operations introduced invalid revision markup (${R}); these are generated-output issues, not pre-existing input issues.`),{issues:I})}}this.entries=a;let y=this.toUint8Array();this.originalBytes=y;let b=pe(y),x=[...a].filter(([S,A])=>!o.has(S)||!ya(A,o.get(S))).map(([S])=>S);return{...g,status:g.status||"ok",written:!0,artifactsChanged:x,validation:{originalIssues:s,generatedIssues:[]},uint8Array:y,toUint8Array:()=>new Uint8Array(y),buffer:b,inspection:this.inspect(),toBuffer:()=>pe(y)}}catch(f){this.entries=o;let u=f.issues||[{source:"package",code:"PACKAGE_OPERATION_FAILED",severity:"error",message:f.message}],d=gp(c,Array.isArray(t)?t.length:0),m=pe(this.originalBytes);return{...d,status:"error",hasChanges:!1,written:!1,artifactsChanged:[],error:yt({code:"PACKAGE_OPERATION_FAILED",message:f.message,stage:"package",issues:u}),validation:{originalIssues:s,generatedIssues:u},issues:u,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>pe(this.originalBytes)}}}async resolveRevisions(t,r={}){let n=t==="accept"?nn:t==="reject"?Ur:null;if(!n)return zt(this.originalBytes,"INVALID_ACTION",`Unknown revision action: ${t}`);let o=this.originalBytes,a=this.entries,i=To(this.entries),l=new Pr(i),s=n(te(i,"word/document.xml"),{author:r.author,allAuthors:r.allAuthors===!0});if(s.status==="error"||s.error)return zt(o,s.error?.code||"REVISION_OPERATION_FAILED",s.error?.message||"Revision operation failed.");let c=new Map;for(let m of this.inspectHeadersFooters()){let p=te(i,m.path);if(!p)continue;let g=n(p,{author:r.author,allAuthors:r.allAuthors===!0});if(g.status==="error"||g.error)return zt(o,g.error?.code||"REVISION_OPERATION_FAILED",`${m.path}: ${g.error?.message||"Revision operation failed."}`);g.hasChanges&&c.set(m.path,g.oxml)}if(!(s.hasChanges||c.size>0)){let m=pe(o);return{...s,status:"ok",written:!1,artifactsChanged:[],uint8Array:o,toUint8Array:()=>new Uint8Array(o),buffer:m,toBuffer:()=>pe(o)}}s.hasChanges&&i.set("word/document.xml",ar.encode(s.oxml));for(let[m,p]of c)i.set(m,ar.encode(p));try{await lo(l),r.validate!==!1&&await Vr(l)}catch(m){return zt(o,"PACKAGE_VALIDATION",m.message)}this.entries=i;let u=this.toUint8Array();this.originalBytes=u;let d=pe(u);return{...s,status:"ok",written:!0,hasChanges:!0,artifactsChanged:[...i].filter(([m,p])=>!a.has(m)||!ya(p,a.get(m))).map(([m])=>m),uint8Array:u,toUint8Array:()=>new Uint8Array(u),buffer:d,toBuffer:()=>pe(u)}}async resolveComment(t,r={}){let n=this.originalBytes,o=To(this.entries),a=r.resolved!==!1,i=u=>{let d=pe(n);return{status:"ok",hasChanges:!1,written:!1,artifactsChanged:[],...u,uint8Array:n,toUint8Array:()=>new Uint8Array(n),buffer:d,toBuffer:()=>pe(n)}},l=ci({commentsXml:te(o,"word/comments.xml"),commentsExtendedXml:te(o,"word/commentsExtended.xml"),commentId:t,resolved:a});if(l.status==="error")return zt(n,l.error.code,l.error.message);if(!l.hasChanges)return i({resolved:a,threadRootId:l.threadRootId,commentIds:l.commentIds});let s=new Pr(o);try{l.commentsXml&&o.set("word/comments.xml",ar.encode(l.commentsXml)),await vi(s,l.commentsExtendedXml,{replaceExisting:!0}),await lo(s),r.validate!==!1&&await Vr(s)}catch(u){return zt(n,"PACKAGE_VALIDATION",u.message)}let c=[...o].filter(([u,d])=>!this.entries.has(u)||!ya(d,this.entries.get(u))).map(([u])=>u);this.entries=o;let f=this.toUint8Array();return this.originalBytes=f,{status:"ok",hasChanges:!0,written:!0,resolved:a,threadRootId:l.threadRootId,commentIds:l.commentIds,artifactsChanged:c,uint8Array:f,toUint8Array:()=>new Uint8Array(f),buffer:pe(f),toBuffer:()=>pe(f)}}async deleteComments(t={}){let r=this.originalBytes,n=To(this.entries),o=te(n,"word/comments.xml"),a=pe(r);if(!o)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>pe(r)};let i=j(o,"application/xml");if(!i.doc||i.error)return zt(r,"PARSE_ERROR",i.error?.message||"Could not parse comments.xml.");let l=Array.isArray(t.ids)?new Set(t.ids.map(String)):null;if(l){let x=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).map(A=>A.getAttribute("w:id")||A.getAttribute("id"))),S=[...l].filter(A=>!x.has(A));if(S.length)return zt(r,"COMMENT_NOT_FOUND",`Comment id(s) not found: ${S.join(", ")}.`)}let s=x=>l?l.has(x.getAttribute("w:id")||x.getAttribute("id")):t.allAuthors===!0||(x.getAttribute("w:author")||x.getAttribute("author"))===t.author,c=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).filter(s).map(x=>x.getAttribute("w:id")||x.getAttribute("id")).filter(Boolean));if(!c.size)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>pe(r)};let f=te(n,"word/commentsExtended.xml"),u=null,d=new Set;if(f){if(u=j(f,"application/xml"),!u.doc||u.error)return zt(r,"PARSE_ERROR",u.error?.message||"Could not parse commentsExtended.xml.");let x=new Map;for(let A of Array.from(i.doc.getElementsByTagNameNS("*","comment"))){let E=A.getAttribute("w:id")||A.getAttribute("id"),I=Tt(A);I&&x.set(I,E)}for(let[A,E]of x)c.has(E)&&d.add(A);let S=!0;for(;S;){S=!1;for(let A of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let E=(A.getAttribute("w15:paraId")||A.getAttribute("paraId")||"").toUpperCase(),I=(A.getAttribute("w15:paraIdParent")||A.getAttribute("paraIdParent")||"").toUpperCase();I&&d.has(I)&&!d.has(E)&&(d.add(E),x.has(E)&&c.add(x.get(E)),S=!0)}}}let m=l?o:Os(o,{author:t.author,allAuthors:t.allAuthors===!0}).oxml,p=j(m,"application/xml");if(!p.doc||p.error)return zt(r,"PARSE_ERROR",p.error?.message||"Could not parse updated comments.xml.");for(let x of Array.from(p.doc.getElementsByTagNameNS("*","comment"))){let S=x.getAttribute("w:id")||x.getAttribute("id");c.has(S)&&x.parentNode?.removeChild(x)}let g=j(te(n,"word/document.xml"),"application/xml");if(!g.doc||g.error)return zt(r,"PARSE_ERROR",g.error?.message||"Could not parse document.xml.");let h=0;for(let x of["commentRangeStart","commentRangeEnd","commentReference"])for(let S of Array.from(g.doc.getElementsByTagNameNS("*",x))){let A=S.getAttribute("w:id")||S.getAttribute("id");if(!c.has(A)||!S.parentNode)continue;let E=S.parentNode;E.removeChild(S),h+=1,x==="commentReference"&&E.localName==="r"&&!Array.from(E.childNodes||[]).some(I=>I.nodeType===1&&I.localName!=="rPr")&&E.parentNode?.removeChild(E)}let v=le();if(n.set("word/comments.xml",ar.encode(v.serializeToString(p.doc))),u?.doc){for(let x of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let S=(x.getAttribute("w15:paraId")||x.getAttribute("paraId")||"").toUpperCase();d.has(S)&&x.parentNode?.removeChild(x)}n.set("word/commentsExtended.xml",ar.encode(v.serializeToString(u.doc)))}n.set("word/document.xml",ar.encode(v.serializeToString(g.doc)));try{pp(n);let x=new Pr(n);await lo(x),t.validate!==!1&&await Vr(x)}catch(x){return zt(r,"PACKAGE_VALIDATION",x.message)}let w=[...n].filter(([x,S])=>!this.entries.has(x)||!ya(S,this.entries.get(x))).map(([x])=>x);this.entries=n;let y=this.toUint8Array();this.originalBytes=y;let b=pe(y);return{status:"ok",hasChanges:!0,written:!0,commentsRemoved:c.size,referencesRemoved:h,artifactsChanged:w,uint8Array:y,toUint8Array:()=>new Uint8Array(y),buffer:b,toBuffer:()=>pe(y)}}};function rx(e){return new Ui(e)}function nx(e,t){let r=typeof t?.numberingXml=="string"&&t.numberingXml.trim()?t.numberingXml:null,n=t?.numberingIdState&&typeof t.numberingIdState=="object"?t.numberingIdState:r?Ht(r):null;if(!n||!e?.hasChanges||typeof e.oxml!="string"||!e.oxml.includes("/word/numbering.xml"))return e;let o=Ve(e.oxml),a=Array.from(o.getElementsByTagNameNS("*","part")),i=d=>{let p=a.find(g=>(g.getAttribute("pkg:name")||g.getAttribute("name"))===d)?.getElementsByTagNameNS("*","xmlData")[0];return p&&Array.from(p.childNodes).find(g=>g.nodeType===1)||null},l=i("/word/numbering.xml"),s=i("/word/document.xml")?.getElementsByTagNameNS("*","body")[0];if(!l||!s)return e;let c=Array.from(s.childNodes).filter(d=>d.nodeType===1&&d.localName!=="sectPr"),f=mn(Kt(l),c,n),u=o.importNode(Ve(f.numberingXml).documentElement,!0);return l.parentNode.replaceChild(u,l),c.forEach((d,m)=>s.replaceChild(f.replacementNodes[m],d)),{...e,oxml:Kt(o)}}async function yp(e,t,r,n={}){let o=await $o(e,t,r,n),a=nx(o,n);if(a?.useNativeApi&&typeof a?.oxml!="string"){let i=Array.isArray(a?.warnings)?a.warnings:[];return Ce({...a,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return a}async function FP(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=bt(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await yp(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function $P(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,a=n.sanitizeInput===!0?Ls(r):r,i=a!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],l=dn({oxml:e,originalText:t,modifiedText:a,allowExistingList:o}),s=n.preferListStructuralFallback!==!1,c=[];if(l&&s){let g=await Qn(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(g?.hasChanges&&g?.oxml){let h=kr(g.oxml,{includeNumbering:g.includeNumbering??!0,numberingXml:g.numberingXml}),v=Array.isArray(g?.warnings)?g.warnings:[];return Ce({oxml:h,hasChanges:!0,warnings:[...i,...v],listStructuralFallbackApplied:!0,listStructuralFallbackKey:g.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:g.numberingXml||null})}c=Array.isArray(g?.warnings)?g.warnings:[]}let f=await yp(e,t,r,n);if(!l)return{...f,warnings:[...Array.isArray(f?.warnings)?f.warnings:[],...c],listStructuralFallbackApplied:!1};if(s)return{...f,warnings:[...Array.isArray(f?.warnings)?f.warnings:[],...c],listStructuralFallbackApplied:!1};if(f?.hasChanges)return{...f,listStructuralFallbackApplied:!1};let u=await Qn(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!u?.hasChanges||!u?.oxml){let g=Array.isArray(f?.warnings)?f.warnings:[],h=Array.isArray(u?.warnings)?u.warnings:[];return{...f,warnings:[...g,...h],listStructuralFallbackApplied:!1}}let d=kr(u.oxml,{includeNumbering:u.includeNumbering??!0,numberingXml:u.numberingXml}),m=Array.isArray(f?.warnings)?f.warnings:[],p=Array.isArray(u?.warnings)?u.warnings:[];return Ce({...f,oxml:d,hasChanges:!0,warnings:[...m,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:u.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:u.numberingXml||null})}export{Ln as ContainerKind,Ec as ContentType,Bt as DiffOp,Ui as DocxDocument,B as NS_W,ur as NumberingService,sa as ReceiptCollector,_o as ReconciliationPipeline,co as RoutePlanKind,H as RunKind,fe as WORD_MAIN_NS,nn as acceptTrackedChangesInOoxml,Ho as allocateNumberingDefinition,Hs as allocateNumberingForReplacement,Ea as analyzeStructuredContent,il as applyCommentReplyToParts,vv as applyFormattingRemovalToOoxml,sl as applyHighlightToOoxml,yp as applyRedlineToOxml,$P as applyRedlineToOxmlWithListFallback,Ef as applyStartOverridesToNum,yn as areRevisionTokensEqual,Yo as buildCommentElement,Js as buildCommentsPartXml,ni as buildExplicitDecimalMultilevelNumberingXml,ww as buildListMarkdown,Rv as buildReconciliationPlan,rl as buildRevisionTokenFraming,dn as buildSingleLineListStructuralFallbackPlan,$s as buildTargetReferenceSnapshot,$w as canonicalNumberingDefinition,Vo as clearSingleLineListFallbackExplicitSequence,hf as collectContiguousListParagraphBlock,pv as compareDocumentInspections,Qo as computeDocumentPartsRevisionToken,mc as computePackageRevisionToken,Uf as computeRevisionToken,Zo as computeRevisionTokenSync,Pp as configureLogger,Op as configureXmlProvider,fr as containsTrackedChanges,Uw as copyLevelGeometry,Ht as createDynamicNumberingIdState,ke as createEmptyReceipt,Ot as createParagraphFingerprint,Os as deleteCommentsByAuthorInOoxml,ei as enforceListBindingOnParagraphNodes,yl as ensureCommentsArtifactsInZip,vi as ensureCommentsExtendedArtifactsInZip,wi as ensureNumberingArtifactsInZip,Qe as escapeXml,Qn as executeSingleLineListStructuralFallback,Y as extractCanonicalParagraphText,ui as extractDocumentPartsEntries,ri as extractFirstParagraphNumId,Pv as extractParagraphIdFromOoxml,Oa as extractParagraphRevisionSegments,hl as extractReplacementNodesFromOoxml,ut as findContainingWordElement,Bs as findParagraphByBestTextMatch,df as findParagraphByReference,Ka as findParagraphByStrictText,Ga as findStrictTargetCandidates,mr as generateTableOoxml,gl as getBodyElementFromDocument,ae as getDefaultAuthor,se as getDocumentParagraphNodes,fl as getPackagePartName,He as getParagraphId,Oe as getParagraphListInfo,_e as getParagraphText,Wi as getPlatform,Mr as getTrackedChangeAuthors,zs as hasListItems,So as inferNumberingStyleFromMarker,js as inferTableReplacementParagraphBlock,Dn as ingestOoxml,Qw as ingestWordOoxmlToMarkdown,Lf as ingestWordOoxmlToMarkdownResult,Zw as ingestWordOoxmlToPlainText,Mf as ingestWordOoxmlToPlainTextResult,al as injectCommentsIntoOoxml,hv as injectCommentsIntoPackage,Sv as insertBodyElementBeforeSectPr,di as inspectDocumentParts,ol as inspectionReviewShape,Tf as isLikelyStructuredTableSourceParagraph,sn as isMarkdownTableText,tn as isNodeVisibleInRevisionView,vr as mergeNumberingParts,Pf as mergeNumberingXmlBySchemaOrder,hi as normalizeBodySectionOrderStandalone,ud as normalizeContentEscapesForRouting,vw as normalizeListItemsWithLevels,Df as normalizeOpcEntryName,q as normalizeWhitespaceForTargeting,rx as openDocx,ti as overwriteParagraphNumIds,Xo as parseMarkdownListContent,Ve as parseOoxml,j as parseOoxmlSafe,Fs as parseParagraphReference,Us as planListInsertionOnlyEdit,Zg as planStructuredReplacement,qe as preprocessMarkdown,gr as readCanonicalRunText,FP as reconcileMarkdownTableOoxml,la as reconcileReceiptsAgainstOutput,Qa as recordSingleLineListFallbackExplicitSequence,Ur as rejectTrackedChangesInOoxml,mn as remapNumberingPayloadForDocument,Qf as removeFormattingFromRPr,lo as repairKnownContentTypes,Wo as reserveNextNumberingId,to as reserveNextNumberingIdPair,Lr as resolveExistingRevisionsPolicy,cn as resolveParagraphRangeByRefs,Za as resolveSingleLineListFallbackNumberingAction,ln as resolveTargetParagraph,Jn as resolveTargetParagraphWithSnapshot,Ls as sanitizeAiResponse,Av as sanitizeNestedParagraphsInTables,Kt as serializeOoxml,ct as serializeToOoxml,Fp as setDefaultAuthor,$p as setPlatform,uw as splitLeadingParagraphMarker,cw as stripLeadingParagraphMarker,un as stripRedundantLeadingListMarkers,Xs as stripSingleLineListMarkerPrefix,Ds as synthesizeExpandedListScopeEdit,Ws as synthesizeTableMarkdownFromMultilineCellEdit,Vr as validateDocxPackage,ro as validateNumberingIntegrity,Mt as validateRedlineOoxml,vn as validateRevisionToken,kr as wrapInDocumentFragment};
230
233
  //# sourceMappingURL=docx-redline-js.esm.min.js.map