@betteroffice/docx 0.3.0 → 0.4.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 +64 -0
- package/dist/chunk-24Z6ZVFZ.mjs +1 -0
- package/dist/chunk-2QHGQA3V.mjs +1 -0
- package/dist/{chunk-ACGKK7IB.mjs → chunk-3CYO46ML.mjs} +1 -1
- package/dist/chunk-6CHGYCFU.mjs +1 -0
- package/dist/chunk-AOWJ4WDE.mjs +1 -0
- package/dist/chunk-DLXIZBB6.mjs +1 -0
- package/dist/chunk-F2VBW6RB.mjs +1 -0
- package/dist/chunk-HPZFJGGM.mjs +0 -0
- package/dist/chunk-L2ML3DDI.mjs +1 -0
- package/dist/chunk-LIGZ75FP.mjs +1 -0
- package/dist/chunk-LT2GCWZ3.mjs +0 -0
- package/dist/chunk-ND3FBCB3.mjs +16 -0
- package/dist/{chunk-NT2OYIJ4.mjs → chunk-NMDQHUQB.mjs} +1 -1
- package/dist/chunk-NVN26RHH.mjs +1 -0
- package/dist/{chunk-H5YYCN42.mjs → chunk-OK5UFGX3.mjs} +1 -1
- package/dist/{chunk-VQXNED2P.mjs → chunk-RZQ3OXZY.mjs} +1 -1
- package/dist/{chunk-QE4ZDRKV.mjs → chunk-YLFKV2NT.mjs} +1 -1
- package/dist/collaboration/index.d.mts +5 -4
- package/dist/compareDocx-IHFPGIGV.mjs +1 -0
- package/dist/computeLayout-4MNWHE2T.mjs +1 -0
- package/dist/core.d.mts +4 -4
- package/dist/core.mjs +1 -1
- package/dist/{displayListQueries-BYFrBkw5.d.mts → displayListQueries-H5YnU_hX.d.mts} +23 -5
- package/dist/docx/index.mjs +1 -1
- package/dist/editor/index.d.mts +15 -7
- package/dist/editor/index.mjs +1 -1
- package/dist/{fontLoader-CkXcPB1C.d.mts → fontLoader-BNSs0E8K.d.mts} +54 -1
- package/dist/{frameDelta-CVt5FAXT.d.mts → frameDelta-ByU7HBuB.d.mts} +21 -1
- package/dist/generated/edit/docx_edit_bg.wasm +0 -0
- package/dist/generated/layout/docx_layout_bg.wasm +0 -0
- package/dist/generated/opc/ooxml_opc_bg.wasm +0 -0
- package/dist/generated/parse/docx_parse_bg.wasm +0 -0
- package/dist/{index-BbZwdkPz.d.mts → index-CHy6_Yuo.d.mts} +470 -14
- package/dist/layout/index.d.mts +2 -2
- package/dist/layout/index.mjs +1 -1
- package/dist/layout/pagination/index.d.mts +2 -2
- package/dist/layout/render/index.d.mts +118 -31
- package/dist/layout/render/index.mjs +1 -1
- package/dist/loadWasmAsset-Cr95TImt.d.mts +25 -0
- package/dist/{pagedExport-D3E4jZ-B.d.mts → pagedExport---0Dlmzo.d.mts} +1 -1
- package/dist/parseWasm-NLAG22EU.mjs +1 -0
- package/dist/plugin-api/RenderedDomContext.d.mts +6 -4
- package/dist/plugin-api/RenderedDomContext.mjs +1 -1
- package/dist/{rustDisplayList-CwOoUn3t.d.mts → rustDisplayList-LcRZHCSL.d.mts} +12 -4
- package/dist/{rustMeasureSource-CyBMcy1x.d.mts → rustMeasureSource-BkCx1FDx.d.mts} +2 -0
- package/dist/types/document.d.mts +3 -0
- package/dist/{types-B4jD0rrc.d.mts → types-D6Pra38E.d.mts} +12 -3
- package/dist/utils/index.d.mts +14 -2
- package/dist/utils/index.mjs +1 -1
- package/dist/wasm-GSI2XMOH.mjs +1 -0
- package/dist/{wasm-G62X4WRW.mjs → wasm-K6DRABAA.mjs} +1 -1
- package/dist/wasm-NF6B3AH7.mjs +1 -0
- package/dist/wasm-edit.d.mts +177 -18
- package/dist/wasm-edit.mjs +1 -1
- package/dist/wasm-layout.d.mts +1 -1
- package/dist/wasm-layout.mjs +1 -1
- package/dist/wasm-opc.d.mts +1 -1
- package/dist/wasm-opc.mjs +1 -1
- package/dist/wasm-parse.d.mts +1 -1
- package/dist/wasm-parse.mjs +1 -1
- package/dist/yrs/index.d.mts +4 -3
- package/dist/yrs/index.mjs +1 -1
- package/dist/yrs/residentEngineWorker.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-5B4VMUXM.mjs +0 -16
- package/dist/chunk-5F6DLQZP.mjs +0 -1
- package/dist/chunk-5JEQC76K.mjs +0 -1
- package/dist/chunk-7GJG6LLU.mjs +0 -1
- package/dist/chunk-FE6FWGBJ.mjs +0 -1
- package/dist/chunk-HLDJMU3R.mjs +0 -1
- package/dist/chunk-J7LNO6SM.mjs +0 -1
- package/dist/chunk-PGMXWI5X.mjs +0 -1
- package/dist/chunk-Z4HZIPBS.mjs +0 -1
- package/dist/compareDocx-XXTZV4CG.mjs +0 -1
- package/dist/computeLayout-LWLAJWYA.mjs +0 -1
- package/dist/loadWasmAsset-CMvnVkfA.d.mts +0 -3
- package/dist/wasm-US6R7SWN.mjs +0 -1
package/dist/yrs/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {f,g,c,a,d as d$2,e}from'../chunk-5JEQC76K.mjs';export{g as yrsToDocument}from'../chunk-5JEQC76K.mjs';export{a as residentCaretDeviceRect,b as residentCaretSnapshotForFrame}from'../chunk-J7LNO6SM.mjs';import {d as d$1}from'../chunk-VQXNED2P.mjs';import {b as b$5}from'../chunk-OBQGPMPQ.mjs';import {d,a as a$1,b as b$3}from'../chunk-47Q2FMFF.mjs';import {b as b$2,p}from'../chunk-LTVVQMHB.mjs';import {b as b$4}from'../chunk-CTBUQRYQ.mjs';import {b as b$1,c as c$1}from'../chunk-QE4ZDRKV.mjs';import'../chunk-HLDJMU3R.mjs';import'../chunk-ACGKK7IB.mjs';import'../chunk-5F6DLQZP.mjs';import {b}from'../chunk-TTRUPDAB.mjs';function Xt(e,r){let n=0,o=r.map(s=>{let a={paraId:s.paraId,length:Math.max(0,Math.trunc(s.length)),displayStart:n};return n+=a.length+2,a});return {story:e,paragraphs:o}}function Ce(e,r){let n=e.paragraphs.find(o=>o.paraId===r.paraId);return !n||r.story!==e.story?e.paragraphs[0]?.displayStart??0:n.displayStart+1+Math.min(Math.max(0,r.offset),n.length)}function Qt(e,r){if(e.paragraphs.length===0)return null;let n=Math.max(0,Math.trunc(r)),o=e.paragraphs[0];for(let s of e.paragraphs){if(s.displayStart>n)break;o=s;}return {story:e.story,paraId:o.paraId,offset:Math.min(Math.max(0,n-(o.displayStart+1)),o.length)}}function Zt(e,r,n){return Ce(e,r)-Ce(e,n)}var nt={bootstrap:15e3,sync:15e3,attachCanvases:15e3,buildFrame:5e3,applyInput:5e3,applyDelete:5e3};function ot(){return new Worker(new URL("./residentEngineWorker.mjs",import.meta.url),{type:"module",name:"openooxml-resident-engine"})}var oe=class{constructor(r=ot()){b(this,"worker",r);b(this,"pending",new Map);b(this,"nextId",1);b(this,"terminalError",null);b(this,"ready",false);b(this,"revision",0);b(this,"remoteVector",null);b(this,"appliedFontsRevision",null);this.worker.onmessage=n=>{let o=n.data;if(o.ok&&o.stateVector&&(this.remoteVector=new Uint8Array(o.stateVector)),!o.ok&&o.terminal){this.fail(new U(o.error));return}let s=this.pending.get(o.id);s&&(this.pending.delete(o.id),clearTimeout(s.timeout),o.ok?s.resolve(o):s.reject(at(o.error,o.residentUnavailable)));},this.worker.onerror=n=>{this.fail(new O(`Resident engine worker failed: ${n.message}`));},this.worker.onmessageerror=()=>{this.fail(new O("Resident engine worker returned an unreadable message"));};}isReady(){return this.ready}layoutRevision(){return this.revision}remoteStateVector(){return this.remoteVector}syncedFontsRevision(){return this.appliedFontsRevision}async bootstrap(r,n){let o=r.fontsRevision,s=await this.request({type:"bootstrap",snapshot:r,extras:n,expectedFrameEpoch:0},ve(r)),a=j(s);return this.recordSync(s,o),this.ready=true,this.revision=a.layoutRevision,a}async sync(r,n,o,s=false){let a=r.fontsRevision,d=await this.request({type:"sync",snapshot:r,extras:n,expectedFrameEpoch:o,paintCaret:s},ve(r)),u=j(d);return this.recordSync(d,a),this.ready=true,this.revision=u.layoutRevision,u}async buildFrame(r,n,o=false){return j(await this.request({type:"buildFrame",extras:r,expectedFrameEpoch:n,paintCaret:o}))}async applyInput(r,n,o,s=false,a=false){if(!this.ready)return {applied:false};try{return {applied:!0,...j(await this.request({type:"applyInput",text:r,selection:n,expectedFrameEpoch:o,profile:s,paintCaret:a}))}}catch(d){if(d instanceof U)return {applied:false};throw d}}async applyDelete(r,n,o,s=false,a=false){if(!this.ready)return {applied:false};try{return {applied:!0,...j(await this.request({type:"applyDelete",direction:r,selection:n,expectedFrameEpoch:o,profile:s,paintCaret:a}))}}catch(d){if(d instanceof U)return {applied:false};throw d}}eraseCaret(){if(this.terminalError)return;let n={id:this.nextId++,type:"eraseCaret"};this.worker.postMessage(n);}invalidate(r,n){if(this.terminalError)return;this.ready=false;let o=r.slice(),a={id:this.nextId++,type:"applyUpdate",update:o,selection:n};this.worker.postMessage(a,[o.buffer]);}async attachCanvases(r,n,o,s,a){let d=r.map(u=>u.canvas);await this.request({type:"attachCanvases",pages:r,activePageIds:n,devicePixelRatio:o,zoom:s,caretStyle:a},d);}destroy(){if(this.terminalError)return;let n={id:this.nextId++,type:"destroy"};this.worker.postMessage(n),this.fail(new O("Resident engine worker was destroyed"));}request(r,n=[]){if(this.terminalError)return Promise.reject(this.terminalError);let o=this.nextId++,s=nt[r.type];return new Promise((a,d)=>{let u=setTimeout(()=>{this.fail(new O(`Resident engine worker did not answer ${r.type} within ${s}ms`));},s);this.pending.set(o,{resolve:a,reject:d,timeout:u}),this.worker.postMessage({...r,id:o},n);})}recordSync(r,n){this.appliedFontsRevision=n;}fail(r){this.terminalError=r,this.ready=false,this.worker.terminate();for(let n of this.pending.values())clearTimeout(n.timeout),n.reject(r);this.pending.clear();}},U=class extends Error{},O=class extends Error{};function at(e,r=false){return r?new U(e):new Error(e)}function ve(e){return [e.state.buffer,...e.fonts.flatMap(r=>r instanceof Uint8Array?[r.buffer]:[])]}function j(e){if(!e.frame)throw new O("Resident engine worker response omitted its FrameDelta");if(!e.caret)throw new O("Resident engine worker response omitted its caret snapshot");if(e.selection===void 0)throw new O("Resident engine worker response omitted its selection");return {frame:new Uint8Array(e.frame),updates:(e.updates??[]).map(r=>new Uint8Array(r)),engineMs:e.engineMs??0,workerTotalMs:e.workerTotalMs??0,engineProfile:e.engineProfile,caret:e.caret,selection:e.selection,caretPainted:e.caretPainted??false,replayMs:e.replayMs??0,replayedPages:e.replayedPages??0,layoutRevision:e.layoutRevision??0}}function st(){return typeof Worker<"u"}function ae(e,r,n,o,s,a){let d=r?.pPr;if(!r?.tblStylePr?.some(T=>T.pPr))return d;let u=e.formatting?.look??r.tblPr?.look,c=(T,E)=>u?.[T]??(Number.parseInt(u?.value??(u?"0":"04A0"),16)&E)!==0,f=c("firstRow",32),l=c("lastRow",64),y=c("firstColumn",128),b=c("lastColumn",256),S=e.rows[n].formatting?.gridBefore??0;o+=S,s+=S;let h=!!f&&n===0,p=!!l&&n===e.rows.length-1,x=!!y&&o===0,C=!!b&&s===a,I=e.formatting?.styleRowBandSize??r.tblPr?.styleRowBandSize??1,w=e.formatting?.styleColBandSize??r.tblPr?.styleColBandSize??1,Y=[];!c("noHBand",512)&&!h&&!p&&I>0&&Y.push(Math.floor((n-+!!f)/I)%2===0?"band1Horz":"band2Horz"),!c("noVBand",1024)&&!x&&!C&&w>0&&Y.push(Math.floor((o-+!!y)/w)%2===0?"band1Vert":"band2Vert");for(let[T,E]of [["firstCol",x],["lastCol",C],["firstRow",h],["lastRow",p],["nwCell",h&&x],["neCell",h&&C],["swCell",p&&x],["seCell",p&&C]])E&&Y.push(T);for(let T of Y)d=b$3(d,r.tblStylePr.find(E=>E.type===T)?.pPr);return d}function Ie(e){return Math.max(e.columnWidths?.length??0,...e.rows.map(r=>r.cells.reduce((n,o)=>n+(o.formatting?.gridSpan??1),(r.formatting?.gridBefore??0)+(r.formatting?.gridAfter??0))))}function D(e){if(Array.isArray(e))return e.map(D);if(e!==null&&typeof e=="object"){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=D(o));return r}return e}var it={styleId:"pStyle",_sectionProperties:"sectPr"},lt=new Set(["paraId","textId","renderedPageBreakBefore","numPrFromStyle"]);function Te(e){let r={};for(let[n,o]of Object.entries(e))lt.has(n)||o===null||o===void 0||(r[it[n]??n]=D(o));return r}var dt=new Set(["columnWidths"]);function K(e,r=new Set){let n={};for(let[o,s]of Object.entries(e))r.has(o)||s===null||s===void 0||(n[o]=D(s));return n}function Ye(e){return K(e,dt)}function we(e){let r=e.columnWidths;return Array.isArray(r)?r.map(D):[]}function _e(e){return K(e)}function Ae(e,r){let n=K(e);return r&&(n.header=true),n}function se(e,r,n,o){return `${e}:t${r}:r${n}c${o}`}function De(e,r){return `${e}:sdt${r}`}function Oe(e){return K(e)}function G(e){return `hf:${e}`}function Fe(e){return `fn:${e}`}function Me(e){return `en:${e}`}function ut(e){let r=e.package.settings?.compatibilityFlags?.compatibilityMode;return typeof r=="number"&&Number.isFinite(r)?Math.trunc(r):12}var pt=new Set(["bold","italic","superscript","subscript","allCaps","smallCaps","emboss","imprint","textShadow","textOutline","hidden","rtl"]);function W(e){if(e==null)return "null";if(Array.isArray(e))return `[${e.map(W).join(",")}]`;if(typeof e=="object"){let r=e;return `{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${W(r[n])}`).join(",")}}`}return JSON.stringify(e)}function ct(e,r){if(!e||!r)return e;let n=r.resolveRunStyle(e.styleId);return n?a$1(n,e):e}function Be(e){if(!e)return [];let r=[],n=(d,u={})=>r.push({name:d,attrs:u});e.bold&&n("bold"),e.italic&&n("italic"),e.underline&&e.underline.style!=="none"&&n("underline",{style:e.underline.style,color:e.underline.color??null}),(e.strike||e.doubleStrike)&&n("strike",{double:e.doubleStrike||false}),e.color&&!e.color.auto&&n("textColor",{rgb:e.color.rgb??null,themeColor:e.color.themeColor??null,themeTint:e.color.themeTint??null,themeShade:e.color.themeShade??null});let o=e.shading?.fill,s=(!e.shading?.pattern||e.shading.pattern==="clear")&&o?.rgb&&!o.auto?p(o.rgb):void 0,a=e.highlight&&e.highlight!=="none"?e.highlight:s;return a&&n("highlight",{color:a}),(e.fontSize!=null||e.fontSizeCs!=null)&&n("fontSize",{size:e.fontSize??null,sizeCs:e.fontSizeCs??null}),e.fontFamily&&n("fontFamily",{ascii:e.fontFamily.ascii??null,hAnsi:e.fontFamily.hAnsi??null,eastAsia:e.fontFamily.eastAsia??null,cs:e.fontFamily.cs??null,asciiTheme:e.fontFamily.asciiTheme??null,hAnsiTheme:e.fontFamily.hAnsiTheme??null,eastAsiaTheme:e.fontFamily.eastAsiaTheme??null,csTheme:e.fontFamily.csTheme??null}),e.vertAlign==="superscript"?n("superscript"):e.vertAlign==="subscript"&&n("subscript"),e.allCaps&&n("allCaps"),e.smallCaps&&n("smallCaps"),(e.spacing!=null||e.position!=null||e.scale!=null||e.kerning!=null)&&n("characterSpacing",{spacing:e.spacing??null,position:e.position??null,scale:e.scale??null,kerning:e.kerning??null}),e.emboss&&n("emboss"),e.imprint&&n("imprint"),e.shadow&&n("textShadow"),e.emphasisMark&&e.emphasisMark!=="none"&&n("emphasisMark",{type:e.emphasisMark}),e.outline&&n("textOutline"),e.hidden&&n("hidden"),e.rtl&&n("rtl"),e.snapToGrid===false&&r.push({name:"snapToGrid",attrs:{}}),e.effect&&e.effect!=="none"&&n("textEffect",{effect:e.effect}),e.modernEffects&&n("modernTextEffects",{effects:e.modernEffects}),e.styleId&&n("runStyle",{styleId:e.styleId}),r}function Le(e){let r={};for(let n of e)n.name==="comment"||n.name==="footnoteRef"||(pt.has(n.name)?r[n.name]=true:n.name==="snapToGrid"?r.snapToGrid=false:n.name==="highlight"?r.highlight=n.attrs.color:n.name==="insertion"||n.name==="deletion"?r[n.name==="insertion"?"ins":"del"]=D({id:n.attrs.revisionId,author:n.attrs.author,date:n.attrs.date}):r[n.name]=D(n.attrs));return r}function ft(e){return e.filter(r=>r.name!=="hyperlink"&&r.name!=="comment").map(r=>`${r.name}:${JSON.stringify(r.attrs)}`).sort().join("|")}function gt(e,r){return [...e.filter(n=>n.name!==r.name),r]}function z(e,r,n){return {kind:"text",text:e,attrs:Le(r),pmSize:e.length,...n!==void 0?{commentId:n}:{},marks:[...r]}}function v(e,r,n=[],o,s=1){return {kind:"embed",embedKind:e,payload:r,attrs:Le(n),pmSize:s,...o!==void 0?{commentId:o}:{},marks:[...n]}}function Ue(e,r,n){let o=e.formatting?.styleId?n?.getRunStyleOwnProperties(e.formatting.styleId):void 0,s=Be(a$1(a$1(r,o),e.formatting)),a=e.formatting?.styleId,d=a?n?.getStyle(a)?.name:void 0;if([a,d].some(u=>/^(?:Followed)?Hyperlink$/i.test(u??""))){for(let[u,c]of [["color","textColor"],["underline","underline"]])if(e.formatting?.[u]===void 0&&o?.[u]!==void 0){let f=s.find(l=>l.name===c);f&&(f.attrs.inheritedHyperlink=true);}}return s}function mt(e){let r=e.size?.width?b$4(e.size.width):void 0,n=e.size?.height?b$4(e.size.height):void 0,o=e.wrap.type,s=e.wrap.wrapText,a=e.position?.horizontal?.alignment,d;o==="inline"||o==="topAndBottom"?d="none":o==="square"||o==="tight"||o==="through"?s==="left"?d="right":s==="right"?d="left":a==="left"||a==="right"?d=a:d="none":d="none";let u=o==="inline"?"inline":o==="topAndBottom"?"block":b$5(o)||d&&d!=="none"?"float":"block",c=[];e.transform?.rotation&&c.push(`rotate(${e.transform.rotation}deg)`),e.transform?.flipH&&c.push("scaleX(-1)"),e.transform?.flipV&&c.push("scaleY(-1)");let f,l,y;if(e.outline?.width){f=Math.round(e.outline.width/914400*96*100)/100,e.outline.color?.rgb&&(l=`#${e.outline.color.rgb}`);let b={solid:"solid",dot:"dotted",dash:"dashed",lgDash:"dashed",dashDot:"dashed",lgDashDot:"dashed",lgDashDotDot:"dashed",sysDot:"dotted",sysDash:"dashed",sysDashDot:"dashed",sysDashDotDot:"dashed"};y=e.outline.style&&b[e.outline.style]||"solid";}return D({src:e.src||"",alt:e.alt??null,title:e.title??null,width:r??null,height:n??null,rId:e.rId??null,wrapType:o,displayMode:u,cssFloat:d??null,transform:c.length>0?c.join(" "):null,distTop:e.wrap.distT!=null?b$4(e.wrap.distT):null,distBottom:e.wrap.distB!=null?b$4(e.wrap.distB):null,distLeft:e.wrap.distL!=null?b$4(e.wrap.distL):null,distRight:e.wrap.distR!=null?b$4(e.wrap.distR):null,position:e.position?{relativeHeight:e.position.relativeHeight,horizontal:e.position.horizontal?{relativeTo:e.position.horizontal.relativeTo,posOffset:e.position.horizontal.posOffset,align:e.position.horizontal.alignment}:void 0,vertical:e.position.vertical?{relativeTo:e.position.vertical.relativeTo,posOffset:e.position.vertical.posOffset,align:e.position.vertical.alignment}:void 0}:null,borderWidth:f??null,borderColor:l??null,borderStyle:y??null,wrapText:s??null,hlinkHref:e.hlinkHref??null,cropTop:e.crop?.top??null,cropRight:e.crop?.right??null,cropBottom:e.crop?.bottom??null,cropLeft:e.crop?.left??null,shapeType:e.shapeType??null,opacity:e.opacity??null,effectExtentTop:e.padding?.top?b$4(e.padding.top):null,effectExtentBottom:e.padding?.bottom?b$4(e.padding.bottom):null,effectExtentLeft:e.padding?.left?b$4(e.padding.left):null,effectExtentRight:e.padding?.right?b$4(e.padding.right):null,layoutInCell:e.layoutInCell??null,allowOverlap:e.allowOverlap??null})}function yt(e){return {shapeJson:JSON.stringify(e)}}function ht(e){return D({chartJson:JSON.stringify(e),chartType:e.chartType??null,title:e.title??null,width:e.size?.width?b$4(e.size.width):320,height:e.size?.height?b$4(e.size.height):220,rId:e.rId??null,path:e.path??null})}function $(e,r){let n="",o,s=e.type==="simpleField"?e.content:e.fieldResult;for(let u of s)if(u.type==="run"){for(let c of u.content)c.type==="text"&&(n+=c.text);!o&&u.formatting&&(o=u.formatting);}let a=o??(e.type==="complexField"?e.formatting:void 0),d=e.fieldTree?.displayMode??"result";return {payload:{fieldType:e.fieldType,instruction:e.instruction,displayText:n,fieldKind:e.type==="simpleField"?"simple":"complex",fldLock:e.fldLock??false,dirty:e.dirty??false,displayMode:d,hasCachedResult:n.length>0,fieldData:JSON.stringify(e),modelKind:"field"},marks:Be(a$1(r,a))}}function de(e){return {display:e.display,ommlXml:e.ommlXml,plainText:e.plainText||""}}function bt(e){return {name:"hyperlink",attrs:{href:e.href||(e.anchor?`#${e.anchor}`:""),tooltip:e.tooltip??null,rId:e.rId??null}}}function St(e,r,n,o){let s=e.structuredResult?.inline??[],d=[...(e.type==="complexField"?e.structuredCode?.inline??[]:[]).map((y,b)=>({child:y,index:-b-1})),...s.map((y,b)=>({child:y,index:b}))];if(e.type!=="complexField"||!d.some(({child:y})=>y.type==="hyperlink"||y.type==="simpleField")){let y=$(e,r);return [v("field",y.payload,y.marks)]}let u=[],c=[];d.forEach(({child:y,index:b})=>{if(y.type!=="hyperlink"&&y.type!=="simpleField")return;let S=y.type==="simpleField"?$(y,r):null,h=y.type==="hyperlink"?Q(y,r,n):[v("field",S.payload,S.marks)];c.push({index:b,items:h.map(p=>p.kind==="text"?{kind:"text",text:p.text,attributes:p.attrs}:{kind:"embed",embedKind:p.embedKind,payload:p.payload,attributes:p.attrs})});for(let p of h)p.attrs={...p.attrs,fieldResult:{id:o,index:b}};u.push(...h);});let f={...e,fieldResult:s.filter(y=>y.type==="run")},l=$(f,r);return l.payload.fieldData=JSON.stringify(e),l.payload.resultProjection={id:o,children:c},u.push(v("field",l.payload,l.marks)),u}function Ee(e,r,n,o){let s={name:"footnoteRef",attrs:{id:String(e),noteType:r}},a=[...n,s];return v("noteRef",r==="endnote"?{endnoteRefId:e}:{footnoteRefId:e},a,o)}function ie(e){return e.filter(r=>r.name==="insertion"||r.name==="deletion")}function ue(e,r,n){switch(e.type){case "text":return e.text?[z(e.text,r,n)]:[];case "tab":return [z(" ",r,n)];case "break":return e.breakType===void 0||e.breakType==="textWrapping"?[v("break",{},r,n)]:[];case "softHyphen":return [z("\xAD",r,n)];case "noBreakHyphen":return [z("\u2011",r,n)];case "symbol":{let o=Number.parseInt(e.char,16);if(!Number.isInteger(o)||o<0||o>1114111)return [];let s={name:"fontFamily",attrs:{ascii:e.font||null,hAnsi:e.font||null,eastAsia:e.font||null,cs:e.font||null,asciiTheme:null,hAnsiTheme:null,eastAsiaTheme:null,csTheme:null}};return [z(String.fromCodePoint(o),gt(r,s),n)]}case "commentReference":return [v("field",{fieldType:"COMMENT",instruction:"",displayText:"",fieldKind:"simple",fldLock:false,dirty:false,displayMode:"result",hasCachedResult:false,modelKind:"commentReference",...e.id!==void 0?{commentId:e.id}:{}})];case "drawing":return [v("image",mt(e.image),ie(r))];case "horizontalRule":return [v("horizontalRule",{rule:e.rule},r,n)];case "shape":return [v("shape",yt(e.shape),ie(r))];case "chart":return [v("chart",ht(e.chart),ie(r))];case "footnoteRef":return [Ee(e.id,"footnote",r,n)];case "endnoteRef":return [Ee(e.id,"endnote",r,n)];default:return []}}function X(e,r,n,o,s=[]){let a=[...Ue(e,r,n),...s];return e.content.flatMap(d=>ue(d,a,o))}function Q(e,r,n,o=[]){let s=[],a=bt(e);for(let d of e.structuredChildren??e.children)if(d.type==="run"){let u=[...Ue(d,r,n),...o,a];for(let c of d.content)s.push(...ue(c,u));}else if(d.type==="simpleField"||d.type==="complexField"){let u=$(d,r);s.push(v("field",u.payload,[...u.marks,...o,a]));}else d.type==="mathEquation"&&s.push(v("math",de(d),[...o,a]));return s}function Rt(e,r,n){return {name:r,attrs:{revisionId:e.id,author:e.author,date:e.date??null,isMovePair:n}}}function xt(e,r,n,o){let s=e.type==="insertion"||e.type==="moveTo"?"insertion":"deletion",a=Rt(e.info,s,e.type==="moveFrom"||e.type==="moveTo"),d=[];for(let u of e.content)if(u.type==="run")d.push(...X(u,r,n,o,[a]));else {let c=Q(u,r,n,[a]);for(let f of c)o!==void 0&&(f.commentId=o);d.push(...c);}return d}function We(e,r,n){let o=[],s=a=>{if(a.kind==="text"){if((a.text===" "?"tab":"text")==="tab"){o.push({kind:"tab",attrs:a.attrs});return}let u=o[o.length-1];u&&"text"in u&&W(u.attrs)===W(a.attrs)?u.text+=a.text:o.push({kind:"text",text:a.text,attrs:a.attrs});return}o.push({kind:a.embedKind,payload:a.payload,attrs:a.attrs});};for(let a of e.content)if(a.type==="run")X(a,r,n).forEach(s);else if(a.type==="hyperlink")Q(a,r,n).forEach(s);else if(a.type==="simpleField"||a.type==="complexField"){let d=$(a,r);s(v("field",d.payload,d.marks));}else a.type==="inlineSdt"?s(v("sdt",We(a,r,n))):a.type==="mathEquation"&&s(v("math",de(a)));return D({...d$2(e.properties),propertiesJson:JSON.stringify(e.properties),content:o})}function kt(e,r,n){let o=r?r.resolveParagraphStyle(e.formatting?.styleId).runFormatting:void 0;return a$1(o,n)}function Pt(e){let r=[];for(let n of e.content)n.type==="footnoteRefMark"?r.push("footnote"):n.type==="endnoteRefMark"&&r.push("endnote");return r}function je(e){return e.map(r=>{if(r.kind==="text")return r.text;let n=r.payload.footnoteRefId??r.payload.endnoteRefId;return String(n??"")}).join("")}function Ne(e){return e.type!=="break"?null:e.breakType==="page"||e.breakType==="column"?e.breakType:null}function Ct(e){if(!e.content.some(o=>Ne(o)!==null))return [];let r=[],n=0;for(let o of e.content){let s=Ne(o);if(s!==null){r.push({offset:n,type:s});continue}n+=je(ue(o,[])).length;}return r}function vt(e,r,n){let o=X(e,r,n);if(o.some(c=>c.kind!=="text"&&c.embedKind!=="noteRef"))return null;let s=o.map(c=>ft(c.marks));if(s.some(c=>c!==s[0]))return null;let a=Pt(e),d=Ct(e),u=s[0];return {text:je(o),...a.length>0?{noteMarks:a}:{},...d.length>0?{breaks:d}:{},...u!==void 0?{marksKey:u}:{},...e.formatting?{formatting:e.formatting}:{},...e.propertyChanges?{propertyChanges:e.propertyChanges}:{}}}function It(e,r,n,o,s){let a=e.formatting,d=a?.styleId,u=a?.indentFirstLine===0?void 0:a?.indentFirstLine,c=u??e.listRendering?.indentFirstLine??a?.indentFirstLine,f=u===void 0&&e.listRendering?.indentFirstLine!==void 0?e.listRendering.hangingIndent:a?.hangingIndent??e.listRendering?.hangingIndent,l={paraId:e.paraId??null,textId:e.textId??null,styleId:d??null,numPr:a?.numPr??null,numPrFromStyle:a?.numPrFromStyle??null,listNumFmt:e.listRendering?.numFmt??null,listIsBullet:e.listRendering?.isBullet??null,listMarker:e.listRendering?.marker??null,listMarkerHidden:e.listRendering?.markerHidden||null,listMarkerFontFamily:e.listRendering?.markerFontFamily||null,listMarkerFontSize:e.listRendering?.markerFontSize||null,listMarkerBold:e.listRendering?.markerBold??null,listMarkerItalic:e.listRendering?.markerItalic??null,listMarkerColor:e.listRendering?.markerColor??null,listMarkerSuffix:e.listRendering?.markerSuffix||null,listLevelNumFmts:e.listRendering?.levelNumFmts||null,listAbstractNumId:e.listRendering?.abstractNumId??null,listStartOverride:e.listRendering?.startOverride??null,_originalFormatting:a??null};if(r){let h=r.resolveParagraphStyle(d,s),p=h.paragraphFormatting;l.alignment=a?.alignment??p?.alignment??null,l.spaceBefore=a?.spaceBefore??p?.spaceBefore??null,l.spaceAfter=a?.spaceAfter??p?.spaceAfter??null,l.spaceBeforeLines=a?.spaceBeforeLines??p?.spaceBeforeLines??null,l.spaceAfterLines=a?.spaceAfterLines??p?.spaceAfterLines??null,l.beforeAutospacing=a?.beforeAutospacing??p?.beforeAutospacing??null,l.afterAutospacing=a?.afterAutospacing??p?.afterAutospacing??null,l.lineSpacing=a?.lineSpacing??p?.lineSpacing??null,l.lineSpacingRule=a?.lineSpacingRule??p?.lineSpacingRule??null,l.spacingExplicit=a?.spacingExplicit||null,l.indentLeft=a?.indentLeft??e.listRendering?.indentLeft??p?.indentLeft??null,l.indentRight=a?.indentRight??p?.indentRight??null;let C=a?.numPr?.numId===0&&p?.numPr&&p.numPr.numId!==0?void 0:p;l.indentFirstLine=c??C?.indentFirstLine??null,l.hangingIndent=f??C?.hangingIndent??false,l.borders=a?.borders??p?.borders??null,l.shading=a?.shading??p?.shading??null,l.tabs=a?.tabs??p?.tabs??null,l.pageBreakBefore=a?.pageBreakBefore??p?.pageBreakBefore??null,l.keepNext=a?.keepNext??p?.keepNext??null,l.keepLines=a?.keepLines??p?.keepLines??null,l.widowControl=a?.widowControl??p?.widowControl??null,l.contextualSpacing=a?.contextualSpacing??p?.contextualSpacing??null,l.snapToGrid=a?.snapToGrid??p?.snapToGrid??null,l.autoSpaceDE=a?.autoSpaceDE??p?.autoSpaceDE??null,l.autoSpaceDN=a?.autoSpaceDN??p?.autoSpaceDN??null,l.outlineLevel=a?.outlineLevel??p?.outlineLevel??null,l.bidi=a?.bidi??p?.bidi??null;let I=r.getDefaultCharacterStyle()?.rPr,w=I?a$1(h.runFormatting,I):h.runFormatting;l.defaultTextFormatting=a$1(w,ct(a?.runProperties,r))??null,!a?.numPr&&p?.numPr&&p.numPr.numId!==0&&(l.numPr=p.numPr,l.numPrFromStyle=p.numPr);}else l.alignment=a?.alignment??null,l.spaceBefore=a?.spaceBefore??null,l.spaceAfter=a?.spaceAfter??null,l.spaceBeforeLines=a?.spaceBeforeLines??null,l.spaceAfterLines=a?.spaceAfterLines??null,l.beforeAutospacing=a?.beforeAutospacing??null,l.afterAutospacing=a?.afterAutospacing??null,l.lineSpacing=a?.lineSpacing??null,l.lineSpacingRule=a?.lineSpacingRule??null,l.spacingExplicit=a?.spacingExplicit||null,l.indentLeft=a?.indentLeft??e.listRendering?.indentLeft??null,l.indentRight=a?.indentRight??null,l.indentFirstLine=c??null,l.hangingIndent=f??false,l.borders=a?.borders??null,l.shading=a?.shading??null,l.tabs=a?.tabs??null,l.pageBreakBefore=a?.pageBreakBefore??null,l.keepNext=a?.keepNext??null,l.keepLines=a?.keepLines??null,l.widowControl=a?.widowControl??null,l.snapToGrid=a?.snapToGrid??null,l.autoSpaceDE=a?.autoSpaceDE??null,l.autoSpaceDN=a?.autoSpaceDN??null,l.outlineLevel=a?.outlineLevel??null,l.bidi=a?.bidi??null,l.defaultTextFormatting=a?.runProperties??null;if(e.sectionProperties){l._sectionProperties=e.sectionProperties;let h=e.sectionProperties.sectionStart;(h==="nextPage"||h==="continuous"||h==="oddPage"||h==="evenPage"||h==="nextColumn")&&(l.sectionBreakType=h);}e.renderedPageBreakBefore&&(l.renderedPageBreakBefore=true),wt(e)&&(l.pageBreakBeforeRun=true),e.pPrIns&&(l.pPrIns={revisionId:e.pPrIns.id,author:e.pPrIns.author,date:e.pPrIns.date??null}),e.pPrDel&&(l.pPrDel={revisionId:e.pPrDel.id,author:e.pPrDel.author,date:e.pPrDel.date??null}),e.propertyChanges?.length&&(l.pPrChange=e.propertyChanges);let y=[],b=0,S=0;for(let h of e.content)if(h.type==="bookmarkStart")y.push({id:h.id,name:h.name,kind:"start",offset:S,...h.colFirst!==void 0?{colFirst:h.colFirst}:{},...h.colLast!==void 0?{colLast:h.colLast}:{}});else if(h.type==="bookmarkEnd")y.push({id:h.id,kind:"end",offset:S});else {let p=Tt(h);for(let x=0;x<p;x+=1)S+=n[b]?.pmSize??0,b+=1;}return y.length>0&&(l.bookmarks=y),o?.length&&(l._originalRunBoundaries=o),l}var ze=new WeakMap;function Tt(e){return ze.get(e)??0}function Yt(e,r,n,o){let s=[],a=new Set,d=[],u=kt(e,r,n);for(let[f,l]of e.content.entries()){let y=s.length,b=a.values().next().value;if(l.type==="commentRangeStart")a.add(l.id);else if(l.type==="commentRangeEnd")a.delete(l.id);else if(l.type==="run"){let S=vt(l,u,r);S&&d?d.push(S):d=void 0,s.push(...X(l,u,r,b));}else if(l.type==="hyperlink"){d=void 0;let S=Q(l,u,r);for(let h of S)b!==void 0&&(h.commentId=b);s.push(...S);}else l.type==="simpleField"||l.type==="complexField"?(d=void 0,s.push(...St(l,u,r,f))):l.type==="inlineSdt"?(d=void 0,s.push(v("sdt",We(l,u,r),[],void 0,2))):l.type==="insertion"||l.type==="deletion"||l.type==="moveFrom"||l.type==="moveTo"?(d=void 0,s.push(...xt(l,u,r,b))):l.type==="mathEquation"?(d=void 0,s.push(v("math",de(l)))):l.type!=="bookmarkStart"&&l.type!=="bookmarkEnd"&&l.type!=="rawXml"&&(d=void 0);ze.set(l,s.length-y);}let c=It(e,r,s,d,o);return {units:s,ppr:Te(c)}}function H(e,r){for(let n of e.content)n.type==="break"&&n.breakType==="page"?r.push("pageBreak"):(n.type!=="text"||n.text.length>0)&&r.push("visible");}function pe(e,r){for(let n of e)if(n.type==="run")H(n,r);else if(n.type==="hyperlink")for(let o of n.children)o.type==="run"&&H(o,r);else if(n.type==="simpleField")for(let o of n.content)o.type==="run"&&H(o,r);else if(n.type==="complexField")for(let o of [...n.fieldCode,...n.fieldResult])H(o,r);else if(n.type==="inlineSdt")pe(n.content,r);else if(n.type==="insertion"||n.type==="deletion"||n.type==="moveFrom"||n.type==="moveTo")for(let o of n.content)o.type==="run"&&H(o,r);else n.type==="mathEquation"&&r.push("visible");}function wt(e){let r=[];return pe(e.content,r),r[0]==="pageBreak"}function _t(e){let r=[];pe(e.content,r);let n=false,o=false;for(let s of r)if(s==="pageBreak"){if(o||n)return true;n=true;}else o=true;return false}function At(e){let r=new Map,n=new Map;return e.rows.forEach((o,s)=>{let a=0,d=o.cells.map(c=>{let f=a;return a+=c.formatting?.gridSpan??1,{column:f,vMerge:c.formatting?.vMerge,key:`${s}-${f}`}});if(d.length>0&&d.every(c=>c.vMerge==="continue"&&n.has(c.column))){for(let c of d)n.delete(c.column),r.set(c.key,{rowSpan:1,skip:false});return}for(let c of d)if(c.vMerge==="restart")n.set(c.column,s),r.set(c.key,{rowSpan:1,skip:false});else if(c.vMerge==="continue"){let f=n.get(c.column);if(f===void 0)r.set(c.key,{rowSpan:1,skip:false});else {let l=r.get(`${f}-${c.column}`);l&&(l.rowSpan+=1),r.set(c.key,{rowSpan:1,skip:true});}}else n.delete(c.column),r.set(c.key,{rowSpan:1,skip:false});}),r}function le(e){return {revisionId:e.id,author:e.author,date:e.date??null}}function Dt(e,r,n,o,s,a){let d=r?{top:n?r.top:r.insideH,bottom:o?r.bottom:r.insideH,left:s?r.left:r.insideV,right:a?r.right:r.insideV}:void 0;return d||e?.borders?{...d??{},...e?.borders??{}}:void 0}function Je(e,r){let n=e.formatting,o=b$2(n?.shading?.fill,r.theme),s=n?.width?.value??r.gridWidth,a=n?.width?.type??(r.gridWidth!==void 0?"pct":null),d={colspan:n?.gridSpan??1,rowspan:r.rowspan,width:s??null,widthType:a,verticalAlign:n?.verticalAlign??null,backgroundColor:o??null,borders:Dt(n,r.tableBorders,r.firstRow,r.lastRow,r.firstColumn,r.lastColumn)??null,margins:n?.margins?{top:n.margins.top?.value,bottom:n.margins.bottom?.value,left:n.margins.left?.value??(r.tableBidi?n.margins.end?.value:n.margins.start?.value),right:n.margins.right?.value??(r.tableBidi?n.margins.start?.value:n.margins.end?.value)}:r.defaultMargins??null,textDirection:n?.textDirection??null,noWrap:n?.noWrap??false,_originalFormatting:n??null,_originalResolvedFill:o??null};if(e.structuralChange){let u=e.structuralChange,c=le(u.info);u.type==="tableCellInsertion"?d.cellMarker={kind:"ins",info:c}:u.type==="tableCellDeletion"?d.cellMarker={kind:"del",info:c}:u.type==="tableCellMerge"&&(d.cellMarker={kind:"merge",info:c,vMerge:u.vMerge??"cont",...u.vMergeOrig?{vMergeOrig:u.vMergeOrig}:{}});}return e.propertyChanges?.length&&(d.tcPrChange=e.propertyChanges),{attrs:Ae(d,r.isHeader),content:e.content.length>0?e.content:[{type:"paragraph",content:[]}]}}function Ot(e,r,n,o,s,a,d,u,c){let f={height:e.formatting?.height?.value??null,heightRule:e.formatting?.heightRule??null,isHeader:!!e.formatting?.header,_originalFormatting:e.formatting??null};e.structuralChange&&(e.structuralChange.type==="tableRowInsertion"?f.trIns=le(e.structuralChange.info):e.structuralChange.type==="tableRowDeletion"&&(f.trDel=le(e.structuralChange.info))),e.propertyChanges?.length&&(f.trPrChange=e.propertyChanges);let l=r.columnWidths,y=l?.reduce((p,x)=>p+x,0)??0,b=l?.length??Math.max(0,...r.rows.map(p=>p.cells.reduce((x,C)=>x+(C.formatting?.gridSpan??1),0))),S=0,h=[];return e.cells.forEach(p=>{let x=p.formatting?.gridSpan??1,C=S,I=o.get(`${n}-${C}`),w;if(l&&y>0){let Y=0;for(let T=0;T<x&&C+T<l.length;T+=1)Y+=l[C+T];w=Math.round(Y/y*100);}S+=x,!I?.skip&&h.push({paragraphFormatting:ae(r,u,n,C,S,c),...Je(p,{isHeader:n===0&&!!r.formatting?.look?.firstRow,rowspan:I?.rowSpan??1,gridWidth:w,firstRow:n===0,lastRow:n===r.rows.length-1,firstColumn:C===0,lastColumn:S===b,tableBorders:s,defaultMargins:a,theme:d,tableBidi:!!r.formatting?.bidi})});}),h.length===0&&h.push({paragraphFormatting:ae(r,u,n,0,b,c),...Je({formatting:b>1?{gridSpan:b}:void 0,content:[{type:"paragraph",content:[]}]},{isHeader:n===0&&!!r.formatting?.look?.firstRow,rowspan:1,gridWidth:y>0?100:void 0,firstRow:n===0,lastRow:n===r.rows.length-1,firstColumn:true,lastColumn:true,tableBorders:s,defaultMargins:a,theme:d,tableBidi:!!r.formatting?.bidi})}),{attrs:_e(f),cells:h}}function Ft(e,r,n,o){let s=r?.getDefaultTableStyle(),a=e.formatting?.styleId,d=a??s?.styleId,u=d?r?.getStyle(d):void 0,c=e.formatting?.borders??u?.tblPr?.borders??s?.tblPr?.borders,f=e.formatting?.cellMargins??u?.tblPr?.cellMargins??s?.tblPr?.cellMargins,l=e.formatting?.bidi?f?.end:f?.start,y=e.formatting?.bidi?f?.start:f?.end,b=f?{top:f.top?.value,bottom:f.bottom?.value,left:f.left?.value??l?.value,right:f.right?.value??y?.value}:void 0,S=[],h=new Set,p=u;for(;p?.basedOn&&S.length<32&&!h.has(p.basedOn);)h.add(p.basedOn),S.unshift(p.basedOn),p=r?.getStyle(p.basedOn);let x={...e.formatting??{},styleCascade:{...a?{selectedStyleId:a}:{},...s?.styleId?{defaultStyleId:s.styleId}:{},...S.length>0?{basedOnStyleIds:S}:{}}},C={styleId:a??null,width:e.formatting?.width?.value??null,widthType:e.formatting?.width?.type??null,justification:e.formatting?.justification??null,columnWidths:e.columnWidths??null,tableLayout:e.formatting?.layout??null,floating:e.formatting?.floating??null,cellMargins:b??null,look:e.formatting?.look??null,bidi:e.formatting?.bidi||null,compatibilityMode:o===12?null:o,_originalFormatting:x};e.propertyChanges?.length&&(C.tblPrChange=e.propertyChanges);let I=At(e),w=Ie(e);return {attrs:C,rows:e.rows.map((Y,T)=>Ot(Y,e,T,I,c,b,n,u??s,w))}}function Mt(e){return Oe(d$2(e))}function Et(e){let r=0;for(let n of e.units){let o=n.kind==="text"?n.text.length:1;if(n.commentId!==void 0&&n.commentId!==0){let s=e.commentCoverage.get(n.commentId),a=s?.[s.length-1];a&&a[1]===r?a[1]=r+o:s?s.push([r,r+o]):e.commentCoverage.set(n.commentId,[[r,r+o]]);}r+=o;}}function He(e,r,n){if(c(n))return null;if(n.type==="paragraph"){let o=e.paragraph++;return !n.repeatedParaId&&n.paraId||`${r}:p${o}`}return n.type==="table"?`${r}:t${e.table++}`:De(r,e.sdt++)}function Nt(e){return /^\d+$/.test(e.trim())}function Jt(e){let r=e.structuredResult?.blocks??[],n=r[r.length-1];return !n||n.type!=="paragraph"||(n.content?.length??0)>0?null:r.length}function Bt(e,r,n,o,s,a){for(let d of e){if(d.kind!=="embed"||d.embedKind!=="field")continue;let u=d.payload.instruction;if(typeof u!="string"||!Nt(u))continue;let c=d.payload.fieldData;if(typeof c!="string")continue;let f;try{f=JSON.parse(c);}catch{continue}let l=Jt(f);if(l===null||o+1+l>n.length)continue;let y={...s},b=[];for(let S=0;S<l;S+=1){let h=n[o+1+S],p=He(y,r,h);p!==null&&(h.type==="table"&&a.set(o+1+S,p),b.push(p));}b.length>0&&(d.payload.fieldResultBlocks=b);}}function J(e,r,n,o){let s={storyId:r,units:[],commentCoverage:new Map};e.plans.push(s);let a=n.length>0,d=a?[...n]:[{type:"paragraph",content:[]}],u={paragraph:0,table:0,sdt:0},c$1=new Map,f=null;for(let[l,y]of d.entries()){if(c(y))continue;let b=u.table,S=He(u,r,y);if(S===null)continue;if(y.type==="paragraph"){let p=Yt(y,e.styleResolver,o.extraRunFormatting,o.tableParagraphFormatting);Bt(p.units,r,d,l,u,c$1),s.units.push(...p.units),s.units.push(v("pilcrow",{...p.ppr,...a&&y.paraId?{sourceParaId:y.paraId}:{},...a?{}:{paraOrigin:"synthetic"},paraId:S})),o.includePageBreaks&&_t(y)&&s.units.push(v("pageBreak",{})),f="paragraph";continue}if(y.type==="table"){let p=Ft(y,e.styleResolver,e.theme,e.compatibilityMode),x=p.rows.map((I,w)=>({trPr:I.attrs,cells:I.cells.map((Y,T)=>({tcPr:Y.attrs,story:se(r,b,w,T)}))})),C=c$1.get(l);s.units.push(v("table",{tblPr:Ye(p.attrs),grid:we(p.attrs),rows:x,...C===void 0?{}:{blockId:C}})),p.rows.forEach((I,w)=>{I.cells.forEach((Y,T)=>{J(e,se(r,b,w,T),Y.content,{includePageBreaks:false,appendBodyTail:false,seedComments:false,extraRunFormatting:Y.extraRunFormatting,tableParagraphFormatting:Y.paragraphFormatting});});}),f="table";continue}let h=S;s.units.push(v("blockSdt",{...Mt(y.properties),story:h})),J(e,h,y.content,{includePageBreaks:o.includePageBreaks,appendBodyTail:false,seedComments:false,tableParagraphFormatting:o.tableParagraphFormatting}),f="blockSdt";}o.appendBodyTail&&(f==="table"||f==="blockSdt")&&s.units.push(v("pilcrow",{hangingIndent:false,paraId:`${r}:p${u.paragraph}`,paraOrigin:"synthetic"})),o.seedComments&&Et(s);}function Lt(e){let r=[{op:"delete",index:0,len:1}],n=0,o="",s={},a=W(s),d=()=>{o&&(r.push({op:"insert",index:n,text:o,attrs:s}),n+=o.length,o="");};for(let u of e)if(u.kind==="text"){let c=W(u.attrs);o&&c!==a&&d(),s=u.attrs,a=c,o+=u.text;}else d(),r.push({op:"insertEmbed",index:n,kind:u.embedKind,payload:u.payload,attrs:u.attrs}),n+=1;return d(),r}function Ut(e,r){let n=Lt(r.units);for(let[o,s]of r.commentCoverage)n.push({op:"setComment",id:String(o),ranges:s,author:"",date:"",body:null});e.applySeedRawOps(r.storyId,n);}function Wt(e,r,n={}){f(e,"all");let o={styleResolver:r.package.styles?d(r.package.styles):null,theme:r.package.theme??null,plans:[],compatibilityMode:ut(r)};J(o,"body",r.package.document.content,{includePageBreaks:true,appendBodyTail:true,seedComments:true});for(let[s,a]of r.package.headers??[])J(o,G(s),a.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let[s,a]of r.package.footers??[])o.plans.some(d=>d.storyId===G(s))||J(o,G(s),a.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let s of r.package.footnotes??[])J(o,Fe(s.id),s.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let s of r.package.endnotes??[])J(o,Me(s.id),s.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let s of o.plans)e.createStory(s.storyId,"","Normal","left");for(let s of o.plans)Ut(e,s);e.beginOpening(n.generation);}function jt(e){let r=e.package;return [r.document.content,...[...r.headers?.values()??[]].map(n=>n.content),...[...r.footers?.values()??[]].map(n=>n.content),...(r.footnotes??[]).map(n=>n.content),...(r.endnotes??[]).map(n=>n.content)]}var zt="word/comments.xml";function $e(e){if(Array.isArray(e)&&e.length>0&&e.every(n=>n?.type==="paragraph"))return e;let r=typeof e=="string"?e:"";return [{type:"paragraph",formatting:{},content:r?[{type:"run",formatting:{},content:[{type:"text",text:r}]}]:[]}]}function Ht(e,r){let n=r.package.document.comments??[],o=new Map(e.listComments().map(f=>[f.id,f])),s=false,a=n.map(f=>{let l=o.get(String(f.id));return o.delete(String(f.id)),!l||!l.author&&!l.date&&l.body==null?f:(s=true,{...f,...l.author?{author:l.author}:{},...l.date?{date:l.date}:{},...l.body==null?{}:{content:$e(l.body)}})}),d=new Set(n.map(f=>f.id)),u=new Map,c=Math.max(0,...d)+1;for(let f of o.values()){s=true;let l=/^\d+$/.test(f.id)?Number(f.id):Number.NaN;if(!Number.isSafeInteger(l)||d.has(l)){for(;d.has(c);)c+=1;l=c;}d.add(l),String(l)!==f.id&&u.set(l,f.id),a.push({id:l,author:f.author,...f.date?{date:f.date}:{},content:$e(f.body)});}return {comments:a,sessionIds:u,changed:s}}function $t(e$1,r){let n=new Map(r.paragraphs.flatMap(a=>a.session?[[a.session.paraId,a]]:[])),o=[],s=a=>{for(let d of a)if(d.type==="table")for(let u of d.rows)for(let c of u.cells)s(c.content);else if(d.type==="blockSdt")s(d.content);else if(d.type==="paragraph"&&d.paraId){let u=e(d),c=u===void 0?void 0:n.get(u);if(!c?.session||!c.persisted)continue;o.push({session:c.session,persisted:{...c.persisted,paraId:d.paraId}});}};for(let a of jt(e$1))s(a);return o}function qe(e){return {identities:e.paragraphIdentities(),plan:e.paragraphSavePlan()}}async function Ve(e,r,n,o,s={},a=()=>true){let d={...n.plan,patchedParts:n.plan.patchedParts.filter(({part:p})=>a(p))},u=$t(r,n.identities),{buffer:c}=await d$1(r,o,s,void 0,void 0,d),f=new Uint8Array(c),l=e.writtenParagraphIds(f),y=(p,x)=>l[p]?.includes(x.toUpperCase())??false,b=u.filter(({persisted:p})=>y(p.story.partUri,p.paraId)),S=new Set(e.recordSavedParagraphIds([...b.map(({session:p,persisted:x})=>[p.paraId,x.paraId]),...d.assignments.filter(({part:p,paraId:x})=>y(`/${p}`,x)).map(({part:p,ordinal:x,paraId:C})=>[`/${p}#${x}`,C])]).map(([p,x])=>`${p}\0${x}`)),h=({session:p,persisted:x})=>S.has(`${p.paraId}\0${x.paraId}`);return {bytes:f,paragraphs:b.filter(p=>!h(p)),conflicts:b.filter(h)}}async function qt(e,r={}){let n=e.materializeDocx();if(!n?.originalBuffer)throw new Error("saveYrsDocx requires a session opened from DOCX bytes");let o=qe(e),s=Ht(e,n),a=g(e,s.changed?{...n,package:{...n.package,document:{...n.package.document,comments:s.comments}}}:n,{commentIds:s.sessionIds});return Ve(e,a,o,n.originalBuffer,r,d=>!s.changed||d!==zt)}function wr(e,r){return !e||!r?e===r:e.anchor.story===r.anchor.story&&e.anchor.paraId===r.anchor.paraId&&e.anchor.offset===r.anchor.offset&&e.head.story===r.head.story&&e.head.paraId===r.head.paraId&&e.head.offset===r.head.offset}function Vt(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}function Ke(e){return JSON.stringify("revisionId"in e?{revisionId:e.revisionId}:{story:e.story,startPara:e.start.paraId,startOffset:e.start.offset,endPara:e.end.paraId,endOffset:e.end.offset})}function Ge(e){return JSON.stringify(e.map(r=>({story:r.story,startPara:r.start.paraId,startOffset:r.start.offset,endPara:r.end.paraId,endOffset:r.end.offset})))}function Xe(e){return e.kind==="search"?e.within.story:e.story}function Qe(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function Kt(e,r){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("DOCX host metadata must be an object");let o=n;if(!Array.isArray(o.referencedFonts)||!o.referencedFonts.every(a=>typeof a=="string"))throw new TypeError("DOCX host referencedFonts must be a string array");let s=c$1(o.envelope,Qe(r));return {document:s.document,referencedFonts:o.referencedFonts,embeddedFonts:s.embeddedFonts,...s.fontTableRelationshipsXml===void 0?{}:{fontTableRelationshipsXml:s.fontTableRelationshipsXml}}}function Gt(e,r){let n=new Map,o=[],s=false,a$1=false,d=0,u=0,c=false,f$1=false,l,y=null,b=[],S=new Map,h=new Map,p=null,x=false,C=0,I=0,w=false,Y=null,T=()=>{l=void 0,y=null;},E=()=>{if(!(a$1||c||u!==0)){c=true;try{for(;!a$1&&o.length>0;){let t=o.shift();if(!t)break;for(let[i,g]of [...n]){if(a$1)return;if(n.get(i)===g)try{g(t.update.slice(),t.origin);}catch{}}}}finally{c=false,a$1&&(o.length=0);}}},m=t=>{T(),u+=1;try{return t()}finally{u-=1,u===0&&E();}},ce=t=>t?{anchor:{...t.anchor},head:{...t.head}}:null,R=t=>{f$1||(e.track_undo(),f$1=true),t!==void 0&&(e.select_story(t),P(t));},P=t=>{f(Z,t);},_=t=>(P(t.createdStoryIds),P(t.deletedStoryIds),P(t.changedStoryIds),t),q=()=>(l!==void 0?l:JSON.parse(e.selection()))?.head.story??"all",Ze=()=>{s||(e.set_update_observer((t,i)=>{i!==0&&i!==1||(o.push({update:t.slice(),origin:i===0?"local":"remote"}),E());}),s=true);},et=()=>{!s||n.size>0||a$1||(o.length=0,e.clear_update_observer(),s=false);},fe=(t,i,g={})=>{let k=t.slice();P("all");let F=m(()=>e.open_docx(k,i,g.generation)),ee=Kt(F,k);return Y=k,ee},Z={clientId:r,registerFont:t=>{w||(e.clear_measure_fonts(),w=true);let i=e.register_measure_font(t);return b.push(t.slice()),I+=1,i},registerSubstituteFont:(t,i)=>{let g=e.register_substitute_measure_font(t,i);return g===t||(b.push({substituteOf:t,family:i}),I+=1),g},clearFonts:()=>{e.clear_measure_fonts(),b.length=0,h.clear(),I+=1,w=true;},measureParagraphJson:t=>{let i=e.measure_paragraph_json(t);return h.set(t,t),i},layoutDocumentJson:t=>{let i=e.layout_document_json(t);return p=t,x=false,C+=1,i},layoutFontRequirementsJson:t=>e.layout_font_requirements_json(t),layoutDocumentWithRegionsJson:t=>{let i=e.layout_document_with_regions_json(t);return p=t,x=true,C+=1,i},layoutDocumentWithRegionsRetainedJson:t=>{let i=e.layout_document_with_regions_retained_json(t);return p=t,x=true,C+=1,i},retainedKernelInputsJson:t=>{if(t!==C)throw new Error(`retained layout revision mismatch: expected ${t}, current ${C}`);return e.retained_kernel_inputs_json()},buildDisplayListJson:t=>e.build_display_list_json(t),buildDisplayListFrame:(t,i)=>e.build_display_list_frame(t,i),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),applyInput:(t,i)=>(R(),P(q()),m(()=>e.apply_input(t,i))),applyDelete:(t,i)=>(R(),P(q()),m(()=>e.apply_delete(t,i))),applyInputProfiled:(t,i)=>{R(),P(q());let g=m(()=>e.apply_input_profiled(t,i)),k=JSON.parse(e.apply_input_profile_json());return {frame:g,profile:k}},applyDeleteProfiled:(t,i)=>{R(),P(q());let g=m(()=>e.apply_delete_profiled(t,i)),k=JSON.parse(e.apply_input_profile_json());return {frame:g,profile:k}},residentWorkerSnapshot:t=>{if(!p||!x&&S.size===0)return null;let i=e.selection(),g=t?.knownFontsRevision===I,k=null;if(t?.knownStateVector)try{k=e.encode_diff(t.knownStateVector.slice());}catch{k=null;}return {clientId:r,state:k??e.encode_state(),selection:JSON.parse(i),fonts:g?[]:b.map(F=>F instanceof Uint8Array?F.slice():{...F}),fontsRevision:I,renderInputs:[...S].map(([F,ee])=>({story:F,env:structuredClone(ee)})),measureInputs:[...h.values()],layoutInput:p,layoutWithRegions:x,layoutRevision:C}},residentWorkerProbe:()=>!p||!x&&S.size===0?null:{layoutRevision:C},displayHitTestRegionsJson:(t,i,g)=>e.display_hit_test_regions_json(t,i,g),displayVerticalMoveJson:(t,i,g)=>e.display_vertical_move_json(t,i,g),displayRangeRectsJson:(t,i)=>e.display_range_rects_json(t,i),displayRangeRectsRegionJson:(t,i,g,k)=>e.display_range_rects_region_json(t,i,g,k),outlineGlyphJson:(t,i)=>e.outline_glyph_json(t,i),loadState:t=>{P("all"),m(()=>e.load(t));},seedFromDocx:(t,i)=>fe(t,true,i),openDocx:fe,beginOpening:t=>m(()=>e.begin_opening(t)),materializeDocx:()=>{let t=Y,i=e.materialize_docx();return !t||i===void 0?null:b$1(i,Qe(t)).document},loadStories:t=>(P(t.map(i=>i.storyId)),m(()=>JSON.parse(e.load_json(JSON.stringify(t))))),encodeState:()=>e.encode_state(),encodeStateVector:()=>e.encode_state_vector(),encodeStateAsUpdate:t=>t===void 0?e.encode_state():e.encode_diff(t.slice()),applyUpdate:t=>(P("all"),m(()=>JSON.parse(e.apply_update_with_inference(t)))),applyLocalUpdate:t=>{R(),P("all"),m(()=>e.apply_local_update(t));},onUpdate:t=>{if(a$1)throw new Error("yrs session is destroyed");if(typeof t!="function")throw new TypeError("update listener must be a function");let i=d++;n.set(i,t),Ze();let g=true;return ()=>{g&&(g=false,n.delete(i),et());}},encodeStickyPosition:t=>({story:t.story,encoded:e.encode_sticky_position(t.story,t.paraId,t.offset)}),resolveStickyPosition:t=>{try{return JSON.parse(e.resolve_sticky_position(t.story,t.encoded))}catch{return null}},setSelection:(t,i=t)=>{if(t.story!==i.story)throw new Error("yrs selection must stay inside one story");e.set_selection(t.story,t.paraId,t.offset,i.paraId,i.offset),l={anchor:{...t},head:{...i}};},selection:()=>(l!==void 0||(l=JSON.parse(e.selection())),ce(l)),encodeSelection:()=>{let t=JSON.parse(e.encoded_selection());return t?{story:t.story,anchor:Uint8Array.from(t.anchor),head:Uint8Array.from(t.head)}:null},resolveSelection:t=>{try{return JSON.parse(e.resolve_encoded_selection(t.story,t.anchor,t.head))}catch{return null}},setCellSelection:t=>e.set_cell_selection(JSON.stringify(t)),cellSelection:()=>JSON.parse(e.cell_selection()),beginUndoCapture:R,addUndoBoundary:()=>e.add_undo_boundary(),setUndoCaptureMode:t=>e.set_undo_capture_mode(t),undoCaptureMode:()=>e.undo_capture_mode(),historyStories:()=>e.history_stories(),undo:()=>m(()=>{let t=e.undo();return t&&P(e.history_stories()),t}),redo:()=>m(()=>{let t=e.redo();return t&&P(e.history_stories()),t}),canUndo:()=>e.can_undo(),canRedo:()=>e.can_redo(),createStory:(t,i,g="Normal",k="left")=>(P(t),m(()=>JSON.parse(e.create_story(t,i,g,k)))),deleteStory:t=>(P(t),m(()=>e.delete_story(t))),insertTable:(t,i,g,k)=>(R(t.story),m(()=>_(JSON.parse(e.insert_table(t.story,t.paraId,t.offset,i,g,k?.name,k?.date))))),insertRow:(t,i,g)=>(R(t.story),m(()=>_(JSON.parse(e.insert_row(JSON.stringify(t),i==="below",g?.name,g?.date))))),insertColumn:(t,i)=>(R(t.story),m(()=>_(JSON.parse(e.insert_column(JSON.stringify(t),i==="right"))))),deleteRow:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.delete_row(JSON.stringify(t),i?.name,i?.date))))),deleteColumn:t=>(R(t.anchor.story),m(()=>_(JSON.parse(e.delete_column(JSON.stringify(t)))))),deleteTable:t=>(R(t.story),m(()=>_(JSON.parse(e.delete_table(JSON.stringify(t)))))),mergeCells:t=>(R(t.anchor.story),m(()=>_(JSON.parse(e.merge_cells(JSON.stringify(t)))))),splitCell:(t,i,g)=>(R(t.story),m(()=>_(JSON.parse(e.split_cell(JSON.stringify(t),i,g))))),setCellShading:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.set_cell_shading(JSON.stringify(t),i??void 0))))),setCellTextFormat:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.set_cell_text_format(JSON.stringify(t),JSON.stringify(i)))))),setCellBorders:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.set_cell_borders(JSON.stringify(t),JSON.stringify(i)))))),setColumnWidth:(t,i)=>(R(t.story),m(()=>_(JSON.parse(e.set_column_width(JSON.stringify(t),i))))),setTableWidth:(t,i)=>(R(t.story),m(()=>_(JSON.parse(e.set_table_width(JSON.stringify(t),i))))),insertText:(t,i,g)=>(R(t.story),m(()=>JSON.parse(e.insert_text(t.story,t.paraId,t.offset,i,g?.name,g?.date)))),deleteRange:(t,i)=>(R(t.story),m(()=>JSON.parse(e.delete_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i?.name,i?.date)))),replaceRange:(t,i,g)=>(R(t.story),m(()=>JSON.parse(e.replace_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i,g?.name,g?.date)))),splitParagraph:(t,i)=>(R(t.story),m(()=>JSON.parse(e.split_paragraph(t.story,t.paraId,t.offset,i?.name,i?.date)))),mergeParagraphs:(t,i,g)=>(R(t),m(()=>JSON.parse(e.merge_paragraphs(t,i,g?.name,g?.date)))),toggleMark:(t,i)=>{R(t.story),m(()=>e.toggle_mark(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},formatRange:(t,i)=>{R(t.story),m(()=>e.format_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},setHyperlink:(t,i)=>{R(t.story),m(()=>e.set_hyperlink(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},clearFormatting:t=>{R(t.story),m(()=>e.clear_formatting(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset));},applyParagraphStyle:(t,i,g)=>{R(t.story),m(()=>e.apply_paragraph_style(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i,g?.name,g?.date));},setParagraphAttrs:(t,i,g)=>{R(t.story),m(()=>e.set_paragraph_attrs(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i),g?.name,g?.date));},insertImage:(t,i,g)=>(R(t.story),m(()=>JSON.parse(e.insert_image(t.story,t.paraId,t.offset,JSON.stringify(i),g?.name,g?.date)))),setContentControlValue:(t,i)=>{R(),P("all"),m(()=>e.set_content_control_value(t,JSON.stringify(i)));},setContentControlValueAt:(t,i)=>{R(t.story),typeof i=="string"&&P("all"),m(()=>e.set_content_control_value_at(t.story,t.paraId,t.offset,JSON.stringify(i)));},clearContentControlValue:t=>{R(),P("all"),m(()=>e.clear_content_control_value(t));},setImageGeometry:(t,i)=>{R(),P("all"),m(()=>e.set_image_geometry(t,JSON.stringify(i)));},setImageGeometryAt:(t,i)=>{R(t.story),m(()=>e.set_image_geometry_at(t.story,t.paraId,t.offset,JSON.stringify(i)));},insertPageBreak:t=>{R(t.story),m(()=>e.insert_page_break(t.story,t.paraId,t.offset));},insertSectionBreak:(t,i)=>{R(t.story),m(()=>e.insert_section_break(t.story,t.paraId,t.offset,i));},insertWatermark:(t,i)=>{R(t.story),m(()=>e.insert_watermark(t.story,t.paraId,t.offset,JSON.stringify(i)));},applyRawOps:(t,i)=>{let g=i.some(k=>k.op==="insertEmbed"&&k.kind==="pilcrow"||k.op==="setEmbedAttr"&&k.key==="paraId");P(g?"all":t),m(()=>e.apply_raw_ops(t,JSON.stringify(i)));},applySeedRawOps:(t,i)=>{P(t),m(()=>e.apply_seed_raw_ops(t,JSON.stringify(i)));},setParagraphAttr:(t,i,g)=>{P("all"),m(()=>e.set_paragraph_attr(t,i,JSON.stringify(g??null)));},addComment:(t,i,g,k)=>(P(t.map(F=>F.story)),m(()=>JSON.parse(e.add_comment(Ge(t),i,g,JSON.stringify(k??null))))),setCommentRanges:(t,i)=>{R(),m(()=>{e.set_comment_ranges(t,Ge(i)),P("all");});},acceptChange:t=>(P("all"),m(()=>JSON.parse(e.accept_change(Ke(t))))),rejectChange:t=>(P("all"),m(()=>JSON.parse(e.reject_change(Ke(t))))),selectionContext:t=>{let i=JSON.stringify(t);if(y?.key===i)return JSON.parse(y.json);let g=e.selection_context(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset),k=JSON.parse(g);return y={key:i,json:g},k},listRevisions:()=>JSON.parse(e.list_revisions()),resolveComment:t=>JSON.parse(e.resolve_comment(t)),listComments:()=>JSON.parse(e.list_comments()),storyIds:()=>e.story_ids(),storyLength:t=>e.story_len(t),storyChecksum:t=>BigInt(e.story_checksum(t)),yrsBlocksForStory:(t,i={})=>{let g=e.yrs_blocks_for_story(t,JSON.stringify(i)),k=JSON.parse(g);return S.set(t,structuredClone(i)),k},paragraphs:t=>JSON.parse(e.paragraphs(t)),searchText:(t,i={})=>{if(!t)return [];let g=i.limit??Number.POSITIVE_INFINITY;if(!Number.isSafeInteger(g)&&g!==Number.POSITIVE_INFINITY||g<0)throw new RangeError("search limit must be a non-negative safe integer");return JSON.parse(e.search_text(t,i.caseSensitive??false,Number.isFinite(g)?Math.min(g,4294967295):void 0))},paragraphSpans:t=>JSON.parse(e.paragraph_spans(t)),storySegments:t=>JSON.parse(e.story_segments(t)),locateParagraph:(t,i)=>JSON.parse(e.locate_paragraph(t,i)),paragraphIdentities:()=>JSON.parse(e.paragraph_identities()),persistParagraphIds:()=>(P("all"),m(()=>JSON.parse(e.persist_paragraph_ids()))),resolveParagraphAnchor:t=>JSON.parse(e.resolve_paragraph_anchor(JSON.stringify(t))),storyParagraphIds:t=>JSON.parse(e.story_paragraph_ids(t)),paragraphSavePlan:()=>JSON.parse(e.paragraph_save_plan()),recordSavedParagraphIds:t=>m(()=>JSON.parse(e.record_saved_paragraph_ids(JSON.stringify(t)))),writtenParagraphIds:t=>JSON.parse(e.written_paragraph_ids(t)),exportStructured:t=>JSON.parse(e.export_structured_json(JSON.stringify(t))),exportMarkdown:t=>JSON.parse(e.export_markdown_json(JSON.stringify(t))),exportStructuredWithPages:t=>JSON.parse(e.export_structured_with_pages_json(JSON.stringify(t),void 0)),exportStructuredWithPagesFor:(t,i)=>JSON.parse(e.export_structured_with_pages_json(JSON.stringify(t),i)),exportSnapshotWithPrivateFonts:(t,i,g,k)=>JSON.parse(e.export_snapshot_with_private_fonts_json(t,i,g,JSON.stringify(k))),headings:t=>JSON.parse(e.headings_json(t)),listContentControls:(t={})=>JSON.parse(e.list_content_controls_json(JSON.stringify(t))),findContentControls:(t,i={})=>JSON.parse(e.find_content_controls_json(JSON.stringify(t),JSON.stringify(i))),version:()=>e.version(),readParagraphs:t=>JSON.parse(e.read_paragraphs_json(JSON.stringify(t))),findText:t=>JSON.parse(e.find_text_json(JSON.stringify(t))),validateEdits:t=>JSON.parse(e.validate_edits_json(JSON.stringify(t))),applyEdits:t=>m(()=>{let i=JSON.parse(e.apply_edits_json(JSON.stringify(t)));return i.ok&&i.applied&&P(i.changedStories),i}),formatTextTarget:(t,i)=>(R(Xe(t)),m(()=>JSON.parse(e.format_text_target_json(JSON.stringify(t),JSON.stringify(i))))),commentTextTarget:(t,i)=>(P(Xe(t)),m(()=>JSON.parse(e.comment_text_target_json(JSON.stringify(t),JSON.stringify({...i,body:i.body??null}))))),selectionText:t=>JSON.parse(e.selection_text_json(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset)),destroy:()=>{a$1||(a$1=true,n.clear(),o.length=0,s&&e.clear_update_observer(),e.free());}};return a(Z,{compareDocx:(t,i,g)=>{P("all");let k=m(()=>e.compare_docx_json(t,i,g));return Y=t.slice(),k},finishComparedDocx:t=>e.finish_compared_docx_json(t),failComparedDocx:t=>e.fail_compared_docx_json(t)}),Z}async function _r(e){let r=e?.clientId??Vt(),n=await import('../wasm-US6R7SWN.mjs');return await n.preloadEditWasm(),Gt(n.createEditSession(r),r)}export{oe as ResidentEngineWorkerClient,O as ResidentWorkerFailureError,st as canUseResidentEngineWorker,qe as captureSessionSave,Zt as compareYrsLocs,Xt as createYrsInputPositionMap,_r as createYrsSession,Qt as displayPositionToYrsLoc,Wt as documentToYrs,wr as sameYrsSelection,qt as saveYrsDocx,Ve as writeSessionSave,Ce as yrsLocToDisplayPosition};
|
|
1
|
+
import {f,g,c as c$1,a,d as d$2,e}from'../chunk-LIGZ75FP.mjs';export{g as yrsToDocument}from'../chunk-LIGZ75FP.mjs';import {a as a$2}from'../chunk-F2VBW6RB.mjs';export{c as residentCaretDeviceRect,d as residentCaretSnapshotForFrame}from'../chunk-F2VBW6RB.mjs';import {d as d$1}from'../chunk-RZQ3OXZY.mjs';import {b as b$5}from'../chunk-OBQGPMPQ.mjs';import {d,a as a$1,b as b$3}from'../chunk-47Q2FMFF.mjs';import {b as b$2,p}from'../chunk-LTVVQMHB.mjs';import {b as b$4}from'../chunk-CTBUQRYQ.mjs';import {c,b as b$1}from'../chunk-YLFKV2NT.mjs';import'../chunk-LT2GCWZ3.mjs';import'../chunk-HPZFJGGM.mjs';import'../chunk-2QHGQA3V.mjs';import'../chunk-3CYO46ML.mjs';export{a as WASM32_MEMORY_LIMIT_BYTES,b as wasmModuleMemories}from'../chunk-6CHGYCFU.mjs';import {b}from'../chunk-TTRUPDAB.mjs';function Ke(e){let r=new Map;for(let n of e.proposals)if(n.state!=="proposed")for(let o of n.revisionIds)r.set(o,n.state);if(r.size!==0)return Object.fromEntries([...r].sort(([n],[o])=>n<o?-1:n>o?1:0))}function Re(e){return Array.isArray(e)?e.map(Re):e===null||typeof e!="object"?e:Object.fromEntries(Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>[r,Re(e[r])]))}function Ft(e){let r=e.op==="replaceText"?{op:e.op,search:e.search,replaceWith:e.replaceWith,occurrence:e.occurrence===void 0||e.occurrence===1?"first":e.occurrence}:{op:e.op,at:e.at,text:e.text};return JSON.stringify(Re({paragraph:e.paragraph,...r}))}function Et(e){if(!e||typeof e!="object")throw new TypeError("a proposal must be an object");let r={...e},n=o=>{if(typeof r[o]!="string")throw new TypeError(`proposal ${o} must be a string`)};if(n("id"),!e.paragraph||typeof e.paragraph!="object")throw new TypeError("proposal paragraph must be a paragraph anchor");if(!e.suggest||typeof e.suggest!="object")throw new TypeError("proposal suggest must carry author and date");if(e.op==="replaceText")n("search"),n("replaceWith");else if(e.op==="insertText")n("text");else throw new TypeError(`unknown proposal op ${JSON.stringify(e.op)}`)}function Ot(e){let r=[],n=-1;for(let o of e)o.range.start.offset<n||(r.push(o),n=o.range.end.offset);return r}function Mt(e,r,n){let o=e.flatMap((a,s)=>a.op==="replaceText"&&a.target.kind==="range"&&!n[s]?[{index:s,range:a.target}]:[]);for(let a of o)for(let s of o)if(r[a.index]!==r[s.index]&&a.range.story===s.range.story&&a.range.start.paraId===s.range.start.paraId&&a.range.end.offset===s.range.start.offset)return a.index<s.index?[a.index,s.index]:[s.index,a.index];return null}function Ge(e){let r=new Map,n=new Set,o=0,a=false,s=false,d=()=>({version:e.version(),previewVersion:o,proposals:[...r.values()].map(({record:l})=>({...l,paragraph:{...l.paragraph},revisionIds:[...l.revisionIds]}))}),u=()=>{if(s=true,!a){a=true;try{for(;s;){if(s=!1,n.size===0)return;let l=d();for(let y of [...n]){try{y(l);}catch(x){console.error("[yrs] a proposal listener threw",x);}if(s)break}}}finally{a=false,s=false;}}},p=(l,y=e.version())=>({ok:false,version:y,failure:l}),g=l=>{let y=(b,P)=>({failure:{code:b,message:P,proposalId:l.id}}),x=e.resolveParagraphAnchor(l.paragraph);switch(x.status){case "found":return x.anchor.kind==="session"?{anchor:x.anchor}:y("unsupported",`proposal ${l.id} targets a paragraph outside the editable stories`);case "missing":return y("missing-target",`proposal ${l.id} targets a paragraph that was not found`);case "ambiguous":return y("ambiguous-target",`proposal ${l.id} targets a paragraph id that ${x.candidates.length} paragraphs carry`);default:return y("unsupported",`proposal ${l.id} targets an anchor this session cannot resolve (${x.reason})`)}},c=(l,y)=>{let x=(C,k)=>({failure:{code:C,message:k,proposalId:l.id}}),{story:b,paraId:P}=y,D={author:l.suggest.author,date:l.suggest.date};if(l.op==="insertText"){if(typeof l.at=="string")return l.at!=="start"&&l.at!=="end"?x("invalid-step",`proposal ${l.id} inserts at an unknown boundary`):{steps:[{op:"insertText",target:{kind:"paragraph",story:b,paraId:P},at:l.at,text:l.text,suggest:D}]};let C=l.at?.offset;if(!Number.isInteger(C)||C<0||C>4294967295)return x("invalid-step",`proposal ${l.id} inserts at an offset that is not a non-negative integer`);let k={paraId:P,offset:C};return {steps:[{op:"insertText",target:{kind:"range",story:b,start:k,end:k,view:"accepted"},at:"start",text:l.text,suggest:D}]}}let T=l.occurrence??"first";if(T!=="first"&&T!=="all"&&!(Number.isSafeInteger(T)&&T>=1))return x("invalid-step",`proposal ${l.id} names occurrence ${String(T)}; use 'first', 'all' or a number from 1`);if(l.search==="")return h(l,y,T);let F=e.findText({text:l.search,within:{kind:"paragraph",story:b,paraId:P},view:"accepted",limit:1e4});if(!F.ok)return {failure:{...F.failure,proposalId:l.id}};let J=Ot(F.matches),_=T==="all"?J:J.slice(T==="first"?0:T-1).slice(0,1);return F.truncated?x("limit-exceeded",`proposal ${l.id} matches more than 10000 times`):_.length===0?x("missing-target",J.length===0?`proposal ${l.id}: ${JSON.stringify(l.search)} was not found in its paragraph`:`proposal ${l.id}: occurrence ${T} of ${JSON.stringify(l.search)} was not found; its paragraph has ${J.length}`):{steps:_.map(C=>({op:"replaceText",target:{kind:"range",...C.range},text:l.replaceWith,suggest:D}))}},h=(l,{story:y,paraId:x},b)=>{let P=e.readParagraphs({story:y,paraIds:[x],view:"accepted"});if(!P.ok)return {failure:{...P.failure,proposalId:l.id}};let D=P.paragraphs.length===1&&P.paragraphs[0].text==="";if(!D||typeof b=="number"&&b>1)return {failure:{code:"missing-target",message:D?`proposal ${l.id}: occurrence ${b} of empty text was not found; its paragraph has 1`:`proposal ${l.id} fills a paragraph that is not empty`,proposalId:l.id}};let T={paraId:x,offset:0};return {steps:[{op:"replaceText",target:{kind:"range",story:y,start:T,end:T,view:"accepted"},text:l.replaceWith,suggest:{author:l.suggest.author,date:l.suggest.date}}]}},R=l=>{if(!l||typeof l!="object"||!Array.isArray(l.proposals))throw new TypeError("a proposal request needs a proposals array");let y=[],x=new Map;for(let _ of l.proposals){if(Et(_),_.id==="")return p({code:"invalid-step",message:"a proposal id must not be empty",proposalId:""});let C=Ft(_),k=r.get(_.id)?.key??x.get(_.id);if(k!==void 0){if(k===C)continue;return p({code:"proposal-id-conflict",message:`proposal id ${_.id} already names a different change`,proposalId:_.id})}x.set(_.id,C),y.push({input:_,key:C});}if(y.length===0)return {ok:true,snapshot:d()};if(l.expectVersion!==e.version())return p({code:"stale-version",message:"the document changed since the expected version was read"});let b=[],P=[],D=[],T=[];for(let[_,{input:C}]of y.entries()){let k=g(C);if("failure"in k)return p(k.failure);let m=c(C,k.anchor);if("failure"in m)return p(m.failure);T.push({anchor:k.anchor,first:b.length,count:m.steps.length});for(let O of m.steps)b.push(O),P.push(_),D.push(C.op==="replaceText"&&C.replaceWith===C.search);}let F=Mt(b,P,D);if(F){let[_,C]=F.map(k=>y[P[k]].input.id);return p({code:"overlapping-steps",message:`proposal ${C} adjoins proposal ${_}; adjacent suggestions would share one revision`,proposalId:C})}let J=e.applyEdits({expectVersion:l.expectVersion,history:"none",steps:b});if(!J.ok){let{stepIndex:_,conflictingStepIndex:C,...k}=J.failure,m=_===void 0?void 0:y[P[_]]?.input.id,O=C===void 0?void 0:y[P[C]]?.input.id;return p({...k,...O!==void 0&&O!==m?{message:`proposal ${m} overlaps proposal ${O}`}:m!==void 0?{message:`proposal ${m}: ${k.message}`}:{},...m!==void 0?{proposalId:m}:{}},J.version)}for(let[_,{input:C,key:k}]of y.entries()){let{anchor:m,first:O,count:w}=T[_],I=J.receipts.slice(O,O+w);r.set(C.id,{key:k,record:{id:C.id,state:"proposed",paragraph:{kind:"session",sessionId:m.sessionId,story:m.story,paraId:m.paraId},revisionIds:[...new Set(I.flatMap(M=>M.revisionIds))],changed:I.some(M=>M.changed)}});}return u(),{ok:true,snapshot:d()}};return {propose(l){let y=()=>R(l);return e.sharedReads?e.sharedReads(y):y()},setStates:l=>{if(!l||typeof l!="object"||!Array.isArray(l.changes))throw new TypeError("a proposal state request needs a changes array");if(l.expectVersion!==e.version())return p({code:"stale-version",message:"the document changed since the expected version was read"});if(l.expectPreviewVersion!==o)return p({code:"stale-preview",message:`the proposals are at preview version ${o}, not ${l.expectPreviewVersion}`});let y=new Map;for(let b of l.changes){if(!b||typeof b.id!="string")throw new TypeError("a state change needs an id");if(b.state!=="proposed"&&b.state!=="accepted"&&b.state!=="rejected")return p({code:"invalid-step",message:`proposal ${b.id} cannot be set to ${JSON.stringify(b.state)}`,proposalId:b.id});if(!r.has(b.id))return p({code:"unknown-proposal",message:`no proposal has id ${b.id}`,proposalId:b.id});let P=y.get(b.id);if(P!==void 0&&P!==b.state)return p({code:"invalid-step",message:`proposal ${b.id} is set to two states`,proposalId:b.id});y.set(b.id,b.state);}let x=false;for(let[b,P]of y){let D=r.get(b);D.record.state!==P&&(D.record={...D.record,state:P},x=true);}return x&&(o+=1,u()),{ok:true,snapshot:d()}},withdraw:l=>{if(!l||typeof l!="object"||!Array.isArray(l.ids))throw new TypeError("a withdrawal request needs an ids array");for(let k of l.ids)if(typeof k!="string")throw new TypeError("a proposal id must be a string");let y=[...new Set(l.ids)].filter(k=>r.has(k));if(y.length===0)return {ok:true,snapshot:d()};if(l.expectVersion!==e.version())return p({code:"stale-version",message:"the document changed since the expected version was read"});let x=new Set(y),b=new Map;for(let[k,{record:m}]of r)if(!x.has(k))for(let O of m.revisionIds)b.set(O,k);let P=new Map;for(let k of y){let{record:m}=r.get(k);for(let O of m.revisionIds){let w=b.get(O);if(w!==void 0)return p({code:"tracked-revision-conflict",message:`proposal ${k} shares revision ${O} with proposal ${w}`,proposalId:k});P.set(O,k);}}let D=Ke(d())??{},T=[...P.keys()],F=T.filter(k=>D[k]==="accepted"),J=T.filter(k=>D[k]!=="accepted"),_=e.listRevisions().find(({revisionId:k,kind:m})=>P.has(k)&&m!=="insertion"&&m!=="deletion");if(_){let k=P.get(_.revisionId);return p({code:"tracked-revision-conflict",message:`proposal ${k} shares revision ${_.revisionId} with a ${_.kind} change made outside the proposals`,proposalId:k})}(F.length>0||J.length>0)&&e.settleRevisions(F,J);let C=false;for(let k of y)C||(C=r.get(k).record.state!=="proposed"),r.delete(k);return C&&(o+=1),u(),{ok:true,snapshot:d()}},snapshot:d,subscribe(l){if(typeof l!="function")throw new TypeError("proposal listener must be a function");return n.add(l),()=>{n.delete(l);}},reset(){r.size!==0&&([...r.values()].some(({record:l})=>l.state!=="proposed")&&(o+=1),r.clear(),u());},destroy(){r.clear(),n.clear();}}}function Or(e,r){let n=0,o=r.map(a=>{let s={paraId:a.paraId,length:Math.max(0,Math.trunc(a.length)),displayStart:n};return n+=s.length+2,s});return {story:e,paragraphs:o}}function Xe(e,r){let n=e.paragraphs.find(o=>o.paraId===r.paraId);return !n||r.story!==e.story?e.paragraphs[0]?.displayStart??0:n.displayStart+1+Math.min(Math.max(0,r.offset),n.length)}function Mr(e,r){if(e.paragraphs.length===0)return null;let n=Math.max(0,Math.trunc(r)),o=e.paragraphs[0];for(let a of e.paragraphs){if(a.displayStart>n)break;o=a;}return {story:e.story,paraId:o.paraId,offset:Math.min(Math.max(0,n-(o.displayStart+1)),o.length)}}function Nr(e,r,n){return Xe(e,r)-Xe(e,n)}var Nt=new Set(["bootstrap","sync","buildFrame","applyInput","applyDelete"]),ke=6e4;function Jt(){return new Worker(new URL("./residentEngineWorker.mjs",import.meta.url),{type:"module",name:"openooxml-resident-engine"})}var le=class{constructor(r=Jt()){b(this,"worker",r);b(this,"pending",new Map);b(this,"watchdog",null);b(this,"nextId",1);b(this,"terminalError",null);b(this,"ready",false);b(this,"revision",0);b(this,"remoteVector",null);b(this,"appliedFontsRevision",null);b(this,"bootstrapped",false);b(this,"openedHeapLimit",null);b(this,"bootstraps",0);b(this,"lastSnapshotId",0);b(this,"keepSurfaces",false);b(this,"lastMemory",null);b(this,"answeredFrameEpoch",0);b(this,"retainBuiltPages",false);this.worker.onmessage=n=>{let o=n.data;if(o.memory&&(this.lastMemory=o.memory),o.ok&&o.caret&&(this.answeredFrameEpoch=Math.max(this.answeredFrameEpoch,o.caret.frameEpoch)),o.ok&&o.stateVector&&o.id>=this.lastSnapshotId&&(this.remoteVector=new Uint8Array(o.stateVector)),!o.ok&&o.terminal){this.fail(o.outOfMemory?new te(o.error,o.memory??[]):new X(o.error));return}this.pending.size>0&&this.armWatchdog();let a=this.pending.get(o.id);a&&(this.pending.delete(o.id),this.pending.size===0&&this.disarmWatchdog(),o.ok?a.resolve(o):a.reject(Lt(o.error,o.residentUnavailable)));},this.worker.onerror=n=>{this.fail(new N(`Resident engine worker failed: ${n.message}`));},this.worker.onmessageerror=()=>{this.fail(new N("Resident engine worker returned an unreadable message"));};}isReady(){return this.ready}hasFailed(){return this.terminalError!==null}memory(){return this.lastMemory}layoutRevision(){return this.revision}answeredFrame(){return this.answeredFrameEpoch}setRetainBuiltPages(r){this.retainBuiltPages=r;}frameRequestPending(){for(let{type:r}of this.pending.values())if(Nt.has(r))return true;return false}remoteStateVector(){return this.remoteVector}syncedFontsRevision(){return this.appliedFontsRevision}bootstrapSent(){return this.bootstrapped}rebootstrap(){this.bootstrapped=false,this.remoteVector=null,this.appliedFontsRevision=null,this.lastSnapshotId=0,this.revision=0,this.keepSurfaces=true,this.openedHeapLimit=null;}async open(r,n={}){if(this.openedHeapLimit||this.bootstrapped)throw new N("Resident engine worker already holds a document");let o={bytes:n.heapLimitBytes};this.openedHeapLimit=o;let a;try{let s=new Uint8Array(r);a=await this.request({type:"open",bytes:s.buffer,...n.digest!==void 0?{digest:n.digest}:{},...n.generation!==void 0?{generation:n.generation}:{},...n.heapLimitBytes!==void 0?{heapLimitBytes:n.heapLimitBytes}:{}},[s.buffer]);}catch(s){throw this.openedHeapLimit===o&&(this.openedHeapLimit=null),s}if(a.hostJson===void 0||!a.stateVector)throw new N("Resident engine worker omitted the opened document");return {hostJson:a.hostJson,stateVector:new Uint8Array(a.stateVector)}}async fontRequirements(r){let n=await this.request({type:"fontRequirements",layoutInput:r});if(n.requirementsJson===void 0)throw new N("Resident engine worker omitted the font requirements");return n.requirementsJson}async encodeState(){let r=await this.request({type:"encodeState"});if(!r.state)throw new N("Resident engine worker omitted its state");return new Uint8Array(r.state)}async warm(){await this.request({type:"warm"});}async bootstrap(r,n,o={}){if(o.opened&&!this.openedHeapLimit)throw new N("Resident engine worker has no opened document");if(o.opened&&o.heapLimitBytes!==void 0&&o.heapLimitBytes!==this.openedHeapLimit?.bytes)throw new N("Resident engine worker opened its document under another heap limit");let a=r.fontsRevision;this.bootstrapped=true;let s=this.keepSurfaces;this.keepSurfaces=false;let d=++this.bootstraps,u=this.request({type:"bootstrap",snapshot:r,extras:n,expectedFrameEpoch:o.frameEpoch??0,...o.layoutExtras!==void 0?{layoutExtras:o.layoutExtras}:{},...o.displayWindow?{displayWindow:o.displayWindow,...this.retainBuiltPages?{retainBuiltPages:true}:{}}:{},...o.provisionalPages!==void 0?{provisionalPages:o.provisionalPages}:{},...s?{keepSurfaces:true}:{},...o.opened?{opened:true}:{},...o.heapLimitBytes!==void 0?{heapLimitBytes:o.heapLimitBytes}:{}},Ze(r));this.recordSent(o.stateVector,a);let p;try{p=await u;}catch(c){throw o.opened&&!this.openedHeapLimit&&d===this.bootstraps&&(this.bootstrapped=false,this.remoteVector=null,this.appliedFontsRevision=null),c}let g=K(p);return this.recordSync(p,a),this.ready=true,this.revision=g.layoutRevision,g}async sync(r,n,o,a=false,s={}){let d=r.fontsRevision,u=this.request({type:"sync",snapshot:r,extras:n,expectedFrameEpoch:o,paintCaret:a,...s.layoutExtras!==void 0?{layoutExtras:s.layoutExtras}:{},...s.displayWindow?{displayWindow:s.displayWindow,...this.retainBuiltPages?{retainBuiltPages:true}:{}}:{}},Ze(r));this.recordSent(s.stateVector,d);let p=await u,g=K(p);return this.recordSync(p,d),this.ready=true,this.revision=g.layoutRevision,g}async completeLayout(r,n=false,o){let a=await this.request({type:"completeLayout",expectedFrameEpoch:r,paintCaret:n,...o?{sliceBlocks:o}:{}});return a.frame?K(a):null}async buildFrame(r,n,o=false,a){return K(await this.request({type:"buildFrame",extras:r,expectedFrameEpoch:n,paintCaret:o,...a?{displayWindow:a,...this.retainBuiltPages?{retainBuiltPages:true}:{}}:{}}))}async buildPages(r,n,o=false){return K(await this.request({type:"buildPages",pages:r,expectedFrameEpoch:n,paintCaret:o}))}async applyInput(r,n,o,a=false,s=false,d){if(!this.ready)return {applied:false};try{return {applied:!0,...K(await this.request({type:"applyInput",text:r,selection:n,expectedFrameEpoch:o,profile:a,paintCaret:s,...d?{displayWindow:d,...this.retainBuiltPages?{retainBuiltPages:!0}:{}}:{}}))}}catch(u){if(Qe(u))return {applied:false};throw u}}async applyDelete(r,n,o,a=false,s=false,d=1,u){if(!this.ready)return {applied:false};try{return {applied:!0,...K(await this.request({type:"applyDelete",direction:r,count:d,selection:n,expectedFrameEpoch:o,profile:a,paintCaret:s,...u?{displayWindow:u,...this.retainBuiltPages?{retainBuiltPages:!0}:{}}:{}}))}}catch(p){if(Qe(p))return {applied:false};throw p}}eraseCaret(){if(this.terminalError)return;let n={id:this.nextId++,type:"eraseCaret"};this.worker.postMessage(n);}invalidate(r,n){if(this.terminalError)return;this.ready=false;let o=r.slice(),s={id:this.nextId++,type:"applyUpdate",update:o,selection:n};this.worker.postMessage(s,[o.buffer]);}async attachCanvases(r,n,o,a,s){let d=r.map(u=>u.canvas);await this.request({type:"attachCanvases",pages:r,activePageIds:n,devicePixelRatio:o,zoom:a,caretStyle:s},d);}destroy(){if(this.terminalError)return;let n={id:this.nextId++,type:"destroy"};this.worker.postMessage(n),this.fail(new N("Resident engine worker was destroyed"));}request(r,n=[]){if(this.terminalError)return Promise.reject(this.terminalError);let o=this.nextId++;return new Promise((a,s)=>{this.pending.size===0&&this.armWatchdog(),this.pending.set(o,{type:r.type,resolve:a,reject:s}),this.worker.postMessage({...r,id:o},n);})}recordSent(r,n){this.terminalError||(this.lastSnapshotId=this.nextId-1,r&&(this.remoteVector=r.slice()),this.appliedFontsRevision=n);}armWatchdog(){this.disarmWatchdog(),this.watchdog=setTimeout(()=>{this.watchdog=null;let r=this.pending.values().next().value?.type??"a request";this.fail(new N(`Resident engine worker did not answer ${r} within ${ke}ms`));},ke);}disarmWatchdog(){this.watchdog!==null&&(clearTimeout(this.watchdog),this.watchdog=null);}recordSync(r,n){r.id>=this.lastSnapshotId&&(this.appliedFontsRevision=n);}fail(r){this.terminalError=r,this.ready=false,this.disarmWatchdog(),this.worker.terminate();for(let n of this.pending.values())n.reject(r);this.pending.clear();}},X=class extends Error{},N=class extends Error{},te=class extends X{constructor(n,o){super(n);b(this,"memory",o);}};function Qe(e){return e instanceof X&&!(e instanceof te)}function Lt(e,r=false){return r?new X(e):new Error(e)}function Ze(e){return [e.state.buffer,...e.fonts.flatMap(r=>r instanceof Uint8Array?[r.buffer]:[])]}function K(e){if(!e.frame)throw new N("Resident engine worker response omitted its FrameDelta");if(!e.caret)throw new N("Resident engine worker response omitted its caret snapshot");if(e.selection===void 0)throw new N("Resident engine worker response omitted its selection");return {frame:new Uint8Array(e.frame),updates:(e.updates??[]).map(r=>new Uint8Array(r)),engineMs:e.engineMs??0,workerTotalMs:e.workerTotalMs??0,engineProfile:e.engineProfile,caret:e.caret,selection:e.selection,caretPainted:e.caretPainted??false,replayMs:e.replayMs??0,replayedPages:e.replayedPages??0,layoutRevision:e.layoutRevision??0,deletedUnits:e.deletedUnits??0,...e.layoutJson!==void 0?{layoutJson:e.layoutJson}:{},...e.layoutProvisional?{layoutProvisional:true}:{}}}function Pe(){return typeof Worker<"u"}var W=null;function de(e){e.idleTimer!==null&&clearTimeout(e.idleTimer),e.releaseTimer!==null&&clearTimeout(e.releaseTimer),e.idleTimer=null,e.releaseTimer=null;}function ee(e){W===e&&(W=null,de(e),e.client.destroy());}function we(){if(!Pe())return Promise.resolve();if(W&&(W.factory!==Worker||W.client.hasFailed())&&ee(W),!W){let r={client:new le,factory:Worker,ready:Promise.resolve(),owners:0,idleTimer:null,releaseTimer:null};W=r,r.ready=r.client.warm().catch(n=>{throw ee(r),n});}let e=W;return de(e),e.owners===0&&(e.idleTimer=setTimeout(()=>ee(e),ke)),e.ready}function Wt(){let e=W;if(!e)return ()=>{};de(e),e.owners+=1;let r=false;return ()=>{r||(r=true,e.owners-=1,e.owners===0&&W===e&&(e.releaseTimer=setTimeout(()=>ee(e),0)));}}function Bt(){let e=W;return e?!Pe()||e.factory!==Worker||e.client.hasFailed()?(ee(e),null):(W=null,de(e),e.client):null}async function Ut(){let e=[import('../wasm-NF6B3AH7.mjs').then(n=>n.preloadEditWasm()),import('../wasm-GSI2XMOH.mjs').then(n=>n.preloadOpcWasm()),import('../parseWasm-NLAG22EU.mjs').then(n=>n.preloadParseWasm()),import('../wasm-K6DRABAA.mjs').then(n=>n.preloadLayoutWasm())],r;try{r=we();}catch(n){r=Promise.reject(n);}await Promise.all([...e,r]);}function ve(e,r,n,o,a,s){let d=r?.pPr;if(!r?.tblStylePr?.some(T=>T.pPr))return d;let u=e.formatting?.look??r.tblPr?.look,p=(T,F)=>u?.[T]??(Number.parseInt(u?.value??(u?"0":"04A0"),16)&F)!==0,g=p("firstRow",32),c=p("lastRow",64),h=p("firstColumn",128),R=p("lastColumn",256),v=e.rows[n].formatting?.gridBefore??0;o+=v,a+=v;let S=!!g&&n===0,l=!!c&&n===e.rows.length-1,y=!!h&&o===0,x=!!R&&a===s,b=e.formatting?.styleRowBandSize??r.tblPr?.styleRowBandSize??1,P=e.formatting?.styleColBandSize??r.tblPr?.styleColBandSize??1,D=[];!p("noHBand",512)&&!S&&!l&&b>0&&D.push(Math.floor((n-+!!g)/b)%2===0?"band1Horz":"band2Horz"),!p("noVBand",1024)&&!y&&!x&&P>0&&D.push(Math.floor((o-+!!h)/P)%2===0?"band1Vert":"band2Vert");for(let[T,F]of [["firstCol",y],["lastCol",x],["firstRow",S],["lastRow",l],["nwCell",S&&y],["neCell",S&&x],["swCell",l&&y],["seCell",l&&x]])F&&D.push(T);for(let T of D)d=b$3(d,r.tblStylePr.find(F=>F.type===T)?.pPr);return d}function et(e){return Math.max(e.columnWidths?.length??0,...e.rows.map(r=>r.cells.reduce((n,o)=>n+(o.formatting?.gridSpan??1),(r.formatting?.gridBefore??0)+(r.formatting?.gridAfter??0))))}function j(e){if(Array.isArray(e))return e.map(j);if(e!==null&&typeof e=="object"){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=j(o));return r}return e}var jt={styleId:"pStyle",_sectionProperties:"sectPr"},$t=new Set(["paraId","textId","renderedPageBreakBefore","numPrFromStyle"]);function tt(e){let r={};for(let[n,o]of Object.entries(e))$t.has(n)||o===null||o===void 0||(r[jt[n]??n]=j(o));return r}var qt=new Set(["columnWidths"]);function pe(e,r=new Set){let n={};for(let[o,a]of Object.entries(e))r.has(o)||a===null||a===void 0||(n[o]=j(a));return n}function rt(e){return pe(e,qt)}function nt(e){let r=e.columnWidths;return Array.isArray(r)?r.map(j):[]}function ot(e){return pe(e)}function st(e,r){let n=pe(e);return r&&(n.header=true),n}function Te(e,r,n,o){return `${e}:t${r}:r${n}c${o}`}function at(e,r){return `${e}:sdt${r}`}function it(e){return pe(e)}function ue(e){return `hf:${e}`}function lt(e){return `fn:${e}`}function dt(e){return `en:${e}`}function Ht(e){let r=e.package.settings?.compatibilityFlags?.compatibilityMode;return typeof r=="number"&&Number.isFinite(r)?Math.trunc(r):12}var Vt=new Set(["bold","italic","superscript","subscript","allCaps","smallCaps","emboss","imprint","textShadow","textOutline","hidden","rtl"]);function Z(e){if(e==null)return "null";if(Array.isArray(e))return `[${e.map(Z).join(",")}]`;if(typeof e=="object"){let r=e;return `{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${Z(r[n])}`).join(",")}}`}return JSON.stringify(e)}function zt(e,r){if(!e||!r)return e;let n=r.resolveRunStyle(e.styleId);return n?a$1(n,e):e}function ft(e){if(!e)return [];let r=[],n=(d,u={})=>r.push({name:d,attrs:u});e.bold&&n("bold"),e.italic&&n("italic"),e.underline&&e.underline.style!=="none"&&n("underline",{style:e.underline.style,color:e.underline.color??null}),(e.strike||e.doubleStrike)&&n("strike",{double:e.doubleStrike||false}),e.color&&!e.color.auto&&n("textColor",{rgb:e.color.rgb??null,themeColor:e.color.themeColor??null,themeTint:e.color.themeTint??null,themeShade:e.color.themeShade??null});let o=e.shading?.fill,a=(!e.shading?.pattern||e.shading.pattern==="clear")&&o?.rgb&&!o.auto?p(o.rgb):void 0,s=e.highlight&&e.highlight!=="none"?e.highlight:a;return s&&n("highlight",{color:s}),(e.fontSize!=null||e.fontSizeCs!=null)&&n("fontSize",{size:e.fontSize??null,sizeCs:e.fontSizeCs??null}),e.fontFamily&&n("fontFamily",{ascii:e.fontFamily.ascii??null,hAnsi:e.fontFamily.hAnsi??null,eastAsia:e.fontFamily.eastAsia??null,cs:e.fontFamily.cs??null,asciiTheme:e.fontFamily.asciiTheme??null,hAnsiTheme:e.fontFamily.hAnsiTheme??null,eastAsiaTheme:e.fontFamily.eastAsiaTheme??null,csTheme:e.fontFamily.csTheme??null}),e.vertAlign==="superscript"?n("superscript"):e.vertAlign==="subscript"&&n("subscript"),e.allCaps&&n("allCaps"),e.smallCaps&&n("smallCaps"),(e.spacing!=null||e.position!=null||e.scale!=null||e.kerning!=null)&&n("characterSpacing",{spacing:e.spacing??null,position:e.position??null,scale:e.scale??null,kerning:e.kerning??null}),e.emboss&&n("emboss"),e.imprint&&n("imprint"),e.shadow&&n("textShadow"),e.emphasisMark&&e.emphasisMark!=="none"&&n("emphasisMark",{type:e.emphasisMark}),e.outline&&n("textOutline"),e.hidden&&n("hidden"),e.rtl&&n("rtl"),e.snapToGrid===false&&r.push({name:"snapToGrid",attrs:{}}),e.effect&&e.effect!=="none"&&n("textEffect",{effect:e.effect}),e.modernEffects&&n("modernTextEffects",{effects:e.modernEffects}),e.styleId&&n("runStyle",{styleId:e.styleId}),r}function gt(e){let r={};for(let n of e)n.name==="comment"||n.name==="footnoteRef"||(Vt.has(n.name)?r[n.name]=true:n.name==="snapToGrid"?r.snapToGrid=false:n.name==="highlight"?r.highlight=n.attrs.color:n.name==="insertion"||n.name==="deletion"?r[n.name==="insertion"?"ins":"del"]=j({id:n.attrs.revisionId,author:n.attrs.author,date:n.attrs.date}):r[n.name]=j(n.attrs));return r}function Kt(e){return e.filter(r=>r.name!=="hyperlink"&&r.name!=="comment").map(r=>`${r.name}:${JSON.stringify(r.attrs)}`).sort().join("|")}function Gt(e,r){return [...e.filter(n=>n.name!==r.name),r]}function re(e,r,n){return {kind:"text",text:e,attrs:gt(r),pmSize:e.length,...n!==void 0?{commentId:n}:{},marks:[...r]}}function A(e,r,n=[],o,a=1){return {kind:"embed",embedKind:e,payload:r,attrs:gt(n),pmSize:a,...o!==void 0?{commentId:o}:{},marks:[...n]}}function mt(e,r,n){let o=e.formatting?.styleId?n?.getRunStyleOwnProperties(e.formatting.styleId):void 0,a=ft(a$1(a$1(r,o),e.formatting)),s=e.formatting?.styleId,d=s?n?.getStyle(s)?.name:void 0;if([s,d].some(u=>/^(?:Followed)?Hyperlink$/i.test(u??""))){for(let[u,p]of [["color","textColor"],["underline","underline"]])if(e.formatting?.[u]===void 0&&o?.[u]!==void 0){let g=a.find(c=>c.name===p);g&&(g.attrs.inheritedHyperlink=true);}}return a}function Xt(e){let r=e.size?.width?b$4(e.size.width):void 0,n=e.size?.height?b$4(e.size.height):void 0,o=e.wrap.type,a=e.wrap.wrapText,s=e.position?.horizontal?.alignment,d;o==="inline"||o==="topAndBottom"?d="none":o==="square"||o==="tight"||o==="through"?a==="left"?d="right":a==="right"?d="left":s==="left"||s==="right"?d=s:d="none":d="none";let u=o==="inline"?"inline":o==="topAndBottom"?"block":b$5(o)||d&&d!=="none"?"float":"block",p=[];e.transform?.rotation&&p.push(`rotate(${e.transform.rotation}deg)`),e.transform?.flipH&&p.push("scaleX(-1)"),e.transform?.flipV&&p.push("scaleY(-1)");let g,c,h;if(e.outline?.width){g=Math.round(e.outline.width/914400*96*100)/100,e.outline.color?.rgb&&(c=`#${e.outline.color.rgb}`);let R={solid:"solid",dot:"dotted",dash:"dashed",lgDash:"dashed",dashDot:"dashed",lgDashDot:"dashed",lgDashDotDot:"dashed",sysDot:"dotted",sysDash:"dashed",sysDashDot:"dashed",sysDashDotDot:"dashed"};h=e.outline.style&&R[e.outline.style]||"solid";}return j({src:e.src||"",alt:e.alt??null,title:e.title??null,width:r??null,height:n??null,rId:e.rId??null,wrapType:o,displayMode:u,cssFloat:d??null,transform:p.length>0?p.join(" "):null,distTop:e.wrap.distT!=null?b$4(e.wrap.distT):null,distBottom:e.wrap.distB!=null?b$4(e.wrap.distB):null,distLeft:e.wrap.distL!=null?b$4(e.wrap.distL):null,distRight:e.wrap.distR!=null?b$4(e.wrap.distR):null,position:e.position?{relativeHeight:e.position.relativeHeight,horizontal:e.position.horizontal?{relativeTo:e.position.horizontal.relativeTo,posOffset:e.position.horizontal.posOffset,align:e.position.horizontal.alignment}:void 0,vertical:e.position.vertical?{relativeTo:e.position.vertical.relativeTo,posOffset:e.position.vertical.posOffset,align:e.position.vertical.alignment}:void 0}:null,borderWidth:g??null,borderColor:c??null,borderStyle:h??null,wrapText:a??null,hlinkHref:e.hlinkHref??null,cropTop:e.crop?.top??null,cropRight:e.crop?.right??null,cropBottom:e.crop?.bottom??null,cropLeft:e.crop?.left??null,shapeType:e.shapeType??null,opacity:e.opacity??null,effectExtentTop:e.padding?.top?b$4(e.padding.top):null,effectExtentBottom:e.padding?.bottom?b$4(e.padding.bottom):null,effectExtentLeft:e.padding?.left?b$4(e.padding.left):null,effectExtentRight:e.padding?.right?b$4(e.padding.right):null,layoutInCell:e.layoutInCell??null,allowOverlap:e.allowOverlap??null})}function Qt(e){return {shapeJson:JSON.stringify(e)}}function Zt(e){return j({chartJson:JSON.stringify(e),chartType:e.chartType??null,title:e.title??null,width:e.size?.width?b$4(e.size.width):320,height:e.size?.height?b$4(e.size.height):220,rId:e.rId??null,path:e.path??null})}function oe(e,r){let n="",o,a=e.type==="simpleField"?e.content:e.fieldResult;for(let u of a)if(u.type==="run"){for(let p of u.content)p.type==="text"&&(n+=p.text);!o&&u.formatting&&(o=u.formatting);}let s=o??(e.type==="complexField"?e.formatting:void 0),d=e.fieldTree?.displayMode??"result";return {payload:{fieldType:e.fieldType,instruction:e.instruction,displayText:n,fieldKind:e.type==="simpleField"?"simple":"complex",fldLock:e.fldLock??false,dirty:e.dirty??false,displayMode:d,hasCachedResult:n.length>0,fieldData:JSON.stringify(e),modelKind:"field"},marks:ft(a$1(r,s))}}function Q(e){let r=new Set,n=[[e,false]];for(;n.length>0;){let[o,a]=n.pop();if(Array.isArray(o))for(let s=o.length-1;s>=0;s--)n.push([o[s],a]);else if(o!==null&&typeof o=="object"){let s=o;if(o!==e&&(s.type==="complexField"||s.type==="simpleField")&&typeof s.instruction=="string"){let u=ce(s.instruction);u!==void 0&&r.add(u);}if(s.type==="hyperlink"&&!a)for(let u of se(o))r.add(u);let d=a||s.type==="hyperlink";for(let u of Object.keys(s).sort().reverse())n.push([s[u],d]);}}return [...r]}function se(e){let r=[e],n=[],o=[],a=s=>{if(Array.isArray(s))for(let d=s.length-1;d>=0;d--)r.push(s[d]);};for(;r.length>0;){let s=r.pop();if(s){if((s.type==="simpleField"||s.type==="complexField")&&typeof s.instruction=="string"){let d=ce(s.instruction);d!==void 0&&o.push(d);}switch(s.type){case "hyperlink":a(s.structuredChildren??s.children);break;case "inlineSdt":a(s.content);break;case "simpleField":a(s.structuredResult?.inline??s.fieldTree?.result?.inline??s.content);break;case "complexField":a(s.structuredResult?.inline??s.fieldTree?.result?.inline??s.fieldResult),a(s.structuredCode?.inline??s.fieldTree?.code?.inline??s.fieldCode);break;case "run":if(!Array.isArray(s.content))break;for(let d of s.content){if(!d)continue;let u;if(d.type==="fieldChar")d.charType==="begin"?n.push(""):d.charType==="separate"&&n.length>0?(u=n[n.length-1],n[n.length-1]=void 0):d.charType==="end"&&(u=n.pop());else if(d.type==="instrText"){let g=n.length-1;n[g]!==void 0&&(n[g]+=typeof d.text=="string"?d.text:"");}let p=u===void 0?void 0:ce(u);p!==void 0&&o.push(p);}break}}}return o}function ce(e){let r=e.matchAll(/"([^"]*)(?:"|$)|([^\p{White_Space}]+)/gu),n=r.next().value,o=r.next().value,a=n?.[1]??n?.[2],s=o?.[1]??o?.[2];if(!(!a||!/^[sS][eE][qQ]$/.test(a)||s===void 0||s.startsWith("\\")))return s.toLowerCase()}function Ce(e){return {display:e.display,ommlXml:e.ommlXml,plainText:e.plainText||""}}function er(e){return {name:"hyperlink",attrs:{href:e.href||(e.anchor?`#${e.anchor}`:""),tooltip:e.tooltip??null,rId:e.rId??null}}}function tr(e,r,n,o,a){let s=e.structuredResult?.inline??[],u=[...(e.type==="complexField"?e.structuredCode?.inline??[]:[]).map((R,v)=>({child:R,index:-v-1})),...s.map((R,v)=>({child:R,index:v}))];if(e.type!=="complexField"||!u.some(({child:R})=>R.type==="hyperlink"||R.type==="simpleField")){a.push(...Q(e));let R=oe(e,r);return [A("field",R.payload,R.marks)]}let p=[],g=[];u.forEach(({child:R,index:v})=>{if(R.type!=="hyperlink"&&R.type!=="simpleField")return;a.push(...R.type==="hyperlink"?se(R):Q(R));let S=R.type==="simpleField"?oe(R,r):null,l=R.type==="hyperlink"?ge(R,r,n,a):[A("field",S.payload,S.marks)];g.push({index:v,items:l.map(y=>y.kind==="text"?{kind:"text",text:y.text,attributes:y.attrs}:{kind:"embed",embedKind:y.embedKind,payload:y.payload,attributes:y.attrs})});for(let y of l)y.attrs={...y.attrs,fieldResult:{id:o,index:v}};p.push(...l);});let c={...e,fieldResult:s.filter(R=>R.type==="run")},h=oe(c,r);return a.push(...Q(ce(e.instruction??"")===void 0?c:e)),h.payload.fieldData=JSON.stringify(e),h.payload.resultProjection={id:o,children:g},p.push(A("field",h.payload,h.marks)),p}function pt(e,r,n,o){let a={name:"footnoteRef",attrs:{id:String(e),noteType:r}},s=[...n,a];return A("noteRef",r==="endnote"?{endnoteRefId:e}:{footnoteRefId:e},s,o)}function Ie(e){return e.filter(r=>r.name==="insertion"||r.name==="deletion")}function Ye(e,r,n,o){if((e.type==="drawing"||e.type==="shape"||e.type==="chart")&&r.some(a=>a.name==="hidden")){let a=e.type==="drawing"?e.image:e.type==="shape"?e.shape:e.chart;n.push(...Q(a));}switch(e.type){case "text":return e.text?[re(e.text,r,o)]:[];case "tab":return [re(" ",r,o)];case "break":return e.breakType===void 0||e.breakType==="textWrapping"?[A("break",{},r,o)]:[];case "softHyphen":return [re("\xAD",r,o)];case "noBreakHyphen":return [re("\u2011",r,o)];case "symbol":{let a=Number.parseInt(e.char,16);if(!Number.isInteger(a)||a<0||a>1114111)return [];let s={name:"fontFamily",attrs:{ascii:e.font||null,hAnsi:e.font||null,eastAsia:e.font||null,cs:e.font||null,asciiTheme:null,hAnsiTheme:null,eastAsiaTheme:null,csTheme:null}};return [re(String.fromCodePoint(a),Gt(r,s),o)]}case "commentReference":return [A("field",{fieldType:"COMMENT",instruction:"",displayText:"",fieldKind:"simple",fldLock:false,dirty:false,displayMode:"result",hasCachedResult:false,modelKind:"commentReference",...e.id!==void 0?{commentId:e.id}:{}})];case "drawing":return [A("image",Xt(e.image),Ie(r))];case "horizontalRule":return [A("horizontalRule",{rule:e.rule},r,o)];case "shape":return [A("shape",Qt(e.shape),Ie(r))];case "chart":return [A("chart",Zt(e.chart),Ie(r))];case "footnoteRef":return [pt(e.id,"footnote",r,o)];case "endnoteRef":return [pt(e.id,"endnote",r,o)];default:return []}}function fe(e,r,n,o,a,s=[]){let d=[...mt(e,r,n),...s];return e.content.flatMap(u=>Ye(u,d,o,a))}function ge(e,r,n,o,a=[]){let s=[],d=er(e);for(let u of e.structuredChildren??e.children)if(u.type==="run"){let p=[...mt(u,r,n),...a,d];for(let g of u.content)s.push(...Ye(g,p,o));}else if(u.type==="simpleField"||u.type==="complexField"){o.push(...Q(u));let p=oe(u,r);s.push(A("field",p.payload,[...p.marks,...a,d]));}else u.type==="mathEquation"&&s.push(A("math",Ce(u),[...a,d]));return s}function rr(e,r,n){return {name:r,attrs:{revisionId:e.id,author:e.author,date:e.date??null,isMovePair:n}}}function nr(e,r,n,o,a){let s=e.type==="insertion"||e.type==="moveTo"?"insertion":"deletion",d=rr(e.info,s,e.type==="moveFrom"||e.type==="moveTo"),u=[];for(let p of e.content)if(p.type==="run")u.push(...fe(p,r,n,a,o,[d]));else {a.push(...se(p));let g=ge(p,r,n,a,[d]);for(let c of g)o!==void 0&&(c.commentId=o);u.push(...g);}return u}function yt(e,r,n,o){let a=[],s=d=>{if(d.kind==="text"){if((d.text===" "?"tab":"text")==="tab"){a.push({kind:"tab",attrs:d.attrs});return}let p=a[a.length-1];p&&"text"in p&&Z(p.attrs)===Z(d.attrs)?p.text+=d.text:a.push({kind:"text",text:d.text,attrs:d.attrs});return}a.push({kind:d.embedKind,payload:d.payload,attrs:d.attrs});};for(let d of e.content)if(d.type==="run")fe(d,r,n,o).forEach(s);else if(d.type==="hyperlink")o.push(...se(d)),ge(d,r,n,o).forEach(s);else if(d.type==="simpleField"||d.type==="complexField"){o.push(...Q(d));let u=oe(d,r);s(A("field",u.payload,u.marks));}else d.type==="inlineSdt"?s(A("sdt",yt(d,r,n,o))):d.type==="mathEquation"&&s(A("math",Ce(d)));return j({...d$2(e.properties),propertiesJson:JSON.stringify(e.properties),content:a})}function or(e,r,n){let o=r?r.resolveParagraphStyle(e.formatting?.styleId).runFormatting:void 0;return a$1(o,n)}function sr(e){let r=[];for(let n of e.content)n.type==="footnoteRefMark"?r.push("footnote"):n.type==="endnoteRefMark"&&r.push("endnote");return r}function ht(e){return e.map(r=>{if(r.kind==="text")return r.text;let n=r.payload.footnoteRefId??r.payload.endnoteRefId;return String(n??"")}).join("")}function ut(e){return e.type!=="break"?null:e.breakType==="page"||e.breakType==="column"?e.breakType:null}function ar(e){if(!e.content.some(o=>ut(o)!==null))return [];let r=[],n=0;for(let o of e.content){let a=ut(o);if(a!==null){r.push({offset:n,type:a});continue}n+=ht(Ye(o,[],[])).length;}return r}function ir(e,r,n){let o=fe(e,r,n,[]);if(o.some(p=>p.kind!=="text"&&p.embedKind!=="noteRef"))return null;let a=o.map(p=>Kt(p.marks));if(a.some(p=>p!==a[0]))return null;let s=sr(e),d=ar(e),u=a[0];return {text:ht(o),...s.length>0?{noteMarks:s}:{},...d.length>0?{breaks:d}:{},...u!==void 0?{marksKey:u}:{},...e.formatting?{formatting:e.formatting}:{},...e.propertyChanges?{propertyChanges:e.propertyChanges}:{}}}function lr(e,r,n,o,a){let s=e.formatting,d=s?.styleId,u=s?.indentFirstLine===0?void 0:s?.indentFirstLine,p=u??e.listRendering?.indentFirstLine??s?.indentFirstLine,g=u===void 0&&e.listRendering?.indentFirstLine!==void 0?e.listRendering.hangingIndent:s?.hangingIndent??e.listRendering?.hangingIndent,c={paraId:e.paraId??null,textId:e.textId??null,styleId:d??null,numPr:s?.numPr??null,numPrFromStyle:s?.numPrFromStyle??null,listNumFmt:e.listRendering?.numFmt??null,listIsBullet:e.listRendering?.isBullet??null,listMarker:e.listRendering?.marker??null,listMarkerHidden:e.listRendering?.markerHidden||null,listMarkerFontFamily:e.listRendering?.markerFontFamily||null,listMarkerFontSize:e.listRendering?.markerFontSize||null,listMarkerBold:e.listRendering?.markerBold??null,listMarkerItalic:e.listRendering?.markerItalic??null,listMarkerColor:e.listRendering?.markerColor??null,listMarkerSuffix:e.listRendering?.markerSuffix||null,listLevelNumFmts:e.listRendering?.levelNumFmts||null,listAbstractNumId:e.listRendering?.abstractNumId??null,listStartOverride:e.listRendering?.startOverride??null,_originalFormatting:s??null};if(r){let S=r.resolveParagraphStyle(d,a),l=S.paragraphFormatting;c.alignment=s?.alignment??l?.alignment??null,c.spaceBefore=s?.spaceBefore??l?.spaceBefore??null,c.spaceAfter=s?.spaceAfter??l?.spaceAfter??null,c.spaceBeforeLines=s?.spaceBeforeLines??l?.spaceBeforeLines??null,c.spaceAfterLines=s?.spaceAfterLines??l?.spaceAfterLines??null,c.beforeAutospacing=s?.beforeAutospacing??l?.beforeAutospacing??null,c.afterAutospacing=s?.afterAutospacing??l?.afterAutospacing??null,c.lineSpacing=s?.lineSpacing??l?.lineSpacing??null,c.lineSpacingRule=s?.lineSpacingRule??l?.lineSpacingRule??null,c.spacingExplicit=s?.spacingExplicit||null,c.indentLeft=s?.indentLeft??e.listRendering?.indentLeft??l?.indentLeft??null,c.indentRight=s?.indentRight??l?.indentRight??null;let x=s?.numPr?.numId===0&&l?.numPr&&l.numPr.numId!==0?void 0:l;c.indentFirstLine=p??x?.indentFirstLine??null,c.hangingIndent=g??x?.hangingIndent??false,c.borders=s?.borders??l?.borders??null,c.shading=s?.shading??l?.shading??null,c.tabs=s?.tabs??l?.tabs??null,c.pageBreakBefore=s?.pageBreakBefore??l?.pageBreakBefore??null,c.keepNext=s?.keepNext??l?.keepNext??null,c.keepLines=s?.keepLines??l?.keepLines??null,c.widowControl=s?.widowControl??l?.widowControl??null,c.contextualSpacing=s?.contextualSpacing??l?.contextualSpacing??null,c.snapToGrid=s?.snapToGrid??l?.snapToGrid??null,c.autoSpaceDE=s?.autoSpaceDE??l?.autoSpaceDE??null,c.autoSpaceDN=s?.autoSpaceDN??l?.autoSpaceDN??null,c.outlineLevel=s?.outlineLevel??l?.outlineLevel??null,c.bidi=s?.bidi??l?.bidi??null;let b=r.getDefaultCharacterStyle()?.rPr,P=b?a$1(S.runFormatting,b):S.runFormatting;c.defaultTextFormatting=a$1(P,zt(s?.runProperties,r))??null,!s?.numPr&&l?.numPr&&l.numPr.numId!==0&&(c.numPr=l.numPr,c.numPrFromStyle=l.numPr);}else c.alignment=s?.alignment??null,c.spaceBefore=s?.spaceBefore??null,c.spaceAfter=s?.spaceAfter??null,c.spaceBeforeLines=s?.spaceBeforeLines??null,c.spaceAfterLines=s?.spaceAfterLines??null,c.beforeAutospacing=s?.beforeAutospacing??null,c.afterAutospacing=s?.afterAutospacing??null,c.lineSpacing=s?.lineSpacing??null,c.lineSpacingRule=s?.lineSpacingRule??null,c.spacingExplicit=s?.spacingExplicit||null,c.indentLeft=s?.indentLeft??e.listRendering?.indentLeft??null,c.indentRight=s?.indentRight??null,c.indentFirstLine=p??null,c.hangingIndent=g??false,c.borders=s?.borders??null,c.shading=s?.shading??null,c.tabs=s?.tabs??null,c.pageBreakBefore=s?.pageBreakBefore??null,c.keepNext=s?.keepNext??null,c.keepLines=s?.keepLines??null,c.widowControl=s?.widowControl??null,c.snapToGrid=s?.snapToGrid??null,c.autoSpaceDE=s?.autoSpaceDE??null,c.autoSpaceDN=s?.autoSpaceDN??null,c.outlineLevel=s?.outlineLevel??null,c.bidi=s?.bidi??null,c.defaultTextFormatting=s?.runProperties??null;if(e.sectionProperties){c._sectionProperties=e.sectionProperties;let S=e.sectionProperties.sectionStart;(S==="nextPage"||S==="continuous"||S==="oddPage"||S==="evenPage"||S==="nextColumn")&&(c.sectionBreakType=S);}e.renderedPageBreakBefore&&(c.renderedPageBreakBefore=true),ur(e)&&(c.pageBreakBeforeRun=true),e.pPrIns&&(c.pPrIns={revisionId:e.pPrIns.id,author:e.pPrIns.author,date:e.pPrIns.date??null}),e.pPrDel&&(c.pPrDel={revisionId:e.pPrDel.id,author:e.pPrDel.author,date:e.pPrDel.date??null}),e.propertyChanges?.length&&(c.pPrChange=e.propertyChanges);let h=[],R=0,v=0;for(let S of e.content)if(S.type==="bookmarkStart")h.push({id:S.id,name:S.name,kind:"start",offset:v,...S.colFirst!==void 0?{colFirst:S.colFirst}:{},...S.colLast!==void 0?{colLast:S.colLast}:{}});else if(S.type==="bookmarkEnd")h.push({id:S.id,kind:"end",offset:v});else {let l=dr(S);for(let y=0;y<l;y+=1)v+=n[R]?.pmSize??0,R+=1;}return h.length>0&&(c.bookmarks=h),o?.length&&(c._originalRunBoundaries=o),c}var bt=new WeakMap;function dr(e){return bt.get(e)??0}function pr(e,r,n,o){let a=[],s=[],d=new Set,u=[],p=or(e,r,n);for(let[c,h]of e.content.entries()){let R=a.length,v=d.values().next().value;if(h.type==="commentRangeStart")d.add(h.id);else if(h.type==="commentRangeEnd")d.delete(h.id);else if(h.type==="run"){let S=ir(h,p,r);S&&u?u.push(S):u=void 0,a.push(...fe(h,p,r,s,v));}else if(h.type==="hyperlink"){u=void 0,s.push(...se(h));let S=ge(h,p,r,s);for(let l of S)v!==void 0&&(l.commentId=v);a.push(...S);}else h.type==="simpleField"||h.type==="complexField"?(u=void 0,a.push(...tr(h,p,r,c,s))):h.type==="inlineSdt"?(u=void 0,a.push(A("sdt",yt(h,p,r,s),[],void 0,2))):h.type==="insertion"||h.type==="deletion"||h.type==="moveFrom"||h.type==="moveTo"?(u=void 0,a.push(...nr(h,p,r,v,s))):h.type==="mathEquation"?(u=void 0,a.push(A("math",Ce(h)))):h.type!=="bookmarkStart"&&h.type!=="bookmarkEnd"&&h.type!=="rawXml"&&(u=void 0);bt.set(h,a.length-R);}let g=lr(e,r,a,u,o);return {units:a,ppr:tt(g),opaqueSequences:s}}function ne(e,r){for(let n of e.content)n.type==="break"&&n.breakType==="page"?r.push("pageBreak"):(n.type!=="text"||n.text.length>0)&&r.push("visible");}function _e(e,r){for(let n of e)if(n.type==="run")ne(n,r);else if(n.type==="hyperlink")for(let o of n.children)o.type==="run"&&ne(o,r);else if(n.type==="simpleField")for(let o of n.content)o.type==="run"&&ne(o,r);else if(n.type==="complexField")for(let o of [...n.fieldCode,...n.fieldResult])ne(o,r);else if(n.type==="inlineSdt")_e(n.content,r);else if(n.type==="insertion"||n.type==="deletion"||n.type==="moveFrom"||n.type==="moveTo")for(let o of n.content)o.type==="run"&&ne(o,r);else n.type==="mathEquation"&&r.push("visible");}function ur(e){let r=[];return _e(e.content,r),r[0]==="pageBreak"}function cr(e){let r=[];_e(e.content,r);let n=false,o=false;for(let a of r)if(a==="pageBreak"){if(o||n)return true;n=true;}else o=true;return false}function fr(e){let r=new Map,n=new Map;return e.rows.forEach((o,a)=>{let s=0,d=o.cells.map(p=>{let g=s;return s+=p.formatting?.gridSpan??1,{column:g,vMerge:p.formatting?.vMerge,key:`${a}-${g}`}});if(d.length>0&&d.every(p=>p.vMerge==="continue"&&n.has(p.column))){for(let p of d)n.delete(p.column),r.set(p.key,{rowSpan:1,skip:false});return}for(let p of d)if(p.vMerge==="restart")n.set(p.column,a),r.set(p.key,{rowSpan:1,skip:false});else if(p.vMerge==="continue"){let g=n.get(p.column);if(g===void 0)r.set(p.key,{rowSpan:1,skip:false});else {let c=r.get(`${g}-${p.column}`);c&&(c.rowSpan+=1),r.set(p.key,{rowSpan:1,skip:true});}}else n.delete(p.column),r.set(p.key,{rowSpan:1,skip:false});}),r}function De(e){return {revisionId:e.id,author:e.author,date:e.date??null}}function gr(e,r,n,o,a,s){let d=r?{top:n?r.top:r.insideH,bottom:o?r.bottom:r.insideH,left:a?r.left:r.insideV,right:s?r.right:r.insideV}:void 0;return d||e?.borders?{...d??{},...e?.borders??{}}:void 0}function ct(e,r){let n=e.formatting,o=b$2(n?.shading?.fill,r.theme),a=n?.width?.value??r.gridWidth,s=n?.width?.type??(r.gridWidth!==void 0?"pct":null),d={colspan:n?.gridSpan??1,rowspan:r.rowspan,width:a??null,widthType:s,verticalAlign:n?.verticalAlign??null,backgroundColor:o??null,borders:gr(n,r.tableBorders,r.firstRow,r.lastRow,r.firstColumn,r.lastColumn)??null,margins:n?.margins?{top:n.margins.top?.value,bottom:n.margins.bottom?.value,left:n.margins.left?.value??(r.tableBidi?n.margins.end?.value:n.margins.start?.value),right:n.margins.right?.value??(r.tableBidi?n.margins.start?.value:n.margins.end?.value)}:r.defaultMargins??null,textDirection:n?.textDirection??null,noWrap:n?.noWrap??false,_originalFormatting:n??null,_originalResolvedFill:o??null};if(e.structuralChange){let u=e.structuralChange,p=De(u.info);u.type==="tableCellInsertion"?d.cellMarker={kind:"ins",info:p}:u.type==="tableCellDeletion"?d.cellMarker={kind:"del",info:p}:u.type==="tableCellMerge"&&(d.cellMarker={kind:"merge",info:p,vMerge:u.vMerge??"cont",...u.vMergeOrig?{vMergeOrig:u.vMergeOrig}:{}});}return e.propertyChanges?.length&&(d.tcPrChange=e.propertyChanges),{attrs:st(d,r.isHeader),content:e.content.length>0?e.content:[{type:"paragraph",content:[]}]}}function mr(e,r,n,o,a,s,d,u,p){let g={height:e.formatting?.height?.value??null,heightRule:e.formatting?.heightRule??null,isHeader:!!e.formatting?.header,_originalFormatting:e.formatting??null};e.structuralChange&&(e.structuralChange.type==="tableRowInsertion"?g.trIns=De(e.structuralChange.info):e.structuralChange.type==="tableRowDeletion"&&(g.trDel=De(e.structuralChange.info))),e.propertyChanges?.length&&(g.trPrChange=e.propertyChanges);let c=r.columnWidths,h=c?.reduce((l,y)=>l+y,0)??0,R=c?.length??Math.max(0,...r.rows.map(l=>l.cells.reduce((y,x)=>y+(x.formatting?.gridSpan??1),0))),v=0,S=[];return e.cells.forEach(l=>{let y=l.formatting?.gridSpan??1,x=v,b=o.get(`${n}-${x}`),P;if(c&&h>0){let D=0;for(let T=0;T<y&&x+T<c.length;T+=1)D+=c[x+T];P=Math.round(D/h*100);}v+=y,!b?.skip&&S.push({paragraphFormatting:ve(r,u,n,x,v,p),...ct(l,{isHeader:n===0&&!!r.formatting?.look?.firstRow,rowspan:b?.rowSpan??1,gridWidth:P,firstRow:n===0,lastRow:n===r.rows.length-1,firstColumn:x===0,lastColumn:v===R,tableBorders:a,defaultMargins:s,theme:d,tableBidi:!!r.formatting?.bidi})});}),S.length===0&&S.push({paragraphFormatting:ve(r,u,n,0,R,p),...ct({formatting:R>1?{gridSpan:R}:void 0,content:[{type:"paragraph",content:[]}]},{isHeader:n===0&&!!r.formatting?.look?.firstRow,rowspan:1,gridWidth:h>0?100:void 0,firstRow:n===0,lastRow:n===r.rows.length-1,firstColumn:true,lastColumn:true,tableBorders:a,defaultMargins:s,theme:d,tableBidi:!!r.formatting?.bidi})}),{attrs:ot(g),cells:S}}function yr(e,r,n,o){let a=r?.getDefaultTableStyle(),s=e.formatting?.styleId,d=s??a?.styleId,u=d?r?.getStyle(d):void 0,p=e.formatting?.borders??u?.tblPr?.borders??a?.tblPr?.borders,g=e.formatting?.cellMargins??u?.tblPr?.cellMargins??a?.tblPr?.cellMargins,c=e.formatting?.bidi?g?.end:g?.start,h=e.formatting?.bidi?g?.start:g?.end,R=g?{top:g.top?.value,bottom:g.bottom?.value,left:g.left?.value??c?.value,right:g.right?.value??h?.value}:void 0,v=[],S=new Set,l=u;for(;l?.basedOn&&v.length<32&&!S.has(l.basedOn);)S.add(l.basedOn),v.unshift(l.basedOn),l=r?.getStyle(l.basedOn);let y={...e.formatting??{},styleCascade:{...s?{selectedStyleId:s}:{},...a?.styleId?{defaultStyleId:a.styleId}:{},...v.length>0?{basedOnStyleIds:v}:{}}},x={styleId:s??null,width:e.formatting?.width?.value??null,widthType:e.formatting?.width?.type??null,justification:e.formatting?.justification??null,columnWidths:e.columnWidths??null,tableLayout:e.formatting?.layout??null,floating:e.formatting?.floating??null,cellMargins:R??null,look:e.formatting?.look??null,bidi:e.formatting?.bidi||null,compatibilityMode:o===12?null:o,_originalFormatting:y};e.propertyChanges?.length&&(x.tblPrChange=e.propertyChanges);let b=fr(e),P=et(e);return {attrs:x,rows:e.rows.map((D,T)=>mr(D,e,T,b,p,R,n,u??a,P))}}function hr(e){return it(d$2(e))}function br(e){let r=0;for(let n of e.units){let o=n.kind==="text"?n.text.length:1;if(n.commentId!==void 0&&n.commentId!==0){let a=e.commentCoverage.get(n.commentId),s=a?.[a.length-1];s&&s[1]===r?s[1]=r+o:a?a.push([r,r+o]):e.commentCoverage.set(n.commentId,[[r,r+o]]);}r+=o;}}function xt(e,r,n){if(c$1(n))return null;if(n.type==="paragraph"){let o=e.paragraph++;return !n.repeatedParaId&&n.paraId||`${r}:p${o}`}return n.type==="table"?`${r}:t${e.table++}`:at(r,e.sdt++)}function xr(e){return /^\d+$/.test(e.trim())}function Sr(e){let r=e.structuredResult?.blocks??[],n=r[r.length-1];return !n||n.type!=="paragraph"||(n.content?.length??0)>0?null:r.length}function Rr(e,r,n,o,a,s){for(let d of e){if(d.kind!=="embed"||d.embedKind!=="field")continue;let u=d.payload.instruction;if(typeof u!="string"||!xr(u))continue;let p=d.payload.fieldData;if(typeof p!="string")continue;let g;try{g=JSON.parse(p);}catch{continue}let c=Sr(g);if(c===null||o+1+c>n.length)continue;let h={...a},R=[];for(let v=0;v<c;v+=1){let S=n[o+1+v],l=xt(h,r,S);l!==null&&(S.type==="table"&&s.set(o+1+v,l),R.push(l));}R.length>0&&(d.payload.fieldResultBlocks=R);}}function G(e,r,n,o){let a={storyId:r,units:[],commentCoverage:new Map};e.plans.push(a);let s=n.length>0,d=s?[...n]:[{type:"paragraph",content:[]}],u={paragraph:0,table:0,sdt:0},p=new Map,g=null;for(let[c,h]of d.entries()){if(c$1(h))continue;let R=u.table,v=xt(u,r,h);if(v===null)continue;if(h.type==="paragraph"){let l=pr(h,e.styleResolver,o.extraRunFormatting,o.tableParagraphFormatting);e.opaqueSequences.push(...l.opaqueSequences),Rr(l.units,r,d,c,u,p),a.units.push(...l.units),a.units.push(A("pilcrow",{...l.ppr,...s&&h.paraId?{sourceParaId:h.paraId}:{},...s?{}:{paraOrigin:"synthetic"},paraId:v})),o.includePageBreaks&&cr(h)&&a.units.push(A("pageBreak",{})),g="paragraph";continue}if(h.type==="table"){let l=yr(h,e.styleResolver,e.theme,e.compatibilityMode),y=l.rows.map((b,P)=>({trPr:b.attrs,cells:b.cells.map((D,T)=>({tcPr:D.attrs,story:Te(r,R,P,T)}))})),x=p.get(c);a.units.push(A("table",{tblPr:rt(l.attrs),grid:nt(l.attrs),rows:y,...x===void 0?{}:{blockId:x}})),l.rows.forEach((b,P)=>{b.cells.forEach((D,T)=>{G(e,Te(r,R,P,T),D.content,{includePageBreaks:false,appendBodyTail:false,seedComments:false,extraRunFormatting:D.extraRunFormatting,tableParagraphFormatting:D.paragraphFormatting});});}),g="table";continue}let S=v;a.units.push(A("blockSdt",{...hr(h.properties),story:S})),G(e,S,h.content,{includePageBreaks:o.includePageBreaks,appendBodyTail:false,seedComments:false,tableParagraphFormatting:o.tableParagraphFormatting}),g="blockSdt";}o.appendBodyTail&&(g==="table"||g==="blockSdt")&&a.units.push(A("pilcrow",{hangingIndent:false,paraId:`${r}:p${u.paragraph}`,paraOrigin:"synthetic"})),o.seedComments&&br(a);}function kr(e){let r=[{op:"delete",index:0,len:1}],n=0,o="",a={},s=Z(a),d=()=>{o&&(r.push({op:"insert",index:n,text:o,attrs:a}),n+=o.length,o="");};for(let u of e)if(u.kind==="text"){let p=Z(u.attrs);o&&p!==s&&d(),a=u.attrs,s=p,o+=u.text;}else d(),r.push({op:"insertEmbed",index:n,kind:u.embedKind,payload:u.payload,attrs:u.attrs}),n+=1;return d(),r}function Pr(e,r){let n=kr(r.units);for(let[o,a]of r.commentCoverage)n.push({op:"setComment",id:String(o),ranges:a,author:"",date:"",body:null});e.applySeedRawOps(r.storyId,n);}function wr(e,r,n={}){f(e,"all");let o={styleResolver:r.package.styles?d(r.package.styles):null,theme:r.package.theme??null,plans:[],compatibilityMode:Ht(r),opaqueSequences:[]};G(o,"body",r.package.document.content,{includePageBreaks:true,appendBodyTail:true,seedComments:true});for(let[a,s]of r.package.headers??[])G(o,ue(a),s.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let[a,s]of r.package.footers??[])o.plans.some(d=>d.storyId===ue(a))||G(o,ue(a),s.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let a of r.package.footnotes??[])G(o,lt(a.id),a.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let a of r.package.endnotes??[])G(o,dt(a.id),a.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let a of o.plans)e.createStory(a.storyId,"","Normal","left");for(let a of o.plans)Pr(e,a);e.seedOpaqueSequences(o.opaqueSequences),e.beginOpening(n.generation);}function vr(e){let r=e.package;return [r.document.content,...[...r.headers?.values()??[]].map(n=>n.content),...[...r.footers?.values()??[]].map(n=>n.content),...(r.footnotes??[]).map(n=>n.content),...(r.endnotes??[]).map(n=>n.content)]}var Tr="word/comments.xml";function St(e){if(Array.isArray(e)&&e.length>0&&e.every(n=>n?.type==="paragraph"))return e;let r=typeof e=="string"?e:"";return [{type:"paragraph",formatting:{},content:r?[{type:"run",formatting:{},content:[{type:"text",text:r}]}]:[]}]}function Ir(e,r){let n=r.package.document.comments??[],o=new Map(e.listComments().map(g=>[g.id,g])),a=false,s=n.map(g=>{let c=o.get(String(g.id));return o.delete(String(g.id)),!c||!c.author&&!c.date&&c.body==null?g:(a=true,{...g,...c.author?{author:c.author}:{},...c.date?{date:c.date}:{},...c.body==null?{}:{content:St(c.body)}})}),d=new Set(n.map(g=>g.id)),u=new Map,p=Math.max(0,...d)+1;for(let g of o.values()){a=true;let c=/^\d+$/.test(g.id)?Number(g.id):Number.NaN;if(!Number.isSafeInteger(c)||d.has(c)){for(;d.has(p);)p+=1;c=p;}d.add(c),String(c)!==g.id&&u.set(c,g.id),s.push({id:c,author:g.author,...g.date?{date:g.date}:{},content:St(g.body)});}return {comments:s,sessionIds:u,changed:a}}function Dr(e$1,r){let n=new Map(r.paragraphs.flatMap(s=>s.session?[[s.session.paraId,s]]:[])),o=[],a=s=>{for(let d of s)if(d.type==="table")for(let u of d.rows)for(let p of u.cells)a(p.content);else if(d.type==="blockSdt")a(d.content);else if(d.type==="paragraph"&&d.paraId){let u=e(d),p=u===void 0?void 0:n.get(u);if(!p?.session||!p.persisted)continue;o.push({session:p.session,persisted:{...p.persisted,paraId:d.paraId}});}};for(let s of vr(e$1))a(s);return o}function Rt(e){return {identities:e.paragraphIdentities(),plan:e.paragraphSavePlan()}}async function kt(e,r,n,o,a={},s=()=>true){let d={...n.plan,patchedParts:n.plan.patchedParts.filter(({part:l})=>s(l))},u=Dr(r,n.identities),{buffer:p}=await d$1(r,o,a,void 0,void 0,d),g=new Uint8Array(p),c=e.writtenParagraphIds(g),h=(l,y)=>c[l]?.includes(y.toUpperCase())??false,R=u.filter(({persisted:l})=>h(l.story.partUri,l.paraId)),v=new Set(e.recordSavedParagraphIds([...R.map(({session:l,persisted:y})=>[l.paraId,y.paraId]),...d.assignments.filter(({part:l,paraId:y})=>h(`/${l}`,y)).map(({part:l,ordinal:y,paraId:x})=>[`/${l}#${y}`,x])]).map(([l,y])=>`${l}\0${y}`)),S=({session:l,persisted:y})=>v.has(`${l.paraId}\0${y.paraId}`);return {bytes:g,paragraphs:R.filter(l=>!S(l)),conflicts:R.filter(S)}}async function Cr(e,r={}){let n=e.materializeDocx();if(!n?.originalBuffer)throw new Error("saveYrsDocx requires a session opened from DOCX bytes");let o=Rt(e),a=Ir(e,n),s=g(e,a.changed?{...n,package:{...n.package,document:{...n.package.document,comments:a.comments}}}:n,{commentIds:a.sessionIds});return kt(e,s,o,n.originalBuffer,r,d=>!a.changed||d!==Tr)}var Fe=new WeakMap;async function xn(e){let r=new Uint8Array(e),n=globalThis.crypto?.subtle;if(!n)return r;try{let o=new Uint8Array(await n.digest("SHA-256",r));Fe.set(r,Array.from(o,a=>a.toString(16).padStart(2,"0")).join(""));}catch{}return r}function Sn(e){return Fe.get(e)}function Rn(e,r){return !e||!r?e===r:e.anchor.story===r.anchor.story&&e.anchor.paraId===r.anchor.paraId&&e.anchor.offset===r.anchor.offset&&e.head.story===r.head.story&&e.head.paraId===r.head.paraId&&e.head.offset===r.head.offset}function Yr(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}function Pt(e){return JSON.stringify("revisionId"in e?{revisionId:e.revisionId}:{story:e.story,startPara:e.start.paraId,startOffset:e.start.offset,endPara:e.end.paraId,endOffset:e.end.offset})}function wt(e){return JSON.stringify(e.map(r=>({story:r.story,startPara:r.start.paraId,startOffset:r.start.offset,endPara:r.end.paraId,endOffset:r.end.offset})))}function vt(e){return e.kind==="search"?e.within.story:e.story}function Tt(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function kn(e,r){return Ae(e,r)}function Ae(e,r){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("DOCX host metadata must be an object");let o=n;if(!Array.isArray(o.referencedFonts)||!o.referencedFonts.every(d=>typeof d=="string"))throw new TypeError("DOCX host referencedFonts must be a string array");let a=o.unusedScriptFonts??[];if(!Array.isArray(a)||!a.every(d=>typeof d=="string"))throw new TypeError("DOCX host unusedScriptFonts must be a string array");let s=c(o.envelope,Tt(r));return {document:s.document,referencedFonts:o.referencedFonts,unusedScriptFonts:a,embeddedFonts:s.embeddedFonts,...s.fontTableRelationshipsXml===void 0?{}:{fontTableRelationshipsXml:s.fontTableRelationshipsXml}}}var _r=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;function Ar(e,r){let n=new Map,o=[],a$1=false,s=false,d=0,u=0,p=false,g=false,c,h=null,R=[],v=new Map,S=new Map,l=null,y=false,x=0,b=false,P=null,D=t=>(t.layoutJson!==void 0&&P!==null&&(l=P,y=true,x+=1,b=false,P=null),t),T=0,F=null,J=()=>{c=void 0,h=null;},_=()=>{if(!(s||p||u!==0)){p=true;try{for(;!s&&o.length>0;){let t=o.shift();if(!t)break;for(let[i,f]of [...n]){if(s)return;if(n.get(i)===f)try{f(t.update.slice(),t.origin);}catch{}}}}finally{p=false,s&&(o.length=0);}}},C=false,k=false,m=t=>{if(C)throw new Error("A document preview is display-only");J(),u+=1;try{return t()}finally{u-=1,u===0&&_();}},O=t=>t?{anchor:{...t.anchor},head:{...t.head}}:null,w=t=>{g||(e.track_undo(),g=true),t!==void 0&&(e.select_story(t),I(t));},I=t=>{f(B,t);},M=t=>(I(t.createdStoryIds),I(t.deletedStoryIds),I(t.changedStoryIds),t),ae=()=>(c!==void 0?c:JSON.parse(e.selection()))?.head.story??"all",It=()=>{a$1||(e.set_update_observer((t,i)=>{i!==0&&i!==1||(o.push({update:t.slice(),origin:i===0?"local":"remote"}),_());}),a$1=true);},Dt=()=>{!a$1||n.size>0||s||(o.length=0,e.clear_update_observer(),a$1=false);},me=new Map,Ee=0,ye=()=>{me.clear(),Ee+=1;},Oe=(t,i,f={})=>{let Y=t.slice();I("all"),ye();let U=m(()=>{e.set_media_tokens(f.mediaTokens===!0);let he=e.open_docx(Y,i,f.generation,Fe.get(t));return $.reset(),he}),z=Ne(Ae(U,Y));return F=Y,k=false,z},Me=t=>{if(s||!t.startsWith("media:"))return null;let i=me.get(t);return i===void 0&&(i=e.media_data_url(t)??null,me.set(t,i)),i},Ne=t=>(a$2(t.document.package.document.comments,Me),t),$=Ge({version:()=>B.version(),resolveParagraphAnchor:t=>B.resolveParagraphAnchor(t),findText:t=>B.findText(t),readParagraphs:t=>B.readParagraphs(t),applyEdits:t=>B.applyEdits(t),listRevisions:()=>B.listRevisions(),settleRevisions:(t,i)=>{let f=B.storiesChangedSince(Number.MAX_SAFE_INTEGER).revision;e.settle_revisions_json(JSON.stringify({accept:t,reject:i})),I(B.storiesChangedSince(f).stories);},...typeof e.begin_shared_reads=="function"&&typeof e.end_shared_reads=="function"?{sharedReads:t=>{e.begin_shared_reads();try{return t()}finally{e.end_shared_reads();}}}:{}}),B={clientId:r,openDocxPreview:(t,i)=>{I("all"),ye();let f=m(()=>e.open_docx_preview(t,i));return f===void 0?null:(C=true,k=true,Ne(Ae(f,t)))},isDisplayOnly:()=>C,setPartialDocument:t=>{k=t,e.set_partial_document(t);},layoutDocumentWithRegionsPrefixRetainedJson:(t,i)=>{let f=e.layout_document_with_regions_prefix_retained_json(t,i);return l=t,y=true,x+=1,b=false,f},registerFont:t=>{let i=e.register_measure_font(t);return R.push(t.slice()),T+=1,i},registerSubstituteFont:(t,i)=>{let f=e.register_substitute_measure_font(t,i);return f===t||(R.push({substituteOf:t,family:i}),T+=1),f},clearFonts:()=>{e.clear_measure_fonts(),R.length=0,S.clear(),T+=1;},measureParagraphJson:t=>{let i=e.measure_paragraph_json(t);return S.set(t,t),i},layoutDocumentJson:t=>{let i=e.layout_document_json(t);return l=t,y=false,x+=1,b=false,i},layoutFontRequirementsJson:t=>e.layout_font_requirements_json(t),layoutDocumentWithRegionsJson:t=>{let i=e.layout_document_with_regions_json(t);return l=t,y=true,x+=1,b=false,i},layoutDocumentWithRegionsRetainedJson:t=>{let i=e.layout_document_with_regions_retained_json(t);return l=t,y=true,x+=1,b=false,i},beginRegionLayout:t=>(P=t,D(JSON.parse(e.begin_region_layout(t)))),resumeRegionLayout:t=>D(JSON.parse(e.resume_region_layout(t))),adoptResidentWorkerLayout:t=>(l=t,y=true,x+=1,b=true,x),residentLayoutInWorker:()=>b,retainedKernelInputsJson:t=>{if(b)throw new Error("the retained layout was computed in the resident worker");if(t!==x)throw new Error(`retained layout revision mismatch: expected ${t}, current ${x}`);return e.retained_kernel_inputs_json()},buildDisplayListJson:t=>e.build_display_list_json(t),resetFrameBase:()=>{s||e.reset_frame_base();},buildDisplayListFrame:(t,i)=>e.build_display_list_frame(t,i),setDisplayWindow:(t,i)=>e.set_display_window(t,i),setDisplayRetainBuiltPages:t=>e.set_display_retain_built_pages(t),buildDisplayPagesFrame:(t,i)=>e.build_display_pages_frame(Uint32Array.from(t),i),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),applyInput:(t,i)=>(w(),I(ae()),m(()=>e.apply_input(t,i))),applyDelete:(t,i,f=1)=>(w(),I(ae()),m(()=>e.apply_delete(t,i,f))),residentDeletedUnits:()=>e.resident_deleted_units(),applyInputProfiled:(t,i)=>{w(),I(ae());let f=m(()=>e.apply_input_profiled(t,i)),Y=JSON.parse(e.apply_input_profile_json());return {frame:f,profile:Y}},applyDeleteProfiled:(t,i,f=1)=>{w(),I(ae());let Y=m(()=>e.apply_delete_profiled(t,i,f)),U=JSON.parse(e.apply_input_profile_json());return {frame:Y,profile:U}},residentWorkerSnapshot:t=>{if(!l||!y&&v.size===0)return null;let i=e.selection(),f=e.media_sources_json(),Y=t?.knownFontsRevision===T,U=null;if(t?.knownStateVector)try{U=e.encode_diff(t.knownStateVector.slice());}catch{U=null;}return {clientId:r,state:U??e.encode_state(),selection:JSON.parse(i),fonts:Y?[]:R.map(z=>z instanceof Uint8Array?z.slice():{...z}),fontsRevision:T,renderInputs:[...v].map(([z,he])=>({story:z,env:structuredClone(he)})),measureInputs:[...S.values()],layoutInput:l,layoutWithRegions:y,layoutRevision:x,...k?{partialDocument:true}:{},...f?{mediaSources:f}:{}}},residentWorkerProbe:()=>!l||!y&&v.size===0?null:{layoutRevision:x},displayHitTestRegionsJson:(t,i,f)=>e.display_hit_test_regions_json(t,i,f),displayVerticalMoveJson:(t,i,f)=>e.display_vertical_move_json(t,i,f),displayRangeRectsJson:(t,i)=>e.display_range_rects_json(t,i),displayRangeRectsRegionJson:(t,i,f,Y)=>e.display_range_rects_region_json(t,i,f,Y),outlineGlyphJson:(t,i)=>e.outline_glyph_json(t,i),loadState:t=>{I("all"),m(()=>{e.load(t),$.reset();});},seedFromDocx:(t,i)=>Oe(t,true,i),openDocx:Oe,beginOpening:t=>{m(()=>{e.begin_opening(t),$.reset();});},seedOpaqueSequences:t=>{I("all"),m(()=>e.seed_opaque_sequences(JSON.stringify(t)));},mediaSource:t=>{if(s||!t.startsWith("media:"))return null;let i=e.media_bytes(t),f=i&&e.media_type(t);return i&&f?{bytes:i,mimeType:f}:null},loadMediaSources:t=>e.load_media_sources(t),mediaDataUrl:Me,mediaScope:()=>Ee,materializeDocx:()=>{let t=F,i=e.materialize_docx();return !t||i===void 0?null:b$1(i,Tt(t)).document},loadStories:t=>(I(t.map(i=>i.storyId)),m(()=>JSON.parse(e.load_json(JSON.stringify(t))))),encodeState:()=>e.encode_state(),encodeStateVector:()=>e.encode_state_vector(),encodeStateAsUpdate:t=>t===void 0?e.encode_state():e.encode_diff(t.slice()),applyUpdate:t=>(I("all"),m(()=>JSON.parse(e.apply_update_with_inference(t)))),applyLocalUpdate:t=>{w(),I("all"),m(()=>e.apply_local_update(t));},onUpdate:t=>{if(s)throw new Error("yrs session is destroyed");if(typeof t!="function")throw new TypeError("update listener must be a function");let i=d++;n.set(i,t),It();let f=true;return ()=>{f&&(f=false,n.delete(i),Dt());}},encodeStickyPosition:t=>({story:t.story,encoded:e.encode_sticky_position(t.story,t.paraId,t.offset)}),resolveStickyPosition:t=>{try{return JSON.parse(e.resolve_sticky_position(t.story,t.encoded))}catch{return null}},setSelection:(t,i=t)=>{if(t.story!==i.story)throw new Error("yrs selection must stay inside one story");e.set_selection(t.story,t.paraId,t.offset,i.paraId,i.offset),c={anchor:{...t},head:{...i}};},selection:()=>(c!==void 0||(c=JSON.parse(e.selection())),O(c)),encodeSelection:()=>{let t=JSON.parse(e.encoded_selection());return t?{story:t.story,anchor:Uint8Array.from(t.anchor),head:Uint8Array.from(t.head)}:null},resolveSelection:t=>{try{return JSON.parse(e.resolve_encoded_selection(t.story,t.anchor,t.head))}catch{return null}},setCellSelection:t=>e.set_cell_selection(JSON.stringify(t)),cellSelection:()=>JSON.parse(e.cell_selection()),beginUndoCapture:w,addUndoBoundary:()=>e.add_undo_boundary(),setUndoCaptureMode:t=>e.set_undo_capture_mode(t),undoCaptureMode:()=>e.undo_capture_mode(),historyStories:()=>e.history_stories(),undo:()=>m(()=>{let t=e.undo();return t&&I(e.history_stories()),t}),redo:()=>m(()=>{let t=e.redo();return t&&I(e.history_stories()),t}),canUndo:()=>e.can_undo(),canRedo:()=>e.can_redo(),createStory:(t,i,f="Normal",Y="left")=>(I(t),m(()=>JSON.parse(e.create_story(t,i,f,Y)))),deleteStory:t=>(I(t),m(()=>e.delete_story(t))),insertTable:(t,i,f,Y)=>(w(t.story),m(()=>M(JSON.parse(e.insert_table(t.story,t.paraId,t.offset,i,f,Y?.name,Y?.date))))),insertRow:(t,i,f)=>(w(t.story),m(()=>M(JSON.parse(e.insert_row(JSON.stringify(t),i==="below",f?.name,f?.date))))),insertColumn:(t,i)=>(w(t.story),m(()=>M(JSON.parse(e.insert_column(JSON.stringify(t),i==="right"))))),deleteRow:(t,i)=>(w(t.anchor.story),m(()=>M(JSON.parse(e.delete_row(JSON.stringify(t),i?.name,i?.date))))),deleteColumn:t=>(w(t.anchor.story),m(()=>M(JSON.parse(e.delete_column(JSON.stringify(t)))))),deleteTable:t=>(w(t.story),m(()=>M(JSON.parse(e.delete_table(JSON.stringify(t)))))),mergeCells:t=>(w(t.anchor.story),m(()=>M(JSON.parse(e.merge_cells(JSON.stringify(t)))))),splitCell:(t,i,f)=>(w(t.story),m(()=>M(JSON.parse(e.split_cell(JSON.stringify(t),i,f))))),setCellShading:(t,i)=>(w(t.anchor.story),m(()=>M(JSON.parse(e.set_cell_shading(JSON.stringify(t),i??void 0))))),setCellTextFormat:(t,i)=>(w(t.anchor.story),m(()=>M(JSON.parse(e.set_cell_text_format(JSON.stringify(t),JSON.stringify(i)))))),setCellBorders:(t,i)=>(w(t.anchor.story),m(()=>M(JSON.parse(e.set_cell_borders(JSON.stringify(t),JSON.stringify(i)))))),setColumnWidth:(t,i)=>(w(t.story),m(()=>M(JSON.parse(e.set_column_width(JSON.stringify(t),i))))),setTableWidth:(t,i)=>(w(t.story),m(()=>M(JSON.parse(e.set_table_width(JSON.stringify(t),i))))),insertText:(t,i,f)=>(w(t.story),m(()=>JSON.parse(e.insert_text(t.story,t.paraId,t.offset,i,f?.name,f?.date)))),deleteRange:(t,i)=>(w(t.story),m(()=>JSON.parse(e.delete_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i?.name,i?.date)))),replaceRange:(t,i,f)=>(w(t.story),m(()=>JSON.parse(e.replace_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i,f?.name,f?.date)))),splitParagraph:(t,i)=>(w(t.story),m(()=>JSON.parse(e.split_paragraph(t.story,t.paraId,t.offset,i?.name,i?.date)))),mergeParagraphs:(t,i,f)=>(w(t),m(()=>JSON.parse(e.merge_paragraphs(t,i,f?.name,f?.date)))),toggleMark:(t,i)=>{w(t.story),m(()=>e.toggle_mark(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},formatRange:(t,i)=>{w(t.story),m(()=>e.format_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},setHyperlink:(t,i)=>{w(t.story),m(()=>e.set_hyperlink(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},clearFormatting:t=>{w(t.story),m(()=>e.clear_formatting(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset));},applyParagraphStyle:(t,i,f)=>{w(t.story),m(()=>e.apply_paragraph_style(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i,f?.name,f?.date));},setParagraphAttrs:(t,i,f)=>{w(t.story),m(()=>e.set_paragraph_attrs(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i),f?.name,f?.date));},insertImage:(t,i,f)=>(w(t.story),m(()=>JSON.parse(e.insert_image(t.story,t.paraId,t.offset,JSON.stringify(i),f?.name,f?.date)))),setContentControlValue:(t,i)=>{w(),I("all"),m(()=>e.set_content_control_value(t,JSON.stringify(i)));},setContentControlValueAt:(t,i)=>{w(t.story),typeof i=="string"&&I("all"),m(()=>e.set_content_control_value_at(t.story,t.paraId,t.offset,JSON.stringify(i)));},clearContentControlValue:t=>{w(),I("all"),m(()=>e.clear_content_control_value(t));},setImageGeometry:(t,i)=>{w(),I("all"),m(()=>e.set_image_geometry(t,JSON.stringify(i)));},setImageGeometryAt:(t,i)=>{w(t.story),m(()=>e.set_image_geometry_at(t.story,t.paraId,t.offset,JSON.stringify(i)));},insertPageBreak:t=>{w(t.story),m(()=>e.insert_page_break(t.story,t.paraId,t.offset));},insertSectionBreak:(t,i)=>{w(t.story),m(()=>e.insert_section_break(t.story,t.paraId,t.offset,i));},insertWatermark:(t,i)=>{w(t.story),m(()=>e.insert_watermark(t.story,t.paraId,t.offset,JSON.stringify(i)));},applyRawOps:(t,i)=>{let f=i.some(Y=>Y.op==="insertEmbed"&&Y.kind==="pilcrow"||Y.op==="setEmbedAttr"&&Y.key==="paraId");I(f?"all":t),m(()=>e.apply_raw_ops(t,JSON.stringify(i)));},applySeedRawOps:(t,i)=>{I(t),m(()=>e.apply_seed_raw_ops(t,JSON.stringify(i)));},setParagraphAttr:(t,i,f)=>{I("all"),m(()=>e.set_paragraph_attr(t,i,JSON.stringify(f??null)));},addComment:(t,i,f,Y)=>(I(t.map(U=>U.story)),m(()=>JSON.parse(e.add_comment(wt(t),i,f,JSON.stringify(Y??null))))),setCommentRanges:(t,i)=>{w(),m(()=>{e.set_comment_ranges(t,wt(i)),I("all");});},acceptChange:t=>(I("all"),m(()=>JSON.parse(e.accept_change(Pt(t))))),rejectChange:t=>(I("all"),m(()=>JSON.parse(e.reject_change(Pt(t))))),selectionContext:t=>{let i=JSON.stringify(t);if(h?.key===i)return JSON.parse(h.json);let f=e.selection_context(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset),Y=JSON.parse(f);return h={key:i,json:f},Y},listRevisions:()=>JSON.parse(e.list_revisions()),resolveComment:t=>JSON.parse(e.resolve_comment(t)),listComments:()=>JSON.parse(e.list_comments()),storyIds:()=>e.story_ids(),hasStory:t=>!_r.test(t)&&e.has_story(t),storyLength:t=>e.story_len(t),storyChecksum:t=>BigInt(e.story_checksum(t)),yrsBlocksForStory:(t,i={})=>{let f=e.yrs_blocks_for_story(t,JSON.stringify(i)),Y=JSON.parse(f);return v.set(t,structuredClone(i)),Y},paragraphs:t=>JSON.parse(e.paragraphs(t)),searchText:(t,i={})=>{if(!t)return [];let f=i.limit??Number.POSITIVE_INFINITY;if(!Number.isSafeInteger(f)&&f!==Number.POSITIVE_INFINITY||f<0)throw new RangeError("search limit must be a non-negative safe integer");return JSON.parse(e.search_text(t,i.caseSensitive??false,Number.isFinite(f)?Math.min(f,4294967295):void 0))},paragraphSpans:t=>JSON.parse(e.paragraph_spans(t)),storySegments:t=>JSON.parse(e.story_segments(t)),storiesChangedSince:t=>JSON.parse(e.stories_changed_since(t)),storySegmentUnitDigests:t=>JSON.parse(e.story_segment_unit_digests(t)),storySegmentUnits:(t,i)=>JSON.parse(e.story_segment_units(t,Uint32Array.from(i))),tablePayload:(t,i)=>{if(!Number.isInteger(i)||i<0||i>4294967295)return e.story_len(t),null;let f=e.table_payload(t,i);return f===void 0?null:JSON.parse(f)},locateParagraph:(t,i)=>JSON.parse(e.locate_paragraph(t,i)),paragraphIdentities:()=>JSON.parse(e.paragraph_identities()),persistParagraphIds:()=>(I("all"),m(()=>JSON.parse(e.persist_paragraph_ids()))),resolveParagraphAnchor:t=>JSON.parse(e.resolve_paragraph_anchor(JSON.stringify(t))),storyParagraphIds:t=>JSON.parse(e.story_paragraph_ids(t)),paragraphSavePlan:()=>JSON.parse(e.paragraph_save_plan()),recordSavedParagraphIds:t=>m(()=>JSON.parse(e.record_saved_paragraph_ids(JSON.stringify(t)))),writtenParagraphIds:t=>JSON.parse(e.written_paragraph_ids(t)),exportStructured:t=>JSON.parse(e.export_structured_json(JSON.stringify(t))),exportMarkdown:t=>JSON.parse(e.export_markdown_json(JSON.stringify(t))),exportStructuredWithPages:t=>JSON.parse(e.export_structured_with_pages_json(JSON.stringify(t),void 0)),exportStructuredWithPagesFor:(t,i)=>JSON.parse(e.export_structured_with_pages_json(JSON.stringify(t),i)),exportSnapshotWithPrivateFonts:(t,i,f,Y)=>JSON.parse(e.export_snapshot_with_private_fonts_json(t,i,f,JSON.stringify(Y))),headings:t=>JSON.parse(e.headings_json(t)),listContentControls:(t={})=>JSON.parse(e.list_content_controls_json(JSON.stringify(t))),findContentControls:(t,i={})=>JSON.parse(e.find_content_controls_json(JSON.stringify(t),JSON.stringify(i))),version:()=>e.version(),readParagraphs:t=>JSON.parse(e.read_paragraphs_json(JSON.stringify(t))),findText:t=>JSON.parse(e.find_text_json(JSON.stringify(t))),validateEdits:t=>JSON.parse(e.validate_edits_json(JSON.stringify(t))),applyEdits:t=>m(()=>{let i=JSON.parse(e.apply_edits_json(JSON.stringify(t)));return i.ok&&i.applied&&I(i.changedStories),i}),proposeChanges:t=>m(()=>$.propose(t)),setProposalStates:t=>$.setStates(t),withdrawProposals:t=>m(()=>$.withdraw(t)),getProposals:()=>$.snapshot(),onProposalChange:t=>{if(s)throw new Error("yrs session is destroyed");return $.subscribe(t)},formatTextTarget:(t,i)=>(w(vt(t)),m(()=>JSON.parse(e.format_text_target_json(JSON.stringify(t),JSON.stringify(i))))),commentTextTarget:(t,i)=>(I(vt(t)),m(()=>JSON.parse(e.comment_text_target_json(JSON.stringify(t),JSON.stringify({...i,body:i.body??null}))))),selectionText:t=>JSON.parse(e.selection_text_json(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset)),destroy:()=>{s||(s=true,ye(),n.clear(),$.destroy(),o.length=0,a$1&&e.clear_update_observer(),e.free());}};return a(B,{compareDocx:(t,i,f)=>{I("all");let Y=m(()=>{let U=e.compare_docx_json(t,i,f);return $.reset(),U});return F=t.slice(),Y},finishComparedDocx:t=>e.finish_compared_docx_json(t),failComparedDocx:t=>e.fail_compared_docx_json(t)}),B}async function Pn(e){let r=e?.clientId??Yr(),n=await import('../wasm-NF6B3AH7.mjs');return await n.preloadEditWasm(),Ar(n.createEditSession(r),r)}export{le as ResidentEngineWorkerClient,N as ResidentWorkerFailureError,te as ResidentWorkerOutOfMemoryError,Pe as canUseResidentEngineWorker,Rt as captureSessionSave,Nr as compareYrsLocs,Or as createYrsInputPositionMap,Pn as createYrsSession,kn as decodeDocxHostJson,Mr as displayPositionToYrsLoc,wr as documentToYrs,Ut as preloadDocxEngine,we as preloadResidentEngineWorker,xn as prepareDocxBytes,Sn as preparedDocxDigest,Ke as proposalRevisionPreview,Wt as retainPreloadedResidentEngineWorker,Rn as sameYrsSelection,Cr as saveYrsDocx,Bt as takePreloadedResidentEngineWorker,kt as writeSessionSave,Xe as yrsLocToDisplayPosition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import'../chunk-EUUIJVM6.mjs';import {b as b$1,a as a$2}from'../chunk-J7LNO6SM.mjs';import {a as a$3,b as b$2}from'../chunk-Z4HZIPBS.mjs';import {u as u$1,s,a as a$1,g,j as j$1,i}from'../chunk-PGMXWI5X.mjs';import'../chunk-5F6DLQZP.mjs';import'../chunk-TTRUPDAB.mjs';async function q(){await a$3();let e=b$2(le()),o=new Set,r=false,i=false,l=false,c=()=>{l||(e.track_undo(),l=true);},R=()=>{r||(e.set_update_observer((t,n)=>{if(!(n!==0&&n!==1))for(let p of [...o])p(t,n===0?"local":"remote");}),r=true);};return {registerFont:t=>e.register_measure_font(t),registerSubstituteFont:(t,n)=>e.register_substitute_measure_font(t,n),clearFonts:()=>e.clear_measure_fonts(),encodeStateVector:()=>e.encode_state_vector(),measureParagraphJson:t=>e.measure_paragraph_json(t),layoutDocumentJson:t=>e.layout_document_json(t),layoutFontRequirementsJson:t=>e.layout_font_requirements_json(t),layoutDocumentWithRegionsRetainedJson:t=>e.layout_document_with_regions_retained_json(t),buildDisplayListFrame:(t,n)=>e.build_display_list_frame(t,n),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),selection:()=>JSON.parse(e.selection()),applyInput:(t,n)=>(c(),e.apply_input(t,n)),applyDelete:(t,n)=>(c(),e.apply_delete(t,n)),applyInputProfiled:(t,n)=>{c();let p=e.apply_input_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:p,profile:s}},applyDeleteProfiled:(t,n)=>{c();let p=e.apply_delete_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:p,profile:s}},outlineGlyphJson:(t,n)=>e.outline_glyph_json(t,n),loadState:t=>e.load(t),applyUpdate:t=>JSON.parse(e.apply_update_with_inference(t)),onUpdate:t=>(o.add(t),R(),()=>o.delete(t)),setSelection:(t,n=t)=>{if(t.story!==n.story)throw new Error("yrs selection must stay inside one story");e.set_selection(t.story,t.paraId,t.offset,n.paraId,n.offset);},yrsBlocksForStory:(t,n={})=>JSON.parse(e.yrs_blocks_for_story(t,JSON.stringify(n))),destroy:()=>{i||(i=true,o.clear(),r&&e.clear_update_observer(),e.free());}}}function le(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}var ae=self,a=null,E=null,u=[],z=0,L=-1,ee=Promise.resolve(),d=null,O=null,h=new Map,F=new Map,S=new Set,w=new Set,U=1,B=1,D={color:"#000",width:2},_=null,y=null,P=null,J=null,C=new Set,Y=null;ae.onmessage=e=>{ee=ee.then(()=>{if(Y)throw Y;return fe(e.data)}).catch(o=>{if(o instanceof WebAssembly.RuntimeError){Y=o,b({id:e.data.id,ok:false,error:`Resident engine worker trapped: ${o.message}`,terminal:true});return}b({id:e.data.id,ok:false,error:o instanceof Error?o.message:String(o)});});};async function fe(e){if(e.type==="destroy"){re();return}if(e.type==="bootstrap"){re(),a=await q(),te(e.snapshot),ne();let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r);return}if(e.type==="eraseCaret"){_=null,y!==null&&await M(false),b({id:e.id,ok:true});return}if(!a)throw new Error("Resident engine worker is not initialized");if(e.type==="sync"){E?.(),E=null,te(e.snapshot),ne();let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r,false,e.paintCaret);return}if(e.type==="buildFrame"){u=[];let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r,false,e.paintCaret);return}if(e.type==="applyUpdate"){a.applyUpdate(e.update),e.selection&&a.setSelection(e.selection.anchor,e.selection.head);return}if(e.type==="attachCanvases"){let r=h.size>0&&(U!==e.devicePixelRatio||B!==e.zoom),i=new Set(e.pages.map(l=>l.pageId));for(let l of e.activePageIds)w.has(l)||i.add(l);for(let{pageId:l,canvas:c}of e.pages)h.set(l,c);w=new Set(e.activePageIds),U=e.devicePixelRatio,B=e.zoom,D=e.caretStyle;for(let[l,c]of h)w.has(l)||(c.width=0,c.height=0,F.delete(l),oe(l));await M(r?true:i),b({id:e.id,ok:true});return}a.setSelection(e.selection.anchor,e.selection.head),u=[];let o=performance.now();try{let r=e.type==="applyDelete"?e.profile?a.applyDeleteProfiled(e.direction,e.expectedFrameEpoch):{frame:a.applyDelete(e.direction,e.expectedFrameEpoch),profile:void 0}:e.profile?a.applyInputProfiled(e.text,e.expectedFrameEpoch):{frame:a.applyInput(e.text,e.expectedFrameEpoch),profile:void 0};await x(e.id,r.frame,performance.now()-o,u,r.profile,o,!0,e.paintCaret);}catch(r){if(r instanceof WebAssembly.RuntimeError)throw r;let i=r instanceof Error?r.message:String(r);b({id:e.id,ok:false,error:i,residentUnavailable:i.includes("resident input state is not ready")});}finally{u=[];}}function te(e){if(!a)throw new Error("Resident engine worker is not initialized");if(a.loadState(e.state),e.fontsRevision!==L){a.clearFonts();for(let o of e.fonts)o instanceof Uint8Array?a.registerFont(o):a.registerSubstituteFont(o.substituteOf,o.family);L=e.fontsRevision;}for(let{story:o,env:r}of e.renderInputs)a.yrsBlocksForStory(o,r);for(let o of e.measureInputs)a.measureParagraphJson(o);e.layoutWithRegions?a.layoutDocumentWithRegionsRetainedJson(e.layoutInput):a.layoutDocumentJson(e.layoutInput),e.selection&&a.setSelection(e.selection.anchor,e.selection.head),z=e.layoutRevision,u=[];}function ne(){a&&(E=a.onUpdate(e=>u.push(e.slice())));}function re(){E?.(),E=null,a?.destroy(),a=null,u=[],z=0,L=-1,d=null,O=null,h.clear(),F.clear(),S.clear(),w.clear(),_=null,y=null,P=null,J=null,C.clear();}function oe(e){C.delete(e),y===e&&(y=null,P=null);}async function x(e,o,r,i=u,l,c=performance.now(),R=false,t=false){d=u$1(d,s(o));for(let f of d.damagedPageIds)S.add(f.toString());d={...d,pages:d.pages.map(f=>({...f,primitiveIds:f.primitiveIds.slice()}))};let n=a?.residentCaretSnapshot();if(!n||!b$1(n,d))throw new Error("Resident caret snapshot does not match the produced frame");if(R&&!n.caretRect)throw new Error("Resident input frame omitted collapsed caret geometry");let p=a?.selection()??null;_=t?n.caretRect??null:null;let s$1=new Set(d.pages.map(f=>f.pageId.toString()));for(let f of S)s$1.has(f)||S.delete(f);for(let f of h.keys())s$1.has(f)||(h.delete(f),F.delete(f),oe(f));let k=performance.now(),{replayedPages:W,caretPainted:A}=await M(false),v=performance.now()-k,I=j(o),g=i.map(j),m=a?j(a.encodeStateVector()):void 0;b({id:e,ok:true,frame:I,updates:g,engineMs:r,workerTotalMs:performance.now()-c,engineProfile:l,caret:n,selection:p,caretPainted:A,replayMs:v,replayedPages:W,layoutRevision:z,...m?{stateVector:m}:{}},[I,...g,...m?[m]:[]]);}async function M(e){let o=e===true?w:e;if(o)for(let n of o)S.add(n);if(!d||h.size===0)return {replayedPages:0,caretPainted:false};!O&&a&&(O=new a$1({provider:(n,p)=>a.outlineGlyphJson(n,p)}));let r=_&&w.has(_.pageId)?_:null,i$1=r?a$2(r,D,U,B):null,l=r&&i$1?`${r.pageId}|${i$1.x}|${i$1.y}|${i$1.width}|${i$1.height}|${D.color}`:null,c=[];for(let n=0;n<d.pages.length;n+=1){let s=d.pages[n].pageId.toString();if(!w.has(s))continue;let k=S.has(s),W=s===r?.pageId&&!(y===s&&P===l),A=s===y&&s!==r?.pageId;if(!k&&!W&&!A)continue;let v=h.get(s),I=d.displayList.pages[n];if(!v||!I)continue;let g$1=s,m=F.get(g$1);m||(m=new OffscreenCanvas(1,1),F.set(g$1,m));let f=m;if(!k&&C.has(g$1)){c.push(Promise.resolve({canvas:v,buffer:f,pageId:g$1}));continue}c.push(g(f,I,{glyphCache:O??void 0},U,B).then(()=>({canvas:v,buffer:f,pageId:g$1})));}let R=await Promise.all(c).catch(async n=>{throw await Promise.allSettled(c),n}),t=r!==null&&y===r.pageId&&P===l;for(let{canvas:n,buffer:p,pageId:s}of R)r&&i$1&&s===r.pageId?(J||(J=new OffscreenCanvas(1,1)),j$1(n,p,J,{...i$1,color:D.color}),C.add(s),y=s,P=l,t=true):(i(n,p),C.delete(s),y===s&&(y=null,P=null)),S.delete(s);return {replayedPages:R.length,caretPainted:t}}function j(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function b(e,o=[]){ae.postMessage(e,o);}
|
|
1
|
+
import'../chunk-EUUIJVM6.mjs';import {d,c as c$1,b as b$2}from'../chunk-F2VBW6RB.mjs';import {a,b as b$1,c as c$2}from'../chunk-L2ML3DDI.mjs';import {k as k$1,C as C$1,w as w$1,u,a as a$1,h as h$1,l,j as j$1}from'../chunk-24Z6ZVFZ.mjs';import {b}from'../chunk-6CHGYCFU.mjs';import'../chunk-TTRUPDAB.mjs';async function Q(e){await a(),b$1(e);let n=c$2(We()),o=new Set,a$1=false,i=false,d=false,u=()=>{d||(n.track_undo(),d=true);},b=()=>{a$1||(n.set_update_observer((t,s)=>{if(!(s!==0&&s!==1))for(let l of [...o])l(t,s===0?"local":"remote");}),a$1=true);};return {openDocx:(t,s,l)=>b$2(n.open_docx(t,true,l,s),f=>f.startsWith("media:")?n.media_data_url(f)??null:null),encodeState:()=>n.encode_state(),registerFont:t=>n.register_measure_font(t),registerSubstituteFont:(t,s)=>n.register_substitute_measure_font(t,s),clearFonts:()=>n.clear_measure_fonts(),encodeStateVector:()=>n.encode_state_vector(),measureParagraphJson:t=>n.measure_paragraph_json(t),layoutDocumentJson:t=>n.layout_document_json(t),layoutFontRequirementsJson:t=>n.layout_font_requirements_json(t),layoutDocumentWithRegionsRetainedJson:t=>n.layout_document_with_regions_retained_json(t),beginRegionLayout:t=>JSON.parse(n.begin_region_layout(t)),resumeRegionLayout:t=>JSON.parse(n.resume_region_layout(t)),setPartialDocument:t=>n.set_partial_document(t),layoutDocumentWithRegionsPrefixRetainedJson:(t,s)=>n.layout_document_with_regions_prefix_retained_json(t,s),layoutDocumentWithRegionsRetained:t=>n.layout_document_with_regions_retained(t),retainedHeadersFootersJson:()=>n.retained_headers_footers_json(),buildDisplayListFrame:(t,s)=>n.build_display_list_frame(t,s),setDisplayWindow:(t,s)=>n.set_display_window(t,s),setDisplayRetainBuiltPages:t=>n.set_display_retain_built_pages(t),setWindowedIncrementalBuilds:t=>n.set_windowed_incremental_builds(t),buildDisplayPagesFrame:(t,s)=>n.build_display_pages_frame(Uint32Array.from(t),s),residentCaretSnapshot:()=>JSON.parse(n.resident_caret_snapshot_json()),selection:()=>JSON.parse(n.selection()),applyInput:(t,s)=>(u(),n.apply_input(t,s)),applyDelete:(t,s,l=1)=>(u(),n.apply_delete(t,s,l)),residentDeletedUnits:()=>n.resident_deleted_units(),applyInputProfiled:(t,s)=>{u();let l=n.apply_input_profiled(t,s),f=JSON.parse(n.apply_input_profile_json());return {frame:l,profile:f}},applyDeleteProfiled:(t,s,l=1)=>{u();let f=n.apply_delete_profiled(t,s,l),L=JSON.parse(n.apply_input_profile_json());return {frame:f,profile:L}},outlineGlyphJson:(t,s)=>n.outline_glyph_json(t,s),loadMediaSources:t=>n.load_media_sources(t),loadState:t=>n.load(t),applyUpdate:t=>JSON.parse(n.apply_update_with_inference(t)),onUpdate:t=>(o.add(t),b(),()=>o.delete(t)),setSelection:(t,s=t)=>{if(t.story!==s.story)throw new Error("yrs selection must stay inside one story");n.set_selection(t.story,t.paraId,t.offset,s.paraId,s.offset);},yrsBlocksForStory:(t,s={})=>JSON.parse(n.yrs_blocks_for_story(t,JSON.stringify(s))),destroy:()=>{i||(i=true,o.clear(),a$1&&n.clear_update_observer(),n.free());}}}function We(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}var ve=self,r=null,T=null,v=null,c=[],te=0,X=-1,be=Promise.resolve(),w=null,j=null,R=new Map,A=new Map,E=new Set,C=new Set,H=1,G=1,z={color:"#000",width:2},J=null,h=null,k=null,$=null,B=new Set,_=null,g=null,I=null,y=null,Be=24,Oe=3,Ae=2**32-1,Ee=0,Re=new Set;ve.onmessage=e=>{Ce(()=>Me(e.data),e.data.id);};function Ce(e,n,o=()=>true){be=be.then(()=>{if(o()){if(_)throw _;return Ee=n,e()}}).catch(a=>Ie(n,a));}function Ie(e,n){let o=_??n;if(o instanceof WebAssembly.RuntimeError){Fe(e,o);return}p({id:e,ok:false,error:n instanceof Error?n.message:String(n)});}function Fe(e,n){if(Re.has(e))return;Re.add(e),_=n;let o=ke();p({id:e,ok:false,error:o>0?`Resident engine worker ran out of memory allocating ${o} bytes: ${n.message}`:`Resident engine worker trapped: ${n.message}`,terminal:true,...o>0?{outOfMemory:true}:{}});}async function Me(e){if(e.type==="warm"){try{await a(),p({id:e.id,ok:!0});}catch(o){p({id:e.id,ok:false,error:o instanceof Error?o.message:String(o)});}return}if(e.type==="destroy"){Pe();return}if(e.type==="open"){if(r)throw new Error("Resident engine worker already holds a document");let o=await Q(e.heapLimitBytes),a;try{a=o.openDocx(new Uint8Array(e.bytes),e.digest,e.generation);}catch(d){throw d instanceof WebAssembly.RuntimeError||o.destroy(),d}r=o,T={heapLimitBytes:e.heapLimitBytes};let i=O(r.encodeStateVector());p({id:e.id,ok:true,hostJson:a,stateVector:i},[i]);return}if(e.type==="bootstrap"){if(!e.opened)Pe(e.keepSurfaces===true),r=await Q(e.heapLimitBytes);else {if(!r||!T)throw new Error("Resident engine worker has no opened document");if(e.heapLimitBytes!==void 0&&e.heapLimitBytes!==T.heapLimitBytes)throw new Error("Resident engine worker opened its document under another heap limit")}v?.(),v=null,P(r,e.displayWindow,e.retainBuiltPages);let{layoutJson:o,provisional:a}=_e(e.snapshot,e.provisionalPages,e.layoutExtras!==void 0,e.opened!==true);a&&(g={layoutInput:e.snapshot.layoutInput,extras:e.extras,layoutExtras:e.layoutExtras}),Se();let i=performance.now(),d=r.buildDisplayListFrame(ee(e.extras,e.layoutExtras,o),e.expectedFrameEpoch);await D(e.id,d,performance.now()-i,c,void 0,i,false,false,e.layoutExtras===void 0?void 0:o??void 0,a);return}if(e.type==="fontRequirements"){if(!r)throw new Error("Resident engine worker is not initialized");p({id:e.id,ok:true,requirementsJson:r.layoutFontRequirementsJson(e.layoutInput)});return}if(e.type==="encodeState"){if(!r)throw new Error("Resident engine worker is not initialized");let o=O(r.encodeState());p({id:e.id,ok:true,state:o},[o]);return}if(e.type==="eraseCaret"){J=null,h!==null&&await ne(false),p({id:e.id,ok:true});return}if(!r)throw new Error("Resident engine worker is not initialized");if(e.type==="sync"){v?.(),v=null,P(r,e.displayWindow,e.retainBuiltPages);let{layoutJson:o}=_e(e.snapshot,void 0,e.layoutExtras!==void 0);Se();let a=performance.now(),i=r.buildDisplayListFrame(ee(e.extras,e.layoutExtras,o),e.expectedFrameEpoch);await D(e.id,i,performance.now()-a,c,void 0,a,false,e.paintCaret,e.layoutExtras===void 0?void 0:o??void 0);return}if(e.type==="buildPages"){P(r),c=[];let o=performance.now(),a=r.buildDisplayPagesFrame(e.pages,e.expectedFrameEpoch);await D(e.id,a,performance.now()-o,c,void 0,o,false,e.paintCaret);return}if(e.type==="completeLayout"){if(P(r),g&&e.sliceBlocks){re(),y={id:e.id,expectedFrameEpoch:e.expectedFrameEpoch,paintCaret:e.paintCaret,blocks:e.sliceBlocks,begun:false,restarts:0},q(y);return}await V(),await oe(e.id,e.expectedFrameEpoch,e.paintCaret);return}if(e.type==="buildFrame"){await V(),P(r,e.displayWindow,e.retainBuiltPages),c=[];let o=performance.now(),a=r.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await D(e.id,a,performance.now()-o,c,void 0,o,false,e.paintCaret);return}if(e.type==="applyUpdate"){r.applyUpdate(e.update),e.selection&&r.setSelection(e.selection.anchor,e.selection.head);return}if(e.type==="attachCanvases"){let o=R.size>0&&(H!==e.devicePixelRatio||G!==e.zoom),a=new Set(e.pages.map(i=>i.pageId));for(let i of e.activePageIds)C.has(i)||a.add(i);for(let{pageId:i,canvas:d}of e.pages)R.set(i,d);C=new Set(e.activePageIds),H=e.devicePixelRatio,G=e.zoom,z=e.caretStyle;for(let[i,d]of R)C.has(i)||(k$1(d),A.delete(i),De(i));await ne(o?true:a),p({id:e.id,ok:true});return}await V(),I=null,P(r,e.displayWindow,e.retainBuiltPages),r.setSelection(e.selection.anchor,e.selection.head),c=[];let n=performance.now();try{let o=e.type==="applyDelete"?e.profile?r.applyDeleteProfiled(e.direction,e.expectedFrameEpoch,e.count):{frame:r.applyDelete(e.direction,e.expectedFrameEpoch,e.count),profile:void 0}:e.profile?r.applyInputProfiled(e.text,e.expectedFrameEpoch):{frame:r.applyInput(e.text,e.expectedFrameEpoch),profile:void 0};await D(e.id,o.frame,performance.now()-n,c,o.profile,n,e.selection.head.story==="body",e.paintCaret,void 0,!1,e.type==="applyDelete"?r.residentDeletedUnits():void 0);}catch(o){if(_)throw _;if(o instanceof WebAssembly.RuntimeError)throw o;let a=o instanceof Error?o.message:String(o);p({id:e.id,ok:false,error:a,residentUnavailable:a.includes("resident input state is not ready"),...c.length>0?{terminal:true}:{}});}finally{c=[];}}function _e(e,n,o=true,a=true){if(!r)throw new Error("Resident engine worker is not initialized");if(re(),g=null,I=null,a&&r.loadState(e.state),r.setPartialDocument(e.partialDocument===true),r.loadMediaSources(e.mediaSources??""),e.fontsRevision!==X){r.clearFonts();for(let u of e.fonts)u instanceof Uint8Array?r.registerFont(u):r.registerSubstituteFont(u.substituteOf,u.family);X=e.fontsRevision;}for(let{story:u,env:b}of e.renderInputs)r.yrsBlocksForStory(u,b);for(let u of e.measureInputs)r.measureParagraphJson(u);let i=null,d=false;return e.layoutWithRegions&&n!==void 0?(i=r.layoutDocumentWithRegionsPrefixRetainedJson(e.layoutInput,n),d=JSON.parse(i).provisional===true):e.layoutWithRegions&&!o?r.layoutDocumentWithRegionsRetained(e.layoutInput):e.layoutWithRegions?i=r.layoutDocumentWithRegionsRetainedJson(e.layoutInput):r.layoutDocumentJson(e.layoutInput),e.selection&&r.setSelection(e.selection.anchor,e.selection.head),te=e.layoutRevision,c=[],{layoutJson:i,provisional:d}}function P(e,n,o){n&&(e.setDisplayWindow(...n),e.setDisplayRetainBuiltPages(o===true)),e.setWindowedIncrementalBuilds(n!==void 0);}async function V(){if(!r||!g)return;let e=y;y=null;let{layoutInput:n,...o}=g;g=null;try{let a;if(e?.begun)try{a=r.resumeRegionLayout(Ae).layoutJson;}catch(i){if(i instanceof WebAssembly.RuntimeError)throw i}I={...o,layoutJson:a??r.layoutDocumentWithRegionsRetainedJson(n),headersFootersJson:r.retainedHeadersFootersJson()},e&&await oe(e.id,e.expectedFrameEpoch,e.paintCaret);}catch(a){throw e&&Ie(e.id,a),a}}async function oe(e,n,o){let a=I;if(I=null,!r||!a){p({id:e,ok:true});return}P(r),c=[];let i=performance.now(),d=r.buildDisplayListFrame(ee(a.extras,a.layoutExtras,null,a.headersFootersJson),n);await D(e,d,performance.now()-i,c,void 0,i,false,o,a.layoutJson);}var K=typeof MessageChannel=="function"?new MessageChannel:null,xe=[];K&&(K.port1.onmessage=()=>xe.shift()?.());function Ue(e){if(!K){setTimeout(e,0);return}xe.push(e),K.port2.postMessage(null);}function q(e){Ue(()=>{y===e&&Ce(async()=>{try{await Ye(e);}catch(n){throw y===e&&(y=null),n}},e.id,()=>y===e);});}async function Ye(e){if(!r||y!==e||!g)return;let n;if(!e.begun)n=r.beginRegionLayout(g.layoutInput),e.begun=true;else {let i=performance.now();try{n=r.resumeRegionLayout(e.blocks);}catch(u){if(u instanceof WebAssembly.RuntimeError)throw u;if(e.begun=false,e.restarts+=1,e.restarts>Oe){try{await V();}catch{}return}q(e);return}let d=Math.max(1,performance.now()-i);e.blocks=Math.min(8192,Math.max(8,Math.round(e.blocks*Be/d)));}if(n.layoutJson===void 0){q(e);return}let{layoutInput:o,...a}=g;g=null,y=null,I={...a,layoutJson:n.layoutJson,headersFootersJson:r.retainedHeadersFootersJson()},await oe(e.id,e.expectedFrameEpoch,e.paintCaret);}function re(){let e=y;y=null,e&&p({id:e.id,ok:true});}function ee(e,n,o,a){if(n===void 0)return e;let i=a??(o===null?void 0:r?.retainedHeadersFootersJson()),d=i===void 0?void 0:JSON.parse(i);return C$1({...JSON.parse(n),...d?{headersFooters:d}:{}})}function Se(){r&&(v=r.onUpdate(e=>c.push(e.slice())));}function Pe(e=false){v?.(),v=null,r?.destroy(),r=null,T=null,c=[],te=0,X=-1,re(),g=null,I=null,w=null,j=null,A.clear(),E.clear(),e||(R.clear(),C.clear()),J=null,h=null,k=null,$=null,B.clear();}function De(e){B.delete(e),h===e&&(h=null,k=null);}async function D(e,n,o,a=c,i,d$1=performance.now(),u$1=false,b=false,t,s=false,l){w=w$1(w,u(n));for(let m of w.damagedPageIds)E.add(m.toString());let f=r?.residentCaretSnapshot();if(!f||!d(f,w))throw new Error("Resident caret snapshot does not match the produced frame");if(u$1&&!f.caretRect)throw new Error("Resident input frame omitted collapsed caret geometry");let L=r?.selection()??null;J=b?f.caretRect??null:null;let M=new Set(w.pages.map(m=>m.pageId.toString()));for(let m of E)M.has(m)||E.delete(m);for(let m of R.keys())M.has(m)||(R.delete(m),A.delete(m),De(m));let W=performance.now(),{replayedPages:U,caretPainted:S}=await ne(false),F=performance.now()-W,x=O(n),ae=a.map(O),Y=r?O(r.encodeStateVector()):void 0;p({id:e,ok:true,frame:x,updates:ae,engineMs:o,workerTotalMs:performance.now()-d$1,engineProfile:i,caret:f,selection:L,caretPainted:S,replayMs:F,replayedPages:U,layoutRevision:te,...l===void 0?{}:{deletedUnits:l},...Y?{stateVector:Y}:{},...t!==void 0?{layoutJson:t}:{},...s?{layoutProvisional:s}:{}},[x,...ae,...Y?[Y]:[]]);}async function ne(e){let n=e===true?C:e;if(n)for(let t of n)E.add(t);if(!w||R.size===0)return {replayedPages:0,caretPainted:false};!j&&r&&(j=new a$1({provider:(t,s)=>{try{return r.outlineGlyphJson(t,s)}catch(l){throw l instanceof WebAssembly.RuntimeError&&ke()>0&&Fe(Ee,l),l}}}));let o=J&&C.has(J.pageId)?J:null,a=o?c$1(o,z,H,G):null,i=o&&a?`${o.pageId}|${a.x}|${a.y}|${a.width}|${a.height}|${z.color}`:null,d=[];for(let t=0;t<w.pages.length;t+=1){let l=w.pages[t].pageId.toString();if(!C.has(l))continue;let f=E.has(l),L=l===o?.pageId&&!(h===l&&k===i),M=l===h&&l!==o?.pageId;if(!f&&!L&&!M)continue;let W=R.get(l),U=w.displayList.pages[t];if(!W||!U)continue;let S=l,F=A.get(S);F||(F=new OffscreenCanvas(1,1),A.set(S,F));let x=F;if(!f&&B.has(S)){d.push(Promise.resolve({canvas:W,buffer:x,pageId:S}));continue}d.push(h$1(x,U,{glyphCache:j??void 0},H,G).then(()=>({canvas:W,buffer:x,pageId:S})));}let u=await Promise.all(d).catch(async t=>{throw await Promise.allSettled(d),t}),b=o!==null&&h===o.pageId&&k===i;for(let{canvas:t,buffer:s,pageId:l$1}of u)o&&a&&l$1===o.pageId?($||($=new OffscreenCanvas(1,1)),l(t,s,$,{...a,color:z.color}),B.add(l$1),h=l$1,k=i,b=true):(j$1(t,s),B.delete(l$1),h===l$1&&(h=null,k=null)),E.delete(l$1);return {replayedPages:u.length,caretPainted:b}}function O(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function ke(){return b().find(e=>e.label==="docx-edit")?.failedAllocationBytes??0}function p(e,n=[]){if(_&&e.ok)throw _;ve.postMessage({...e,memory:b()},n);}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@betteroffice/docx",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"sideEffects": [
|
|
5
5
|
"**/residentEngineWorker.*"
|
|
6
6
|
],
|
|
@@ -217,7 +217,7 @@
|
|
|
217
217
|
}
|
|
218
218
|
},
|
|
219
219
|
"devDependencies": {
|
|
220
|
-
"@betteroffice/fonts": "0.
|
|
220
|
+
"@betteroffice/fonts": "0.4.0",
|
|
221
221
|
"tsup": "^8.0.1",
|
|
222
222
|
"typescript": "^6.0.3",
|
|
223
223
|
"@types/bun": "^1.0.0",
|
package/dist/chunk-5B4VMUXM.mjs
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import {d as d$1}from'./chunk-QE4ZDRKV.mjs';import {a,b as b$1}from'./chunk-HLDJMU3R.mjs';import {a as a$1}from'./chunk-ACGKK7IB.mjs';async function pe(n){if(n instanceof ArrayBuffer)return n;if(n instanceof Uint8Array){let e=new ArrayBuffer(n.byteLength);return new Uint8Array(e).set(n),e}if(n instanceof Blob)return n.arrayBuffer();throw new TypeError(`Unsupported DocxInput type: ${typeof n}`)}function P(n){let e=n.replace(/[^0-9a-fA-F]/g,"");if(e.length!==32)return null;let t=new Uint8Array(16);for(let r=0;r<16;r++){let i=Number.parseInt(e.slice(r*2,r*2+2),16);if(Number.isNaN(i))return null;t[r]=i;}let o=new Uint8Array(16);for(let r=0;r<16;r++)o[r]=t[15-r];return o}function B(n){return n?P(n)!==null:false}function v(n,e){let t=P(e);if(!t)throw new Error(`Invalid embedded-font key: "${e}"`);let o=new Uint8Array(n.slice(0)),r=Math.min(32,o.length);for(let i=0;i<r;i++)o[i]^=t[i%16];return o.buffer}var W={calibri:{googleFont:"Carlito",category:"sans-serif",fallbackStack:["Calibri","Carlito","Arial","Helvetica","sans-serif"],singleLineRatio:1.2207},cambria:{googleFont:"Caladea",category:"serif",fallbackStack:["Cambria","Caladea","Georgia","serif"],singleLineRatio:1.2676},arial:{googleFont:"Arimo",category:"sans-serif",fallbackStack:["Arial","Arimo","Helvetica","sans-serif"],singleLineRatio:1.1172},"times new roman":{googleFont:"Tinos",category:"serif",fallbackStack:["Times New Roman","Tinos","Times","serif"],singleLineRatio:1.1074},"courier new":{googleFont:"Cousine",category:"monospace",fallbackStack:["Courier New","Cousine","Courier","monospace"],singleLineRatio:1.1328},georgia:{googleFont:"Tinos",category:"serif",fallbackStack:["Georgia","Tinos","Times New Roman","serif"],singleLineRatio:1.1362},verdana:{googleFont:"Open Sans",category:"sans-serif",fallbackStack:["Verdana","Open Sans","Arial","sans-serif"],singleLineRatio:1.2153},tahoma:{googleFont:"Open Sans",category:"sans-serif",fallbackStack:["Tahoma","Open Sans","Arial","sans-serif"],singleLineRatio:1.2075},"trebuchet ms":{googleFont:"Fira Sans",category:"sans-serif",fallbackStack:["Trebuchet MS","Fira Sans","Arial","sans-serif"],singleLineRatio:1.1431},"comic sans ms":{googleFont:"Comic Neue",category:"cursive",fallbackStack:["Comic Sans MS","Comic Neue","cursive"],singleLineRatio:1.3936},impact:{googleFont:"Anton",category:"sans-serif",fallbackStack:["Impact","Anton","Arial Black","sans-serif"],singleLineRatio:1.2197},"palatino linotype":{googleFont:"EB Garamond",category:"serif",fallbackStack:["Palatino Linotype","EB Garamond","Palatino","Georgia","serif"],singleLineRatio:1.0259},"book antiqua":{googleFont:"EB Garamond",category:"serif",fallbackStack:["Book Antiqua","EB Garamond","Palatino","Georgia","serif"],singleLineRatio:1.0259},garamond:{googleFont:"EB Garamond",category:"serif",fallbackStack:["Garamond","EB Garamond","Georgia","serif"],singleLineRatio:1.068},"century gothic":{googleFont:"Questrial",category:"sans-serif",fallbackStack:["Century Gothic","Questrial","Arial","sans-serif"],singleLineRatio:1.1611},"lucida sans":{googleFont:"Open Sans",category:"sans-serif",fallbackStack:["Lucida Sans","Open Sans","Arial","sans-serif"],singleLineRatio:1.1655},"lucida console":{googleFont:"Cousine",category:"monospace",fallbackStack:["Lucida Console","Cousine","Courier New","monospace"],singleLineRatio:1.1387},consolas:{googleFont:"Inconsolata",category:"monospace",fallbackStack:["Consolas","Inconsolata","Cousine","Courier New","monospace"],singleLineRatio:1.1626},"ms mincho":{googleFont:"Noto Serif JP",category:"serif",fallbackStack:["MS Mincho","Noto Serif JP","serif"],singleLineRatio:1.15},"\uFF4D\uFF53 \u660E\u671D":{googleFont:"Noto Serif JP",category:"serif",fallbackStack:["MS Mincho","\uFF2D\uFF33 \u660E\u671D","Noto Serif JP","serif"],singleLineRatio:1.15},"\uFF4D\uFF53 \uFF50\u660E\u671D":{googleFont:"Noto Serif JP",category:"serif",fallbackStack:["MS PMincho","\uFF2D\uFF33 \uFF30\u660E\u671D","Noto Serif JP","serif"],singleLineRatio:1.15},"ms gothic":{googleFont:"Noto Sans JP",category:"sans-serif",fallbackStack:["MS Gothic","Noto Sans JP","sans-serif"],singleLineRatio:1.15},"\uFF4D\uFF53 \u30B4\u30B7\u30C3\u30AF":{googleFont:"Noto Sans JP",category:"sans-serif",fallbackStack:["MS Gothic","\uFF2D\uFF33 \u30B4\u30B7\u30C3\u30AF","Noto Sans JP","sans-serif"],singleLineRatio:1.15},"\uFF4D\uFF53 \uFF50\u30B4\u30B7\u30C3\u30AF":{googleFont:"Noto Sans JP",category:"sans-serif",fallbackStack:["MS PGothic","\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF","Noto Sans JP","sans-serif"],singleLineRatio:1.15},simhei:{googleFont:"Noto Sans SC",category:"sans-serif",fallbackStack:["SimHei","Noto Sans SC","sans-serif"],singleLineRatio:1.15},simsun:{googleFont:"Noto Serif SC",category:"serif",fallbackStack:["SimSun","Noto Serif SC","serif"],singleLineRatio:1.15},"malgun gothic":{googleFont:"Noto Sans KR",category:"sans-serif",fallbackStack:["Malgun Gothic","Noto Sans KR","sans-serif"],singleLineRatio:1.15},\u5B8B\u4F53:{googleFont:"Noto Serif SC",category:"serif",fallbackStack:["SimSun","\u5B8B\u4F53","Noto Serif SC","serif"],singleLineRatio:1.15},\u9ED1\u4F53:{googleFont:"Noto Sans SC",category:"sans-serif",fallbackStack:["SimHei","\u9ED1\u4F53","Noto Sans SC","sans-serif"],singleLineRatio:1.15},\u5FAE\u8F6F\u96C5\u9ED1:{googleFont:"Noto Sans SC",category:"sans-serif",fallbackStack:["Microsoft YaHei","\u5FAE\u8F6F\u96C5\u9ED1","Noto Sans SC","sans-serif"],singleLineRatio:1.15},\u7B49\u7EBF:{googleFont:"Noto Sans SC",category:"sans-serif",fallbackStack:["DengXian","\u7B49\u7EBF","Noto Sans SC","sans-serif"],singleLineRatio:1.15},\u4EFF\u5B8B:{googleFont:"Noto Serif SC",category:"serif",fallbackStack:["FangSong","\u4EFF\u5B8B","Noto Serif SC","serif"],singleLineRatio:1.15},\u6977\u4F53:{googleFont:"Noto Serif SC",category:"serif",fallbackStack:["KaiTi","\u6977\u4F53","Noto Serif SC","serif"],singleLineRatio:1.15},\u65B0\u7D30\u660E\u9AD4:{googleFont:"Noto Serif TC",category:"serif",fallbackStack:["PMingLiU","\u65B0\u7D30\u660E\u9AD4","Noto Serif TC","serif"],singleLineRatio:1.15},\u7D30\u660E\u9AD4:{googleFont:"Noto Serif TC",category:"serif",fallbackStack:["MingLiU","\u7D30\u660E\u9AD4","Noto Serif TC","serif"],singleLineRatio:1.15},\u5FAE\u8EDF\u6B63\u9ED1\u9AD4:{googleFont:"Noto Sans TC",category:"sans-serif",fallbackStack:["Microsoft JhengHei","\u5FAE\u8EDF\u6B63\u9ED1\u9AD4","Noto Sans TC","sans-serif"],singleLineRatio:1.15},\u6A19\u6977\u9AD4:{googleFont:"Noto Serif TC",category:"serif",fallbackStack:["DFKai-SB","\u6A19\u6977\u9AD4","Noto Serif TC","serif"],singleLineRatio:1.15},"\uB9D1\uC740 \uACE0\uB515":{googleFont:"Noto Sans KR",category:"sans-serif",fallbackStack:["Malgun Gothic","\uB9D1\uC740 \uACE0\uB515","Noto Sans KR","sans-serif"],singleLineRatio:1.15},\uAD74\uB9BC:{googleFont:"Noto Sans KR",category:"sans-serif",fallbackStack:["Gulim","\uAD74\uB9BC","Noto Sans KR","sans-serif"],singleLineRatio:1.15},\uB3CB\uC6C0:{googleFont:"Noto Sans KR",category:"sans-serif",fallbackStack:["Dotum","\uB3CB\uC6C0","Noto Sans KR","sans-serif"],singleLineRatio:1.15},\uBC14\uD0D5:{googleFont:"Noto Serif KR",category:"serif",fallbackStack:["Batang","\uBC14\uD0D5","Noto Serif KR","serif"],singleLineRatio:1.15},\uAD81\uC11C:{googleFont:"Noto Serif KR",category:"serif",fallbackStack:["Gungsuh","\uAD81\uC11C","Noto Serif KR","serif"],singleLineRatio:1.15}},q={"sans-serif":"Arial, Helvetica, sans-serif",serif:"Times New Roman, Times, serif",monospace:"Courier New, Courier, monospace",cursive:"cursive",fantasy:"fantasy","system-ui":"system-ui, sans-serif"};function J(n){let e=n.toLowerCase();return e.includes("mono")||e.includes("courier")||e.includes("consolas")||e.includes("console")||e.includes("code")||e.includes("terminal")?"monospace":e.includes("times")||e.includes("georgia")||e.includes("garamond")||e.includes("palatino")||e.includes("baskerville")||e.includes("bodoni")||e.includes("cambria")||e.includes("mincho")||e.includes("\u660E\u671D")||e.includes("\u660E\u9AD4")||e.includes("\u5B8B")||e.includes("ming")||e.includes("song")||e.includes("serif")?"serif":e.includes("script")||e.includes("cursive")||e.includes("comic")||e.includes("brush")||e.includes("hand")?"cursive":"sans-serif"}var Y={"microsoft yahei":"\u5FAE\u8F6F\u96C5\u9ED1",dengxian:"\u7B49\u7EBF",fangsong:"\u4EFF\u5B8B",kaiti:"\u6977\u4F53",pmingliu:"\u65B0\u7D30\u660E\u9AD4",mingliu:"\u7D30\u660E\u9AD4","microsoft jhenghei":"\u5FAE\u8EDF\u6B63\u9ED1\u9AD4","dfkai-sb":"\u6A19\u6977\u9AD4",gulim:"\uAD74\uB9BC",dotum:"\uB3CB\uC6C0",batang:"\uBC14\uD0D5",gungsuh:"\uAD81\uC11C",meiryo:"ms gothic",\u30E1\u30A4\u30EA\u30AA:"ms gothic","yu gothic":"ms gothic",\u6E38\u30B4\u30B7\u30C3\u30AF:"ms gothic","yu mincho":"ms mincho",\u6E38\u660E\u671D:"ms mincho"};function O(n){let e=n.trim().toLowerCase(),t=W[Y[e]??e];if(t)return {googleFont:t.googleFont,cssFallback:t.fallbackStack.map(D).join(", "),originalFont:n,hasGoogleEquivalent:true,singleLineRatio:t.singleLineRatio};let o=J(n),r=q[o];return {googleFont:null,cssFallback:`${D(n)}, ${r}`,originalFont:n,hasGoogleEquivalent:false,singleLineRatio:1.15}}var V={"\n":"\\a ","\r":"\\d ","\f":"\\c "};function X(n){return n.replace(/["\\]/g,"\\$&").replace(/[\n\r\f]/g,e=>V[e])}function D(n){return ["serif","sans-serif","monospace","cursive","fantasy","system-ui"].includes(n.toLowerCase())?n:/[\s,'"()]/.test(n)?`"${X(n)}"`:n}var g=new Set,m=new Map,C=new Set,f=new Map,w=new Set,b=new Set,d=false,L=true,h=new Set,E=new Set;function p(n,e){let t=n instanceof Error?n.message:String(n),o=new Error(`[font] ${e}: ${t}`,{cause:n});if(b.size>0)for(let r of b)try{r(o);}catch(i){console.error("Font error subscriber threw:",i);}else console.warn(o.message);}function M(n,e="normal",t="normal"){return `${n.trim()}|${e}|${t}`}function R(n){return h.has(n)?false:E.has(n)?true:re(n)?(E.add(n),queueMicrotask(()=>T([n])),true):false}function Q(n){let e=`${n}|`,t=[];for(let[o,r]of f)o.startsWith(e)&&t.push(r);return t}function $(n,e){C.add(n),g.add(e),T([e]);}function Z(n,e=[400,700],t=["normal","italic"]){let o=encodeURIComponent(n),r=[];for(let a of t){let s=a==="italic"?1:0;for(let c of e)r.push(`${s},${c}`);}r.sort();let i=r.join(";");return `https://fonts.googleapis.com/css2?family=${o}:ital,wght@${i}&display=swap`}async function A(n,e){if(typeof document>"u")return false;let t=n.trim();if(g.has(t))return true;let o=m.get(t);if(o)return o;if(!e&&R(t))return true;let r=Q(t);if(!L&&r.length===0)return false;let i=(async()=>{d=true;try{if(r.length>0&&(await Promise.all(r),g.has(t)||!e&&R(t)))return !0;if(!L)return !1;let a=Z(t,e?.weights,e?.styles),s=document.createElement("link");return s.rel="stylesheet",s.href=a,await new Promise(l=>{let u=setTimeout(()=>l(!1),5e3);s.onload=()=>{clearTimeout(u),l(!0);},s.onerror=()=>{clearTimeout(u),l(!1);},document.head.appendChild(s);})?(await I(t,3e3),g.add(t),T([t]),!0):!1}catch(a){return p(a,`failed to load "${t}"`),false}finally{m.delete(t),m.size===0&&f.size===0&&(d=false);}})();return m.set(t,i),i}async function ee(n,e){let t=n.filter(o=>!g.has(o.trim()));t.length!==0&&await Promise.all(t.map(o=>A(o,e)));}function ne(n){let e=n.trim();return g.has(e)||E.has(e)}function Re(n){L=n;}function Ae(){return L}function Ce(){return d}function Te(){return Array.from(new Set([...g,...E]))}function Ie(n){return w.add(n),()=>{w.delete(n);}}function T(n){for(let e of w)try{e(n);}catch(t){p(t,"load callback threw");}}function _e(n){return b.add(n),()=>{b.delete(n);}}async function I(n,e){if("fonts"in document)try{let t=`400 16px "${n}"`;return await Promise.race([document.fonts.load(t),new Promise(o=>setTimeout(o,e))]),document.fonts.check(t)}catch{}return await new Promise(t=>setTimeout(t,100)),true}var F,U=new Map,te="abcdefghijklmnopqrstuvwxyz0123456789";function oe(){return F===void 0&&(F=document.createElement("canvas").getContext("2d"),F&&(F.textBaseline="top")),F}function re(n,e="sans-serif"){if(typeof document>"u")return false;let t=oe();if(!t)return false;let o=i=>(t.font=i,t.measureText(te).width),r=i=>{let a=U.get(i);return a===void 0&&(a=o(`72px ${i}`),U.set(i,a)),o(`72px "${n}", ${i}`)!==a};return r(e)||r(e==="sans-serif"?"serif":"sans-serif")}var ie={"<":"\\3c ",">":"\\3e ","\n":"\\a ","\r":"\\d ","\f":"\\c "},K=n=>n.replace(/["\\]/g,"\\$&").replace(/[<>\n\r\f]/g,e=>ie[e]);async function H(n,e,t){if(typeof document>"u")return false;let o=n.trim(),r=t?.style??"normal",i=M(o,t?.weight,r);if(h.add(o),C.has(i))return true;let a=f.get(i);if(a)return a;let s=(async()=>{d=true;try{let c=new Blob([e],{type:"font/ttf"}),l=URL.createObjectURL(c),u=document.createElement("style");return u.textContent=`
|
|
2
|
-
@font-face {
|
|
3
|
-
font-family: "${K(o)}";
|
|
4
|
-
src: url(${l}) format('truetype');
|
|
5
|
-
font-weight: ${t?.weight??"normal"};
|
|
6
|
-
font-style: ${r};
|
|
7
|
-
font-display: swap;
|
|
8
|
-
}
|
|
9
|
-
`,document.head.appendChild(u),await I(o,3e3),$(i,o),!0}catch(c){return p(c,`failed to load "${o}" from buffer`),false}finally{f.delete(i),m.size===0&&f.size===0&&(d=false);}})();return f.set(i,s),s}function ae(n){let e=n.split("?")[0].split("#")[0].toLowerCase();return e.endsWith(".woff2")?"woff2":e.endsWith(".woff")?"woff":e.endsWith(".otf")?"opentype":"truetype"}async function se(n,e,t){if(typeof document>"u")return false;if(/[<>]/.test(e))return p(new Error(`invalid src URL for "${n}": contains '<' or '>'`),"rejected src"),false;let o=n.trim(),r=M(o,t?.weight);if(h.add(o),C.has(r))return true;let i=f.get(r);if(i)return i;let a=(async()=>{d=true;try{let s=document.createElement("style");return s.textContent=`
|
|
10
|
-
@font-face {
|
|
11
|
-
font-family: "${K(o)}";
|
|
12
|
-
src: url(${JSON.stringify(e)}) format('${ae(e)}');
|
|
13
|
-
font-weight: ${t?.weight??"normal"};
|
|
14
|
-
font-display: swap;
|
|
15
|
-
}
|
|
16
|
-
`,document.head.appendChild(s),await I(o,3e3),$(r,o),!0}catch(s){return p(s,`failed to load "${o}" from ${e}`),false}finally{f.delete(r),m.size===0&&f.size===0&&(d=false);}})();return f.set(r,a),a}async function Ge(n){!n||n.length===0||await Promise.all(n.map(e=>se(e.family,e.src,{weight:e.weight})));}var le={Calibri:"Carlito",Cambria:"Caladea",Arial:"Arimo","Times New Roman":"Tinos","Courier New":"Cousine",Garamond:"EB Garamond","Book Antiqua":"EB Garamond",Georgia:"Tinos",Verdana:"Open Sans",Tahoma:"Open Sans","Trebuchet MS":"Source Sans Pro","Century Gothic":"Poppins","Franklin Gothic":"Libre Franklin",Palatino:"EB Garamond","Palatino Linotype":"EB Garamond","Lucida Sans":"Open Sans","Segoe UI":"Open Sans",Impact:"Anton","Comic Sans MS":"Comic Neue",Consolas:"Inconsolata","Lucida Console":"Inconsolata",Monaco:"Fira Code"};function ce(n){let e=n.trim();return le[e]||O(e).googleFont||e}async function fe(n){let e=n.trim(),t=ce(e);if(t!==e){if(!h.has(e)&&ne(e)||R(e))return true;let o=await A(t);return o&&g.add(e),o}return A(t)}async function ge(n){let e=[...new Set(n.map(t=>t.trim()))];await Promise.all(e.map(t=>fe(t)));}async function xe(){await ee(["Carlito","Caladea","Arimo","Tinos","Cousine","EB Garamond"]);}function ue(n){let e=new Set;if(typeof n!="object"||n===null)return e;let t=[n],o=new WeakSet,r=0,i=1e5;for(;t.length>0&&r++<i;){let a=t.pop();if(typeof a!="object"||a===null||o.has(a))continue;if(o.add(a),Array.isArray(a)){for(let l of a)t.push(l);continue}let s=a,c=s.fontFamily;if(typeof c=="object"&&c!==null){let l=c;for(let u of ["ascii","hAnsi","eastAsia","cs"]){let N=l[u];typeof N=="string"&&N.trim()&&e.add(N.trim());}}typeof s.name=="string"&&("altName"in s||"panose1"in s||"embedRegular"in s)&&(s.name.trim()&&e.add(s.name.trim()),typeof s.altName=="string"&&s.altName.trim()&&e.add(s.altName.trim()));for(let l of Object.values(s))t.push(l);}return e}async function Pe(n){let e=ue(n);e.size!==0&&await ge(Array.from(e));}function de(n){let e=new TextDecoder("utf-8",{ignoreBOM:true});return {paths:()=>[...n.keys()],file:t=>n.get(t)??null,text:t=>{let o=n.get(t);return o?e.decode(o):null}}}function z(n){let e=b$1(new Uint8Array(n));return de(new Map(Object.entries(e)))}function me(n){let e=new Set;if(!n)return e;for(let t of n.fonts)(t.embedRegular||t.embedBold||t.embedItalic||t.embedBoldItalic)&&e.add(t.name);return e}var ye=[{key:"embedRegular",weight:"normal",style:"normal"},{key:"embedBold",weight:"bold",style:"normal"},{key:"embedItalic",weight:"normal",style:"italic"},{key:"embedBoldItalic",weight:"bold",style:"italic"}];function Se(n,e){let t=n.replace(/^\/+/,""),r=(t.toLowerCase().startsWith("word/")?t:`word/${t}`).toLowerCase();for(let[i,a]of e)if(i.toLowerCase()===r)return a}function Fe(n,e,t,o,r){let i=r.get(e.relId);if(!i)return null;let a=Se(i,o);if(!a)return null;let s;if(e.fontKey&&B(e.fontKey))try{s=v(a,e.fontKey);}catch{return null}else s=a.slice(0);return {family:n,weight:t.weight,style:t.style,data:s,subsetted:e.subsetted??false}}function j(n,e,t){if(!n||n.fonts.length===0)return [];if(!t||e.size===0)return [];let o=d$1(t,"word/_rels/fontTable.xml.rels"),r=new Map;for(let[a,s]of o)r.set(a,s.target);let i=[];for(let a of n.fonts)for(let s of ye){let c=a[s.key];if(!c)continue;let l=Fe(a.name,c,s,e,r);l&&i.push(l);}return i}async function We(n){let e=n.package.fontTable;if(!e||me(e).size===0)return [];let t=n.originalBuffer;if(!t)return [];await Promise.all([a(),a$1()]);let o=z(t),r=new Map,i=null;for(let a of o.paths()){if(a.toLowerCase().startsWith("word/fonts/")){let s=o.file(a);s&&r.set(a,s.slice().buffer);}a.toLowerCase()==="word/_rels/fonttable.xml.rels"&&(i=o.text(a));}return j(e,r,i)}async function qe(n,e,t){if(!n||!t||e.size===0)return new Set;await a$1();let o=j(n,e,t),r=new Set;return o.length===0||await Promise.all(o.map(async i=>{await H(i.family,i.data,{weight:i.weight,style:i.style})?r.add(i.family):typeof document<"u"&&console.warn(`[embeddedFonts] embedded face "${i.family}" (${i.weight} ${i.style}) failed to load; text using it falls back to the CSS stack`);})),r}export{We as A,qe as B,pe as a,B as b,v as c,O as d,A as e,ee as f,ne as g,Re as h,Ae as i,Ce as j,Te as k,Ie as l,_e as m,re as n,H as o,se as p,Ge as q,le as r,ce as s,fe as t,ge as u,xe as v,ue as w,Pe as x,me as y,j as z};
|
package/dist/chunk-5F6DLQZP.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function s(e){let n=globalThis.process;if(typeof n?.getBuiltinModule=="function")try{return n.getBuiltinModule(e)}catch{return}}function o(e){if(e.protocol!=="file:")return;let n=s("node:fs"),t=s("node:url");if(!(!n||!t))try{return n.readFileSync(t.fileURLToPath(e.href))}catch{return}}function u(e){return e.protocol!=="file:"?e:o(e)??e}function l(e){let n=false,t;return {preload(r){return n?Promise.resolve():t||(t=e.initAsync({module_or_path:r??u(e.assetUrl())}).then(()=>{n=true;},i=>{throw t=void 0,i instanceof Error?i:new Error(String(i))}),t)},ensure(){if(n)return;let r=o(e.assetUrl());if(r){e.initSync({module:r}),n=true;return}throw new Error(`${e.label} wasm is not initialized; await ${e.preloadName}() before first use (browser builds load the external wasm asset asynchronously)`)}}}export{l as a};
|