@lucio-ai/docxtor 0.4.1 → 0.5.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.
- package/README.md +272 -55
- package/dist/cli.mjs +89 -0
- package/dist/index.cjs +10 -10
- package/dist/index.d.cts +13 -0
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +13 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +13 -13
- package/dist/index.mjs.map +1 -1
- package/package.json +12 -8
- package/logo.png +0 -0
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{readFile as e}from"node:fs/promises";import{parseArgs as t}from"node:util";import n from"jszip";import{XMLBuilder as r,XMLParser as i}from"fast-xml-parser";async function a(e){let t=await n.loadAsync(e),r=await o(t,`word/document.xml`);if(r===void 0)throw Error(`Invalid DOCX: missing word/document.xml`);let i=await o(t,`word/_rels/document.xml.rels`),a=await o(t,`[Content_Types].xml`),s=await o(t,`word/styles.xml`),c=await o(t,`word/settings.xml`),l=await o(t,`word/numbering.xml`),u=await o(t,`word/footnotes.xml`),d=await o(t,`word/endnotes.xml`),f=await o(t,`word/comments.xml`),p=await o(t,`docProps/core.xml`),m=await o(t,`docProps/app.xml`),h=await o(t,`_rels/.rels`),g=new Map,_=new Map;for(let e of Object.keys(t.files))if(/^word\/header\d+\.xml$/i.test(e)){let n=await o(t,e);n!==void 0&&g.set(e,n)}else if(/^word\/footer\d+\.xml$/i.test(e)){let n=await o(t,e);n!==void 0&&_.set(e,n)}return{documentXml:r,headers:g,footers:_,documentRels:i,contentTypes:a,stylesXml:s,settingsXml:c,numberingXml:l,footnotesXml:u,endnotesXml:d,commentsXml:f,coreXml:p,appXml:m,rootRels:h,zip:t}}async function o(e,t){let n=e.file(t);if(n)return n.async(`string`)}const s=[[`documentRelsXml`,`word/_rels/document.xml.rels`],[`contentTypesXml`,`[Content_Types].xml`],[`settingsXml`,`word/settings.xml`],[`numberingXml`,`word/numbering.xml`],[`footnotesXml`,`word/footnotes.xml`],[`endnotesXml`,`word/endnotes.xml`],[`commentsXml`,`word/comments.xml`],[`coreXml`,`docProps/core.xml`],[`appXml`,`docProps/app.xml`],[`rootRelsXml`,`_rels/.rels`]];async function c(e){let{zip:t,documentXml:n,headers:r,footers:i,removedParts:a}=e;if(a)for(let e of a)t.remove(e);if(t.file(`word/document.xml`,n),r)for(let[e,n]of r)t.file(e,n);if(i)for(let[e,n]of i)t.file(e,n);for(let[n,r]of s){let i=e[n];typeof i==`string`&&t.file(r,i)}return await t.generateAsync({type:`nodebuffer`,compression:`DEFLATE`,compressionOptions:{level:6}})}const l=new r({preserveOrder:!0,ignoreAttributes:!1,attributeNamePrefix:`@_`,commentPropName:`#comment`,cdataPropName:`#cdata`,processEntities:!1,format:!1,suppressEmptyNode:!1,suppressBooleanAttributes:!1});function u(e){return l.build(e)}const d=new i({preserveOrder:!0,ignoreAttributes:!1,attributeNamePrefix:`@_`,commentPropName:`#comment`,cdataPropName:`#cdata`,processEntities:!1,trimValues:!1,parseTagValue:!1,parseAttributeValue:!1,ignoreDeclaration:!1,ignorePiTags:!1});function f(e){return d.parse(e)}function p(e){for(let t of Object.keys(e))if(t!==`:@`&&t!==`#text`)return t}function m(e,t){return t in e}function h(e){let t=p(e);if(!t)return[];let n=e[t];return Array.isArray(n)?n:[]}function g(e,t){return h(e).find(e=>t in e)}function _(e,t){return h(e).filter(e=>t in e)}function v(e,t){let n=e[`:@`];if(n)return n[`@_${t}`]}function y(e,t,n){e[`:@`]||={},e[`:@`][`@_${t}`]=n}function ee(e,t){let n=e[`:@`];n&&delete n[`@_${t}`]}function te(e){let t=e[`:@`];if(!t)return{};let n={};for(let[e,r]of Object.entries(t))e.startsWith(`@_`)&&(n[e.slice(2)]=r);return n}function b(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function x(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function ne(e,t){e[`#text`]=b(t)}function re(e){let t=h(e),n=``;for(let e of t)if(`w:t`in e){let t=e[`w:t`];if(Array.isArray(t))for(let e of t)`#text`in e&&(n+=x(String(e[`#text`])))}else if(`w:br`in e){let t=v(e,`w:type`);(!t||t===`textWrapping`)&&(n+=`
|
|
3
|
+
`)}return n}function ie(e){return h(e).find(e=>`w:t`in e)}function ae(e){let t=h(e);for(let e of t)if(`w:br`in e&&v(e,`w:type`)===`page`||`w:lastRenderedPageBreak`in e)return!0;return!1}function oe(e){let t=h(e),n=0;for(let e of t)if(`w:t`in e){let t=e[`w:t`];if(Array.isArray(t))for(let e of t)`#text`in e&&(n+=x(String(e[`#text`])).length)}else if(`w:br`in e){let t=v(e,`w:type`);if(!t||t===`textWrapping`)n+=1;else if(t===`page`)return n}else if(`w:lastRenderedPageBreak`in e)return n;return-1}function se(e){let t=g(e,`w:pPr`);if(t){let e=g(t,`w:pageBreakBefore`);if(e){let t=v(e,`w:val`);if(t!==`0`&&t!==`false`)return!0}}return ce(h(e))}function ce(e){for(let t of e){let e=p(t);if(e===`w:r`){if(ae(t))return!0}else if((e===`w:hyperlink`||e===`w:ins`)&&ce(h(t)))return!0}return!1}function S(e){return JSON.parse(JSON.stringify(e))}function le(e,t,n){let r=h(e),i=r.indexOf(t);if(i===-1)throw Error(`Reference child not found in parent`);return r.splice(i+1,0,n),i+1}function C(e,t){let n=h(e),r=n.indexOf(t);return r===-1?!1:(n.splice(r,1),!0)}function w(e,t=[],n){let r={[e]:t};if(n&&Object.keys(n).length>0){let e={};for(let[t,r]of Object.entries(n))e[`@_${t}`]=r;r[`:@`]=e}return r}function ue(e){return{"#text":b(e)}}function de(e){let t={"w:t":[ue(e)]};return T(e)&&y(t,`xml:space`,`preserve`),t}function T(e){return e.length>0&&(e!==e.trim()||e.includes(` `))}function fe(e,t){let n=[];if(t&&n.push(S(t)),e.includes(`
|
|
4
|
+
`)){let t=e.split(`
|
|
5
|
+
`);for(let e=0;e<t.length;e++){let r=t[e];(r.length>0||e===0)&&n.push(de(r)),e<t.length-1&&n.push({"w:br":[]})}}else n.push(de(e));return{"w:r":n}}function pe(e){let t=h(e),n=[];for(let e of t){let t=p(e);t===`w:r`?n.push(e):(t===`w:hyperlink`||t===`w:ins`)&&me(e,n)}return n}function me(e,t){let n=h(e);for(let e of n){let n=p(e);n===`w:r`?t.push(e):(n===`w:hyperlink`||n===`w:ins`)&&me(e,t)}}function E(e,t){let n=pe(e),r=[],i=0,a;for(let e of n){let t=re(e);if(a===void 0&&ae(e)){let t=oe(e);t>=0&&(a=i+t)}if(t.length===0)continue;let n=ie(e),o=he(e),s={text:t,startOffset:i,endOffset:i+t.length,xmlRef:e,formatting:o};n&&(s.textXmlRef=n),r.push(s),i+=t.length}let o=r.map(e=>e.text).join(``),s=ve(e,r),c={kind:`paragraph`,id:t,text:o,runs:r,xmlRef:e,style:ge(e),listInfo:_e(e)},l=v(e,`w14:paraId`);if(l&&(c.paraId=l.toUpperCase()),s.length>0&&(c.revisions=s),se(e)){c.hasPageBreak=!0;let t=g(e,`w:pPr`);if(t){let e=g(t,`w:pageBreakBefore`);if(e){let t=v(e,`w:val`);if(t!==`0`&&t!==`false`)return c.pageBreakOffset=0,c}}a!==void 0&&(c.pageBreakOffset=a)}return c}function he(e){let t=g(e,`w:rPr`);if(!t)return{};let n={},r=h(t);for(let e of r)if(m(e,`w:b`)){let t=v(e,`w:val`);n.bold=t!==`0`&&t!==`false`}else if(m(e,`w:i`)){let t=v(e,`w:val`);n.italic=t!==`0`&&t!==`false`}else if(m(e,`w:u`))n.underline=v(e,`w:val`)??`single`;else if(m(e,`w:strike`)){let t=v(e,`w:val`);n.strikethrough=t!==`0`&&t!==`false`}else if(m(e,`w:sz`)){let t=v(e,`w:val`);t&&(n.fontSize=parseInt(t,10))}else if(m(e,`w:rFonts`))n.fontFamily=v(e,`w:ascii`)??v(e,`w:hAnsi`);else if(m(e,`w:color`)){n.color=v(e,`w:val`);let t=v(e,`w:themeColor`);t&&(n.themeColor=t)}else m(e,`w:highlight`)&&(n.highlight=v(e,`w:val`));return n}function ge(e){let t=g(e,`w:pPr`);if(!t)return;let n=g(t,`w:pStyle`);if(n)return v(n,`w:val`)}function _e(e){let t=g(e,`w:pPr`);if(!t)return;let n=g(t,`w:numPr`);if(!n)return;let r=g(n,`w:numId`),i=g(n,`w:ilvl`),a=r?v(r,`w:val`):void 0,o=i?v(i,`w:val`):void 0;if(a&&a!==`0`)return{numId:a,level:o?parseInt(o,10):0}}function ve(e,t){let n=[],r=new Set;ye(e,r);for(let i of t)if(r.has(i.xmlRef)){let t=xe(e,i.xmlRef);n.push({type:`insert`,text:i.text,startOffset:i.startOffset,endOffset:i.endOffset,author:t?.author??``,date:t?.date??``,...t?.id===void 0?{}:{id:t.id}})}return we(e,t,n),n}function ye(e,t){let n=h(e);for(let e of n){let n=p(e);n===`w:ins`?be(e,t):n===`w:hyperlink`&&ye(e,t)}}function be(e,t){let n=h(e);for(let e of n){let n=p(e);n===`w:r`?t.add(e):(n===`w:hyperlink`||n===`w:ins`)&&be(e,t)}}function xe(e,t){return Se(h(e),t)}function Se(e,t){for(let n of e){let e=p(n);if(e===`w:ins`){if(Ce(n,t))return{author:v(n,`w:author`)??``,date:v(n,`w:date`)??``,id:v(n,`w:id`)}}else if(e===`w:hyperlink`){let e=Se(h(n),t);if(e)return e}}}function Ce(e,t){let n=h(e);for(let e of n){if(e===t)return!0;let n=p(e);if(n&&n!==`w:del`&&Ce(e,t))return!0}return!1}function we(e,t,n){let r=new Map;for(let e of t)r.set(e.xmlRef,e);Te(h(e),r,n,0)}function Te(e,t,n,r){for(let i of e){let e=p(i);if(e===`w:r`){let e=t.get(i);e&&(r=e.endOffset)}else if(e===`w:del`){let e=Ee(i);e.length>0&&n.push({type:`delete`,text:e,startOffset:r,endOffset:r,author:v(i,`w:author`)??``,date:v(i,`w:date`)??``,...v(i,`w:id`)===void 0?{}:{id:v(i,`w:id`)}})}else (e===`w:hyperlink`||e===`w:ins`)&&(r=Te(h(i),t,n,r))}return r}function Ee(e){let t=h(e),n=``;for(let e of t)if(p(e)===`w:r`){let t=h(e);for(let e of t)if(`w:br`in e){let t=v(e,`w:type`);(!t||t===`textWrapping`)&&(n+=`
|
|
6
|
+
`)}else if(`w:delText`in e){let t=e[`w:delText`];if(Array.isArray(t))for(let e of t)`#text`in e&&(n+=x(String(e[`#text`])))}else if(`w:t`in e){let t=e[`w:t`];if(Array.isArray(t))for(let e of t)`#text`in e&&(n+=x(String(e[`#text`])))}}return n}function D(e,t){let n=[],r=_(e,`w:tr`);for(let e=0;e<r.length;e++){let i=r[e],a=[],o=_(i,`w:tc`);for(let n=0;n<o.length;n++){let r=o[n],i=_(r,`w:p`).map((r,i)=>E(r,`${t}.r${e}.c${n}.p${i}`)),s=_(r,`w:tbl`).map((r,i)=>D(r,`${t}.r${e}.c${n}.tbl${i}`));a.push({rowIndex:e,colIndex:n,paragraphs:i,nestedTables:s,xmlRef:r})}n.push({index:e,cells:a,xmlRef:i})}let i=g(e,`w:tblPr`),a=i?g(i,`w:tblStyle`):void 0;return{kind:`table`,id:t,rows:n,xmlRef:e,style:a?v(a,`w:val`):void 0}}function De(e,t,n,r){let i=t===`header`?`hdr`:`ftr`,a=t===`header`?`w:hdr`:`w:ftr`,o=e.find(e=>p(e)===a),s=[],c=[];if(o){let e=h(o),t=0,r=0;for(let a of e){let e=p(a);e===`w:p`?(s.push(E(a,`${i}.${n}.p${t}`)),t++):e===`w:tbl`&&(c.push(D(a,`${i}.${n}.tbl${r}`)),r++)}}return{type:t,variant:n,rId:r,paragraphs:s,tables:c,xmlRef:e}}function Oe(e){if(e.xmlParts.numbering)return e.xmlParts.numbering;let t=w(`w:numbering`,[],{"xmlns:w":`http://schemas.openxmlformats.org/wordprocessingml/2006/main`,"xmlns:r":`http://schemas.openxmlformats.org/officeDocument/2006/relationships`});if(e.xmlParts.numbering=[t],e.xmlParts.contentTypes){let t=e.xmlParts.contentTypes.find(e=>p(e)===`Types`);if(t){let e=h(t);e.some(e=>p(e)===`Override`&&v(e,`PartName`)===`/word/numbering.xml`)||e.push(w(`Override`,[],{PartName:`/word/numbering.xml`,ContentType:`application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml`}))}}if(e.xmlParts.documentRels){let t=e.xmlParts.documentRels.find(e=>p(e)===`Relationships`);if(t){let e=h(t);if(!e.some(e=>v(e,`Type`)===`http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering`)){let t=0;for(let n of e){let e=v(n,`Id`);if(e){let n=parseInt(e.replace(`rId`,``),10);!isNaN(n)&&n>t&&(t=n)}}e.push(w(`Relationship`,[],{Id:`rId${t+1}`,Type:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering`,Target:`numbering.xml`}))}}}return e.xmlParts.numbering}function ke(e){let t=e.find(e=>p(e)===`w:numbering`);if(!t)return 1;let n=0;for(let e of _(t,`w:num`)){let t=v(e,`w:numId`);if(t){let e=parseInt(t,10);!isNaN(e)&&e>n&&(n=e)}}return n+1}function Ae(e){let t=e.find(e=>p(e)===`w:numbering`);if(!t)return 0;let n=-1;for(let e of _(t,`w:abstractNum`)){let t=v(e,`w:abstractNumId`);if(t){let e=parseInt(t,10);!isNaN(e)&&e>n&&(n=e)}}return n+1}const je=[{char:``,font:`Symbol`},{char:`o`,font:`Courier New`},{char:``,font:`Wingdings`},{char:``,font:`Symbol`},{char:`o`,font:`Courier New`},{char:``,font:`Wingdings`},{char:``,font:`Symbol`},{char:`o`,font:`Courier New`},{char:``,font:`Wingdings`}],Me=[{fmt:`decimal`,textFn:e=>`%${e+1}.`},{fmt:`lowerLetter`,textFn:e=>`%${e+1}.`},{fmt:`lowerRoman`,textFn:e=>`%${e+1}.`}];function Ne(e,t,n=9){let r=Oe(e),i=h(r.find(e=>p(e)===`w:numbering`)),a=Ae(r),o=ke(r),s=[];for(let e=0;e<n;e++){let n,r;if(t===`bullet`){n=`bullet`;let t=je[e%je.length];r=t.char;let i=w(`w:rPr`,[w(`w:rFonts`,[],{"w:ascii":t.font,"w:hAnsi":t.font,"w:hint":`default`})]);s.push(w(`w:lvl`,[w(`w:start`,[],{"w:val":`1`}),w(`w:numFmt`,[],{"w:val":n}),w(`w:lvlText`,[],{"w:val":r}),w(`w:lvlJc`,[],{"w:val":`left`}),i],{"w:ilvl":String(e)}));continue}else if(t===`multilevel`)n=`decimal`,r=Array.from({length:e+1},(e,t)=>`%${t+1}`).join(`.`)+`.`;else{let t=Me[e%Me.length];n=t.fmt,r=t.textFn(e)}s.push(w(`w:lvl`,[w(`w:start`,[],{"w:val":`1`}),w(`w:numFmt`,[],{"w:val":n}),w(`w:lvlText`,[],{"w:val":r}),w(`w:lvlJc`,[],{"w:val":`left`})],{"w:ilvl":String(e)}))}let c=w(`w:abstractNum`,s,{"w:abstractNumId":String(a)}),l=w(`w:num`,[w(`w:abstractNumId`,[],{"w:val":String(a)})],{"w:numId":String(o)}),u=i.findIndex(e=>p(e)===`w:num`);return u>=0?i.splice(u,0,c):i.push(c),i.push(l),String(o)}function Pe(e,t){let n=e.find(e=>p(e)===`w:numbering`);if(!n)return;let r=_(n,`w:num`).find(e=>v(e,`w:numId`)===t);if(!r)return;let i=g(r,`w:abstractNumId`);if(!i)return;let a=v(i,`w:val`);if(!a)return;let o=_(n,`w:abstractNum`).find(e=>v(e,`w:abstractNumId`)===a);if(!o)return;let s=_(o,`w:lvl`),c=!1,l=!1;for(let e of s){let t=g(e,`w:numFmt`);t&&v(t,`w:val`)===`bullet`&&(c=!0);let n=g(e,`w:lvlText`);if(n){let e=(v(n,`w:val`)??``).match(/%\d+/g);e&&e.length>1&&(l=!0)}}return c?`bullet`:l?`multilevel`:`ordered`}function Fe(e,t,n){let r=e.find(e=>p(e)===`w:numbering`);if(!r)return null;let i=_(r,`w:num`).find(e=>v(e,`w:numId`)===t);if(!i)return null;let a=g(i,`w:abstractNumId`);if(!a)return null;let o=v(a,`w:val`);if(!o)return null;let s=_(r,`w:abstractNum`).find(e=>v(e,`w:abstractNumId`)===o);if(!s)return null;let c=_(s,`w:lvl`),l=c.find(e=>v(e,`w:ilvl`)===String(n));if(!l)return null;let u=g(l,`w:numFmt`),d=g(l,`w:lvlText`),f=u?v(u,`w:val`)??`decimal`:`decimal`,m=d?v(d,`w:val`)??``:``,h=new Map,y=m.match(/%(\d+)/g);if(y)for(let e of y){let t=parseInt(e.slice(1),10)-1,n=c.find(e=>v(e,`w:ilvl`)===String(t));if(n){let e=g(n,`w:numFmt`);h.set(t,e?v(e,`w:val`)??`decimal`:`decimal`)}}return{pattern:m,format:f,ancestorFormats:h}}const Ie=new Set([`w:document`,`w:hdr`,`w:ftr`,`w:footnotes`,`w:endnotes`,`w:comments`]),Le=new WeakMap;function Re(e){let t=Le.get(e.xmlParts);if(!t){t=new Set;for(let n of ze(e.xmlParts))Be(n,t);Le.set(e.xmlParts,t)}return t}function*ze(e){for(let t of Object.values(e))if(Array.isArray(t))yield t;else if(t instanceof Map)for(let e of t.values())yield e}function Be(e,t){for(let n of e){let e=p(n);if(!e)continue;if(e===`w:p`){let e=v(n,`w14:paraId`);e&&t.add(e.toUpperCase())}let r=h(n);r.length>0&&Be(r,t)}}function Ve(e){for(;;){let t=(Math.floor(Math.random()*2147483646)+1).toString(16).toUpperCase().padStart(8,`0`);if(!e.has(t))return e.add(t),t}}function He(e){if(!/^[0-9A-Fa-f]{8}$/.test(e))return!1;let t=parseInt(e,16);return t>0&&t<2147483648}function Ue(e){return e?v(e,`xmlns:w14`)!==void 0:!1}function We(e){v(e,`xmlns:w14`)===void 0&&y(e,`xmlns:w14`,`http://schemas.microsoft.com/office/word/2010/wordml`),v(e,`xmlns:mc`)===void 0&&y(e,`xmlns:mc`,`http://schemas.openxmlformats.org/markup-compatibility/2006`);let t=v(e,`mc:Ignorable`);if(t===void 0)y(e,`mc:Ignorable`,`w14`);else{let n=t.split(/\s+/).filter(e=>e.length>0);n.includes(`w14`)||(n.push(`w14`),y(e,`mc:Ignorable`,n.join(` `)))}}function Ge(e){return e.find(e=>{let t=p(e);return t!==void 0&&Ie.has(t)})}function Ke(e,t){let n=Ge(e);if(!n)return 0;let r=0,i=e=>{for(let n of e){let e=p(n);if(!e)continue;if(e===`w:p`){let e=v(n,`w14:paraId`);if(!e||!He(e)){let e=Ve(t);y(n,`w14:paraId`,e),r++,v(n,`w14:textId`)===void 0&&y(n,`w14:textId`,e)}else v(n,`w14:textId`)===void 0&&y(n,`w14:textId`,e.toUpperCase())}let a=h(n);a.length>0&&i(a)}};return i(h(n)),r>0&&We(n),r}function qe(e){let t=new Set;for(let n of ze(e))Be(n,t);Ke(e.document,t);for(let n of e.headers.values())Ke(n,t);for(let n of e.footers.values())Ke(n,t);Le.set(e,t)}function O(e,t,n,r=!1){if(!Ue(n))return;let i=Re(e),a=e=>{for(let t of e){let e=p(t);if(!e)continue;if(e===`w:p`&&(r||v(t,`w14:paraId`)===void 0)){let e=Ve(i);y(t,`w14:paraId`,e),y(t,`w14:textId`,e)}let n=h(t);n.length>0&&a(n)}};a(t)}function k(e,t){let n=t.match(/^(hdr|ftr)\.([^.]+)\./);if(n){let t=n[1]===`hdr`?e.headers:e.footers,r=n[1]===`hdr`?`w:hdr`:`w:ftr`;for(let e of t.values())if(e.variant===n[2])return e.xmlRef.find(e=>p(e)===r);return}return e.xmlParts.document.find(e=>p(e)===`w:document`)}function Je(e,t){let n=f(e.documentXml),r=new Map;for(let[t,n]of e.headers)r.set(t,f(n));let i=new Map;for(let[t,n]of e.footers)i.set(t,f(n));let a=e.stylesXml?$e(e.stylesXml):[],o=e=>e?f(e):void 0,s={document:n,headers:r,footers:i,documentRels:o(e.documentRels),contentTypes:o(e.contentTypes),settings:o(e.settingsXml),numbering:o(e.numberingXml),footnotes:o(e.footnotesXml),endnotes:o(e.endnotesXml),comments:o(e.commentsXml),core:o(e.coreXml),app:o(e.appXml),rootRels:o(e.rootRels)};t?.assignParaIds&&qe(s);let c={body:[],headers:new Map,footers:new Map,xmlParts:s,styles:a,loadOptions:t};return Ye(c),c}function Ye(e){let t=e.loadOptions?.includeHeadersFooters??!0;if(e.body=Xe(e.xmlParts.document),e.headers=new Map,e.footers=new Map,t){let t=Ze(e.xmlParts.documentRels),n=Qe(e.xmlParts.document);for(let r of n){let n=t.get(r.rId);if(!n)continue;let i=`word/${n}`;if(r.type===`header`){let t=e.xmlParts.headers.get(i);t&&e.headers.set(r.rId,De(t,`header`,r.variant,r.rId))}else{let t=e.xmlParts.footers.get(i);t&&e.footers.set(r.rId,De(t,`footer`,r.variant,r.rId))}}}et(e)}function Xe(e){let t=[],n=e.find(e=>p(e)===`w:document`);if(!n)return t;let r=g(n,`w:body`);if(!r)return t;let i=h(r),a=0,o=0,s=0;for(let e of i){let n=p(e);if(n===`w:p`){let n=E(e,`p${a}`);if(n.hasPageBreak&&n.text.trim().length===0){let n={kind:`page_break`,id:`pb${s}`,xmlRef:e};t.push(n),s++;continue}t.push(n),a++}else n===`w:tbl`&&(t.push(D(e,`tbl${o}`)),o++)}return t}function Ze(e){let t=new Map;if(!e)return t;let n=e.find(e=>p(e)===`Relationships`);if(!n)return t;let r=_(n,`Relationship`);for(let e of r){let n=v(e,`Id`),r=v(e,`Target`);n&&r&&t.set(n,r)}return t}function Qe(e){let t=[],n=e.find(e=>p(e)===`w:document`);if(!n)return t;let r=g(n,`w:body`);if(!r)return t;let i=_(r,`w:sectPr`),a=h(r);for(let e of a)if(p(e)===`w:p`){let t=g(e,`w:pPr`);if(t){let e=g(t,`w:sectPr`);e&&i.push(e)}}for(let e of i){let n=h(e);for(let e of n){let n=p(e);if(n===`w:headerReference`){let n=v(e,`r:id`),r=v(e,`w:type`)??`default`;n&&t.push({type:`header`,variant:r,rId:n})}else if(n===`w:footerReference`){let n=v(e,`r:id`),r=v(e,`w:type`)??`default`;n&&t.push({type:`footer`,variant:r,rId:n})}}}return t}function $e(e){let t=f(e),n=[],r=t.find(e=>p(e)===`w:styles`);if(!r)return n;let i=_(r,`w:style`);for(let e of i){let t=v(e,`w:styleId`),r=v(e,`w:type`);if(!t||!r||![`paragraph`,`character`,`table`,`numbering`].includes(r))continue;let i=g(e,`w:name`),a=i?v(i,`w:val`)??t:t;n.push({id:t,name:a,type:r})}return n}function et(e){let t=e.xmlParts.numbering;if(t){for(let n of e.body)if(n.kind===`paragraph`)A(n,t);else if(n.kind===`table`)for(let e of n.rows)for(let n of e.cells)for(let e of n.paragraphs)A(e,t);for(let n of e.headers.values())for(let e of n.paragraphs)A(e,t);for(let n of e.footers.values())for(let e of n.paragraphs)A(e,t)}}function A(e,t){if(!e.listInfo)return;let n=Pe(t,e.listInfo.numId);n&&(e.listInfo.listType=n)}function tt(e){let t=e.split(`
|
|
7
|
+
`),n=[],r=0;for(;r<t.length;){if(r+1<t.length&&ot(t[r])&&st(t[r+1])){let e=ct(t[r]);r+=2;let i=[];for(;r<t.length&&ot(t[r]);){let n=ct(t[r]);for(;n.length<e.length;)n.push(``);n.length>e.length&&(n.length=e.length),i.push(n),r++}n.push({kind:`table`,headers:e,rows:i});continue}let e=at(t[r]);if(e){let i=[],a=e.listType;for(i.push({text:e.text,level:e.level}),r++;r<t.length;){let e=t[r];if(e.trim().length===0){r++;continue}let n=at(e);if(!n||n.listType!==a)break;i.push({text:n.text,level:n.level}),r++}n.push({kind:`list`,listType:a,items:i});continue}let i=n[n.length-1];i&&i.kind===`text`?i.lines.push(t[r]):n.push({kind:`text`,lines:[t[r]]}),r++}return n}function nt(e){return tt(e).some(e=>e.kind!==`text`)}const rt=/^(\s*)[*+-]\s(.*)$/,it=/^(\s*)\d+\.\s(.*)$/;function at(e){let t=e.replace(/\t/g,` `),n=rt.exec(t);if(n){let e=n[1].length;return{listType:`bullet`,text:n[2],level:Math.floor(e/2)}}if(n=it.exec(t),n){let e=n[1].length;return{listType:`ordered`,text:n[2],level:Math.floor(e/2)}}}function ot(e){let t=e.trim();return t.startsWith(`|`)&&t.endsWith(`|`)&&t.length>1}function st(e){let t=e.trim();return!t.startsWith(`|`)||!t.endsWith(`|`)?!1:t.slice(1,-1).split(`|`).every(e=>/^\s*:?-+:?\s*$/.test(e))}function ct(e){let t=e.trim(),n=t.startsWith(`|`)?t.slice(1):t;return(n.endsWith(`|`)?n.slice(0,-1):n).split(`|`).map(e=>e.trim())}function lt(e,t){switch(e.type){case`insert_paragraph`:return j(e.target,t)?!e.text||e.text.length===0?{valid:!1,error:`Empty paragraph text`}:[`before`,`after`].includes(e.position)?nt(e.text)?{valid:!1,error:`Markdown tables and lists are not supported in insert_paragraph; use add_table or add_list with afterId`}:{valid:!0}:{valid:!1,error:`Invalid position: ${e.position}`}:{valid:!1,error:`Paragraph "${e.target}" not found`};case`delete_paragraph`:return j(e.target,t)?{valid:!0}:{valid:!1,error:`Paragraph "${e.target}" not found`};case`add_comment`:return j(e.target,t)?!e.text||e.text.length===0?{valid:!1,error:`Empty comment text`}:e.find!==void 0&&e.find.length===0?{valid:!1,error:`Empty find string`}:e.find!==void 0&&e.occurrence!==void 0&&(e.occurrence<1||!Number.isInteger(e.occurrence))?{valid:!1,error:`Invalid occurrence: ${e.occurrence} (must be a positive integer)`}:{valid:!0}:{valid:!1,error:`Paragraph "${e.target}" not found`};case`replace_text`:case`insert_text`:case`delete_text`:case`replace_cell_text`:return j(e.target,t)?`find`in e&&e.find.length===0?{valid:!1,error:`Empty find string`}:e.type===`insert_text`&&e.text.length===0?{valid:!1,error:`Empty insert text`}:`occurrence`in e&&e.occurrence!==void 0&&(e.occurrence<1||!Number.isInteger(e.occurrence))?{valid:!1,error:`Invalid occurrence: ${e.occurrence} (must be a positive integer)`}:{valid:!0}:{valid:!1,error:`Paragraph "${e.target}" not found`};case`add_table_row`:{let n=pt(e.target,t);return n?e.cells.length===0?{valid:!1,error:`Empty cells array`}:e.afterRow<-1||e.afterRow>=n.rows.length?{valid:!1,error:`Invalid afterRow ${e.afterRow} for table "${e.target}" with ${n.rows.length} rows`}:{valid:!0}:{valid:!1,error:`Table "${e.target}" not found`}}case`delete_table_row`:{let n=pt(e.target,t);return n?e.row<0||e.row>=n.rows.length?{valid:!1,error:`Invalid row index ${e.row} for table "${e.target}" with ${n.rows.length} rows`}:{valid:!0}:{valid:!1,error:`Table "${e.target}" not found`}}case`apply_formatting`:return j(e.target,t)?e.find!==void 0&&e.find.length===0?{valid:!1,error:`Empty find string`}:e.find!==void 0&&e.find.length>0&&e.occurrence!==void 0&&(e.occurrence<1||!Number.isInteger(e.occurrence))?{valid:!1,error:`Invalid occurrence: ${e.occurrence} (must be a positive integer)`}:!e.formatting||!Object.values(e.formatting).some(e=>e!==void 0)?{valid:!1,error:`Empty formatting object`}:{valid:!0}:{valid:!1,error:`Paragraph "${e.target}" not found`};case`apply_style`:{if(!j(e.target,t))return{valid:!1,error:`Paragraph "${e.target}" not found`};if(e.find!==void 0&&e.find.length===0)return{valid:!1,error:`Empty find string`};if(e.find!==void 0&&e.find.length>0&&e.occurrence!==void 0&&(e.occurrence<1||!Number.isInteger(e.occurrence)))return{valid:!1,error:`Invalid occurrence: ${e.occurrence} (must be a positive integer)`};if(!e.style||e.style.length===0)return{valid:!1,error:`Empty style ID`};let n=t.styles.find(t=>t.id===e.style);if(!n)return{valid:!1,error:`Style "${e.style}" not found in document styles`};if(e.find!==void 0&&e.find.length>0){if(n.type!==`character`)return{valid:!1,error:`Style "${e.style}" is type "${n.type}", expected "character" when "find" is specified`}}else if(n.type!==`paragraph`)return{valid:!1,error:`Style "${e.style}" is type "${n.type}", expected "paragraph" when "find" is omitted`};return{valid:!0}}case`append_text`:if(!e.text||e.text.length===0)return{valid:!1,error:`Empty append text`};if(e.container){let n=ut(e.container,t);if(!n.valid)return n}return{valid:!0};case`add_table`:{if((!e.rows||e.rows.length===0)&&(!e.headers||e.headers.length===0))return{valid:!1,error:`Table must have at least one row or headers`};let n=e.headers?.length??(e.rows.length>0?e.rows[0].length:0);if(n===0)return{valid:!1,error:`Table must have at least one column`};for(let t=0;t<e.rows.length;t++)if(e.rows[t].length!==n)return{valid:!1,error:`Row ${t} has ${e.rows[t].length} cells, expected ${n}`};if(e.headers&&e.rows.length>0&&e.headers.length!==e.rows[0].length)return{valid:!1,error:`Headers have ${e.headers.length} cells, but rows have ${e.rows[0].length}`};if(e.afterId){if(e.container)return{valid:!1,error:`"afterId" is not supported when "container" is set — container-targeted tables are appended to the end of the header/footer`};if(!_t(e.afterId,t))return{valid:!1,error:`Element "${e.afterId}" not found`}}if(e.container){let n=ut(e.container,t);if(!n.valid)return n}return{valid:!0}}case`add_header`:case`add_footer`:return[`default`,`first`,`even`].includes(e.variant)?!e.paragraphs||e.paragraphs.length===0?{valid:!1,error:`At least one paragraph is required`}:{valid:!0}:{valid:!1,error:`Invalid variant: ${e.variant}`};case`remove_header`:case`remove_footer`:return[`default`,`first`,`even`].includes(e.variant)?{valid:!0}:{valid:!1,error:`Invalid variant: ${e.variant}`};case`add_list`:if(![`bullet`,`ordered`,`multilevel`].includes(e.listType))return{valid:!1,error:`Invalid listType: ${e.listType}`};if(!e.items||e.items.length===0)return{valid:!1,error:`items must be non-empty`};if(e.afterId&&e.container)return{valid:!1,error:`"afterId" is not supported when "container" is set`};if(e.afterId&&!_t(e.afterId,t))return{valid:!1,error:`Element "${e.afterId}" not found`};if(e.container){let n=ut(e.container,t);if(!n.valid)return n}if(e.numId!==void 0){if(!t.xmlParts.numbering)return{valid:!1,error:`numId "${e.numId}" specified but document has no numbering.xml`};let n=t.xmlParts.numbering.find(e=>p(e)===`w:numbering`);if(!(n&&h(n).some(t=>p(t)===`w:num`&&v(t,`w:numId`)===e.numId)))return{valid:!1,error:`numId "${e.numId}" not found in numbering.xml`}}return{valid:!0};case`add_list_item`:{let n=j(e.target,t);return n?n.listInfo?!e.text&&e.text!==``?{valid:!1,error:`text is required`}:[`before`,`after`].includes(e.position)?e.level!==void 0&&e.level<0?{valid:!1,error:`level must be >= 0`}:{valid:!0}:{valid:!1,error:`Invalid position: ${e.position}`}:{valid:!1,error:`Paragraph "${e.target}" is not a list item`}:{valid:!1,error:`Paragraph "${e.target}" not found`}}case`remove_list_item`:{let n=j(e.target,t);return n?n.listInfo?{valid:!0}:{valid:!1,error:`Paragraph "${e.target}" is not a list item`}:{valid:!1,error:`Paragraph "${e.target}" not found`}}case`convert_to_list`:if(![`bullet`,`ordered`,`multilevel`].includes(e.listType))return{valid:!1,error:`Invalid listType: ${e.listType}`};if(!e.targets||e.targets.length===0)return{valid:!1,error:`targets must be non-empty`};for(let n of e.targets)if(!j(n,t))return{valid:!1,error:`Paragraph "${n}" not found`};return{valid:!0};case`remove_list`:if(!e.targets||e.targets.length===0)return{valid:!1,error:`targets must be non-empty`};for(let n of e.targets){let e=j(n,t);if(!e)return{valid:!1,error:`Paragraph "${n}" not found`};if(!e.listInfo)return{valid:!1,error:`Paragraph "${n}" is not a list item`}}return{valid:!0};case`set_list_properties`:{let n=j(e.target,t);return n?n.listInfo?e.listType===void 0&&e.level===void 0?{valid:!1,error:`At least one of listType or level must be provided`}:e.listType!==void 0&&![`bullet`,`ordered`,`multilevel`].includes(e.listType)?{valid:!1,error:`Invalid listType: ${e.listType}`}:e.level!==void 0&&e.level<0?{valid:!1,error:`level must be >= 0`}:{valid:!0}:{valid:!1,error:`Paragraph "${e.target}" is not a list item`}:{valid:!1,error:`Paragraph "${e.target}" not found`}}default:return{valid:!1,error:`Unknown patch type: ${e.type}`}}}function ut(e,t){return[`header`,`footer`].includes(e.type)?[`default`,`first`,`even`].includes(e.variant)?[...(e.type===`header`?t.headers:t.footers).values()].some(t=>t.variant===e.variant)?{valid:!0}:{valid:!1,error:`No ${e.type} with variant "${e.variant}" found`}:{valid:!1,error:`Invalid container variant: ${e.variant}`}:{valid:!1,error:`Invalid container type: ${e.type}`}}function j(e,t){return e.startsWith(`para:`)?dt(e.slice(5),t):ft(t,t=>t.id===e)}function dt(e,t){let n=e.toUpperCase();return ft(t,e=>e.paraId===n)}function ft(e,t){for(let n of e.body){let e=ht(t,n);if(e)return e}for(let n of e.headers.values()){for(let e of n.paragraphs)if(t(e))return e;for(let e of n.tables){let n=gt(t,e);if(n)return n}}for(let n of e.footers.values()){for(let e of n.paragraphs)if(t(e))return e;for(let e of n.tables){let n=gt(t,e);if(n)return n}}}function pt(e,t){for(let n of t.body)if(n.kind===`table`){let t=mt(e,n);if(t)return t}for(let n of t.headers.values())for(let t of n.tables){let n=mt(e,t);if(n)return n}for(let n of t.footers.values())for(let t of n.tables){let n=mt(e,t);if(n)return n}}function mt(e,t){if(t.id===e)return t;for(let n of t.rows)for(let t of n.cells)for(let n of t.nestedTables){let t=mt(e,n);if(t)return t}}function ht(e,t){if(t.kind===`paragraph`)return e(t)?t:void 0;if(t.kind===`table`)return gt(e,t)}function gt(e,t){for(let n of t.rows)for(let t of n.cells){for(let n of t.paragraphs)if(e(n))return n;for(let n of t.nestedTables){let t=gt(e,n);if(t)return t}}}function _t(e,t){if(e.startsWith(`para:`)){let n=e.slice(5).toUpperCase();return t.body.find(e=>e.kind===`paragraph`&&e.paraId===n)}for(let n of t.body)if(n.kind===`paragraph`&&n.id===e||n.kind===`table`&&n.id===e)return n}function M(e,t,n=1){if(t.length===0)return-1;let r=0,i=0;for(;i<=e.length-t.length;){let a=e.indexOf(t,i);if(a===-1)return-1;if(r++,r===n)return a;i=a+1}return-1}function vt(e,t,n){let r=[];for(let i of e){if(i.endOffset<=t||i.startOffset>=n)continue;let e=Math.max(0,t-i.startOffset),a=Math.min(i.text.length,n-i.startOffset);r.push({run:i,localStart:e,localEnd:a,isFullRun:e===0&&a===i.text.length,isStartAligned:e===0,isEndAligned:a===i.text.length})}return r}function yt(e){if(`w:t`in e)return!0;if(`w:br`in e){let t=v(e,`w:type`);return!t||t===`textWrapping`}return!1}function bt(e){let t={text:``,anchored:[]};for(let n of h(e))if(`w:rPr`in n)t.rPr=n;else if(`w:t`in n){let e=n[`w:t`];if(Array.isArray(e))for(let n of e)`#text`in n&&(t.text+=x(String(n[`#text`])))}else yt(n)?t.text+=`
|
|
8
|
+
`:t.anchored.push({node:n,offset:t.text.length});return t}function xt(e,t){let n=h(e);n.length=0,t.rPr&&n.push(t.rPr);let r=[...t.anchored].sort((e,t)=>e.offset-t.offset),i=t.text,a=0,o=``,s=()=>{o.length>0&&n.push(de(o)),o=``};for(let e=0;e<i.length;e++){for(;a<r.length&&r[a].offset<=e;)s(),n.push(r[a].node),a++;let t=i[e];t===`
|
|
9
|
+
`?(s(),n.push({"w:br":[]})):o+=t}for(s();a<r.length;)n.push(r[a].node),a++;i.length===0&&r.length===0&&n.push(de(``))}function N(e){let t={"w:r":[]};return xt(t,{rPr:e.rPr?S(e.rPr):void 0,text:e.text,anchored:e.anchored}),t}function St(e,t,n,r=`before`){let i={rPr:e.rPr,text:e.text.slice(0,t),anchored:[]},a={rPr:e.rPr,text:e.text.slice(t,n),anchored:[]},o={rPr:e.rPr,text:e.text.slice(n),anchored:[]};for(let s of e.anchored)(r===`before`?s.offset<=t:s.offset<t)?i.anchored.push(s):s.offset>=n?o.anchored.push({node:s.node,offset:s.offset-n}):a.anchored.push({node:s.node,offset:s.offset-t});return{before:i,matched:a,after:o}}function Ct(e){return e.text.length>0||e.anchored.length>0}function P(e,t){let n=h(e);return n.includes(t)?n:wt(n,t)}function wt(e,t){for(let n of e){let e=p(n);if(e===`w:hyperlink`||e===`w:ins`||e===`w:del`){let e=h(n);if(e.includes(t))return e;let r=wt(e,t);if(r)return r}}}function F(e,t){if(t.isFullRun)return{matched:t.run.xmlRef};let n=t.run.xmlRef,r=P(e,n);if(!r)throw Error(`Run not found in paragraph children or hyperlink children`);let i=r.indexOf(n),a=St(bt(n),t.localStart,t.localEnd),o={matched:void 0},s=[];if(Ct(a.before)){let e=N(a.before);o.before=e,s.push(e)}let c=N(a.matched);if(o.matched=c,s.push(c),Ct(a.after)){let e=N(a.after);o.after=e,s.push(e)}return r.splice(i,1,...s),o}function Tt(e,t,n,r=`before`){let i=P(e,t);if(!i)throw Error(`Run not found in paragraph children or hyperlink children`);let a=i.indexOf(t),o=St(bt(t),n,n,r),s=[],c={parentChildren:i,index:a};return Ct(o.before)&&(c.before=N(o.before),s.push(c.before),c.index=a+1),Ct(o.after)&&(c.after=N(o.after),s.push(c.after)),i.splice(a,1,...s),c}function I(e,t){if(t.length===0)return[];if(t.length===1)return[F(e,t[0]).matched];let n=[],r=[],i=t[t.length-1];if(!i.isEndAligned){let n=F(e,i);r.push({index:t.length-1,split:n})}let a=t[0];if(!a.isStartAligned){let t=F(e,a);r.push({index:0,split:t})}for(let i=0;i<t.length;i++){let a=t[i],o=r.find(e=>e.index===i);if(o)n.push(o.split.matched);else{let t=P(e,a.run.xmlRef);t&&t.includes(a.run.xmlRef)&&n.push(a.run.xmlRef)}}return n}function Et(e,t){return{nextId:Ot(e)+1,author:t.revisionAuthor??`docxtor`,date:t.revisionDate??new Date().toISOString()}}function L(e){let t=String(e.nextId);return e.nextId++,t}const Dt=new Set([`w:ins`,`w:del`,`w:rPrChange`,`w:pPrChange`,`w:trPrChange`,`w:tblPrChange`,`w:sectPrChange`,`w:cellIns`,`w:cellDel`,`w:cellMerge`]);function Ot(e){let t=0;t=Math.max(t,R(e.xmlParts.document));for(let n of e.xmlParts.headers.values())t=Math.max(t,R(n));for(let n of e.xmlParts.footers.values())t=Math.max(t,R(n));for(let n of[`footnotes`,`endnotes`,`comments`]){let r=e.xmlParts[n];r&&(t=Math.max(t,R(r)))}return t}function R(e){let t=0;for(let n of e){let e=p(n);if(e&&Dt.has(e)){let e=v(n,`w:id`);if(e){let n=parseInt(e,10);!isNaN(n)&&n>t&&(t=n)}}if(e){let e=h(n);e.length>0&&(t=Math.max(t,R(e)))}}return t}function z(e,t){return w(`w:ins`,t,{"w:id":L(e),"w:author":e.author,"w:date":e.date})}function kt(e,t){return w(`w:del`,t,{"w:id":L(e),"w:author":e.author,"w:date":e.date})}function At(e,t){let n=L(e);return w(`w:rPrChange`,[S(t)],{"w:id":n,"w:author":e.author,"w:date":e.date})}function B(e,t){let n=L(e);return w(`w:pPrChange`,[S(t)],{"w:id":n,"w:author":e.author,"w:date":e.date})}function jt(e){return w(`w:ins`,[],{"w:id":L(e),"w:author":e.author,"w:date":e.date})}function Mt(e){return w(`w:del`,[],{"w:id":L(e),"w:author":e.author,"w:date":e.date})}function Nt(e){let t=h(e);for(let e=0;e<t.length;e++){let n=t[e];if(`w:t`in n){let r=n[`w:t`],i=n[`:@`],a={"w:delText":r};i&&(a[`:@`]=i),t[e]=a}else if(`w:instrText`in n){let r={"w:delInstrText":n[`w:instrText`]};n[`:@`]&&(r[`:@`]=n[`:@`]),t[e]=r}}}function Pt(e,t){let n=[];if(t&&n.push(S(t)),e.includes(`
|
|
10
|
+
`)){let t=e.split(`
|
|
11
|
+
`);for(let e=0;e<t.length;e++){let r=t[e];if(r.length>0||e===0){let e={"w:t":[{"#text":b(r)}]};T(r)&&y(e,`xml:space`,`preserve`),n.push(e)}e<t.length-1&&n.push({"w:br":[]})}}else{let t={"w:t":[{"#text":b(e)}]};T(e)&&y(t,`xml:space`,`preserve`),n.push(t)}return{"w:r":n}}const Ft=new Set([`*`,`_`,`~`,`<`,`\\`]);function V(e,t=!0){return t?H(e).map(e=>e.text).join(``):e}function H(e,t=!0){if(!t)return e.length>0?[{text:e}]:[];let n=[],r=0,i=``,a=!1,o=!1,s=!1,c=!1;function l(){if(i.length>0){let e={text:i};a&&(e.bold=!0),o&&(e.italic=!0),s&&(e.strikethrough=!0),c&&(e.underline=!0),n.push(e),i=``}}for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length&&Ft.has(e[r+1])){i+=e[r+1],r+=2;continue}if(e.slice(r,r+3)===`<u>`){l(),c=!0,r+=3;continue}if(e.slice(r,r+4)===`</u>`){l(),c=!1,r+=4;continue}if(e[r]===`~`&&e[r+1]===`~`){l(),s=!s,r+=2;continue}if(e[r]===`*`&&e[r+1]===`*`){l(),a=!a,r+=2;continue}if(e[r]===`_`&&It(e,r,o)){l(),o=!o,r+=1;continue}i+=e[r],r++}return l(),Lt(n)}function It(e,t,n){let r=t>0?e[t-1]:``,i=t+1<e.length?e[t+1]:``;return r===`_`||i===`_`?!1:n?r!==``&&!/\s/.test(r):t===0||/\W/.test(r)?i!==``&&!/\s/.test(i):t===e.length-1||/\W/.test(i)}function Lt(e){if(e.length<=1)return e;let t=[e[0]];for(let n=1;n<e.length;n++){let r=t[t.length-1],i=e[n];!!r.bold==!!i.bold&&!!r.italic==!!i.italic&&!!r.strikethrough==!!i.strikethrough&&!!r.underline==!!i.underline?r.text+=i.text:t.push(i)}return t}function Rt(e,t){if(C(e,t))return;let n=h(e);for(let e of n){let n=p(e);if(n===`w:hyperlink`||n===`w:ins`||n===`w:del`){if(C(e,t))return;let n=h(e);for(let e of n){let n=p(e);if((n===`w:hyperlink`||n===`w:ins`||n===`w:del`)&&C(e,t))return}}}}function zt(e,t){let n=h(e);if(!n.includes(t))for(let e of n){let n=p(e);if(n===`w:hyperlink`||n===`w:ins`||n===`w:del`){let n=h(e);if(n.includes(t))return e;for(let e of n){let n=p(e);if((n===`w:hyperlink`||n===`w:ins`||n===`w:del`)&&h(e).includes(t))return e}}}}function Bt(e,t,n,r=!0){let i=t.occurrence??1,a=V(t.find,r),o=M(e.text,a,i);if(o===-1)throw Error(`Text "${a}" not found in paragraph "${e.id}" (occurrence ${i})`);let s=o+a.length,c=vt(e.runs,o,s);if(c.length===0)throw Error(`No runs found for text range [${o}, ${s}] in paragraph "${e.id}"`);n?Ht(e,t,c,n,r):Vt(e,t,c,r)}function Vt(e,t,n,r){let i=H(t.replace,r),a=i.some(e=>e.bold||e.italic||e.strikethrough||e.underline),o=V(t.replace,r);if(n.length===1){let t=n[0],r=F(e.xmlRef,t);a?$t(e.xmlRef,r.matched,i):en(r.matched,o)}else{let t=I(e.xmlRef,n);if(t.length===0)throw Error(`Failed to isolate matched runs in paragraph "${e.id}"`);a?$t(e.xmlRef,t[0],i):en(t[0],o);for(let n=1;n<t.length;n++){let r=bt(t[n]);r.anchored.length>0?xt(t[n],{...r,text:``}):Rt(e.xmlRef,t[n])}}}function Ht(e,t,n,r,i){let a;if(n.length===1){let t=n[0];a=[F(e.xmlRef,t).matched]}else a=I(e.xmlRef,n);if(a.length===0)throw Error(`Failed to isolate matched runs in paragraph "${e.id}"`);let o=g(a[0],`w:rPr`),s=H(t.replace,i),c=s.some(e=>e.bold||e.italic||e.strikethrough||e.underline),l=V(t.replace,i),u=[];s.length>0&&l.length>0&&(u=c?Qt(s,o):[Pt(l,o)]);let d=Ut(e.xmlRef,a,r);u.length!==0&&(d.container?Wt(e.xmlRef,d.container,d.index,u,r):d.parentChildren.splice(d.index,0,z(r,u)))}function Ut(e,t,n){let r,i=[];for(let n of t){let t=P(e,n);if(!t)throw Error(`Matched run not found in paragraph`);let a=zt(e,n),o=a!=null&&p(a)===`w:ins`,s=t.indexOf(n);if(t.splice(s,1),o){let n=!0,i,o=-1;t.length===0&&(i=P(e,a),i&&(o=i.indexOf(a),i.splice(o,1),n=!1)),r||=n?{parentChildren:t,index:s,container:a}:{parentChildren:i,index:o};continue}let c=i[i.length-1];c&&c.parent===t&&c.index===s?c.runs.push(n):i.push({parent:t,index:s,runs:[n]})}for(let e=i.length-1;e>=0;e--){let t=i[e],r=t.runs.map(e=>{let t=S(e);return Nt(t),t});t.parent.splice(t.index,0,kt(n,r))}if(!r){let e=i[0];r={parentChildren:e.parent,index:e.index+1}}return r}function Wt(e,t,n,r,i){let a=h(t),o=P(e,t);if(!o)throw Error(`Insertion container not found in paragraph`);let s=o.indexOf(t);if(r.length===0){a.length===0&&o.splice(s,1);return}if(v(t,`w:author`)===i.author){a.splice(n,0,...r);return}let c=a.splice(n),l=[];if(a.length>0&&l.push(t),l.push(z(i,r)),c.length>0){let e=w(`w:ins`,c,{"w:id":L(i),"w:author":v(t,`w:author`)??``,"w:date":v(t,`w:date`)??``});l.push(e)}o.splice(s,1,...l)}function Gt(e,t,n,r=!0){let i=t.occurrence??1,a=V(t.anchor,r),o=M(e.text,a,i);if(o===-1)throw Error(`Anchor text "${a}" not found in paragraph "${e.id}" (occurrence ${i})`);let s=t.position===`before`?o:o+a.length;n?qt(e,t,s,n,r):Kt(e,t,s,r)}function Kt(e,t,n,r){let i;for(let t of e.runs)if(n>=t.startOffset&&n<=t.endOffset){i=t;break}if(!i){let t=e.runs[e.runs.length-1];if(!t)throw Error(`No runs found in paragraph "${e.id}" for insertion`);i=t}let a=H(t.text,r);if(a.some(e=>e.bold||e.italic||e.strikethrough||e.underline)){let r=n-i.startOffset,o=Qt(a,g(i.xmlRef,`w:rPr`)),s=Tt(e.xmlRef,i.xmlRef,r,Jt(t));s.parentChildren.splice(s.index,0,...o)}else{let e=V(t.text,r),a=n-i.startOffset,o=re(i.xmlRef),s=o.slice(0,a)+e+o.slice(a),c=Jt(t);en(i.xmlRef,s,t=>t<a||t===a&&c===`before`?t:t+e.length)}}function qt(e,t,n,r,i){let a;for(let t of e.runs)if(n>=t.startOffset&&n<=t.endOffset){a=t;break}if(!a){let t=e.runs[e.runs.length-1];if(!t)throw Error(`No runs found in paragraph "${e.id}" for insertion`);a=t}let o=n-a.startOffset,s=g(a.xmlRef,`w:rPr`),c=H(t.text,i),l=c.some(e=>e.bold||e.italic||e.strikethrough||e.underline),u;u=l?Qt(c,s):[Pt(V(t.text,i),s)];let d=z(r,u),f=P(e.xmlRef,a.xmlRef);if(!f)throw Error(`Target run not found in paragraph`);let p=f.indexOf(a.xmlRef),m=o===0,h=o===a.text.length;if(m)f.splice(p,0,d);else if(h)f.splice(p+1,0,d);else{let n=Tt(e.xmlRef,a.xmlRef,o,Jt(t));n.parentChildren.splice(n.index,0,d)}}function Jt(e){return e.position===`after`?`after`:`before`}function Yt(e,t){let n=[];if(t&&n.push(S(t)),e.includes(`
|
|
12
|
+
`)){let t=e.split(`
|
|
13
|
+
`);for(let e=0;e<t.length;e++){let r=t[e];if(r.length>0||e===0){let e={"w:t":[{"#text":b(r)}]};T(r)&&y(e,`xml:space`,`preserve`),n.push(e)}e<t.length-1&&n.push({"w:br":[]})}}else{let t={"w:t":[{"#text":b(e)}]};T(e)&&y(t,`xml:space`,`preserve`),n.push(t)}return{"w:r":n}}function Xt(e,t,n,r=!0){n?Zt(e,t,n,r):Bt(e,{type:`replace_text`,target:t.target,find:t.find,replace:``,occurrence:t.occurrence},void 0,r)}function Zt(e,t,n,r){let i=t.occurrence??1,a=V(t.find,r),o=M(e.text,a,i);if(o===-1)throw Error(`Text "${a}" not found in paragraph "${e.id}" (occurrence ${i})`);let s=o+a.length,c=vt(e.runs,o,s);if(c.length===0)throw Error(`No runs found for text range [${o}, ${s}] in paragraph "${e.id}"`);let l;if(c.length===1){let t=c[0];l=[F(e.xmlRef,t).matched]}else l=I(e.xmlRef,c);if(l.length===0)throw Error(`Failed to isolate matched runs in paragraph "${e.id}"`);Ut(e.xmlRef,l,n)}function Qt(e,t){let n=[];for(let r of e){if(r.text.length===0)continue;let e=Yt(r.text,t);if(r.bold||r.italic||r.strikethrough||r.underline){let t=g(e,`w:rPr`);t||(t=w(`w:rPr`,[]),h(e).unshift(t));let n=h(t);r.bold&&!g(t,`w:b`)&&n.push(w(`w:b`,[])),r.italic&&!g(t,`w:i`)&&n.push(w(`w:i`,[])),r.strikethrough&&!g(t,`w:strike`)&&n.push(w(`w:strike`,[])),r.underline&&!g(t,`w:u`)&&n.push(w(`w:u`,[],{"w:val":`single`}))}n.push(e)}return n}function $t(e,t,n){let r=bt(t),i=Qt(n,r.rPr);if(i.length===0){en(t,``);return}let a=r.anchored.filter(e=>e.offset<=0).map(e=>e.node),o=r.anchored.filter(e=>e.offset>0).map(e=>e.node);if(a.length>0){let e=h(i[0]),t=+(e.length>0&&`w:rPr`in e[0]);e.splice(t,0,...a)}o.length>0&&h(i[i.length-1]).push(...o);let s=P(e,t);if(s){let e=s.indexOf(t);if(e!==-1){s.splice(e,1,...i);return}}en(t,n.map(e=>e.text).join(``))}function en(e,t,n){let r=bt(e),i=ie(e);if(i!==void 0&&r.anchored.length===0&&!t.includes(`
|
|
14
|
+
`)&&!r.text.includes(`
|
|
15
|
+
`)&&h(e).filter(e=>`w:t`in e).length===1){let e=i[`w:t`];if(Array.isArray(e)){let n=e.find(e=>`#text`in e);n?ne(n,t):e.push({"#text":b(t)})}T(t)&&y(i,`xml:space`,`preserve`);return}let a=n??(e=>e<=0?0:t.length);xt(e,{rPr:r.rPr,text:t,anchored:r.anchored.map(e=>({node:e.node,offset:a(e.offset)}))})}function tn(e,t,n){if(e.rows.length===0)throw Error(`Table "${e.id}" has no rows to clone from`);if(t.afterRow<-1||t.afterRow>=e.rows.length)throw Error(`Invalid afterRow ${t.afterRow} for table "${e.id}" with ${e.rows.length} rows`);let r=t.afterRow>=0?t.afterRow:0,i=e.rows[r];if(t.cells.length!==i.cells.length)throw Error(`Cell count mismatch: patch has ${t.cells.length} cells, but row has ${i.cells.length} cells`);let a=S(i.xmlRef),o=_(a,`w:tc`);for(let e=0;e<o.length;e++){let n=o[e],r=t.cells[e],i=g(n,`w:p`);if(i){let e=h(i),t=e.filter(e=>`w:r`in e||`w:ins`in e||`w:del`in e);for(let n of t){let t=e.indexOf(n);t!==-1&&e.splice(t,1)}let n={"w:t":[{"#text":b(r)}]};T(r)&&(n[`:@`]||={},n[`:@`][`@_xml:space`]=`preserve`);let a={"w:r":[n]};e.push(a)}}let s=h(e.xmlRef);if(t.afterRow===-1){let e=s.find(e=>`w:tr`in e);if(e){let t=s.indexOf(e);s.splice(t,0,a)}else s.push(a)}else le(e.xmlRef,i.xmlRef,a);if(n){let e=h(a),t=e.find(e=>`w:trPr`in e);t||(t=w(`w:trPr`,[]),e.unshift(t)),h(t).push(jt(n))}return a}function nn(e,t,n){if(t.row<0||t.row>=e.rows.length)throw Error(`Invalid row index ${t.row} for table "${e.id}" with ${e.rows.length} rows`);let r=e.rows[t.row];if(n){let e=h(r.xmlRef),t=e.find(e=>`w:trPr`in e);t||(t=w(`w:trPr`,[]),e.unshift(t)),h(t).push(Mt(n))}else C(e.xmlRef,r.xmlRef)}function rn(e,t,n,r=!0){Bt(e,{type:`replace_text`,target:t.target,find:t.find,replace:t.replace,occurrence:t.occurrence},n,r)}function an(e,t){let n=e?.length??(t.length>0?t[0].length:0),r={"w:val":`single`,"w:sz":`4`,"w:space":`0`,"w:color":`auto`},i=w(`w:tblBorders`,[w(`w:top`,[],r),w(`w:left`,[],r),w(`w:bottom`,[],r),w(`w:right`,[],r),w(`w:insideH`,[],r),w(`w:insideV`,[],r)]),a=w(`w:tblPr`,[w(`w:tblStyle`,[],{"w:val":`TableGrid`}),w(`w:tblW`,[],{"w:w":`0`,"w:type":`auto`}),i,w(`w:tblLook`,[],{"w:val":`04A0`,"w:firstRow":`1`,"w:lastRow":`0`,"w:firstColumn":`1`,"w:lastColumn":`0`,"w:noHBand":`0`,"w:noVBand":`1`})]),o=[];for(let e=0;e<n;e++)o.push(w(`w:gridCol`,[]));let s=w(`w:tblGrid`,o),c=[];e&&c.push(on(e));for(let e of t)c.push(on(e));return w(`w:tbl`,[a,s,...c])}function on(e){let t=[];for(let n of e){let e={"w:t":[{"#text":b(n)}]};T(n)&&(e[`:@`]||={},e[`:@`][`@_xml:space`]=`preserve`);let r={"w:p":[{"w:r":[e]}]},i=w(`w:tc`,[w(`w:tcPr`,[w(`w:tcW`,[],{"w:w":`0`,"w:type":`auto`})]),r]);t.push(i)}return w(`w:tr`,t)}function sn(e,t,n){t.find!==void 0&&t.find.length>0?cn(e,t.find,t.occurrence??1,t.formatting,n):ln(e,t.formatting,n)}function cn(e,t,n,r,i){let a=M(e.text,t,n);if(a===-1)throw Error(`Text "${t}" not found in paragraph "${e.id}" (occurrence ${n})`);let o=a+t.length,s=vt(e.runs,a,o);if(s.length===0)throw Error(`No runs found for text range [${a}, ${o}] in paragraph "${e.id}"`);let c=I(e.xmlRef,s);for(let e of c)un(e,r,i)}function ln(e,t,n){for(let r of e.runs)un(r.xmlRef,t,n)}function un(e,t,n){let r=Object.entries(t).some(([,e])=>e!==null&&e!==!1&&e!==void 0),i=g(e,`w:rPr`);if(!i&&!r)return;let a=n&&i?S(i):void 0;if(i||(i=w(`w:rPr`),h(e).unshift(i)),t.bold!==void 0&&dn(i,`w:b`,t.bold),t.italic!==void 0&&dn(i,`w:i`,t.italic),t.strikethrough!==void 0&&dn(i,`w:strike`,t.strikethrough),t.underline!==void 0&&fn(i,`w:u`,`w:val`,t.underline),t.fontSize!==void 0&&fn(i,`w:sz`,`w:val`,t.fontSize===null?null:String(t.fontSize)),t.fontFamily!==void 0&&pn(i,t.fontFamily),t.color!==void 0&&fn(i,`w:color`,`w:val`,t.color),t.highlight!==void 0&&fn(i,`w:highlight`,`w:val`,t.highlight),n){let e=g(i,`w:rPrChange`);e&&C(i,e);let t=At(n,a??w(`w:rPr`));h(i).push(t)}}function dn(e,t,n){let r=g(e,t);n===!0?r||h(e).push(w(t)):r&&C(e,r)}function fn(e,t,n,r){let i=g(e,t);if(r!==null)if(i)y(i,n,r);else{let i=w(t,[],{[n]:r});h(e).push(i)}else i&&C(e,i)}function pn(e,t){let n=g(e,`w:rFonts`);if(t!==null)if(n)y(n,`w:ascii`,t),y(n,`w:hAnsi`,t);else{let n=w(`w:rFonts`,[],{"w:ascii":t,"w:hAnsi":t});h(e).push(n)}else n&&(ee(n,`w:ascii`),ee(n,`w:hAnsi`),Object.keys(te(n)).length===0&&C(e,n))}function mn(e,t,n,r){let i=n.styles.find(e=>e.id===t.style);if(!i)throw Error(`Style "${t.style}" not found in document styles.xml`);if(t.find!==void 0&&t.find.length>0){if(i.type!==`character`)throw Error(`Style "${t.style}" is type "${i.type}", but character style is required when "find" is specified`);gn(e,t.find,t.occurrence??1,t.style,r)}else{if(i.type!==`paragraph`)throw Error(`Style "${t.style}" is type "${i.type}", but paragraph style is required when "find" is omitted`);hn(e,t.style,r)}}function hn(e,t,n){let r=e.xmlRef,i=g(r,`w:pPr`),a=n&&i?S(i):void 0;i||(i=w(`w:pPr`),h(r).unshift(i));let o=g(i,`w:pStyle`);if(o?y(o,`w:val`,t):(o=w(`w:pStyle`,[],{"w:val":t}),h(i).unshift(o)),n){let e=g(i,`w:pPrChange`);e&&C(i,e);let t=B(n,a??w(`w:pPr`));h(i).push(t)}}function gn(e,t,n,r,i){let a=M(e.text,t,n);if(a===-1)throw Error(`Text "${t}" not found in paragraph "${e.id}" (occurrence ${n})`);let o=a+t.length,s=vt(e.runs,a,o);if(s.length===0)throw Error(`No runs found for text range [${a}, ${o}] in paragraph "${e.id}"`);let c=I(e.xmlRef,s);for(let e of c)_n(e,r,i)}function _n(e,t,n){let r=g(e,`w:rPr`),i=n&&r?S(r):void 0;r||(r=w(`w:rPr`),h(e).unshift(r));let a=g(r,`w:rStyle`);a&&C(r,a);let o=w(`w:rStyle`,[],{"w:val":t});if(h(r).unshift(o),n){let e=g(r,`w:rPrChange`);e&&C(r,e);let t=At(n,i??w(`w:rPr`));h(r).push(t)}}const vn=new Set([`PAGE`,`NUMPAGES`,`DATE`,`TIME`,`FILENAME`]);function yn(e){let t=[],n=/\{\{(\w+)\}\}/g,r=0,i;for(;(i=n.exec(e))!==null;){let n=i[1];vn.has(n)&&(i.index>r&&t.push({kind:`text`,text:e.slice(r,i.index)}),t.push({kind:`field`,fieldCode:n}),r=i.index+i[0].length)}return r<e.length&&t.push({kind:`text`,text:e.slice(r)}),t.length===0&&t.push({kind:`text`,text:e}),t}function bn(e){if(!e.includes(``))return``;for(let t=57344;t<=63743;t++){let n=String.fromCharCode(t);if(!e.includes(n))return n}throw Error(`Cannot find a placeholder character for field codes`)}function U(e,t,n=!0){let r=yn(e);if(r.length===1&&r[0].kind===`text`)return xn(H(r[0].text,n),t);let i=r.filter(e=>e.kind===`field`).map(e=>e.fieldCode),a=bn(e),o=H(r.map(e=>e.kind===`text`?e.text:a).join(``),n),s=[],c=[],l=0,u=()=>{c.length>0&&(s.push(...xn(c,t)),c=[])};for(let e of o){let n=e.text.split(a);for(let r=0;r<n.length;r++){let a=n[r];if(a.length>0&&c.push({...e,text:a}),r<n.length-1){u();let n=Cn(t,{bold:!!e.bold,italic:!!e.italic,strikethrough:!!e.strikethrough,underline:!!e.underline});s.push(...Sn(i[l++],n))}}}return u(),s}function xn(e,t){if(e.some(e=>e.bold||e.italic||e.strikethrough||e.underline))return Qt(e,t);let n=e.map(e=>e.text).join(``);return n.length>0?[fe(n,t)]:[]}function Sn(e,t){let n=()=>t?[JSON.parse(JSON.stringify(t))]:[],r={"w:r":[...n(),w(`w:fldChar`,[],{"w:fldCharType":`begin`})]},i={"w:instrText":[{"#text":` ${e} `}]};return y(i,`xml:space`,`preserve`),[r,{"w:r":[...n(),i]},{"w:r":[...n(),w(`w:fldChar`,[],{"w:fldCharType":`separate`})]},{"w:r":[...n(),w(`w:fldChar`,[],{"w:fldCharType":`end`})]}]}function Cn(e,t){let n=t.bold||t.italic||t.strikethrough||t.underline;if(!e&&!n)return;let r=e?JSON.parse(JSON.stringify(e)):w(`w:rPr`,[]);if(!n)return r;let i=h(r);return t.bold&&!i.some(e=>`w:b`in e)&&i.push(w(`w:b`,[])),t.italic&&!i.some(e=>`w:i`in e)&&i.push(w(`w:i`,[])),t.strikethrough&&!i.some(e=>`w:strike`in e)&&i.push(w(`w:strike`,[])),t.underline&&!i.some(e=>`w:u`in e)&&i.push(w(`w:u`,[],{"w:val":`single`})),r}const wn={default:`default`,first:`first`,even:`even`};function Tn(e,t,n,r=!0){kn(e,`header`,t.variant,t.paragraphs,n,r)}function En(e,t,n,r=!0){kn(e,`footer`,t.variant,t.paragraphs,n,r)}function Dn(e,t){An(e,`header`,t.variant)}function On(e,t){An(e,`footer`,t.variant)}function kn(e,t,n,r,i,a=!0){let o=t===`header`?e.xmlParts.headers:e.xmlParts.footers,s=`${t}${jn(o,t)}.xml`,c=`word/${s}`,l=t===`header`?`w:hdr`:`w:ftr`,u=[];for(let e of r){let t=U(e,void 0,a);if(i){let e=z(i,t.map(e=>e));u.push({"w:p":[e]})}else u.push({"w:p":t})}let d=[w(l,u,{"xmlns:w":`http://schemas.openxmlformats.org/wordprocessingml/2006/main`,"xmlns:r":`http://schemas.openxmlformats.org/officeDocument/2006/relationships`})],f=Mn(e);Nn(e,f,s,t),In(e,c,t),zn(e,t,n,f),o.set(c,d);let p=De(d,t,n,f);t===`header`?e.headers.set(f,p):e.footers.set(f,p)}function An(e,t,n){let r=t===`header`?`w:headerReference`:`w:footerReference`,i=Rn(e);if(!i)throw Error(`No sectPr found in document`);let a=h(i),o=a.find(e=>p(e)===r?(v(e,`w:type`)??`default`)===wn[n]:!1);if(!o)throw Error(`No ${t} with variant "${n}" found in sectPr`);let s=v(o,`r:id`);if(!s)throw Error(`${t} reference has no r:id`);let c=a.indexOf(o);c!==-1&&a.splice(c,1);let l=Pn(e,s),u=l?`word/${l}`:void 0;Fn(e,s),u&&Ln(e,u);let d=t===`header`?e.xmlParts.headers:e.xmlParts.footers;u&&d.delete(u),t===`header`?e.headers.delete(s):e.footers.delete(s)}function jn(e,t){let n=0,r=RegExp(`${t}(\\d+)\\.xml$`,`i`);for(let t of e.keys()){let e=t.match(r);if(e){let t=parseInt(e[1],10);t>n&&(n=t)}}return n+1}function Mn(e){let t=e.xmlParts.documentRels;if(!t)return`rId1`;let n=0,r=t.find(e=>p(e)===`Relationships`);if(r){let e=_(r,`Relationship`);for(let t of e){let e=v(t,`Id`);if(e){let t=parseInt(e.replace(/^rId/,``),10);!isNaN(t)&&t>n&&(n=t)}}}return`rId${n+1}`}function Nn(e,t,n,r){e.xmlParts.documentRels||(e.xmlParts.documentRels=[w(`Relationships`,[],{xmlns:`http://schemas.openxmlformats.org/package/2006/relationships`})]);let i=w(`Relationship`,[],{Id:t,Type:r===`header`?`http://schemas.openxmlformats.org/officeDocument/2006/relationships/header`:`http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer`,Target:n}),a=e.xmlParts.documentRels.find(e=>p(e)===`Relationships`);a&&h(a).push(i)}function Pn(e,t){let n=e.xmlParts.documentRels;if(!n)return;let r=n.find(e=>p(e)===`Relationships`);if(!r)return;let i=_(r,`Relationship`);for(let e of i)if(v(e,`Id`)===t)return v(e,`Target`)}function Fn(e,t){let n=e.xmlParts.documentRels;if(!n)return;let r=n.find(e=>p(e)===`Relationships`);if(!r)return;let i=h(r),a=i.findIndex(e=>p(e)===`Relationship`&&v(e,`Id`)===t);a!==-1&&i.splice(a,1)}function In(e,t,n){if(!e.xmlParts.contentTypes)return;let r=n===`header`?`application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml`:`application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml`,i=w(`Override`,[],{PartName:`/${t}`,ContentType:r}),a=e.xmlParts.contentTypes.find(e=>p(e)===`Types`);a&&h(a).push(i)}function Ln(e,t){if(!e.xmlParts.contentTypes)return;let n=e.xmlParts.contentTypes.find(e=>p(e)===`Types`);if(!n)return;let r=h(n),i=r.findIndex(e=>{if(p(e)!==`Override`)return!1;let n=v(e,`PartName`);return n===`/${t}`||n===t});i!==-1&&r.splice(i,1)}function Rn(e){let t=e.xmlParts.document.find(e=>p(e)===`w:document`);if(!t)return;let n=g(t,`w:body`);if(!n)return;let r=h(n);for(let e=r.length-1;e>=0;e--)if(p(r[e])===`w:sectPr`)return r[e]}function zn(e,t,n,r){let i=Rn(e);if(!i){i=w(`w:sectPr`,[]);let t=e.xmlParts.document.find(e=>p(e)===`w:document`);if(!t)throw Error(`Cannot find w:document`);let n=g(t,`w:body`);if(!n)throw Error(`Cannot find w:body`);h(n).push(i)}let a=w(t===`header`?`w:headerReference`:`w:footerReference`,[],{"w:type":wn[n],"r:id":r});if(h(i).unshift(a),n===`first`){let e=h(i);e.some(e=>p(e)===`w:titlePg`)||e.push(w(`w:titlePg`,[]))}n===`even`&&Bn(e)}function Bn(e){e.xmlParts.settings||(e.xmlParts.settings=[w(`w:settings`,[w(`w:evenAndOddHeaders`,[])],{"xmlns:w":`http://schemas.openxmlformats.org/wordprocessingml/2006/main`})]);let t=e.xmlParts.settings.find(e=>p(e)===`w:settings`);if(!t)return;let n=h(t);n.some(e=>p(e)===`w:evenAndOddHeaders`)||n.push(w(`w:evenAndOddHeaders`,[])),Vn(e),Hn(e)}function Vn(e){e.xmlParts.documentRels||(e.xmlParts.documentRels=[w(`Relationships`,[],{xmlns:`http://schemas.openxmlformats.org/package/2006/relationships`})]);let t=e.xmlParts.documentRels.find(e=>p(e)===`Relationships`);if(!t)return;let n=`http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings`,r=h(t);r.some(e=>p(e)===`Relationship`?v(e,`Type`)===n&&v(e,`Target`)===`settings.xml`:!1)||r.push(w(`Relationship`,[],{Id:Mn(e),Type:n,Target:`settings.xml`}))}function Hn(e){e.xmlParts.contentTypes||(e.xmlParts.contentTypes=[w(`Types`,[],{xmlns:`http://schemas.openxmlformats.org/package/2006/content-types`})]);let t=e.xmlParts.contentTypes.find(e=>p(e)===`Types`);if(!t)return;let n=`/word/settings.xml`,r=h(t);r.some(e=>p(e)===`Override`?v(e,`PartName`)===n:!1)||r.push(w(`Override`,[],{PartName:n,ContentType:`application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml`}))}function Un(e){let t=e.xmlParts.document.find(e=>p(e)===`w:document`);if(!t)throw Error(`Cannot find w:document in FXP tree`);let n=g(t,`w:body`);if(!n)throw Error(`Cannot find w:body in FXP tree`);return h(n)}function Wn(e,t,n){if(n){let r=e.indexOf(n);if(r!==-1){e.splice(r+1,0,...t);return}}let r=e.findIndex(e=>p(e)===`w:sectPr`);r===-1?e.push(...t):e.splice(r,0,...t)}function Gn(e){let t=-1;for(let n of e.body)if(n.kind===`paragraph`){let e=parseInt(n.id.replace(`p`,``),10);!isNaN(e)&&e>t&&(t=e)}return t+1}function Kn(e,t){let n=Un(e);if(n.includes(t))return n;for(let e of n)if(p(e)===`w:tbl`){let n=qn(e,t);if(n)return n}for(let n of[...e.headers.values(),...e.footers.values()]){let e=n.type===`header`?`w:hdr`:`w:ftr`,r=n.xmlRef.find(t=>p(t)===e);if(r){let e=h(r);if(e.includes(t))return e;for(let n of e)if(p(n)===`w:tbl`){let e=qn(n,t);if(e)return e}}}}function qn(e,t){for(let n of h(e).filter(e=>p(e)===`w:tr`))for(let e of h(n).filter(e=>p(e)===`w:tc`)){let n=h(e);if(n.includes(t))return n;for(let e of n)if(p(e)===`w:tbl`){let n=qn(e,t);if(n)return n}}}function Jn(e,t){let n=e.body.findIndex(e=>e.id===t);if(n!==-1)return{array:e.body,index:n};for(let n of[...e.headers.values(),...e.footers.values()]){let e=n.paragraphs.findIndex(e=>e.id===t);if(e!==-1)return{array:n.paragraphs,index:e}}let r=[];for(let t of e.body)t.kind===`table`&&r.push(t);for(let t of[...e.headers.values(),...e.footers.values()])r.push(...t.tables);for(let e of r){let n=Yn(e,t);if(n)return n}}function Yn(e,t){for(let n of e.rows)for(let e of n.cells){let n=e.paragraphs.findIndex(e=>e.id===t);if(n!==-1)return{array:e.paragraphs,index:n};for(let n of e.nestedTables){let e=Yn(n,t);if(e)return e}}}function Xn(e,t){let n=e.match(/^(.*p)(\d+)$/);if(!n)return`p${Date.now()}`;let r=n[1],i=-1;for(let e of t)if(e.id.startsWith(r)){let t=e.id.slice(r.length),n=parseInt(t,10);!isNaN(n)&&n>i&&(i=n)}return`${r}${i+1}`}function W(e,t){let n=E(t.xmlRef,t.id);t.text=n.text,t.runs=n.runs,t.style=n.style,t.listInfo=n.listInfo,t.revisions=n.revisions,t.paraId=n.paraId,t.hasPageBreak=n.hasPageBreak,t.pageBreakOffset=n.pageBreakOffset,e.xmlParts.numbering&&A(t,e.xmlParts.numbering)}function Zn(e,t,n,r,i=!0){let a=w(`w:pPr`,[w(`w:numPr`,[w(`w:ilvl`,[],{"w:val":String(n)}),w(`w:numId`,[],{"w:val":t})])]),o=U(e,void 0,i),s;return s=r?[a,z(r,o)]:[a,...o],{"w:p":s}}function Qn(e,t,n,r=!0){let i=t.numId??Ne(e,t.listType),a=t.level??0,o=[];for(let e of t.items){let t=typeof e==`string`?e:e.text,s=typeof e==`string`?a:e.level??a;o.push(Zn(t,i,s,n,r))}if(t.container){let n=t.container.type===`header`?e.headers:e.footers;for(let r of n.values())if(r.variant===t.container.variant){let n=r.type===`header`?`w:hdr`:`w:ftr`,i=r.xmlRef.find(e=>p(e)===n);if(i){let n=h(i);O(e,o,i),n.push(...o);let a=t.container.type===`header`?`hdr`:`ftr`,s=r.paragraphs.length;for(let n of o){let i=E(n,`${a}.${t.container.variant}.p${s++}`);e.xmlParts.numbering&&A(i,e.xmlParts.numbering),r.paragraphs.push(i)}}return}return}let s=Un(e),c,l;if(t.afterId){let n=_t(t.afterId,e);n&&(c=n.xmlRef,l=n.id)}O(e,o,k(e,`body`)),Wn(s,o,c);let u=Gn(e),d=l===void 0?-1:e.body.findIndex(e=>e.id===l);for(let t=0;t<o.length;t++){let n=`p${u++}`,r=E(o[t],n);e.xmlParts.numbering&&A(r,e.xmlParts.numbering),d===-1?e.body.push(r):e.body.splice(d+1+t,0,r)}}function $n(e,t,n,r=!0){let i=j(t.target,e),a=i.listInfo.numId,o=t.level??i.listInfo.level,s=Zn(t.text,a,o,n,r);O(e,[s],k(e,i.id));let c=Kn(e,i.xmlRef);if(!c)throw Error(`Cannot find parent container for target paragraph`);let l=c.indexOf(i.xmlRef);if(l===-1)throw Error(`Target xmlRef not found in parent`);t.position===`after`?c.splice(l+1,0,s):c.splice(l,0,s);let u=Jn(e,i.id),d=u?u.array:e.body,f=E(s,Xn(i.id,d));e.xmlParts.numbering&&A(f,e.xmlParts.numbering),u?t.position===`after`?u.array.splice(u.index+1,0,f):u.array.splice(u.index,0,f):e.body.push(f)}function er(e,t,n){let r=j(t.target,e);if(n){let t=h(r.xmlRef),i=g(r.xmlRef,`w:pPr`);if(i){let e=B(n,i);h(i).push(e)}for(let e=t.length-1;e>=0;e--){let r=t[e],i=p(r);if(i===`w:r`){let i=S(r);Nt(i),t[e]=kt(n,[i])}else i===`w:ins`&&t.splice(e,1)}W(e,r);return}let i=Kn(e,r.xmlRef);if(i){let e=i.indexOf(r.xmlRef);e!==-1&&i.splice(e,1)}let a=Jn(e,r.id);a&&a.array.splice(a.index,1)}function tr(e,t,n){let r=Ne(e,t.listType),i=t.level??0;for(let a of t.targets){let t=j(a,e),o=t.xmlRef,s=g(o,`w:pPr`),c=h(o);if(n&&s){let e=B(n,s);h(s).push(e)}s||(s=w(`w:pPr`,[]),c.unshift(s));let l=h(s),u=l.findIndex(e=>p(e)===`w:numPr`);u!==-1&&l.splice(u,1);let d=w(`w:numPr`,[w(`w:ilvl`,[],{"w:val":String(i)}),w(`w:numId`,[],{"w:val":r})]);l.unshift(d),W(e,t)}}function nr(e,t,n){for(let r of t.targets){let t=j(r,e),i=g(t.xmlRef,`w:pPr`);if(!i)continue;if(n){let e=B(n,i);h(i).push(e)}let a=h(i),o=a.findIndex(e=>p(e)===`w:numPr`);o!==-1&&a.splice(o,1),W(e,t)}}function rr(e,t,n){let r=j(t.target,e),i=g(r.xmlRef,`w:pPr`);if(!i)throw Error(`No w:pPr found on target paragraph`);if(n){let e=B(n,i);h(i).push(e)}let a=g(i,`w:numPr`);if(!a)throw Error(`No w:numPr found on target paragraph`);if(t.level!==void 0){let e=g(a,`w:ilvl`);e?y(e,`w:val`,String(t.level)):h(a).unshift(w(`w:ilvl`,[],{"w:val":String(t.level)}))}if(t.listType!==void 0){let n=Ne(e,t.listType),r=g(a,`w:numId`);r?y(r,`w:val`,n):h(a).push(w(`w:numId`,[],{"w:val":n}))}W(e,r)}const ir=new Set([`w:sectPr`,`w:pPrChange`,`w:rPr`]),ar=new Set([`w:ins`,`w:del`,`w:moveFrom`,`w:moveTo`,`w:rPrChange`]);function or(e){let t=g(e,`w:pPr`);if(!t)return;let n=[],r;for(let e of h(t)){let t=p(e);if(t){if(t===`w:rPr`){let t=h(e).filter(e=>{let t=p(e);return t!==void 0&&!ar.has(t)}).map(S);t.length>0&&(r=w(`w:rPr`,t));continue}ir.has(t)||n.push(S(e))}}if(r&&n.push(r),n.length!==0)return w(`w:pPr`,n)}function sr(e){let t=e.runs[e.runs.length-1];if(!t)return;let n=g(t.xmlRef,`w:rPr`);if(!n)return;let r=h(n).filter(e=>p(e)!==`w:rPrChange`).map(S);if(r.length!==0)return w(`w:rPr`,r)}function cr(e,t,n){let r=g(e,`w:pPr`);r||(r=w(`w:pPr`,[]),h(e).unshift(r));let i=h(r),a=g(r,`w:rPr`);if(!a){a=w(`w:rPr`,[]);let e=i.findIndex(e=>{let t=p(e);return t===`w:sectPr`||t===`w:pPrChange`});e===-1?i.push(a):i.splice(e,0,a)}let o=w(`w:${t}`,[],{"w:id":L(n),"w:author":n.author,"w:date":n.date});h(a).unshift(o)}function lr(e,t){let n=g(e,`w:pPr`);if(!n)return;let r=g(n,`w:rPr`);if(r)return g(r,`w:${t}`)}function ur(e,t,n,r){let i=t.inheritStyle??!0,a=i?or(e.xmlRef):void 0,o=i?sr(e):void 0,s=t.text.split(`
|
|
16
|
+
`),c=[];for(let e of s){let t=[];a&&t.push(S(a));let i=U(e,o,r);n?i.length>0&&t.push(z(n,i)):t.push(...i);let s={"w:p":t};n&&cr(s,`ins`,n),c.push(s)}return c}function dr(e,t,n,r,i=!0){let a=Kn(e,t.xmlRef);if(!a)throw Error(`Cannot find parent container for paragraph "${t.id}"`);let o=a.indexOf(t.xmlRef);if(o===-1)throw Error(`Paragraph "${t.id}" not found in its parent`);let s=ur(t,n,r,i);O(e,s,k(e,t.id));let c=n.position===`after`?o+1:o;a.splice(c,0,...s);let l=Jn(e,t.id);if(!l)throw Error(`Paragraph "${t.id}" not found in normalized document`);let u=n.position===`after`?l.index+1:l.index,d=[];for(let n=0;n<s.length;n++){let r=Xn(t.id,l.array),i=E(s[n],r);e.xmlParts.numbering&&A(i,e.xmlParts.numbering),l.array.splice(u+n,0,i),d.push(i)}return d}const fr=new Set([`w:hyperlink`,`w:smartTag`,`w:customXml`,`w:dir`,`w:bdo`,`w:moveTo`,`w:sdtContent`,`w:fldSimple`]);function pr(e,t){let n=0;for(;n<e.length;){let r=e[n],i=p(r);if(i===`w:r`){let r=n;for(;r<e.length&&p(e[r])===`w:r`;)r++;let i=e.slice(n,r);for(let e of i)Nt(e);e.splice(n,r-n,kt(t,i)),n++;continue}if(i===`w:ins`){if(v(r,`w:author`)===t.author){e.splice(n,1);continue}pr(h(r),t),n++;continue}if(i===`w:sdt`){let e=g(r,`w:sdtContent`);e&&pr(h(e),t),n++;continue}i&&fr.has(i)&&pr(h(r),t),n++}}function mr(e,t){let n=lr(e,`ins`);if(!n||v(n,`w:author`)!==t)return!1;let r=e=>{for(let n of e){let e=p(n);if(e===`w:r`)return!1;if(e===`w:ins`){if(v(n,`w:author`)!==t)return!1;continue}if(e===`w:del`||e===`w:moveFrom`)return!1;if(e===`w:sdt`){let e=g(n,`w:sdtContent`);if(e&&!r(h(e)))return!1;continue}if(e&&fr.has(e)&&!r(h(n)))return!1}return!0};return r(h(e))}function hr(e,t){let n=Kn(e,t.xmlRef);if(!n)throw Error(`Cannot find parent container for paragraph "${t.id}"`);let r=Jn(e,t.id);if(!r)throw Error(`Paragraph "${t.id}" not found in normalized document`);let i=r.array===e.body;if(n.filter(e=>{let t=p(e);return t===`w:p`||i&&t===`w:tbl`}).length===1){let n=h(t.xmlRef),r=g(t.xmlRef,`w:pPr`);n.length=0,r&&n.push(r),W(e,t);return}let a=n.indexOf(t.xmlRef);a!==-1&&n.splice(a,1),r.array.splice(r.index,1)}function gr(e,t,n,r){if(!r){hr(e,t);return}if(mr(t.xmlRef,r.author)){hr(e,t);return}pr(h(t.xmlRef),r),lr(t.xmlRef,`del`)||cr(t.xmlRef,`del`,r),W(e,t)}function _r(){return[{"?xml":[{"#text":``}],":@":{"@_version":`1.0`,"@_encoding":`UTF-8`,"@_standalone":`yes`}},w(`Relationships`,[],{xmlns:`http://schemas.openxmlformats.org/package/2006/relationships`})]}function vr(){return[w(`Types`,[w(`Default`,[],{Extension:`rels`,ContentType:`application/vnd.openxmlformats-package.relationships+xml`}),w(`Default`,[],{Extension:`xml`,ContentType:`application/xml`})],{xmlns:`http://schemas.openxmlformats.org/package/2006/content-types`})]}function yr(e){return e.find(e=>p(e)===`Relationships`)}function br(e){return e.find(e=>p(e)===`Types`)}function xr(e){let t=0,n=yr(e);if(n)for(let e of _(n,`Relationship`)){let n=v(e,`Id`);if(n){let e=parseInt(n.replace(/^rId/,``),10);!isNaN(e)&&e>t&&(t=e)}}return`rId${t+1}`}function Sr(e,t,n){let r=yr(e);if(!r)throw Error(`Relationships root not found`);for(let e of _(r,`Relationship`))if(v(e,`Type`)===t&&v(e,`Target`)===n)return v(e,`Id`)??``;let i=xr(e);return h(r).push(w(`Relationship`,[],{Id:i,Type:t,Target:n})),i}function Cr(e,t){if(!e)return[];let n=yr(e);if(!n)return[];let r=h(n),i=[];for(let e=r.length-1;e>=0;e--){let n=r[e];p(n)===`Relationship`&&v(n,`Type`)===t&&(i.push(v(n,`Target`)??``),r.splice(e,1))}return i}function wr(e,t,n){let r=br(e);if(!r)return;let i=t.startsWith(`/`)?t:`/${t}`;_(r,`Override`).some(e=>v(e,`PartName`)===i)||h(r).push(w(`Override`,[],{PartName:i,ContentType:n}))}function Tr(e,t){if(!e)return;let n=br(e);if(!n)return;let r=h(n),i=t.startsWith(`/`)?t:`/${t}`,a=r.findIndex(e=>p(e)===`Override`&&v(e,`PartName`)===i);a!==-1&&r.splice(a,1)}function Er(e){e.xmlParts.comments||(e.xmlParts.comments=[{"?xml":[{"#text":``}],":@":{"@_version":`1.0`,"@_encoding":`UTF-8`,"@_standalone":`yes`}},w(`w:comments`,[],{"xmlns:w":`http://schemas.openxmlformats.org/wordprocessingml/2006/main`,"xmlns:r":`http://schemas.openxmlformats.org/officeDocument/2006/relationships`})],e.xmlParts.documentRels||(e.xmlParts.documentRels=_r()),Sr(e.xmlParts.documentRels,`http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments`,`comments.xml`),e.xmlParts.contentTypes||(e.xmlParts.contentTypes=vr()),wr(e.xmlParts.contentTypes,`/word/comments.xml`,`application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml`));let t=e.xmlParts.comments.find(e=>p(e)===`w:comments`);if(!t)throw Error(`word/comments.xml has no w:comments root`);return t}function Dr(e){let t=-1;for(let n of _(e,`w:comment`)){let e=parseInt(v(n,`w:id`)??``,10);!isNaN(e)&&e>t&&(t=e)}return String(t+1)}function Or(e){return e.split(/\s+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()).join(``).slice(0,3)||`A`}function kr(e,t,n,r,i,a,o){let s=a.styles.some(e=>e.id===`CommentText`),c=a.styles.some(e=>e.id===`CommentReference`);return w(`w:comment`,i.split(`
|
|
17
|
+
`).map((e,t)=>{let n=[];if(s&&n.push(w(`w:pPr`,[w(`w:pStyle`,[],{"w:val":`CommentText`})])),t===0){let e=[];c&&e.push(w(`w:rPr`,[w(`w:rStyle`,[],{"w:val":`CommentReference`})])),e.push(w(`w:annotationRef`,[])),n.push({"w:r":e})}return n.push(...U(e,void 0,o)),{"w:p":n}}),{"w:id":e,"w:author":t,"w:date":r,"w:initials":n})}function Ar(e,t){let n=[];return t.styles.some(e=>e.id===`CommentReference`)&&n.push(w(`w:rPr`,[w(`w:rStyle`,[],{"w:val":`CommentReference`})])),n.push(w(`w:commentReference`,[],{"w:id":e})),{"w:r":n}}function jr(e,t,n,r){let i=n.author&&n.author.length>0?n.author:r.defaultAuthor,a=n.initials??Or(i),o;if(n.find!==void 0&&n.find.length>0){let e=n.occurrence??1,i=V(n.find,r.markers??!0),a=M(t.text,i,e);if(a===-1)throw Error(`Text "${i}" not found in paragraph "${t.id}" (occurrence ${e})`);let s=vt(t.runs,a,a+i.length);if(s.length===0)throw Error(`No runs found for "${i}" in paragraph "${t.id}"`);if(o=I(t.xmlRef,s),o.length===0)throw Error(`Failed to isolate matched runs in paragraph "${t.id}"`)}let s=Er(e),c=Dr(s),l=w(`w:commentRangeStart`,[],{"w:id":c}),u=w(`w:commentRangeEnd`,[],{"w:id":c}),d=Ar(c,e);if(o){let e=o[0],n=o[o.length-1],r=P(t.xmlRef,e);if(!r)throw Error(`Matched run not found in paragraph`);r.splice(r.indexOf(e),0,l);let i=P(t.xmlRef,n);if(!i)throw Error(`Matched run not found in paragraph`);i.splice(i.indexOf(n)+1,0,u,d)}else{let e=h(t.xmlRef),n=g(t.xmlRef,`w:pPr`),r=n?e.indexOf(n)+1:0;e.splice(r,0,l),e.push(u,d)}h(s).push(kr(c,i,a,r.date,n.text,e,r.markers??!0))}function Mr(e,t,n){return n?.atomic?Pr(e,t,n):Nr(e,t,n)}function Nr(e,t,n){let r=[],i=n?.trackRevisions?Et(e,n):void 0;for(let a of t){let t=Lr(e,a,i,n);r.push(t)}return r}function Pr(e,t,n){let r=Fr(e),i=Nr(r,t,{...n,atomic:!1});return i.every(e=>e.success)&&(e.body=r.body,e.headers=r.headers,e.footers=r.footers,e.xmlParts=r.xmlParts),i}function Fr(e){let t={};for(let[n,r]of Object.entries(e.xmlParts))if(r!==void 0)if(r instanceof Map){let e=new Map;for(let[t,n]of r)e.set(t,JSON.parse(JSON.stringify(n)));t[n]=e}else t[n]=JSON.parse(JSON.stringify(r));let n={body:[],headers:new Map,footers:new Map,xmlParts:t,styles:e.styles,loadOptions:e.loadOptions};return Ye(n),n}function Ir(e,t){return e.markers??t?.inlineMarkers??!0}function Lr(e,t,n,r){let i=lt(t,e);if(!i.valid)return{success:!1,patch:t,error:i.error};let a=Ir(t,r);try{switch(t.type){case`replace_text`:{let r=j(t.target,e);Bt(r,t,n,a),W(e,r);break}case`insert_text`:{let r=j(t.target,e);Gt(r,t,n,a),W(e,r);break}case`delete_text`:{let r=j(t.target,e);Xt(r,t,n,a),W(e,r);break}case`insert_paragraph`:dr(e,j(t.target,e),t,n,a);break;case`delete_paragraph`:gr(e,j(t.target,e),t,n);break;case`add_comment`:{let n=j(t.target,e);jr(e,n,t,{defaultAuthor:r?.revisionAuthor??`docxtor`,date:r?.revisionDate??new Date().toISOString(),markers:a}),W(e,n);break}case`replace_cell_text`:{let r=j(t.target,e);rn(r,t,n,a),W(e,r);break}case`add_table_row`:{let r=pt(t.target,e);O(e,[tn(r,t,n)],k(e,r.id),!0),Rr(e,r);break}case`delete_table_row`:{let r=pt(t.target,e);nn(r,t,n),Rr(e,r);break}case`apply_formatting`:{let r=j(t.target,e);sn(r,t,n),W(e,r);break}case`apply_style`:{let r=j(t.target,e);mn(r,t,e,n),W(e,r);break}case`append_text`:Vr(e,t,n,a);break;case`add_table`:Hr(e,t,n);break;case`add_header`:Tn(e,t,n,a);break;case`add_footer`:En(e,t,n,a);break;case`remove_header`:Dn(e,t);break;case`remove_footer`:On(e,t);break;case`add_list`:Qn(e,t,n,a);break;case`add_list_item`:$n(e,t,n,a);break;case`remove_list_item`:er(e,t,n);break;case`convert_to_list`:tr(e,t,n);break;case`remove_list`:nr(e,t,n);break;case`set_list_properties`:rr(e,t,n);break}return{success:!0,patch:t}}catch(e){return{success:!1,patch:t,error:e instanceof Error?e.message:String(e)}}}function Rr(e,t){let n=D(t.xmlRef,t.id);if(t.rows=n.rows,t.style=n.style,e.xmlParts.numbering)for(let n of t.rows)for(let t of n.cells)for(let n of t.paragraphs)A(n,e.xmlParts.numbering)}function zr(e){let t=-1,n=-1;for(let r of e.body)if(r.kind===`paragraph`){let e=parseInt(r.id.replace(`p`,``),10);!isNaN(e)&&e>t&&(t=e)}else if(r.kind===`table`){let e=parseInt(r.id.replace(`tbl`,``),10);!isNaN(e)&&e>n&&(n=e)}return{nextPIdx:t+1,nextTblIdx:n+1}}function Br(e,t){let n=_(e,`w:tr`);for(let e of n){let n=h(e),r=n.find(e=>`w:trPr`in e);r||(r=w(`w:trPr`,[]),n.unshift(r)),h(r).push(jt(t))}}function Vr(e,t,n,r){if(t.container){Wr(e,t,n,r);return}let i=Un(e),a=tt(t.text),o=[],s,c;for(let t of a)if(t.kind===`text`){t.lines.some(e=>e.trim().length>0)&&(s=void 0,c=void 0);for(let e of t.lines){let t=U(e,void 0,r);if(n){let e=z(n,t);o.push({"w:p":[e]})}else o.push({"w:p":t})}}else if(t.kind===`table`){let e=an(t.headers,t.rows);n&&Br(e,n),o.push(e)}else{let i;i=s&&c===t.listType?s:Ne(e,t.listType),s=i,c=t.listType;for(let e of t.items){let t=w(`w:pPr`,[w(`w:numPr`,[w(`w:ilvl`,[],{"w:val":String(e.level)}),w(`w:numId`,[],{"w:val":i})])]),a=U(e.text,void 0,r);if(n){let e=z(n,a);o.push({"w:p":[t,e]})}else o.push({"w:p":[t,...a]})}}O(e,o,k(e,`body`)),Wn(i,o);let{nextPIdx:l,nextTblIdx:u}=zr(e);for(let t of o)if(`w:tbl`in t){let n=D(t,`tbl${u++}`);e.body.push(n)}else{let n=E(t,`p${l++}`);e.xmlParts.numbering&&A(n,e.xmlParts.numbering),e.body.push(n)}}function Hr(e,t,n){if(t.container){if(t.afterId)throw Error(`"afterId" is not supported when "container" is set`);Gr(e,t,n);return}let r=Un(e),i=an(t.headers,t.rows);n&&Br(i,n),O(e,[i],k(e,`body`));let a,o;if(t.afterId){let n=_t(t.afterId,e);n&&(a=n.xmlRef,o=n.id)}Wn(r,[i],a);let{nextTblIdx:s}=zr(e),c=D(i,`tbl${s}`);if(o!==void 0){let t=e.body.findIndex(e=>e.id===o);if(t!==-1){e.body.splice(t+1,0,c);return}}e.body.push(c)}function Ur(e,t,n){let r=t===`header`?e.headers:e.footers;for(let e of r.values())if(e.variant===n){let n=t===`header`?`w:hdr`:`w:ftr`,r=e.xmlRef.find(e=>p(e)===n);if(r)return{rootNode:r,hf:e}}}function Wr(e,t,n,r){let i=t.container,a=Ur(e,i.type,i.variant);if(!a)throw Error(`${i.type} with variant "${i.variant}" not found`);let{rootNode:o,hf:s}=a,c=h(o),l=i.type===`header`?`hdr`:`ftr`,u=tt(t.text),d=s.paragraphs.length,f,p;for(let t of u)if(t.kind===`text`){t.lines.some(e=>e.trim().length>0)&&(f=void 0,p=void 0);for(let a of t.lines){let t,u=U(a,void 0,r);t=n?{"w:p":[z(n,u)]}:{"w:p":u},O(e,[t],o),c.push(t);let f=E(t,`${l}.${i.variant}.p${d++}`);s.paragraphs.push(f)}}else if(t.kind===`table`){let r=an(t.headers,t.rows);n&&Br(r,n),O(e,[r],o),c.push(r);let a=s.tables.length,u=D(r,`${l}.${i.variant}.tbl${a}`);s.tables.push(u)}else{let a;a=f&&p===t.listType?f:Ne(e,t.listType),f=a,p=t.listType;for(let u of t.items){let t=w(`w:pPr`,[w(`w:numPr`,[w(`w:ilvl`,[],{"w:val":String(u.level)}),w(`w:numId`,[],{"w:val":a})])]),f=U(u.text,void 0,r),p;p=n?{"w:p":[t,z(n,f)]}:{"w:p":[t,...f]},O(e,[p],o),c.push(p);let m=E(p,`${l}.${i.variant}.p${d++}`);e.xmlParts.numbering&&A(m,e.xmlParts.numbering),s.paragraphs.push(m)}}}function Gr(e,t,n){let r=t.container,i=Ur(e,r.type,r.variant);if(!i)throw Error(`${r.type} with variant "${r.variant}" not found`);let{rootNode:a,hf:o}=i,s=h(a),c=an(t.headers,t.rows);n&&Br(c,n),O(e,[c],a),s.push(c);let l=r.type===`header`?`hdr`:`ftr`,u=o.tables.length,d=D(c,`${l}.${r.variant}.tbl${u}`);o.tables.push(d)}function Kr(e,t={}){let n=t.runFilter,r=(t.includeFormatting??!1)||n!==void 0,i=t.includeHeadersFooters??!0,a=t.includeTables??!0,o=t.includeRevisions??!1,s=t.includePageBreaks??!1,c=[];for(let t of e.body)t.kind===`paragraph`?c.push(Jr(t,r,o,s,n)):t.kind===`table`&&a?c.push(Yr(t,r,o,n)):t.kind===`page_break`&&s&&c.push({id:t.id,type:`page_break`});let l={body:c};if(e.styles.length>0&&(l.styles=e.styles),i){if(e.headers.size>0){l.headers=[];for(let t of e.headers.values()){let e={type:`header`,variant:t.variant,paragraphs:t.paragraphs.map(e=>Jr(e,r,o,!1,n))};a&&t.tables.length>0&&(e.tables=t.tables.map(e=>Yr(e,r,o,n))),l.headers.push(e)}}if(e.footers.size>0){l.footers=[];for(let t of e.footers.values()){let e={type:`footer`,variant:t.variant,paragraphs:t.paragraphs.map(e=>Jr(e,r,o,!1,n))};a&&t.tables.length>0&&(e.tables=t.tables.map(e=>Yr(e,r,o,n))),l.footers.push(e)}}}return l}function qr(e,t){let n=(e,t)=>e!==void 0&&t!==void 0&&e.toUpperCase()===t.toUpperCase();return!(t.bold!==void 0&&(e.bold??!1)!==t.bold||t.italic!==void 0&&(e.italic??!1)!==t.italic||t.strikethrough!==void 0&&(e.strikethrough??!1)!==t.strikethrough||t.underline!==void 0&&!n(e.underline,t.underline)||t.color!==void 0&&!n(e.color,t.color)||t.highlight!==void 0&&!n(e.highlight,t.highlight))}function Jr(e,t,n=!1,r=!1,i){let a={id:e.id,text:e.text};if(e.paraId&&(a.paraId=e.paraId),e.style&&(a.style=e.style),e.listInfo&&(a.listLevel=e.listInfo.level,e.listInfo.listType&&(a.listType=e.listInfo.listType),a.numId=e.listInfo.numId),t&&e.runs.length>0){let t=[];for(let n of e.runs){if(i){if(!qr(n.formatting,i))continue}else if(!(n.formatting.bold||n.formatting.italic||n.formatting.underline||n.formatting.strikethrough||n.formatting.fontSize||n.formatting.fontFamily||n.formatting.color||n.formatting.highlight))continue;let e={text:n.text,startOffset:n.startOffset,endOffset:n.endOffset};n.formatting.bold&&(e.bold=!0),n.formatting.italic&&(e.italic=!0),n.formatting.underline&&(e.underline=n.formatting.underline),n.formatting.strikethrough&&(e.strikethrough=!0),n.formatting.fontSize&&(e.fontSize=n.formatting.fontSize),n.formatting.fontFamily&&(e.fontFamily=n.formatting.fontFamily),n.formatting.color&&(e.color=n.formatting.color),n.formatting.themeColor&&(e.themeColor=n.formatting.themeColor),n.formatting.highlight&&(e.highlight=n.formatting.highlight),t.push(e)}t.length>0&&(a.formatting=t)}return n&&e.revisions&&e.revisions.length>0&&(a.revisions=e.revisions),r&&e.hasPageBreak&&(a.hasPageBreak=!0,e.pageBreakOffset!==void 0&&(a.pageBreakOffset=e.pageBreakOffset)),a}function Yr(e,t=!1,n=!1,r){let i={id:e.id,style:e.style,rows:e.rows.map(i=>i.cells.map(a=>{let o={id:a.paragraphs[0]?.id??`${e.id}.r${i.index}.c${a.colIndex}.p0`,text:a.paragraphs.map(e=>e.text).join(`
|
|
18
|
+
`)};return a.paragraphs[0]?.paraId&&(o.paraId=a.paragraphs[0].paraId),(a.paragraphs.length>1||r!==void 0)&&(o.paragraphs=a.paragraphs.map(e=>Jr(e,t,n,!1,r))),o}))},a=[];for(let i of e.rows)for(let e of i.cells)for(let i of e.nestedTables)a.push(Yr(i,t,n,r));return a.length>0&&(i.nestedTables=a),i}function Xr(e,t){switch(t){case`decimal`:return String(e);case`lowerLetter`:{let t=``,n=e;for(;n>0;)n--,t=String.fromCharCode(97+n%26)+t,n=Math.floor(n/26);return t}case`upperLetter`:{let t=``,n=e;for(;n>0;)n--,t=String.fromCharCode(65+n%26)+t,n=Math.floor(n/26);return t}case`lowerRoman`:return Zr(e).toLowerCase();case`upperRoman`:return Zr(e);default:return String(e)}}function Zr(e){let t=[1e3,900,500,400,100,90,50,40,10,9,5,4,1],n=[`M`,`CM`,`D`,`CD`,`C`,`XC`,`L`,`XL`,`X`,`IX`,`V`,`IV`,`I`],r=``,i=e;for(let e=0;e<t.length;e++)for(;i>=t[e];)r+=n[e],i-=t[e];return r}const Qr=[`decimal`,`lowerLetter`,`lowerRoman`];function $r(e,t,n){if(!e.listInfo)return``;let{numId:r,level:i,listType:a}=e.listInfo,o=` `.repeat(i);for(let e of t.keys()){let[n,a]=e.split(`:`);n===r&&Number(a)>i&&t.delete(e)}let s=`${r}:${i}`,c=(t.get(s)??0)+1;if(t.set(s,c),a===`bullet`||!a)return`${o}- `;if(a===`multilevel`&&n){let e=Fe(n,r,i);if(e){let n=e.pattern,i=n.match(/%(\d+)/g);if(i)for(let a of i){let i=parseInt(a.slice(1),10)-1,o=t.get(`${r}:${i}`)??1,s=e.ancestorFormats.get(i)??`decimal`;n=n.replaceAll(a,Xr(o,s))}return`${o}${n} `}}let l=Qr[i%Qr.length]??`decimal`;if(n){let e=Fe(n,r,i);e&&(l=e.format)}return`${o}${Xr(c,l)}. `}function ei(e,t={}){let n=t.includeHeadersFooters??!0,r=t.includeTables??!0,i=t.includeRevisions??!1,a=t.includePageBreaks??!1,o=t.includeFormatting??!1,s=[],c=new Map,l=e.xmlParts.numbering;for(let t of e.body)if(t.kind===`paragraph`){let e=$r(t,c,l);s.push(ti(t,i,a,o,e))}else t.kind===`table`&&r?(s.push(``),s.push(...oi(t,i,o)),s.push(``)):t.kind===`page_break`&&a&&(s.push(``),s.push(`[${t.id}] --- PAGE BREAK ---`),s.push(``));if(n){for(let t of e.headers.values()){s.push(``),s.push(`--- Header (${t.variant}) ---`);let e=new Map;for(let n of t.paragraphs){let t=$r(n,e,l);s.push(ti(n,i,!1,o,t))}if(r)for(let e of t.tables)s.push(``),s.push(...oi(e,i))}for(let t of e.footers.values()){s.push(``),s.push(`--- Footer (${t.variant}) ---`);let e=new Map;for(let n of t.paragraphs){let t=$r(n,e,l);s.push(ti(n,i,!1,o,t))}if(r)for(let e of t.tables)s.push(``),s.push(...oi(e,i))}}if(e.styles.length>0){s.push(``),s.push(`--- Available Styles ---`);for(let t of e.styles)s.push(`[${t.type}] ${t.id} — ${t.name}`)}return s.join(`
|
|
19
|
+
`).trim()}function ti(e,t=!1,n=!1,r=!1,i=``){let a=e.style?` (${e.style})`:``,o=r?ri(e.text,e.runs):e.text,s=t&&e.revisions&&e.revisions.length>0;if(s)if(r){let t=e.revisions.map(t=>({...t,startOffset:G(t.startOffset,e.runs),endOffset:G(t.endOffset,e.runs)}));o=ai(o,t)}else o=ai(e.text,e.revisions);if(n&&e.hasPageBreak){let t=e.pageBreakOffset??0;if(r&&(t=G(t,e.runs)),s)if(r){let n=e.revisions.map(t=>({...t,startOffset:G(t.startOffset,e.runs),endOffset:G(t.endOffset,e.runs)}));t=ii(t,n)}else t=ii(t,e.revisions);let n=o.slice(0,t),i=o.slice(t);o=n.length===0?`[PAGE BREAK] ${i}`:i.length===0?`${n} [PAGE BREAK]`:`${n} [PAGE BREAK] ${i}`}let c=e.listInfo?` {list:${e.listInfo.numId} L${e.listInfo.level}}`:``;return`[${ni(e)}]${a}${c} ${i}${o}`}function ni(e){return e.paraId?`${e.id} ¶${e.paraId}`:e.id}function ri(e,t){if(t.length===0)return e;let n=[],r=0;for(let i of t){i.startOffset>r&&n.push(e.slice(r,i.startOffset));let t=e.slice(i.startOffset,i.endOffset),{bold:a,italic:o,strikethrough:s,underline:c}=i.formatting;if(!a&&!o&&!s&&!c)n.push(t);else{let e=t;c&&(e=`<u>${e}</u>`),o&&(e=`_${e}_`),a&&(e=`**${e}**`),s&&(e=`~~${e}~~`),n.push(e)}r=i.endOffset}return r<e.length&&n.push(e.slice(r)),n.join(``)}function G(e,t){let n=0;for(let r of t){let{bold:t,italic:i,strikethrough:a,underline:o}=r.formatting;if(!t&&!i&&!a&&!o)continue;let s=0,c=0;a&&(s+=2,c+=2),t&&(s+=2,c+=2),i&&(s+=1,c+=1),o&&(s+=3,c+=4),e>=r.startOffset&&(n+=s),e>=r.endOffset&&(n+=c)}return e+n}function ii(e,t){let n=[...t].sort((e,t)=>e.startOffset-t.startOffset),r=0;for(let t of n)t.type===`insert`?(e>=t.startOffset&&(r+=2),e>=t.endOffset&&(r+=2)):t.type===`delete`&&e>=t.startOffset&&(r+=t.text.length+4);return e+r}function ai(e,t){let n=[...t].sort((e,t)=>t.startOffset-e.startOffset),r=e;for(let e of n)if(e.type===`insert`)r=`${r.slice(0,e.startOffset)}{+${r.slice(e.startOffset,e.endOffset)}+}${r.slice(e.endOffset)}`;else if(e.type===`delete`){let t=r.slice(0,e.startOffset),n=r.slice(e.startOffset);r=`${t}{-${e.text}-}${n}`}return r}function oi(e,t=!1,n=!1){let r=[];for(let i of e.rows){let a=i.cells.map(r=>{let a;a=n?r.paragraphs.map(e=>{let n=ri(e.text,e.runs);if(t&&e.revisions&&e.revisions.length>0){let t=e.revisions.map(t=>({...t,startOffset:G(t.startOffset,e.runs),endOffset:G(t.endOffset,e.runs)}));n=ai(n,t)}return n}).join(` `):t?r.paragraphs.map(e=>e.revisions&&e.revisions.length>0?ai(e.text,e.revisions):e.text).join(` `):r.paragraphs.map(e=>e.text).join(` `);let o=r.paragraphs[0];return`[${o?ni(o):`${e.id}.r${i.index}.c${r.colIndex}.p0`}] ${a}`});r.push(`| ${a.join(` | `)} |`)}return r}function si(e,t=`json`,n={}){switch(t){case`json`:return Kr(e,n);case`markdown`:return ei(e,n);default:throw Error(`Unknown projection format: ${t}`)}}const ci={"w:rPrChange":new Set([`w:ins`,`w:del`,`w:moveFrom`,`w:moveTo`]),"w:pPrChange":new Set([`w:rPr`,`w:sectPr`]),"w:trPrChange":new Set([`w:ins`,`w:del`]),"w:tcPrChange":new Set([`w:cellIns`,`w:cellDel`,`w:cellMerge`]),"w:tblPrChange":new Set,"w:tblPrExChange":new Set,"w:tblGridChange":new Set,"w:sectPrChange":new Set},li=new Set([`w:rPr`,`w:trPr`,`w:tcPr`]),ui=new Set([`w:moveFromRangeStart`,`w:moveToRangeStart`]),di=new Set([`w:moveFromRangeEnd`,`w:moveToRangeEnd`]),fi=new Set([`w:bookmarkStart`,`w:bookmarkEnd`,`w:proofErr`,`w:permStart`,`w:permEnd`,`w:commentRangeStart`,`w:commentRangeEnd`,`w:customXmlInsRangeStart`,`w:customXmlInsRangeEnd`,`w:customXmlDelRangeStart`,`w:customXmlDelRangeEnd`]);function pi(e,t){let n=hi(`accept`,t);return gi(e,n),{accepted:n.count}}function mi(e,t){let n=hi(`reject`,t);return gi(e,n),{rejected:n.count}}function hi(e,t){return{mode:e,authors:t?.authors?new Set(t.authors):void 0,ids:t?.ids?new Set(t.ids.map(String)):void 0,count:0,moveRangeIds:new Set}}function gi(e,t){let n=[e.xmlParts.document,...e.xmlParts.headers.values(),...e.xmlParts.footers.values()];for(let t of[`footnotes`,`endnotes`,`comments`]){let r=e.xmlParts[t];r&&n.push(r)}for(let e of n)t.ids&&_i(e,t.ids),t.moveRangeIds=vi(e,t),q(e,void 0,t)}function K(e,t){if(t.ids){let n=v(e,`w:id`);if(n===void 0||!t.ids.has(n))return!1}if(!t.authors)return!0;let n=v(e,`w:author`);return n!==void 0&&t.authors.has(n)}function _i(e,t){let n={from:[],to:[]},r=[],i=new Map,a=new Map,o=e=>{for(let t of e){let e=p(t);if(!e)continue;let s=v(t,`w:id`);if(s!==void 0){if(e===`w:moveFromRangeStart`||e===`w:moveToRangeStart`){let o=v(t,`w:name`),c=o!==void 0&&a.get(o)||[];c.length||r.push(c),o!==void 0&&a.set(o,c),c.push(s),i.set(s,c),(e===`w:moveFromRangeStart`?n.from:n.to).push(s)}else if(e===`w:moveFromRangeEnd`||e===`w:moveToRangeEnd`){let t=e===`w:moveFromRangeEnd`?n.from:n.to,r=t.lastIndexOf(s);r!==-1&&t.splice(r,1)}else if(e===`w:moveFrom`||e===`w:moveTo`)for(let t of e===`w:moveFrom`?n.from:n.to)i.get(t).push(s)}let c=h(t);c.length>0&&o(c)}};o(e);for(let e of r)if(e.some(e=>t.has(e)))for(let n of e)t.add(n)}function vi(e,t){let n=new Set,r=e=>{for(let i of e){let e=p(i);if(!e)continue;if(ui.has(e)&&K(i,t)){let e=v(i,`w:id`);e!==void 0&&n.add(e)}let a=h(i);a.length>0&&r(a)}};return r(e),n}function q(e,t,n){let r=0;for(;r<e.length;){let i=e[r],a=p(i);if(!a){r++;continue}let o=t!==void 0&&li.has(t);if((a===`w:ins`||a===`w:moveTo`)&&!o){if(K(i,n)){n.count++,n.mode===`accept`?e.splice(r,1,...h(i)):e.splice(r,1);continue}q(h(i),a,n),r++;continue}if((a===`w:del`||a===`w:moveFrom`)&&!o){if(K(i,n)){if(n.count++,n.mode===`accept`)e.splice(r,1);else{let t=h(i);for(let e of t)yi(e);e.splice(r,1,...t)}continue}q(h(i),a,n),r++;continue}if(ui.has(a)||di.has(a)){let t=v(i,`w:id`);if(ui.has(a)?K(i,n):t!==void 0&&n.moveRangeIds.has(t)){e.splice(r,1);continue}r++;continue}if(a in ci){if(K(i,n)){n.count++,n.mode===`accept`?e.splice(r,1):xi(e,i,a),r=0;continue}r++;continue}if(a===`w:p`){if(q(h(i),a,n),Si(e,r,i,n))continue;r++;continue}if(a===`w:tr`){if(wi(e,r,i,n))continue;q(h(i),a,n),r++;continue}if(a===`w:tc`){if(Ti(e,r,i,n))continue;q(h(i),a,n),r++;continue}let s=h(i);s.length>0&&q(s,a,n),r++}}function yi(e){let t=p(e);if(t){if(t===`w:r`){let t=h(e);for(let e=0;e<t.length;e++){let n=t[e];if(`w:delText`in n){let r={"w:t":n[`w:delText`]};n[`:@`]&&(r[`:@`]=n[`:@`]),T(bi(r[`w:t`]))&&y(r,`xml:space`,`preserve`),t[e]=r}else if(`w:delInstrText`in n){let r={"w:instrText":n[`w:delInstrText`]};n[`:@`]&&(r[`:@`]=n[`:@`]),t[e]=r}}return}for(let t of h(e))yi(t)}}function bi(e){let t=``;for(let n of e)`#text`in n&&(t+=x(String(n[`#text`])));return t}function xi(e,t,n){let r=ci[n]??new Set,i=h(t).find(e=>p(e)!==void 0),a=i?h(i).map(S):[],o=e.filter(e=>{let n=p(e);return n!==void 0&&r.has(n)&&e!==t});e.length=0,n===`w:rPrChange`?e.push(...o,...a):e.push(...a,...o)}function Si(e,t,n,r){let i=g(n,`w:pPr`);if(!i)return!1;let a=g(i,`w:rPr`);if(!a)return!1;let o=h(a),s=!1,c=o.findIndex(e=>p(e)===`w:ins`);c!==-1&&K(o[c],r)&&(r.count++,o.splice(c,1),r.mode===`reject`&&(s=!0));let l=o.findIndex(e=>p(e)===`w:del`);if(l!==-1&&K(o[l],r)&&(r.count++,o.splice(l,1),r.mode===`accept`&&(s=!0)),o.length===0){let e=h(i);if(e.splice(e.indexOf(a),1),e.length===0){let e=h(n);e.splice(e.indexOf(i),1)}}return s?Ci(e,t,n):!1}function Ci(e,t,n){let r=g(n,`w:pPr`);if(r&&g(r,`w:sectPr`))return!1;let i=t+1;for(;i<e.length;){let t=p(e[i]);if(t===`w:p`)break;if(t===void 0||fi.has(t)){i++;continue}return!1}if(i>=e.length)return!1;let a=e[i],o=h(a),s=g(a,`w:pPr`),c=s?o.indexOf(s)+1:0,l=h(n).filter(e=>p(e)!==`w:pPr`);return o.splice(c,0,...l),e.splice(t,1),!0}function wi(e,t,n,r){let i=g(n,`w:trPr`);if(!i)return!1;let a=h(i),o=a.findIndex(e=>p(e)===`w:ins`);if(o!==-1&&K(a[o],r)){if(r.count++,r.mode===`reject`)return e.splice(t,1),!0;a.splice(o,1)}let s=a.findIndex(e=>p(e)===`w:del`);if(s!==-1&&K(a[s],r)){if(r.count++,r.mode===`accept`)return e.splice(t,1),!0;a.splice(s,1)}return!1}function Ti(e,t,n,r){let i=g(n,`w:tcPr`);if(!i)return!1;let a=h(i),o=a.findIndex(e=>p(e)===`w:cellIns`);if(o!==-1&&K(a[o],r)){if(r.count++,r.mode===`reject`)return e.splice(t,1),!0;a.splice(o,1)}let s=a.findIndex(e=>p(e)===`w:cellDel`);if(s!==-1&&K(a[s],r)){if(r.count++,r.mode===`accept`)return e.splice(t,1),!0;a.splice(s,1)}let c=a.find(e=>p(e)===`w:cellMerge`);return c&&K(c,r)&&(r.count++,r.mode===`reject`&&Ei(a,c),a.splice(a.indexOf(c),1)),!1}function Ei(e,t){let n=v(t,`w:vMergeOrig`),r=e.findIndex(e=>p(e)===`w:vMerge`);if(n===void 0){r!==-1&&e.splice(r,1);return}let i={"w:vMerge":[]};if(n===`rest`&&y(i,`w:val`,`restart`),r!==-1)e[r]=i;else{let t=e.findIndex(e=>{let t=p(e);return t===`w:tcBorders`||t===`w:shd`||t===`w:noWrap`||t===`w:tcMar`||t===`w:textDirection`||t===`w:tcFitText`||t===`w:vAlign`||t===`w:hideMark`||t===`w:cellIns`||t===`w:cellDel`||t===`w:cellMerge`||t===`w:tcPrChange`});t===-1?e.push(i):e.splice(t,0,i)}}const Di=`http://schemas.openxmlformats.org/package/2006/metadata/core-properties`,Oi=`http://purl.org/dc/elements/1.1/`,ki=`http://purl.org/dc/terms/`,Ai=`http://purl.org/dc/dcmitype/`,ji=`http://www.w3.org/2001/XMLSchema-instance`,Mi={creator:`dc:creator`,lastModifiedBy:`cp:lastModifiedBy`,title:`dc:title`,subject:`dc:subject`,description:`dc:description`,keywords:`cp:keywords`,category:`cp:category`,contentStatus:`cp:contentStatus`,revision:`cp:revision`,created:`dcterms:created`,modified:`dcterms:modified`},Ni=[`creator`,`lastModifiedBy`,`description`,`keywords`,`category`,`contentStatus`],Pi=new Set([`Company`,`Manager`,`HyperlinkBase`]);function J(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function Fi(e,t){if(e)return e.find(e=>{let n=p(e);return n!==void 0&&J(n)===t})}function Ii(e,t){return h(e).find(e=>{let n=p(e);return n!==void 0&&J(n)===t})}function Li(e){let t=``;for(let n of h(e))`#text`in n&&(t+=x(String(n[`#text`])));return t}function Ri(e,t){let n=p(e);e[n]=t.length>0?[{"#text":b(t)}]:[]}function zi(e,t){let n=h(e),r=n.findIndex(e=>{let n=p(e);return n!==void 0&&J(n)===t});return r===-1?!1:(n.splice(r,1),!0)}function Bi(){return[{"?xml":[{"#text":``}],":@":{"@_version":`1.0`,"@_encoding":`UTF-8`,"@_standalone":`yes`}},w(`cp:coreProperties`,[],{"xmlns:cp":Di,"xmlns:dc":Oi,"xmlns:dcterms":ki,"xmlns:dcmitype":Ai,"xmlns:xsi":ji})]}const Vi={"xmlns:cp":Di,"xmlns:dc":Oi,"xmlns:dcterms":ki,"xmlns:dcmitype":Ai,"xmlns:xsi":ji};function Hi(e){e.xmlParts.core||(e.xmlParts.core=Bi(),e.xmlParts.rootRels||(e.xmlParts.rootRels=_r()),Sr(e.xmlParts.rootRels,`http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties`,`docProps/core.xml`),e.xmlParts.contentTypes||(e.xmlParts.contentTypes=vr()),wr(e.xmlParts.contentTypes,`/docProps/core.xml`,`application/vnd.openxmlformats-package.core-properties+xml`));let t=Fi(e.xmlParts.core,`coreProperties`);if(!t)throw Error(`docProps/core.xml has no coreProperties root`);for(let[e,n]of Object.entries(Vi))v(t,e)===void 0&&y(t,e,n);return t}function Ui(e){let t={},n=Fi(e.xmlParts.core,`coreProperties`);if(!n)return t;for(let e of Object.keys(Mi)){let r=Ii(n,J(Mi[e]));r&&(t[e]=Li(r))}return t}function Wi(e,t){let n=Hi(e);for(let e of Object.keys(t)){let r=t[e];if(r===void 0||!(e in Mi))continue;let i=Mi[e],a=Ii(n,J(i));a||(a=w(i,[]),h(n).push(a)),Ri(a,r),(e===`created`||e===`modified`)&&y(a,`xsi:type`,`dcterms:W3CDTF`)}}function Gi(e){let t=[],n=Fi(e.xmlParts.core,`coreProperties`);if(n){for(let e of Ni)zi(n,J(Mi[e]));Wi(e,{revision:`1`})}let r=Fi(e.xmlParts.app,`Properties`);if(r){let e=h(r);for(let t=e.length-1;t>=0;t--){let n=p(e[t]);n!==void 0&&Pi.has(J(n))&&e.splice(t,1)}}let i=Cr(e.xmlParts.rootRels,`http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties`);Tr(e.xmlParts.contentTypes,`/docProps/custom.xml`),t.push(`docProps/custom.xml`);for(let e of i){let n=e.replace(/^\//,``);n&&!t.includes(n)&&t.push(n)}return{removedParts:t}}var Ki=class t{zipEntries;doc;removedParts=new Set;constructor(e,t){this.zipEntries=e,this.doc=t}static async load(n,r){let i;i=typeof n==`string`?await e(n):n;let o=await a(i);return new t(o,Je(o,r))}static async create(e,r){if(e!==void 0)return t.load(e,r);let i=new n;i.file(`[Content_Types].xml`,`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
20
|
+
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
21
|
+
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
22
|
+
<Default Extension="xml" ContentType="application/xml"/>
|
|
23
|
+
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
|
|
24
|
+
</Types>`),i.file(`_rels/.rels`,`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
25
|
+
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
26
|
+
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
|
|
27
|
+
</Relationships>`),i.file(`word/document.xml`,`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
28
|
+
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
|
29
|
+
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
|
|
30
|
+
<w:body>
|
|
31
|
+
<w:p>
|
|
32
|
+
<w:r>
|
|
33
|
+
<w:t></w:t>
|
|
34
|
+
</w:r>
|
|
35
|
+
</w:p>
|
|
36
|
+
</w:body>
|
|
37
|
+
</w:document>`);let a=await i.generateAsync({type:`nodebuffer`,compression:`DEFLATE`});return t.load(a,r)}project(e=`json`,t={}){return si(this.doc,e,t)}applyPatches(e,t){return Mr(this.doc,e,t)}acceptAllRevisions(e){let t=pi(this.doc,e);return Ye(this.doc),t}rejectAllRevisions(e){let t=mi(this.doc,e);return Ye(this.doc),t}getCoreProperties(){return Ui(this.doc)}setCoreProperties(e){Wi(this.doc,e)}scrubMetadata(){let{removedParts:e}=Gi(this.doc);for(let t of e)this.removedParts.add(t)}toString(){return u(this.doc.xmlParts.document)}async toBuffer(){let e=u(this.doc.xmlParts.document),t=new Map;for(let[e,n]of this.doc.xmlParts.headers)t.set(e,u(n));let n=new Map;for(let[e,t]of this.doc.xmlParts.footers)n.set(e,u(t));let r=[];for(let e of Object.keys(this.zipEntries.zip.files))/^word\/header\d+\.xml$/i.test(e)?this.doc.xmlParts.headers.has(e)||r.push(e):/^word\/footer\d+\.xml$/i.test(e)&&(this.doc.xmlParts.footers.has(e)||r.push(e));for(let e of this.removedParts)r.includes(e)||r.push(e);let i=e=>e?u(e):void 0,a=this.doc.xmlParts;return c({zip:this.zipEntries.zip,documentXml:e,headers:t.size>0?t:void 0,footers:n.size>0?n:void 0,documentRelsXml:i(a.documentRels),contentTypesXml:i(a.contentTypes),settingsXml:i(a.settings),numberingXml:i(a.numbering),footnotesXml:i(a.footnotes),endnotesXml:i(a.endnotes),commentsXml:i(a.comments),coreXml:i(a.core),appXml:i(a.app),rootRelsXml:i(a.rootRels),removedParts:r.length>0?r:void 0})}async toFile(e){let{writeFile:t}=await import(`node:fs/promises`);await t(e,await this.toBuffer())}getAST(){return this.doc}getBody(){return this.doc.body}getParagraphs(){return this.doc.body.filter(e=>e.kind===`paragraph`)}getTables(){return this.doc.body.filter(e=>e.kind===`table`)}getHeaders(){return this.doc.headers}getFooters(){return this.doc.footers}findParagraphById(e){return j(e,this.doc)}findParagraphByParaId(e){return dt(e,this.doc)}findTableById(e){return pt(e,this.doc)}getStyles(){return this.doc.styles}validatePatches(e){return e.map(e=>lt(e,this.doc))}};function qi(e,t){for(let n of e.rows)for(let e of n.cells){for(let n of e.paragraphs)t.push({para:n,where:`table`});for(let n of e.nestedTables)qi(n,t)}}function Ji(e){let t=[];for(let n of e)n.kind===`paragraph`?t.push({para:n,where:`body`}):n.kind===`table`&&qi(n,t);return t}function Yi(e){let t=Ji(e.getBody());for(let[n,r]of[[`header`,e.getHeaders()],[`footer`,e.getFooters()]])for(let e of r.values()){for(let r of e.paragraphs)t.push({para:r,where:n});for(let r of e.tables){let e=[];qi(r,e);for(let r of e)t.push({para:r.para,where:n})}}return t}function Xi(e,t,n){let r=0,i=e.indexOf(t);for(;i!==-1&&i<=n;)r++,i=e.indexOf(t,i+1);return r}function Zi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Qi(e,t,n){if(t.length===0)return[];let r=n?`(?<![\\p{L}\\p{N}_])${Zi(t)}(?![\\p{L}\\p{N}_])`:Zi(t),i=new RegExp(r,`gu`);return[...e.matchAll(i)].map(e=>e.index)}function $i(e){let t=[e];return/['"]/.test(e)&&t.push(e.replace(/'/g,`’`).replace(/"(?=\S)/g,`“`).replace(/"/g,`”`)),/[‘’“”]/.test(e)&&t.push(e.replace(/[‘’]/g,`'`).replace(/[“”]/g,`"`)),[...new Set(t)]}function ea(e,t,n,r=50){let i=Math.max(0,t-r),a=Math.min(e.length,n+r);return`${i>0?`…`:``}${e.slice(i,a)}${a<e.length?`…`:``}`.replace(/\s+/g,` `)}function ta(e,t){let n=e=>e.match(/\s+|\S+/g)??[],r=n(e),i=n(t);if(r.join(``)!==e||i.join(``)!==t)return{offset:0,find:e,replace:t};let a=0;for(;a<r.length&&a<i.length&&r[a]===i[a];)a++;let o=0;for(;o<r.length-a&&o<i.length-a&&r[r.length-1-o]===i[i.length-1-o];)o++;for(;a+o>=r.length&&(a>0||o>0);)o>0?o--:a--;return{offset:r.slice(0,a).join(``).length,find:r.slice(a,r.length-o).join(``),replace:i.slice(a,i.length-o).join(``)}}function na(e,t){let n=ta(e,t),r=n.find,i=n.replace,a=0;for(;a<r.length&&a<i.length&&r[a]===i[a];)a++;let o=0;for(;o<r.length-a&&o<i.length-a&&r[r.length-1-o]===i[i.length-1-o];)o++;if(i.length-a-o===0&&r.length-a-o>0)return{kind:`delete`,offset:n.offset+a,find:r.slice(a,r.length-o)};if(r.length-a-o===0&&i.length-a-o>0){let e=i.slice(a,i.length-o);return a>0?{kind:`insert`,offset:n.offset,anchor:r.slice(0,a),position:`after`,text:e}:{kind:`insert`,offset:n.offset,anchor:r,position:`before`,text:e}}return n.replace===``?{kind:`delete`,offset:n.offset,find:r}:{kind:`replace`,...n}}const ra=new Set([`w:ins`,`w:del`,`w:moveFrom`,`w:moveTo`]),ia=/^w:\w+PrChange$/,aa=new Set([`w:bookmarkStart`,`w:bookmarkEnd`,`w:proofErr`,`w:commentRangeStart`,`w:commentRangeEnd`,`w:moveFromRangeStart`,`w:moveFromRangeEnd`,`w:moveToRangeStart`,`w:moveToRangeEnd`,`w:pPr`]);function oa(e){let t=``;for(let n of h(e)){let e=p(n);if(e===`w:t`||e===`w:delText`)for(let e of h(n))e[`#text`]!==void 0&&(t+=x(String(e[`#text`])));else e===`w:tab`?t+=` `:e===`w:br`||e===`w:cr`?t+=`
|
|
38
|
+
`:e===`w:noBreakHyphen`&&(t+=`-`)}return t}function sa(e){return p(e)===`w:r`?oa(e):h(e).map(e=>sa(e)).join(``)}function ca(e){let t=h(e).find(e=>p(e)===`w:rPr`);return t?h(t).find(e=>p(e)===`w:rPrChange`):void 0}function la(e,t){for(let n of e){let e=p(n);if(!(!e||aa.has(e)))if(e===`w:ins`||e===`w:moveTo`)t.push({kind:`ins`,text:sa(n),node:n});else if(e===`w:del`||e===`w:moveFrom`)t.push({kind:`del`,text:sa(n),node:n});else if(e===`w:r`){let e=ca(n);t.push(e?{kind:`fmt`,text:oa(n),node:e}:{kind:`text`,text:oa(n)})}else (e===`w:hyperlink`||e===`w:smartTag`||e===`w:sdt`||e===`w:sdtContent`||e===`w:fldSimple`)&&la(h(n),t)}}function ua(e){return{id:v(e,`w:id`),author:v(e,`w:author`)??``,date:v(e,`w:date`)??``}}function da(e){let t=[],n=new Set;for(let{para:r}of Yi(e)){let e=[];la(h(r.xmlRef),e);let i=e.filter(e=>!(e.kind===`text`&&e.text===``)),a=[];for(let e=0;e<i.length;e++){let t=i[e];if(t.kind===`ins`||t.kind===`del`){let n=a[a.length-1],r=n?i[n.to]:void 0,o=n?i.slice(n.to+1,e):[];n&&r&&(r.kind===`ins`||r.kind===`del`)&&(o.length===0||r.kind!==t.kind&&o.every(e=>e.kind===`text`&&e.text.trim()===``))?n.to=e:a.push({from:e,to:e})}else t.kind===`fmt`&&a.push({from:e,to:e})}for(let e of a){let a=i.slice(e.from,e.to+1);for(let e of a)e.node&&n.add(e.node);let o=a.filter(e=>e.kind===`del`).map(e=>e.text).join(``),s=a.filter(e=>e.kind===`ins`).map(e=>e.text).join(``),c=a.filter(e=>e.node).map(e=>ua(e.node)),l=a[0].kind===`fmt`,u=i.slice(0,e.from).filter(e=>e.kind!==`del`).map(e=>e.text).join(``),d=i.slice(e.to+1).filter(e=>e.kind!==`del`).map(e=>e.text).join(``),f=l?`[fmt:${a[0].text}]`:a.map(e=>e.kind===`del`?`[-${e.text}-]`:e.kind===`ins`?`[+${e.text}+]`:e.text).join(``);t.push({n:0,paragraph:r.id,kind:l?`formatting`:o&&s?`replacement`:o?`deletion`:`insertion`,ids:c.map(e=>e.id).filter(e=>e!==void 0),authors:[...new Set(c.map(e=>e.author))],date:c[0]?.date??``,deleted:l?``:o,inserted:l?a[0].text:s,context:fa(u,!0)+f+fa(d,!1)})}let o=h(r.xmlRef).find(e=>p(e)===`w:pPr`);if(o)for(let e of h(o)){let a=p(e);if(a===`w:rPr`)for(let a of h(e)){let e=p(a);if(e===`w:ins`||e===`w:del`){n.add(a);let o=ua(a),s=e===`w:ins`?`insertion`:`deletion`,c=t.filter(e=>e.paragraph===r.id&&e.kind!==`paragraph`),l=i.some(e=>e.kind===`text`&&e.text.length>0)||s===`deletion`&&i.some(e=>e.kind===`ins`);if(c.length===1&&c[0].kind===s&&!l&&c[0].authors.includes(o.author)){o.id&&c[0].ids.push(o.id),c[0].kind=s,c[0].context=`whole paragraph ${s===`insertion`?`inserted`:`deleted`}: ${c[0].context}`;continue}t.push({n:0,paragraph:r.id,kind:`paragraph`,ids:o.id?[o.id]:[],authors:[o.author],date:o.date,deleted:``,inserted:``,context:`paragraph mark ${e===`w:ins`?`inserted`:`deleted`} (${e===`w:ins`?`new paragraph break`:`paragraph merged with the next`}): ${fa(r.text,!1)}`})}else e===`w:rPrChange`&&n.add(a)}else if(ia.test(a)){n.add(e);let i=ua(e);t.push({n:0,paragraph:r.id,kind:`formatting`,ids:i.id?[i.id]:[],authors:[i.author],date:i.date,deleted:``,inserted:``,context:`paragraph properties changed: ${fa(r.text,!1)}`})}}}let r=e.getAST().xmlParts,i=[[``,r.document]];for(let[e,t]of r.headers)i.push([`header ${e.replace(/^word\//,``)}`,t]);for(let[e,t]of r.footers)i.push([`footer ${e.replace(/^word\//,``)}`,t]);for(let e of[`footnotes`,`endnotes`,`comments`]){let t=r[e];t&&i.push([e,t])}let a=``,o=e=>{for(let r of e){let e=p(r);if(!(!e||e===`#text`)){if(!n.has(r)&&(ra.has(e)||ia.test(e)||e===`w:cellIns`||e===`w:cellDel`||e===`w:cellMerge`)&&v(r,`w:author`)!==void 0&&v(r,`w:id`)!==void 0){n.add(r);let i=ua(r);t.push({n:0,paragraph:`-`,kind:`other`,ids:[i.id],authors:[i.author],date:i.date,deleted:``,inserted:``,context:`${a?`${a}: `:``}${e}${sa(r)?`: ${fa(sa(r),!1)}`:``}`});continue}o(h(r))}}};for(let[e,t]of i)a=e,o(t);return t.forEach((e,t)=>e.n=t+1),t}function fa(e,t,n=60){return e=e.replace(/\s+/g,` `),e.length<=n?e:t?`…${e.slice(-n)}`:`${e.slice(0,n)}…`}function pa(e){if(e.length===0)return`No tracked changes.`;let t=e.map(e=>{let t=e.kind===`replacement`?`replace "${e.deleted}" -> "${e.inserted}"`:e.kind===`deletion`?`delete "${e.deleted}"`:e.kind===`insertion`?`insert "${e.inserted}"`:e.kind===`formatting`?`formatting${e.inserted?` of "${e.inserted}"`:``}`:e.kind;return`#${e.n} [${e.paragraph}] ids=${e.ids.join(`,`)} by ${e.authors.join(`, `)}: ${t}\n ${e.context}`}),n=[...new Set(e.flatMap(e=>e.authors))];return`${e.length} change${e.length===1?``:`s`} by ${n.map(e=>`"${e}"`).join(`, `)}\n${t.join(`
|
|
39
|
+
`)}`}function ma(e){let t=``;for(let n of e){let e=p(n);if(e===`w:t`)for(let e of h(n))e[`#text`]!==void 0&&(t+=x(String(e[`#text`])));else e===`w:tab`?t+=` `:e===`w:br`||e===`w:cr`?t+=`
|
|
40
|
+
`:e&&e!==`w:delText`&&e!==`w:instrText`&&(t+=ma(h(n)))}return t}function ha(e){let t=e.getAST().xmlParts.comments;if(!t)return[];let n=t.find(e=>p(e)===`w:comments`),r=[];for(let e of n?h(n):[]){if(p(e)!==`w:comment`)continue;let t=h(e).filter(e=>p(e)===`w:p`).map(e=>ma(h(e)));r.push({id:v(e,`w:id`)??``,author:v(e,`w:author`)??``,initials:v(e,`w:initials`)??``,date:v(e,`w:date`)??``,text:t.join(`
|
|
41
|
+
`),paragraph:``,anchor:``})}let i=new Map(r.map(e=>[e.id,e])),a=new Set,o=(e,t)=>{for(let n of e){let e=p(n);if(e===`w:commentRangeStart`||e===`w:commentReference`){let r=i.get(v(n,`w:id`)??``);r&&!r.paragraph&&(r.paragraph=t),r&&e===`w:commentRangeStart`&&a.add(r.id)}else if(e===`w:commentRangeEnd`)a.delete(v(n,`w:id`)??``);else if(e===`w:r`){for(let e of h(n)){if(p(e)!==`w:commentReference`)continue;let n=i.get(v(e,`w:id`)??``);n&&!n.paragraph&&(n.paragraph=t)}let e=ma(h(n));for(let t of a)i.get(t).anchor+=e}else if(e===`w:del`||e===`w:moveFrom`)continue;else e&&o(h(n),t)}};for(let{para:t}of Yi(e)){o(h(t.xmlRef),t.id);for(let e of a)i.get(e).anchor+=`
|
|
42
|
+
`}for(let e of r)e.anchor=e.anchor.replace(/\n+$/,``);return r}function ga(e){if(e.length===0)return`No comments.`;let t=(e,t)=>{let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n},n=e.map((e,n)=>`#${n+1} [${e.paragraph||`-`}] by ${e.author||`(no author)`}${e.date?` ${e.date.slice(0,10)}`:``}: ${e.text.replace(/\n/g,` / `)}`+(e.anchor?`\n on: "${t(e.anchor,160)}"`:``));return`${e.length} comment${e.length===1?``:`s`}\n${n.join(`
|
|
43
|
+
`)}`}const _a=`docxtor <command> [options]
|
|
44
|
+
|
|
45
|
+
Read
|
|
46
|
+
view FILE [--grep REGEX [--context N]] [--formatting] [--no-revisions] [--styles] [--json]
|
|
47
|
+
Paragraphs with their ids ([p12], [tbl0.r1.c0.p0], [hdr.default.p0]).
|
|
48
|
+
Tracked changes show inline as {+inserted+} and {-deleted-}.
|
|
49
|
+
revisions FILE [--json]
|
|
50
|
+
Every tracked change, numbered, with its w:ids, author and context.
|
|
51
|
+
comments FILE [--json]
|
|
52
|
+
Existing comments: author, date, text, and the passage each is on.
|
|
53
|
+
metadata FILE [--json]
|
|
54
|
+
Document properties: author, last modified by, title, company, dates, ...
|
|
55
|
+
|
|
56
|
+
Write (tracked changes by default; -o may equal FILE to update in place)
|
|
57
|
+
replace FILE -o OUT --find TEXT --replace TEXT [--find .. --replace ..]
|
|
58
|
+
[--all] [--in ID] [--occurrence N] [--whole-word]
|
|
59
|
+
Find text anywhere (body, tables, headers, footers) and replace it.
|
|
60
|
+
Refuses a find that matches more than once unless --all, --in or
|
|
61
|
+
--occurrence says which.
|
|
62
|
+
comment FILE -o OUT --text TEXT (--find TEXT | --in ID) [--in ID]
|
|
63
|
+
Add a Word comment anchored to TEXT (or to the whole paragraph ID).
|
|
64
|
+
edit FILE -o OUT [PATCHES.json | -] [--dry-run]
|
|
65
|
+
Apply a JSON array of docxtor patches (stdin when omitted or "-").
|
|
66
|
+
All-or-nothing: if any patch fails nothing is written. --dry-run
|
|
67
|
+
checks every patch and reports each one without writing.
|
|
68
|
+
accept FILE -o OUT [--ids 3,4] [--by AUTHOR] [--others reject|keep]
|
|
69
|
+
reject FILE -o OUT [--ids 3,4] [--by AUTHOR] [--others accept|keep]
|
|
70
|
+
Resolve tracked changes: all of them, or only the listed w:ids
|
|
71
|
+
(from \`revisions\`) / authors. --others decides the rest (default keep).
|
|
72
|
+
metadata FILE -o OUT [--set key=value ...] [--scrub]
|
|
73
|
+
Set document properties, or --scrub identifying ones (author,
|
|
74
|
+
last modified by, company, manager, custom properties).
|
|
75
|
+
|
|
76
|
+
Common write options
|
|
77
|
+
--author NAME revision and comment author (default "docxtor")
|
|
78
|
+
--untracked edit directly instead of as tracked changes
|
|
79
|
+
`,Y={type:`string`},X={type:`boolean`};function Z(e){process.stderr.write(`error: ${e}\n`),process.exit(1)}function Q(e,n){try{return t({args:e,options:n,allowPositionals:!0,strict:!0})}catch(e){Z(`${e.message}\n\n${_a}`)}}const va={out:{...Y,short:`o`},author:Y,untracked:X};function ya(e){return{trackRevisions:!e.untracked,revisionAuthor:e.author??`docxtor`,inlineMarkers:!1,atomic:!0}}async function $(e){e||Z(`missing input file\n\n${_a}`);try{return await Ki.load(e)}catch(t){Z(`cannot open ${e}: ${t.message}`)}}function ba(e){return e||Z(`missing -o OUT (the file to write; it may be the input file to update it in place)`),e}async function xa(e,t,n,r){let i=await e.toBuffer(),a=e.applyPatches(t,n),o=a.filter(e=>!e.success);if(o.length>0){let e=await Sa(i,t,a,n),r=a.flatMap((t,n)=>t.success?[]:[` ${JSON.stringify(t.patch)}\n -> ${e.get(n)}`]);Z(`${o.length} of ${a.length} patches failed; nothing was written.\n${r.join(`
|
|
80
|
+
`)}`)}return await e.toFile(r),a}async function Sa(e,t,n,r){let i=new Map;for(let a=0;a<n.length;a++){if(n[a].success)continue;let o=await Ki.load(e);o.applyPatches(t.slice(0,a),{...r,atomic:!1}),i.set(a,Ca(o,n[a].error??``))}return i}function Ca(e,t){let n=/in paragraph "([^"]+)"/.exec(t);if(n){let r=e.findParagraphById(n[1])??e.findParagraphByParaId(n[1].replace(/^para:/,``));if(r)return`${t}\n ${n[1]} currently reads: "${r.text.length>300?`${r.text.slice(0,300)}…`:r.text}"`}return/not found/i.test(t)&&/["'](p\d|tbl\d|hdr\.|ftr\.|para:)/.test(t)?`${t}\n (ids come from \`view FILE\`; ids are positional, so re-run view after edits that add or remove paragraphs)`:t}async function wa(e){let{values:t,positionals:n}=Q(e,{grep:Y,context:Y,formatting:X,"no-revisions":X,styles:X,json:X}),r=await $(n[0]);if(t.json){process.stdout.write(`${JSON.stringify(r.project(`json`,{includeRevisions:!t[`no-revisions`],includeFormatting:!!t.formatting}),null,1)}\n`);return}let i=r.project(`markdown`,{includeRevisions:!t[`no-revisions`],includeFormatting:!!t.formatting});if(t.styles||(i=i.replace(/\n*--- Available Styles ---[\s\S]*$/,``)),t[`no-revisions`]||(i=Ta(r,i)),t.grep){let e;try{e=new RegExp(t.grep,`iu`)}catch(e){Z(`bad --grep: ${e.message}`)}let n=i.split(`
|
|
81
|
+
`),r=t.context===void 0?0:Number(t.context);(!Number.isInteger(r)||r<0)&&Z(`--context must be a whole number of paragraphs, got "${t.context}"`);let a=new Set;n.forEach((t,i)=>{if(e.test(t))for(let e=Math.max(0,i-r);e<=Math.min(n.length-1,i+r);e++)a.add(e)});let o=[...a].sort((e,t)=>e-t),s=[];o.forEach((e,t)=>{r>0&&t>0&&e!==o[t-1]+1&&s.push(`--`),s.push(n[e])}),i=s.length?s.join(`
|
|
82
|
+
`):`no paragraph matches /${t.grep}/i (try a shorter or different pattern; view FILE without --grep shows everything)`}process.stdout.write(`${i}\n`)}function Ta(e,t){let n=new Map,r=e=>{for(let t of e)for(let e of t.rows){let i=h(e.xmlRef).find(e=>p(e)===`w:trPr`),a=i?h(i).find(e=>p(e)===`w:ins`||p(e)===`w:del`):void 0;if(a){let r=v(a,`w:author`);n.set(`${t.id}.r${e.index}.`,p(a)===`w:ins`?`{+row inserted${r?` by ${r}`:``}+}`:`{-row deleted${r?` by ${r}`:``}-}`)}for(let t of e.cells)r(t.nestedTables)}};r(e.getTables());for(let t of[...e.getHeaders().values(),...e.getFooters().values()])r(t.tables);return n.size===0?t:t.split(`
|
|
83
|
+
`).map(e=>{let t=/^\| \[(\S*\.r\d+\.)c\d+\.p\d+\]/.exec(e),r=t?n.get(t[1]):void 0;return r?`${e} ${r}`:e}).join(`
|
|
84
|
+
`)}async function Ea(e){let{values:t,positionals:n}=Q(e,{json:X}),r=ha(await $(n[0]));process.stdout.write(t.json?`${JSON.stringify(r,null,1)}\n`:`${ga(r)}\n`)}async function Da(e){let{values:t,positionals:n}=Q(e,{json:X}),r=da(await $(n[0]));process.stdout.write(t.json?`${JSON.stringify(r,null,1)}\n`:`${pa(r)}\n`)}async function Oa(e){let{values:t,positionals:n}=Q(e,{...va,find:{...Y,multiple:!0},replace:{...Y,multiple:!0},all:X,in:Y,occurrence:Y,"whole-word":X}),r=t.find??[],i=t.replace??[];(r.length===0||r.length!==i.length)&&Z(`give --find and --replace in pairs`);let a=ba(t.out),o=await $(n[0]),s=(e,n)=>!t.in||e===t.in||n===t.in.replace(/^para:/,``);t.in&&!Yi(o).some(e=>s(e.para.id,e.para.paraId))&&Z(`no paragraph ${t.in}`);let c=ya(t),l=[];for(let e=0;e<r.length;e++){let n=r[e],a=i[e],u=Yi(o).filter(e=>s(e.para.id,e.para.paraId)),d=[];for(let e of $i(n))if(d=u.flatMap(({para:n})=>Qi(n.text,e,!!t[`whole-word`]).map(e=>({id:n.id,text:n.text,start:e}))),d.length){n=e;break}if(d.length===0&&Z(`"${r[e]}" not found${t.in?` in ${t.in}`:``}; nothing was written. Text in a docx may differ from what you expect (quotes, dashes, non-breaking spaces, a tracked deletion); check with: view FILE --grep '<a distinctive word>'`),t.occurrence){let e=Number(t.occurrence);(!Number.isInteger(e)||e<1||e>d.length)&&Z(`--occurrence ${t.occurrence}: there are ${d.length} matches`),d=[d[e-1]]}else if(d.length>1&&!t.all){let e=d.slice(0,20).map((e,t)=>` ${t+1}. [${e.id}] ${ea(e.text,e.start,e.start+n.length,40)}`);Z(`"${n}" matches ${d.length} times; nothing was written. Use --all, --in ID or --occurrence N (counted in this list):\n${e.join(`
|
|
85
|
+
`)}${d.length>20?`
|
|
86
|
+
…`:``}`)}let f=na(n,a),p=[...d].reverse().map(e=>{let t=e.start+f.offset;if(f.kind===`insert`)return{type:`insert_text`,target:e.id,position:f.position,anchor:f.anchor,text:f.text,occurrence:Xi(e.text,f.anchor,t)};let n=Xi(e.text,f.find,t);return f.kind===`delete`?{type:`delete_text`,target:e.id,find:f.find,occurrence:n}:{type:`replace_text`,target:e.id,find:f.find,replace:f.replace,occurrence:n}}),m=o.applyPatches(p,c).filter(e=>!e.success);m.length&&Z(`${m.length} replacements of "${n}" failed; nothing was written.\n${m.map(e=>` ${JSON.stringify(e.patch)} -> ${e.error}`).join(`
|
|
87
|
+
`)}`);let h=[...new Set(d.map(e=>e.id))],g=f.kind===`insert`?`inserted "${f.text}"`:f.kind===`delete`?`deleted "${f.find}"`:`"${f.find}" -> "${f.replace}"`,_=f.kind!==`replace`||f.find!==n||f.replace!==a?` (marked: ${g})`:``;l.push(`"${n}" -> "${a}"${_}: ${d.length} replacement${d.length===1?``:`s`} in ${h.length} paragraph${h.length===1?``:`s`} (${h.slice(0,12).join(`, `)}${h.length>12?`, …`:``})`)}await o.toFile(a),process.stdout.write(`${l.join(`
|
|
88
|
+
`)}\nwrote ${a}${t.untracked?``:` (tracked, author "${t.author??`docxtor`}")`}\n`)}async function ka(e){let{values:t,positionals:n}=Q(e,{...va,find:Y,text:Y,in:Y,occurrence:Y});t.text||Z(`missing --text`),!t.find&&!t.in&&Z(`give --find TEXT (the passage to anchor on) or --in ID`);let r=ba(t.out),i=await $(n[0]),a=t.in,o=t.find,s;if(o){let e=Yi(i).filter(e=>!t.in||e.para.id===t.in||e.para.paraId===t.in.replace(/^para:/,``)),n=[];for(let t of $i(o))if(n=e.flatMap(({para:e})=>Qi(e.text,t,!1).map(t=>({id:e.id,text:e.text,start:t}))),n.length){o=t;break}if(n.length===0&&Z(`"${t.find}" not found; check with: view FILE --grep '<a distinctive word>'`),t.occurrence){let e=Number(t.occurrence);(!Number.isInteger(e)||e<1||e>n.length)&&Z(`--occurrence ${t.occurrence}: there are ${n.length} matches`),n=[n[e-1]]}else if(n.length>1){let e=n.slice(0,20).map((e,t)=>` ${t+1}. [${e.id}] ${ea(e.text,e.start,e.start+o.length,40)}`);Z(`"${o}" matches ${n.length} times; give a longer --find, --in ID or --occurrence N:\n${e.join(`
|
|
89
|
+
`)}`)}a=n[0].id,s=Xi(n[0].text,o,n[0].start)}let c=t.author??`docxtor`;await xa(i,[{type:`add_comment`,target:a,text:t.text,author:c,markers:!1,...o?{find:o,occurrence:s}:{}}],{...ya(t),trackRevisions:!1},r),process.stdout.write(`comment on [${a}]${o?` anchored to "${o}"`:``} by "${c}"\nwrote ${r}\n`)}async function Aa(t){let{values:n,positionals:r}=Q(t,{...va,"dry-run":X}),i=n[`dry-run`]?``:ba(n.out),a=await $(r[0]),o=r[1],s;if(!o||o===`-`){let e=[];for await(let t of process.stdin)e.push(t);s=Buffer.concat(e).toString(`utf8`)}else s=await e(o,`utf8`);let c;try{let e=JSON.parse(s);c=Array.isArray(e)?e:[e]}catch(e){Z(`patches are not valid JSON: ${e.message}`)}if(n[`dry-run`]){let e=await a.toBuffer(),t=a.applyPatches(c,ya(n)),r=t.filter(e=>!e.success).length,i=await Sa(e,c,t,ya(n));t.forEach((e,t)=>process.stdout.write(`${t+1}. ${e.success?`ok`:`FAILS`} ${e.patch.type}${`target`in e.patch&&e.patch.target?` ${e.patch.target}`:``}${e.success?``:`\n -> ${i.get(t)}`}\n`)),process.stdout.write(r?`${r} of ${t.length} would fail; fix them and run again.\n`:`all ${t.length} would apply; run again without --dry-run and with -o OUT to write.\n`),r&&process.exit(1);return}let l=await xa(a,c,ya(n),i);process.stdout.write(`applied ${l.length} patch${l.length===1?``:`es`}\nwrote ${i}${n.untracked?``:` (tracked, author "${n.author??`docxtor`}")`}\n`)}function ja(e){let t=e.getAST().xmlParts.app?.find(e=>p(e)?.endsWith(`Properties`)),n={};for(let e of t?h(t):[]){let t=(p(e)??``).replace(/^.*:/,``);if(t===`Company`||t===`Manager`){let r=h(e).map(e=>e[`#text`]===void 0?``:x(String(e[`#text`]))).join(``);r&&(n[t.toLowerCase()]=r)}}return n}const Ma=[`creator`,`lastModifiedBy`,`title`,`subject`,`description`,`keywords`,`category`,`contentStatus`,`revision`,`created`,`modified`];async function Na(e){let{values:t,positionals:n}=Q(e,{out:{...Y,short:`o`},set:{...Y,multiple:!0},scrub:X,json:X}),r=await $(n[0]),i=()=>{let e={...r.getCoreProperties(),...ja(r)};if(t.json){process.stdout.write(`${JSON.stringify(e,null,1)}\n`);return}for(let t of[...Ma,`company`,`manager`])e[t]!==void 0&&e[t]!==``&&process.stdout.write(`${t}: ${e[t]}\n`)};if(!t.set&&!t.scrub){i();return}let a=ba(t.out);if(t.scrub&&r.scrubMetadata(),t.set){let e={};for(let n of t.set){let t=n.indexOf(`=`),r=n.slice(0,t);(t<1||!Ma.includes(r))&&Z(`--set takes key=value with key one of: ${Ma.join(`, `)}`),e[r]=n.slice(t+1)}r.setCoreProperties(e)}await r.toFile(a),i(),process.stdout.write(`wrote ${a}\n`)}async function Pa(e,t){let{values:n,positionals:r}=Q(t,{out:{...Y,short:`o`},ids:Y,by:{...Y,multiple:!0},others:Y}),i=ba(n.out),a=await $(r[0]),o=n.ids?.split(/[\s,]+/).map(e=>e.replace(/^#/,``)).filter(Boolean),s=e===`accept`?`reject`:`accept`;if(n.others&&n.others!==s&&n.others!==`keep`&&Z(`--others must be ${s} or keep`),o){let e=new Set(da(a).flatMap(e=>e.ids)),t=o.filter(t=>!e.has(t));t.length&&Z(`no tracked change has w:id ${t.join(`, `)} (run: revisions FILE)`)}let c={...o?{ids:o}:{},...n.by?{authors:n.by}:{}},l=e===`accept`?a.acceptAllRevisions(c).accepted:a.rejectAllRevisions(c).rejected,u=``;n.others===s&&(u=`, ${s}ed the other ${s===`accept`?a.acceptAllRevisions().accepted:a.rejectAllRevisions().rejected}`),await a.toFile(i);let d=da(a).length;process.stdout.write(`${e}ed ${l} revision${l===1?``:`s`}${u}; ${d} change${d===1?``:`s`} still tracked\nwrote ${i}\n`)}async function Fa(){let[e,...t]=process.argv.slice(2);switch(e){case`view`:return wa(t);case`revisions`:return Da(t);case`comments`:return Ea(t);case`replace`:return Oa(t);case`comment`:return ka(t);case`edit`:return Aa(t);case`accept`:return Pa(`accept`,t);case`reject`:return Pa(`reject`,t);case`metadata`:return Na(t);case void 0:case`help`:case`-h`:case`--help`:process.stdout.write(_a);return;default:Z(`unknown command "${e}"\n\n${_a}`)}}process.stdout.on(`error`,e=>{throw e.code===`EPIPE`&&process.exit(0),e}),Fa().catch(e=>Z(e.stack??String(e)));export{};
|