@betteroffice/docx 0.2.1 → 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 +586 -3
- 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-NMDQHUQB.mjs +57 -0
- package/dist/chunk-NVN26RHH.mjs +1 -0
- package/dist/chunk-OK5UFGX3.mjs +1 -0
- package/dist/chunk-RZQ3OXZY.mjs +2 -0
- package/dist/chunk-YLFKV2NT.mjs +1 -0
- package/dist/collaboration/index.d.mts +9 -6
- package/dist/compareDocx-IHFPGIGV.mjs +1 -0
- package/dist/computeLayout-4MNWHE2T.mjs +1 -0
- package/dist/{content-CvEtPl0c.d.mts → content-BzoC6bSz.d.mts} +48 -8
- package/dist/core.d.mts +172 -9
- package/dist/core.mjs +1 -1
- package/dist/{displayListQueries-DF8F6fMl.d.mts → displayListQueries-H5YnU_hX.d.mts} +23 -5
- package/dist/docx/index.d.mts +5 -4
- package/dist/docx/index.mjs +1 -1
- package/dist/editor/index.d.mts +19 -9
- package/dist/editor/index.mjs +1 -1
- package/dist/{fontLoader-b8eicJKV.d.mts → fontLoader-BNSs0E8K.d.mts} +55 -2
- package/dist/{formatting-7zKCTu5a.d.mts → formatting-gqLFeJ9X.d.mts} +8 -0
- package/dist/{frameDelta-pA4jrQ1G.d.mts → frameDelta-ByU7HBuB.d.mts} +34 -3
- 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-CHy6_Yuo.d.mts +2026 -0
- package/dist/layout/index.d.mts +6 -6
- package/dist/layout/index.mjs +1 -1
- package/dist/layout/pagination/index.d.mts +4 -4
- package/dist/layout/render/index.d.mts +122 -33
- package/dist/layout/render/index.mjs +1 -1
- package/dist/loadWasmAsset-Cr95TImt.d.mts +25 -0
- package/dist/pagedExport---0Dlmzo.d.mts +907 -0
- package/dist/parseWasm-NLAG22EU.mjs +1 -0
- package/dist/plugin-api/RenderedDomContext.d.mts +12 -9
- package/dist/plugin-api/RenderedDomContext.mjs +1 -1
- package/dist/plugin-api/index.d.mts +21 -4
- package/dist/plugin-api/resolveItemPositions.d.mts +3 -3
- package/dist/rezip-Bxiq4Z_R.d.mts +24 -0
- package/dist/{rustDisplayList-BJqaN9tt.d.mts → rustDisplayList-LcRZHCSL.d.mts} +12 -4
- package/dist/{rustMeasureSource-C0EZB055.d.mts → rustMeasureSource-BkCx1FDx.d.mts} +14 -4
- package/dist/{selectiveSave-CRh-_Y_C.d.mts → selectiveSave-r-NMK6aI.d.mts} +1 -22
- package/dist/styles/index.d.mts +2 -2
- package/dist/{styles-7e-mq3c-.d.mts → styles-AryxLAhx.d.mts} +1 -1
- package/dist/types/content.d.mts +2 -2
- package/dist/types/document.d.mts +9 -6
- package/dist/{types-C4A8mWjU.d.mts → types-D6Pra38E.d.mts} +31 -5
- package/dist/utils/comments.d.mts +2 -2
- package/dist/utils/index.d.mts +20 -5
- package/dist/utils/index.mjs +1 -1
- package/dist/utils/stylePreview.d.mts +2 -2
- package/dist/wasm-GSI2XMOH.mjs +1 -0
- package/dist/wasm-K6DRABAA.mjs +1 -0
- package/dist/wasm-NF6B3AH7.mjs +1 -0
- package/dist/wasm-edit.d.mts +420 -28
- package/dist/wasm-edit.mjs +1 -1
- package/dist/wasm-layout.d.mts +9 -2
- 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 +8 -5
- package/dist/yrs/index.mjs +1 -1
- package/dist/yrs/residentEngineWorker.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-5F6DLQZP.mjs +0 -1
- package/dist/chunk-6LQJAKOC.mjs +0 -1
- package/dist/chunk-AFMVSI4Z.mjs +0 -57
- package/dist/chunk-GD4VNJ64.mjs +0 -1
- package/dist/chunk-HLDJMU3R.mjs +0 -1
- package/dist/chunk-J7LNO6SM.mjs +0 -1
- package/dist/chunk-JHJLG4I6.mjs +0 -16
- package/dist/chunk-PGMXWI5X.mjs +0 -1
- package/dist/chunk-WRWRCBLK.mjs +0 -1
- package/dist/chunk-WTFRNX5K.mjs +0 -1
- package/dist/index-CHl2zLJ7.d.mts +0 -1142
- package/dist/loadWasmAsset-CMvnVkfA.d.mts +0 -3
- package/dist/wasm-7SOSHNGP.mjs +0 -1
- package/dist/wasm-ZQAVP7P2.mjs +0 -1
package/dist/wasm-edit.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{c as createEditSession,e as exportDocxMarkdownJson,d as exportDocxStructuredJson,h as findDocxContentControlsJson,g as listDocxContentControlsJson,a as preloadEditWasm,f as renderDocxMarkdownJson,i as renderDocxMarkdownWithPagesJson,b as setEditWasmHeapLimit}from'./chunk-L2ML3DDI.mjs';import'./chunk-6CHGYCFU.mjs';import'./chunk-TTRUPDAB.mjs';
|
package/dist/wasm-layout.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { W as WasmAsyncInput } from './loadWasmAsset-
|
|
1
|
+
import { W as WasmAsyncInput } from './loadWasmAsset-Cr95TImt.mjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Loader for the docx-layout wasm (the Rust display-list builder and the
|
|
@@ -106,6 +106,13 @@ declare function layoutDocumentJson(input: string): string;
|
|
|
106
106
|
* rejects unparseable input at this boundary).
|
|
107
107
|
*/
|
|
108
108
|
declare function registerMeasureFont(bytes: Uint8Array): number;
|
|
109
|
+
/**
|
|
110
|
+
* Register a measurement view of `base` carrying the vertical metrics and
|
|
111
|
+
* advance pitch Word measures `family` with — for a face the host
|
|
112
|
+
* substituted. Returns `base` unchanged for a family whose metrics the engine
|
|
113
|
+
* does not know.
|
|
114
|
+
*/
|
|
115
|
+
declare function registerSubstituteMeasureFont(base: number, family: string): number;
|
|
109
116
|
/** Drop every registered measurement font (ids restart at 0). Callers must re-register before the next `measureParagraphJson`. */
|
|
110
117
|
declare function clearMeasureFonts(): void;
|
|
111
118
|
/**
|
|
@@ -125,4 +132,4 @@ declare function measureParagraphJson(input: string): string;
|
|
|
125
132
|
*/
|
|
126
133
|
declare function outlineGlyphJson(fontId: number, glyphId: number): string;
|
|
127
134
|
|
|
128
|
-
export { buildDisplayListJson, clearMeasureFonts, closeDisplayList, hasDisplayListSession, hasDisplayListUpdate, hasRangeRectsRegion, hitTestRegionsByHandle, hitTestRegionsJson, layoutDocumentJson, measureParagraphJson, openDisplayList, outlineGlyphJson, preloadLayoutWasm, rangeRectsByHandle, rangeRectsJson, rangeRectsRegionByHandle, rangeRectsRegionJson, registerMeasureFont, updateDisplayList, verticalMoveByHandle, verticalMoveJson };
|
|
135
|
+
export { buildDisplayListJson, clearMeasureFonts, closeDisplayList, hasDisplayListSession, hasDisplayListUpdate, hasRangeRectsRegion, hitTestRegionsByHandle, hitTestRegionsJson, layoutDocumentJson, measureParagraphJson, openDisplayList, outlineGlyphJson, preloadLayoutWasm, rangeRectsByHandle, rangeRectsJson, rangeRectsRegionByHandle, rangeRectsRegionJson, registerMeasureFont, registerSubstituteMeasureFont, updateDisplayList, verticalMoveByHandle, verticalMoveJson };
|
package/dist/wasm-layout.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{p as buildDisplayListJson,
|
|
1
|
+
export{p as buildDisplayListJson,t as clearMeasureFonts,g as closeDisplayList,d as hasDisplayListSession,i as hasDisplayListUpdate,e as hasRangeRectsRegion,j as hitTestRegionsByHandle,b as hitTestRegionsJson,q as layoutDocumentJson,u as measureParagraphJson,f as openDisplayList,v as outlineGlyphJson,a as preloadLayoutWasm,m as rangeRectsByHandle,c as rangeRectsJson,o as rangeRectsRegionByHandle,n as rangeRectsRegionJson,r as registerMeasureFont,s as registerSubstituteMeasureFont,h as updateDisplayList,l as verticalMoveByHandle,k as verticalMoveJson}from'./chunk-OK5UFGX3.mjs';import'./chunk-6CHGYCFU.mjs';import'./chunk-TTRUPDAB.mjs';
|
package/dist/wasm-opc.d.mts
CHANGED
package/dist/wasm-opc.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as preloadOpcWasm,c as rezipContainer,b as unzipContainer}from'./chunk-
|
|
1
|
+
export{a as preloadOpcWasm,c as rezipContainer,b as unzipContainer}from'./chunk-2QHGQA3V.mjs';import'./chunk-6CHGYCFU.mjs';import'./chunk-TTRUPDAB.mjs';
|
package/dist/wasm-parse.d.mts
CHANGED
package/dist/wasm-parse.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{h as decodeTiffImage,b as parseDocxS9Wire,c as parseRelationshipsXmlWire,a as preloadParseWasm,d as serializeDocxS10Wire,e as serializeDocxS11Wire,f as serializeDocxS12Wire,g as writeDocxS13Wire}from'./chunk-
|
|
1
|
+
export{h as decodeTiffImage,b as parseDocxS9Wire,c as parseRelationshipsXmlWire,a as preloadParseWasm,d as serializeDocxS10Wire,e as serializeDocxS11Wire,f as serializeDocxS12Wire,g as writeDocxS13Wire}from'./chunk-3CYO46ML.mjs';import'./chunk-6CHGYCFU.mjs';import'./chunk-TTRUPDAB.mjs';
|
package/dist/yrs/index.d.mts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import '../formatting-gqLFeJ9X.mjs';
|
|
1
2
|
import '../types/document.mjs';
|
|
2
|
-
export { w as CreateYrsSessionOptions, R as ResidentCaretPaintStyle,
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
export { w as CreateYrsSessionOptions, D as DocxOccurrence, x as DocxParagraphAnchor, y as DocxParagraphAnchorResult, z as DocxParagraphIdAssignment, A as DocxParagraphIdDiagnostic, B as DocxParagraphIdOrigin, E as DocxParagraphIdRefusal, F as DocxParagraphIdentity, G as DocxParagraphIdentityReceipt, H as DocxParagraphIdentitySnapshot, I as DocxParagraphOrigin, J as DocxParagraphRef, K as DocxParagraphSavePlan, L as DocxPersistedParagraphAnchor, M as DocxProposalFailure, N as DocxProposalInput, O as DocxProposalRecord, P as DocxProposalRequest, Q as DocxProposalResult, R as DocxProposalSnapshot, S as DocxProposalState, T as DocxProposalStateRequest, U as DocxProposalWithdrawRequest, V as DocxSavedDocument, W as DocxSavedParagraph, X as DocxSessionParagraphAnchor, Z as DocxSessionSave, _ as DocxSourceParagraphAnchor, $ as DocxSourceStory, a0 as ResidentCaretPaintStyle, a1 as ResidentEngineOffscreenPage, a2 as ResidentEngineWorkerApplyResult, a3 as ResidentEngineWorkerClient, a4 as ResidentEngineWorkerFrame, a5 as ResidentEngineWorkerOpened, a6 as ResidentWorkerFailureError, a7 as ResidentWorkerOutOfMemoryError, a8 as YrsAuthor, a9 as YrsCellBorder, aa as YrsCellBorders, ab as YrsCellLoc, ac as YrsChangeTarget, ad as YrsCommentInfo, ae as YrsCommentReceipt, af as YrsContentControlValue, ag as YrsDocxHost, ah as YrsEngineApplyProfile, ai as YrsHyperlinkAttrs, aj as YrsImageGeometry, ak as YrsInlineFormatDelta, al as YrsInputParagraphSeed, am as YrsInputParagraphSpan, an as YrsInputPositionMap, u as YrsLoc, ao as YrsMediaSource, ap as YrsNumberingProperties, aq as YrsOpeningOptions, ar as YrsParaOffset, as as YrsParagraph, at as YrsParagraphAttrs, au as YrsParagraphLength, av as YrsParagraphReceipt, aw as YrsParagraphSeed, ax as YrsParagraphSpan, ay as YrsParagraphTabStop, az as YrsRawOp, aA as YrsRegionLayoutProgress, a as YrsRenderEnv, aB as YrsReplaceReceipt, aC as YrsResidentCaretRect, aD as YrsResidentCaretSnapshot, aE as YrsResidentFontRegistration, aF as YrsResidentWorkerSnapshot, aG as YrsResidentWorkerSyncOptions, aH as YrsResolveReceipt, aI as YrsResolvedCommentAnchor, v as YrsRevisionInfo, aJ as YrsRevisionReceipt, aK as YrsRunMark, j as YrsSelection, aL as YrsSelectionContext, aM as YrsSelectionText, Y as YrsSession, aN as YrsSplitReceipt, aO as YrsStickyPosition, aP as YrsStoryRange, aQ as YrsStorySeed, aR as YrsStorySegment, aS as YrsTableLoc, aT as YrsTableRange, aU as YrsTableReceipt, aV as YrsTargetEditResult, aW as YrsTextColor, aX as YrsTextMatch, aY as YrsTextSearchOptions, aZ as YrsTriState, a_ as YrsUndoCaptureMode, a$ as YrsWatermark, b0 as canUseResidentEngineWorker, b1 as captureSessionSave, b2 as compareYrsLocs, b3 as createYrsInputPositionMap, b4 as createYrsSession, b5 as decodeDocxHostJson, b6 as displayPositionToYrsLoc, b7 as documentToYrs, b8 as preloadDocxEngine, b9 as preloadResidentEngineWorker, ba as prepareDocxBytes, bb as preparedDocxDigest, bc as proposalRevisionPreview, bd as residentCaretDeviceRect, be as residentCaretSnapshotForFrame, bf as retainPreloadedResidentEngineWorker, bg as sameYrsSelection, bh as saveYrsDocx, bi as takePreloadedResidentEngineWorker, bj as writeSessionSave, bk as yrsLocToDisplayPosition, bl as yrsToDocument } from '../index-CHy6_Yuo.mjs';
|
|
4
|
+
export { o as DocxAnchor, p as DocxAnchorScope, ac as DocxAtomKind, q as DocxCachedResult, r as DocxCommentMetadata, s as DocxContentControl, t as DocxContentControlDiagnostic, l as DocxContentControlQuery, k as DocxContentControlReadFailure, u as DocxContentControlSelector, v as DocxContentControlValue, m as DocxContentControlsOptions, w as DocxContentControlsResult, n as DocxContentControlsSnapshot, x as DocxControlMetadata, a1 as DocxEditFailure, a2 as DocxEditFailureCode, ad as DocxEditFailureReason, ae as DocxEditGuard, af as DocxEditHistory, ag as DocxEditOperation, ah as DocxEditPreview, ai as DocxEditReceipt, ab as DocxEditRefusal, a7 as DocxEditRequest, a9 as DocxEditResult, aj as DocxEditSource, ak as DocxEditStep, a0 as DocxEditSuggestion, al as DocxEditTarget, y as DocxExportBlock, z as DocxExportCell, A as DocxExportDiagnostic, B as DocxExportDiagnosticCode, D as DocxExportFailure, C as DocxExportFailureCode, E as DocxExportInline, a as DocxExportOptions, F as DocxExportPage, G as DocxExportRefusal, H as DocxExportResult, I as DocxExportStory, J as DocxExportTable, a5 as DocxFindTextRequest, a6 as DocxFindTextResult, K as DocxFormattingMark, L as DocxFragmentGeometry, M as DocxHeadingInfo, N as DocxHeadlessFont, e as DocxHeadlessLayoutOptions, O as DocxInlineRevision, i as DocxLayoutMap, P as DocxLayoutProvenance, Q as DocxListInfo, b as DocxMarkdownContent, h as DocxMarkdownOptions, R as DocxPageDiagnostic, d as DocxPageExportOptions, S as DocxPageFragment, T as DocxPageMapContent, j as DocxPageMarkdownOptions, f as DocxPagedStructuredContent, U as DocxParagraphData, V as DocxParagraphHeading, am as DocxParagraphInput, an as DocxParagraphTarget, ao as DocxParagraphText, a3 as DocxReadParagraphsRequest, a4 as DocxReadParagraphsResult, ap as DocxResolvedControl, W as DocxRevisionView, aq as DocxSearchScope, ar as DocxSetContentControlTextStep, g as DocxSnapshotLayoutMap, X as DocxSnapshotLayoutProvenance, Y as DocxStoryKind, Z as DocxStoryOccurrence, _ as DocxStorySelection, c as DocxStructuredContent, as as DocxTextAtom, at as DocxTextMatch, au as DocxTextPosition, av as DocxTextRange, aa as DocxTextTarget, aw as DocxTextView, $ as DocxUnlocatedReason, a8 as DocxValidationResult, ax as EditSuccess, ay as OperationFailure, az as OperationRefusal, aA as ValidationSuccess } from '../pagedExport---0Dlmzo.mjs';
|
|
5
|
+
export { b as WASM32_MEMORY_LIMIT_BYTES, c as WasmHeapStats, a as WasmModuleMemory, w as wasmModuleMemories } from '../loadWasmAsset-Cr95TImt.mjs';
|
|
6
|
+
import '../content-BzoC6bSz.mjs';
|
|
5
7
|
import '../docx/wrapTypes.mjs';
|
|
6
|
-
import '../styles-
|
|
7
|
-
import '../frameDelta-
|
|
8
|
+
import '../styles-AryxLAhx.mjs';
|
|
9
|
+
import '../frameDelta-ByU7HBuB.mjs';
|
|
10
|
+
import '../rezip-Bxiq4Z_R.mjs';
|
package/dist/yrs/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{a as residentCaretDeviceRect,b as residentCaretSnapshotForFrame}from'../chunk-J7LNO6SM.mjs';import {b as b$5}from'../chunk-OBQGPMPQ.mjs';import {d,a,b as b$3}from'../chunk-47Q2FMFF.mjs';import {b as b$2,p}from'../chunk-LTVVQMHB.mjs';import {c as c$1,b as b$4}from'../chunk-CTBUQRYQ.mjs';import {b as b$1,c}from'../chunk-6LQJAKOC.mjs';import'../chunk-ACGKK7IB.mjs';import'../chunk-5F6DLQZP.mjs';import {b}from'../chunk-TTRUPDAB.mjs';function Qn(e,t){let n=0,r=t.map(i=>{let o={paraId:i.paraId,length:Math.max(0,Math.trunc(i.length)),displayStart:n};return n+=o.length+2,o});return {story:e,paragraphs:r}}function De(e,t){let n=e.paragraphs.find(r=>r.paraId===t.paraId);return !n||t.story!==e.story?e.paragraphs[0]?.displayStart??0:n.displayStart+1+Math.min(Math.max(0,t.offset),n.length)}function er(e,t){if(e.paragraphs.length===0)return null;let n=Math.max(0,Math.trunc(t)),r=e.paragraphs[0];for(let i of e.paragraphs){if(i.displayStart>n)break;r=i;}return {story:e.story,paraId:r.paraId,offset:Math.min(Math.max(0,n-(r.displayStart+1)),r.length)}}function tr(e,t,n){return De(e,t)-De(e,n)}var At={bootstrap:15e3,sync:15e3,attachCanvases:15e3,buildFrame:5e3,applyInput:5e3,applyDelete:5e3};function Ft(){return new Worker(new URL("./residentEngineWorker.mjs",import.meta.url),{type:"module",name:"openooxml-resident-engine"})}var ce=class{constructor(t=Ft()){b(this,"worker",t);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 r=n.data;if(r.ok&&r.stateVector&&(this.remoteVector=new Uint8Array(r.stateVector)),!r.ok&&r.terminal){this.fail(new $(r.error));return}let i=this.pending.get(r.id);i&&(this.pending.delete(r.id),clearTimeout(i.timeout),r.ok?i.resolve(r):i.reject(Yt(r.error,r.residentUnavailable)));},this.worker.onerror=n=>{this.fail(new J(`Resident engine worker failed: ${n.message}`));},this.worker.onmessageerror=()=>{this.fail(new J("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(t,n){let r=t.fontsRevision,i=await this.request({type:"bootstrap",snapshot:t,extras:n,expectedFrameEpoch:0},Je(t)),o=G(i);return this.recordSync(i,r),this.ready=true,this.revision=o.layoutRevision,o}async sync(t,n,r,i=false){let o=t.fontsRevision,a=await this.request({type:"sync",snapshot:t,extras:n,expectedFrameEpoch:r,paintCaret:i},Je(t)),l=G(a);return this.recordSync(a,o),this.ready=true,this.revision=l.layoutRevision,l}async buildFrame(t,n,r=false){return G(await this.request({type:"buildFrame",extras:t,expectedFrameEpoch:n,paintCaret:r}))}async applyInput(t,n,r,i=false,o=false){if(!this.ready)return {applied:false};try{return {applied:!0,...G(await this.request({type:"applyInput",text:t,selection:n,expectedFrameEpoch:r,profile:i,paintCaret:o}))}}catch(a){if(a instanceof $)return {applied:false};throw a}}async applyDelete(t,n,r,i=false,o=false){if(!this.ready)return {applied:false};try{return {applied:!0,...G(await this.request({type:"applyDelete",direction:t,selection:n,expectedFrameEpoch:r,profile:i,paintCaret:o}))}}catch(a){if(a instanceof $)return {applied:false};throw a}}eraseCaret(){if(this.terminalError)return;let n={id:this.nextId++,type:"eraseCaret"};this.worker.postMessage(n);}invalidate(t,n){if(this.terminalError)return;this.ready=false;let r=t.slice(),o={id:this.nextId++,type:"applyUpdate",update:r,selection:n};this.worker.postMessage(o,[r.buffer]);}async attachCanvases(t,n,r,i,o){let a=t.map(l=>l.canvas);await this.request({type:"attachCanvases",pages:t,activePageIds:n,devicePixelRatio:r,zoom:i,caretStyle:o},a);}destroy(){if(this.terminalError)return;let n={id:this.nextId++,type:"destroy"};this.worker.postMessage(n),this.fail(new J("Resident engine worker was destroyed"));}request(t,n=[]){if(this.terminalError)return Promise.reject(this.terminalError);let r=this.nextId++,i=At[t.type];return new Promise((o,a)=>{let l=setTimeout(()=>{this.fail(new J(`Resident engine worker did not answer ${t.type} within ${i}ms`));},i);this.pending.set(r,{resolve:o,reject:a,timeout:l}),this.worker.postMessage({...t,id:r},n);})}recordSync(t,n){this.appliedFontsRevision=n;}fail(t){this.terminalError=t,this.ready=false,this.worker.terminate();for(let n of this.pending.values())clearTimeout(n.timeout),n.reject(t);this.pending.clear();}},$=class extends Error{},J=class extends Error{};function Yt(e,t=false){return t?new $(e):new Error(e)}function Je(e){return [e.state.buffer,...e.fonts.map(t=>t.buffer)]}function G(e){if(!e.frame)throw new J("Resident engine worker response omitted its FrameDelta");if(!e.caret)throw new J("Resident engine worker response omitted its caret snapshot");if(e.selection===void 0)throw new J("Resident engine worker response omitted its selection");return {frame:new Uint8Array(e.frame),updates:(e.updates??[]).map(t=>new Uint8Array(t)),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 Mt(){return typeof Worker<"u"}function ne(e){return e.type==="rawXml"}function pe(e){return {sdtType:e.sdtType,id:e.id??null,alias:e.alias??null,tag:e.tag??null,lock:e.lock??null,placeholder:e.placeholder??null,showingPlaceholder:e.showingPlaceholder??false,dateFormat:e.dateFormat??null,listItems:e.listItems?JSON.stringify(e.listItems):null,checked:e.checked??null,dataBinding:e.dataBinding?JSON.stringify(e.dataBinding):null,rawPropertiesXml:e.rawPropertiesXml??null,rawEndPropertiesXml:e.rawEndPropertiesXml??null}}function fe(e){let t={sdtType:e.sdtType??"richText"};if(typeof e.id=="number"&&(t.id=e.id),e.alias!=null&&(t.alias=String(e.alias)),e.tag!=null&&(t.tag=String(e.tag)),e.lock!=null&&(t.lock=e.lock),e.placeholder!=null&&(t.placeholder=String(e.placeholder)),e.showingPlaceholder&&(t.showingPlaceholder=true),e.dateFormat!=null&&(t.dateFormat=String(e.dateFormat)),typeof e.listItems=="string"&&e.listItems)try{t.listItems=JSON.parse(e.listItems);}catch{}if(e.checked!=null&&(t.checked=e.checked),typeof e.dataBinding=="string"&&e.dataBinding)try{t.dataBinding=JSON.parse(e.dataBinding);}catch{}return e.rawPropertiesXml!=null&&(t.rawPropertiesXml=String(e.rawPropertiesXml)),e.rawEndPropertiesXml!=null&&(t.rawEndPropertiesXml=String(e.rawEndPropertiesXml)),t}function ge(e,t,n,r,i,o){let a=t?.pPr;if(!t?.tblStylePr?.some(I=>I.pPr))return a;let l=e.formatting?.look??t.tblPr?.look,d=(I,M)=>l?.[I]??(Number.parseInt(l?.value??(l?"0":"04A0"),16)&M)!==0,m=d("firstRow",32),u=d("lastRow",64),c=d("firstColumn",128),y=d("lastColumn",256),f=e.rows[n].formatting?.gridBefore??0;r+=f,i+=f;let h=!!m&&n===0,g=!!u&&n===e.rows.length-1,k=!!c&&r===0,w=!!y&&i===o,T=e.formatting?.styleRowBandSize??t.tblPr?.styleRowBandSize??1,v=e.formatting?.styleColBandSize??t.tblPr?.styleColBandSize??1,P=[];!d("noHBand",512)&&!h&&!g&&T>0&&P.push(Math.floor((n-+!!m)/T)%2===0?"band1Horz":"band2Horz"),!d("noVBand",1024)&&!k&&!w&&v>0&&P.push(Math.floor((r-+!!c)/v)%2===0?"band1Vert":"band2Vert");for(let[I,M]of [["firstCol",k],["lastCol",w],["firstRow",h],["lastRow",g],["nwCell",h&&k],["neCell",h&&w],["swCell",g&&k],["seCell",g&&w]])M&&P.push(I);for(let I of P)a=b$3(a,t.tblStylePr.find(M=>M.type===I)?.pPr);return a}function Ue(e){return Math.max(e.columnWidths?.length??0,...e.rows.map(t=>t.cells.reduce((n,r)=>n+(r.formatting?.gridSpan??1),(t.formatting?.gridBefore??0)+(t.formatting?.gridAfter??0))))}function E(e){if(Array.isArray(e))return e.map(E);if(e!==null&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))r!=null&&(t[n]=E(r));return t}return e}var _t={styleId:"pStyle",_sectionProperties:"sectPr"},Bt=new Set(["paraId","textId","renderedPageBreakBefore","numPrFromStyle"]);function We(e){let t={};for(let[n,r]of Object.entries(e))Bt.has(n)||r===null||r===void 0||(t[_t[n]??n]=E(r));return t}var Ot=new Set(["columnWidths"]);function re(e,t=new Set){let n={};for(let[r,i]of Object.entries(e))t.has(r)||i===null||i===void 0||(n[r]=E(i));return n}function je(e){return re(e,Ot)}function ze(e){let t=e.columnWidths;return Array.isArray(t)?t.map(E):[]}function $e(e){return re(e)}function He(e,t){let n=re(e);return t&&(n.header=true),n}function me(e,t,n,r){return `${e}:t${t}:r${n}c${r}`}function Ve(e,t){return `${e}:sdt${t}`}function Ke(e){return re(e)}function oe(e){return `hf:${e}`}function Xe(e){return `fn:${e}`}function qe(e){return `en:${e}`}var Nt=new Set(["bold","italic","superscript","subscript","allCaps","smallCaps","emboss","imprint","textShadow","textOutline","hidden","rtl"]);function H(e){if(e==null)return "null";if(Array.isArray(e))return `[${e.map(H).join(",")}]`;if(typeof e=="object"){let t=e;return `{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${H(t[n])}`).join(",")}}`}return JSON.stringify(e)}function Et(e,t){if(!e||!t)return e;let n=t.resolveRunStyle(e.styleId);return n?a(n,e):e}function Qe(e){if(!e)return [];let t=[],n=(a,l={})=>t.push({name:a,attrs:l});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 r=e.shading?.fill,i=(!e.shading?.pattern||e.shading.pattern==="clear")&&r?.rgb&&!r.auto?p(r.rgb):void 0,o=e.highlight&&e.highlight!=="none"?e.highlight:i;return o&&n("highlight",{color:o}),(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.effect&&e.effect!=="none"&&n("textEffect",{effect:e.effect}),e.modernEffects&&n("modernTextEffects",{effects:e.modernEffects}),e.styleId&&n("runStyle",{styleId:e.styleId}),t}function et(e){let t={};for(let n of e)n.name==="comment"||n.name==="footnoteRef"||(Nt.has(n.name)?t[n.name]=true:n.name==="highlight"?t.highlight=n.attrs.color:n.name==="insertion"||n.name==="deletion"?t[n.name==="insertion"?"ins":"del"]=E({id:n.attrs.revisionId,author:n.attrs.author,date:n.attrs.date}):t[n.name]=E(n.attrs));return t}function Lt(e){return e.filter(t=>t.name!=="hyperlink"&&t.name!=="comment").map(t=>`${t.name}:${JSON.stringify(t.attrs)}`).sort().join("|")}function Dt(e,t){return [...e.filter(n=>n.name!==t.name),t]}function Z(e,t,n){return {kind:"text",text:e,attrs:et(t),pmSize:e.length,...n!==void 0?{commentId:n}:{},marks:[...t]}}function Y(e,t,n=[],r,i=1){return {kind:"embed",embedKind:e,payload:t,attrs:et(n),pmSize:i,...r!==void 0?{commentId:r}:{},marks:[...n]}}function tt(e,t,n){let r=e.formatting?.styleId?n?.getRunStyleOwnProperties(e.formatting.styleId):void 0,i=Qe(a(a(t,r),e.formatting)),o=e.formatting?.styleId,a$1=o?n?.getStyle(o)?.name:void 0;if([o,a$1].some(l=>/^(?:Followed)?Hyperlink$/i.test(l??""))){for(let[l,d]of [["color","textColor"],["underline","underline"]])if(e.formatting?.[l]===void 0&&r?.[l]!==void 0){let m=i.find(u=>u.name===d);m&&(m.attrs.inheritedHyperlink=true);}}return i}function Jt(e){let t=e.size?.width?b$4(e.size.width):void 0,n=e.size?.height?b$4(e.size.height):void 0,r=e.wrap.type,i=e.wrap.wrapText,o=e.position?.horizontal?.alignment,a;r==="inline"||r==="topAndBottom"?a="none":r==="square"||r==="tight"||r==="through"?i==="left"?a="right":i==="right"?a="left":o==="left"||o==="right"?a=o:a="none":a="none";let l=r==="inline"?"inline":r==="topAndBottom"?"block":b$5(r)||a&&a!=="none"?"float":"block",d=[];e.transform?.rotation&&d.push(`rotate(${e.transform.rotation}deg)`),e.transform?.flipH&&d.push("scaleX(-1)"),e.transform?.flipV&&d.push("scaleY(-1)");let m,u,c;if(e.outline?.width){m=Math.round(e.outline.width/914400*96*100)/100,e.outline.color?.rgb&&(u=`#${e.outline.color.rgb}`);let y={solid:"solid",dot:"dotted",dash:"dashed",lgDash:"dashed",dashDot:"dashed",lgDashDot:"dashed",lgDashDotDot:"dashed",sysDot:"dotted",sysDash:"dashed",sysDashDot:"dashed",sysDashDotDot:"dashed"};c=e.outline.style&&y[e.outline.style]||"solid";}return E({src:e.src||"",alt:e.alt??null,title:e.title??null,width:t??null,height:n??null,rId:e.rId??null,wrapType:r,displayMode:l,cssFloat:a??null,transform:d.length>0?d.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:m??null,borderColor:u??null,borderStyle:c??null,wrapText:i??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 Ut(e){return {shapeJson:JSON.stringify(e)}}function Wt(e){return E({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 ee(e,t){let n="",r,i=e.type==="simpleField"?e.content:e.fieldResult;for(let l of i)if(l.type==="run"){for(let d of l.content)d.type==="text"&&(n+=d.text);!r&&l.formatting&&(r=l.formatting);}let o=r??(e.type==="complexField"?e.formatting:void 0),a$1=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:a$1,hasCachedResult:n.length>0,fieldData:JSON.stringify(e),modelKind:"field"},marks:Qe(a(t,o))}}function ye(e){return {display:e.display,ommlXml:e.ommlXml,plainText:e.plainText||""}}function jt(e){return {name:"hyperlink",attrs:{href:e.href||(e.anchor?`#${e.anchor}`:""),tooltip:e.tooltip??null,rId:e.rId??null}}}function zt(e,t,n,r){let i=e.structuredResult?.inline??[],a=[...(e.type==="complexField"?e.structuredCode?.inline??[]:[]).map((c,y)=>({child:c,index:-y-1})),...i.map((c,y)=>({child:c,index:y}))];if(e.type!=="complexField"||!a.some(({child:c})=>c.type==="hyperlink"||c.type==="simpleField")){let c=ee(e,t);return [Y("field",c.payload,c.marks)]}let l=[],d=[];a.forEach(({child:c,index:y})=>{if(c.type!=="hyperlink"&&c.type!=="simpleField")return;let f=c.type==="simpleField"?ee(c,t):null,h=c.type==="hyperlink"?se(c,t,n):[Y("field",f.payload,f.marks)];d.push({index:y,items:h.map(g=>g.kind==="text"?{kind:"text",text:g.text,attributes:g.attrs}:{kind:"embed",embedKind:g.embedKind,payload:g.payload,attributes:g.attrs})});for(let g of h)g.attrs={...g.attrs,fieldResult:{id:r,index:y}};l.push(...h);});let m={...e,fieldResult:i.filter(c=>c.type==="run")},u=ee(m,t);return u.payload.fieldData=JSON.stringify(e),u.payload.resultProjection={id:r,children:d},l.push(Y("field",u.payload,u.marks)),l}function Ge(e,t,n,r){let i={name:"footnoteRef",attrs:{id:String(e),noteType:t}},o=[...n,i];return Y("noteRef",t==="endnote"?{endnoteRefId:e}:{footnoteRefId:e},o,r)}function nt(e,t,n){switch(e.type){case "text":return e.text?[Z(e.text,t,n)]:[];case "tab":return [Z(" ",t,n)];case "break":return e.breakType===void 0||e.breakType==="textWrapping"?[Y("break",{},t,n)]:[];case "softHyphen":return [Z("\xAD",t,n)];case "noBreakHyphen":return [Z("\u2011",t,n)];case "symbol":{let r=Number.parseInt(e.char,16);if(!Number.isInteger(r)||r<0||r>1114111)return [];let i={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(r),Dt(t,i),n)]}case "commentReference":return [Y("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 [Y("image",Jt(e.image))];case "horizontalRule":return [Y("horizontalRule",{rule:e.rule},t,n)];case "shape":return [Y("shape",Ut(e.shape))];case "chart":return [Y("chart",Wt(e.chart))];case "footnoteRef":return [Ge(e.id,"footnote",t,n)];case "endnoteRef":return [Ge(e.id,"endnote",t,n)];default:return []}}function ie(e,t,n,r,i=[]){let o=[...tt(e,t,n),...i];return e.content.flatMap(a=>nt(a,o,r))}function se(e,t,n,r=[]){let i=[],o=jt(e);for(let a of e.structuredChildren??e.children)if(a.type==="run"){let l=[...tt(a,t,n),...r,o];for(let d of a.content)i.push(...nt(d,l));}else if(a.type==="simpleField"||a.type==="complexField"){let l=ee(a,t);i.push(Y("field",l.payload,[...l.marks,...r,o]));}else a.type==="mathEquation"&&i.push(Y("math",ye(a),[...r,o]));return i}function $t(e,t,n){return {name:t,attrs:{revisionId:e.id,author:e.author,date:e.date??null,isMovePair:n}}}function Ht(e,t,n,r){let i=e.type==="insertion"||e.type==="moveTo"?"insertion":"deletion",o=$t(e.info,i,e.type==="moveFrom"||e.type==="moveTo"),a=[];for(let l of e.content)if(l.type==="run")a.push(...ie(l,t,n,r,[o]));else {let d=se(l,t,n,[o]);for(let m of d)r!==void 0&&(m.commentId=r);a.push(...d);}return a}function rt(e,t,n){let r=[],i=o=>{if(o.kind==="text"){if((o.text===" "?"tab":"text")==="tab"){r.push({kind:"tab",attrs:o.attrs});return}let l=r[r.length-1];l&&"text"in l&&H(l.attrs)===H(o.attrs)?l.text+=o.text:r.push({kind:"text",text:o.text,attrs:o.attrs});return}r.push({kind:o.embedKind,payload:o.payload,attrs:o.attrs});};for(let o of e.content)if(o.type==="run")ie(o,t,n).forEach(i);else if(o.type==="hyperlink")se(o,t,n).forEach(i);else if(o.type==="simpleField"||o.type==="complexField"){let a=ee(o,t);i(Y("field",a.payload,a.marks));}else o.type==="inlineSdt"?i(Y("sdt",rt(o,t,n))):o.type==="mathEquation"&&i(Y("math",ye(o)));return E({...pe(e.properties),propertiesJson:JSON.stringify(e.properties),content:r})}function Vt(e,t,n){let r=t?t.resolveParagraphStyle(e.formatting?.styleId).runFormatting:void 0;return a(r,n)}function Kt(e){let t=[];for(let n of e.content)n.type==="footnoteRefMark"?t.push("footnote"):n.type==="endnoteRefMark"&&t.push("endnote");return t}function Xt(e,t,n){let r=ie(e,t,n);if(r.some(d=>d.kind!=="text"&&d.embedKind!=="noteRef"))return null;let i=r.map(d=>Lt(d.marks));if(i.some(d=>d!==i[0]))return null;let o=Kt(e),a=r.map(d=>{if(d.kind==="text")return d.text;let m=d.payload.footnoteRefId??d.payload.endnoteRefId;return String(m??"")}).join(""),l=i[0];return {text:a,...o.length>0?{noteMarks:o}:{},...l!==void 0?{marksKey:l}:{},...e.formatting?{formatting:e.formatting}:{},...e.propertyChanges?{propertyChanges:e.propertyChanges}:{}}}function qt(e,t,n,r,i){let o=e.formatting,a$1=o?.styleId,l=o?.indentFirstLine===0?void 0:o?.indentFirstLine,d=l??e.listRendering?.indentFirstLine??o?.indentFirstLine,m=l===void 0&&e.listRendering?.indentFirstLine!==void 0?e.listRendering.hangingIndent:o?.hangingIndent??e.listRendering?.hangingIndent,u={paraId:e.paraId??null,textId:e.textId??null,styleId:a$1??null,numPr:o?.numPr??null,numPrFromStyle:o?.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,listMarkerSuffix:e.listRendering?.markerSuffix||null,listLevelNumFmts:e.listRendering?.levelNumFmts||null,listAbstractNumId:e.listRendering?.abstractNumId??null,listStartOverride:e.listRendering?.startOverride??null,_originalFormatting:o??null};if(t){let h=t.resolveParagraphStyle(a$1,i),g=h.paragraphFormatting;u.alignment=o?.alignment??g?.alignment??null,u.spaceBefore=o?.spaceBefore??g?.spaceBefore??null,u.spaceAfter=o?.spaceAfter??g?.spaceAfter??null,u.spaceBeforeLines=o?.spaceBeforeLines??g?.spaceBeforeLines??null,u.spaceAfterLines=o?.spaceAfterLines??g?.spaceAfterLines??null,u.beforeAutospacing=o?.beforeAutospacing??g?.beforeAutospacing??null,u.afterAutospacing=o?.afterAutospacing??g?.afterAutospacing??null,u.lineSpacing=o?.lineSpacing??g?.lineSpacing??null,u.lineSpacingRule=o?.lineSpacingRule??g?.lineSpacingRule??null,u.spacingExplicit=o?.spacingExplicit||null,u.indentLeft=o?.indentLeft??e.listRendering?.indentLeft??g?.indentLeft??null,u.indentRight=o?.indentRight??g?.indentRight??null;let w=o?.numPr?.numId===0&&g?.numPr&&g.numPr.numId!==0?void 0:g;u.indentFirstLine=d??w?.indentFirstLine??null,u.hangingIndent=m??w?.hangingIndent??false,u.borders=o?.borders??g?.borders??null,u.shading=o?.shading??g?.shading??null,u.tabs=o?.tabs??g?.tabs??null,u.pageBreakBefore=o?.pageBreakBefore??g?.pageBreakBefore??null,u.keepNext=o?.keepNext??g?.keepNext??null,u.keepLines=o?.keepLines??g?.keepLines??null,u.widowControl=o?.widowControl??g?.widowControl??null,u.contextualSpacing=o?.contextualSpacing??g?.contextualSpacing??null,u.outlineLevel=o?.outlineLevel??g?.outlineLevel??null,u.bidi=o?.bidi??g?.bidi??null;let T=t.getDefaultCharacterStyle()?.rPr,v=T?a(h.runFormatting,T):h.runFormatting;u.defaultTextFormatting=a(v,Et(o?.runProperties,t))??null,!o?.numPr&&g?.numPr&&g.numPr.numId!==0&&(u.numPr=g.numPr,u.numPrFromStyle=g.numPr);}else u.alignment=o?.alignment??null,u.spaceBefore=o?.spaceBefore??null,u.spaceAfter=o?.spaceAfter??null,u.spaceBeforeLines=o?.spaceBeforeLines??null,u.spaceAfterLines=o?.spaceAfterLines??null,u.beforeAutospacing=o?.beforeAutospacing??null,u.afterAutospacing=o?.afterAutospacing??null,u.lineSpacing=o?.lineSpacing??null,u.lineSpacingRule=o?.lineSpacingRule??null,u.spacingExplicit=o?.spacingExplicit||null,u.indentLeft=o?.indentLeft??e.listRendering?.indentLeft??null,u.indentRight=o?.indentRight??null,u.indentFirstLine=d??null,u.hangingIndent=m??false,u.borders=o?.borders??null,u.shading=o?.shading??null,u.tabs=o?.tabs??null,u.pageBreakBefore=o?.pageBreakBefore??null,u.keepNext=o?.keepNext??null,u.keepLines=o?.keepLines??null,u.widowControl=o?.widowControl??null,u.outlineLevel=o?.outlineLevel??null,u.bidi=o?.bidi??null,u.defaultTextFormatting=o?.runProperties??null;if(e.sectionProperties){u._sectionProperties=e.sectionProperties;let h=e.sectionProperties.sectionStart;(h==="nextPage"||h==="continuous"||h==="oddPage"||h==="evenPage"||h==="nextColumn")&&(u.sectionBreakType=h);}e.renderedPageBreakBefore&&(u.renderedPageBreakBefore=true),Qt(e)&&(u.pageBreakBefore=true),e.pPrIns&&(u.pPrIns={revisionId:e.pPrIns.id,author:e.pPrIns.author,date:e.pPrIns.date??null}),e.pPrDel&&(u.pPrDel={revisionId:e.pPrDel.id,author:e.pPrDel.author,date:e.pPrDel.date??null}),e.propertyChanges?.length&&(u.pPrChange=e.propertyChanges);let c=[],y=0,f=0;for(let h of e.content)if(h.type==="bookmarkStart")c.push({id:h.id,name:h.name,kind:"start",offset:f,...h.colFirst!==void 0?{colFirst:h.colFirst}:{},...h.colLast!==void 0?{colLast:h.colLast}:{}});else if(h.type==="bookmarkEnd")c.push({id:h.id,kind:"end",offset:f});else {let g=Gt(h);for(let k=0;k<g;k+=1)f+=n[y]?.pmSize??0,y+=1;}return c.length>0&&(u.bookmarks=c),r?.length&&(u._originalRunBoundaries=r),u}var ot=new WeakMap;function Gt(e){return ot.get(e)??0}function Zt(e,t,n,r){let i=[],o=new Set,a=[],l=Vt(e,t,n);for(let[m,u]of e.content.entries()){let c=i.length,y=o.values().next().value;if(u.type==="commentRangeStart")o.add(u.id);else if(u.type==="commentRangeEnd")o.delete(u.id);else if(u.type==="run"){let f=Xt(u,l,t);f&&a?a.push(f):a=void 0,i.push(...ie(u,l,t,y));}else u.type==="hyperlink"?(a=void 0,i.push(...se(u,l,t))):u.type==="simpleField"||u.type==="complexField"?(a=void 0,i.push(...zt(u,l,t,m))):u.type==="inlineSdt"?(a=void 0,i.push(Y("sdt",rt(u,l,t),[],void 0,2))):u.type==="insertion"||u.type==="deletion"||u.type==="moveFrom"||u.type==="moveTo"?(a=void 0,i.push(...Ht(u,l,t,y))):u.type==="mathEquation"?(a=void 0,i.push(Y("math",ye(u)))):u.type!=="bookmarkStart"&&u.type!=="bookmarkEnd"&&u.type!=="rawXml"&&(a=void 0);ot.set(u,i.length-c);}let d=qt(e,t,i,a,r);return {units:i,ppr:We(d)}}function Q(e,t){for(let n of e.content)n.type==="break"&&n.breakType==="page"?t.push("pageBreak"):(n.type!=="text"||n.text.length>0)&&t.push("visible");}function be(e,t){for(let n of e)if(n.type==="run")Q(n,t);else if(n.type==="hyperlink")for(let r of n.children)r.type==="run"&&Q(r,t);else if(n.type==="simpleField")for(let r of n.content)r.type==="run"&&Q(r,t);else if(n.type==="complexField")for(let r of [...n.fieldCode,...n.fieldResult])Q(r,t);else if(n.type==="inlineSdt")be(n.content,t);else if(n.type==="insertion"||n.type==="deletion"||n.type==="moveFrom"||n.type==="moveTo")for(let r of n.content)r.type==="run"&&Q(r,t);else n.type==="mathEquation"&&t.push("visible");}function Qt(e){let t=[];return be(e.content,t),t[0]==="pageBreak"}function en(e){let t=[];be(e.content,t);let n=false,r=false;for(let i of t)if(i==="pageBreak"){if(r||n)return true;n=true;}else r=true;return false}function tn(e){let t=new Map,n=new Map;return e.rows.forEach((r,i)=>{let o=0,a=r.cells.map(d=>{let m=o;return o+=d.formatting?.gridSpan??1,{column:m,vMerge:d.formatting?.vMerge,key:`${i}-${m}`}});if(a.length>0&&a.every(d=>d.vMerge==="continue"&&n.has(d.column))){for(let d of a)n.delete(d.column),t.set(d.key,{rowSpan:1,skip:false});return}for(let d of a)if(d.vMerge==="restart")n.set(d.column,i),t.set(d.key,{rowSpan:1,skip:false});else if(d.vMerge==="continue"){let m=n.get(d.column);if(m===void 0)t.set(d.key,{rowSpan:1,skip:false});else {let u=t.get(`${m}-${d.column}`);u&&(u.rowSpan+=1),t.set(d.key,{rowSpan:1,skip:true});}}else n.delete(d.column),t.set(d.key,{rowSpan:1,skip:false});}),t}function he(e){return {revisionId:e.id,author:e.author,date:e.date??null}}function nn(e,t,n,r,i,o){let a=t?{top:n?t.top:t.insideH,bottom:r?t.bottom:t.insideH,left:i?t.left:t.insideV,right:o?t.right:t.insideV}:void 0;return a||e?.borders?{...a??{},...e?.borders??{}}:void 0}function Ze(e,t){let n=e.formatting,r=b$2(n?.shading?.fill,t.theme),i=n?.width?.value??t.gridWidth,o=n?.width?.type??(t.gridWidth!==void 0?"pct":null),a={colspan:n?.gridSpan??1,rowspan:t.rowspan,width:i??null,widthType:o,verticalAlign:n?.verticalAlign??null,backgroundColor:r??null,borders:nn(n,t.tableBorders,t.firstRow,t.lastRow,t.firstColumn,t.lastColumn)??null,margins:n?.margins?{top:n.margins.top?.value,bottom:n.margins.bottom?.value,left:n.margins.left?.value??(t.tableBidi?n.margins.end?.value:n.margins.start?.value),right:n.margins.right?.value??(t.tableBidi?n.margins.start?.value:n.margins.end?.value)}:t.defaultMargins??null,textDirection:n?.textDirection??null,noWrap:n?.noWrap??false,_originalFormatting:n??null,_originalResolvedFill:r??null};if(e.structuralChange){let l=e.structuralChange,d=he(l.info);l.type==="tableCellInsertion"?a.cellMarker={kind:"ins",info:d}:l.type==="tableCellDeletion"?a.cellMarker={kind:"del",info:d}:l.type==="tableCellMerge"&&(a.cellMarker={kind:"merge",info:d,vMerge:l.vMerge??"cont",...l.vMergeOrig?{vMergeOrig:l.vMergeOrig}:{}});}return e.propertyChanges?.length&&(a.tcPrChange=e.propertyChanges),{attrs:He(a,t.isHeader),content:e.content.length>0?e.content:[{type:"paragraph",content:[]}]}}function rn(e,t,n,r,i,o,a,l,d){let m={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"?m.trIns=he(e.structuralChange.info):e.structuralChange.type==="tableRowDeletion"&&(m.trDel=he(e.structuralChange.info))),e.propertyChanges?.length&&(m.trPrChange=e.propertyChanges);let u=t.columnWidths,c=u?.reduce((g,k)=>g+k,0)??0,y=u?.length??Math.max(0,...t.rows.map(g=>g.cells.reduce((k,w)=>k+(w.formatting?.gridSpan??1),0))),f=0,h=[];return e.cells.forEach(g=>{let k=g.formatting?.gridSpan??1,w=f,T=r.get(`${n}-${w}`),v;if(u&&c>0){let P=0;for(let I=0;I<k&&w+I<u.length;I+=1)P+=u[w+I];v=Math.round(P/c*100);}f+=k,!T?.skip&&h.push({paragraphFormatting:ge(t,l,n,w,f,d),...Ze(g,{isHeader:n===0&&!!t.formatting?.look?.firstRow,rowspan:T?.rowSpan??1,gridWidth:v,firstRow:n===0,lastRow:n===t.rows.length-1,firstColumn:w===0,lastColumn:f===y,tableBorders:i,defaultMargins:o,theme:a,tableBidi:!!t.formatting?.bidi})});}),h.length===0&&h.push({paragraphFormatting:ge(t,l,n,0,y,d),...Ze({formatting:y>1?{gridSpan:y}:void 0,content:[{type:"paragraph",content:[]}]},{isHeader:n===0&&!!t.formatting?.look?.firstRow,rowspan:1,gridWidth:c>0?100:void 0,firstRow:n===0,lastRow:n===t.rows.length-1,firstColumn:true,lastColumn:true,tableBorders:i,defaultMargins:o,theme:a,tableBidi:!!t.formatting?.bidi})}),{attrs:$e(m),cells:h}}function on(e,t,n){let r=t?.getDefaultTableStyle(),i=e.formatting?.styleId,o=i??r?.styleId,a=o?t?.getStyle(o):void 0,l=e.formatting?.borders??a?.tblPr?.borders??r?.tblPr?.borders,d=e.formatting?.cellMargins??a?.tblPr?.cellMargins??r?.tblPr?.cellMargins,m=e.formatting?.bidi?d?.end:d?.start,u=e.formatting?.bidi?d?.start:d?.end,c=d?{top:d.top?.value,bottom:d.bottom?.value,left:d.left?.value??m?.value,right:d.right?.value??u?.value}:void 0,y=[],f=new Set,h=a;for(;h?.basedOn&&y.length<32&&!f.has(h.basedOn);)f.add(h.basedOn),y.unshift(h.basedOn),h=t?.getStyle(h.basedOn);let g={...e.formatting??{},styleCascade:{...i?{selectedStyleId:i}:{},...r?.styleId?{defaultStyleId:r.styleId}:{},...y.length>0?{basedOnStyleIds:y}:{}}},k={styleId:i??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:c??null,look:e.formatting?.look??null,bidi:e.formatting?.bidi||null,_originalFormatting:g};e.propertyChanges?.length&&(k.tblPrChange=e.propertyChanges);let w=tn(e),T=Ue(e);return {attrs:k,rows:e.rows.map((v,P)=>rn(v,e,P,w,l,c,n,a??r,T))}}function sn(e){return Ke(pe(e))}function an(e){let t=0;for(let n of e.units){let r=n.kind==="text"?n.text.length:1;if(n.commentId!==void 0&&n.commentId!==0){let i=e.commentCoverage.get(n.commentId),o=i?.[i.length-1];o&&o[1]===t?o[1]=t+r:i?i.push([t,t+r]):e.commentCoverage.set(n.commentId,[[t,t+r]]);}t+=r;}}function z(e,t,n,r){let i={storyId:t,units:[],commentCoverage:new Map};e.plans.push(i);let o=n.length>0?[...n]:[{type:"paragraph",content:[]}],a=0,l=0,d=0,m=null;for(let u of o){if(ne(u))continue;if(u.type==="paragraph"){let f=Zt(u,e.styleResolver,r.extraRunFormatting,r.tableParagraphFormatting);i.units.push(...f.units),i.units.push(Y("pilcrow",{...f.ppr,paraId:u.paraId||`${t}:p${d}`})),d+=1,r.includePageBreaks&&en(u)&&i.units.push(Y("pageBreak",{})),m="paragraph";continue}if(u.type==="table"){let f=a++,h=on(u,e.styleResolver,e.theme),g=h.rows.map((k,w)=>({trPr:k.attrs,cells:k.cells.map((T,v)=>({tcPr:T.attrs,story:me(t,f,w,v)}))}));i.units.push(Y("table",{tblPr:je(h.attrs),grid:ze(h.attrs),rows:g})),h.rows.forEach((k,w)=>{k.cells.forEach((T,v)=>{z(e,me(t,f,w,v),T.content,{includePageBreaks:false,appendBodyTail:false,seedComments:false,extraRunFormatting:T.extraRunFormatting,tableParagraphFormatting:T.paragraphFormatting});});}),m="table";continue}let c=l++,y=Ve(t,c);i.units.push(Y("blockSdt",{...sn(u.properties),story:y})),z(e,y,u.content,{includePageBreaks:r.includePageBreaks,appendBodyTail:false,seedComments:false,tableParagraphFormatting:r.tableParagraphFormatting}),m="blockSdt";}r.appendBodyTail&&(m==="table"||m==="blockSdt")&&i.units.push(Y("pilcrow",{hangingIndent:false,paraId:`${t}:p${d}`})),r.seedComments&&an(i);}function ln(e){let t=[{op:"delete",index:0,len:1}],n=0,r="",i={},o=H(i),a=()=>{r&&(t.push({op:"insert",index:n,text:r,attrs:i}),n+=r.length,r="");};for(let l of e)if(l.kind==="text"){let d=H(l.attrs);r&&d!==o&&a(),i=l.attrs,o=d,r+=l.text;}else a(),t.push({op:"insertEmbed",index:n,kind:l.embedKind,payload:l.payload,attrs:l.attrs}),n+=1;return a(),t}function dn(e,t){let n=ln(t.units);for(let[r,i]of t.commentCoverage)n.push({op:"setComment",id:String(r),ranges:i,author:"",date:"",body:null});e.applySeedRawOps(t.storyId,n);}function un(e,t){let n={styleResolver:t.package.styles?d(t.package.styles):null,theme:t.package.theme??null,plans:[]};z(n,"body",t.package.document.content,{includePageBreaks:true,appendBodyTail:true,seedComments:true});for(let[r,i]of t.package.headers??[])z(n,oe(r),i.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let[r,i]of t.package.footers??[])n.plans.some(o=>o.storyId===oe(r))||z(n,oe(r),i.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let r of t.package.footnotes??[])z(n,Xe(r.id),r.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let r of t.package.endnotes??[])z(n,qe(r.id),r.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let r of n.plans)e.createStory(r.storyId,"","Normal","left");for(let r of n.plans)dn(e,r);}var W=class extends Error{constructor(t){super(t),this.name="ContentControlValueError";}};function ae(e,t,n){let r=new RegExp(`<${t}\\b[^>]*>`).exec(e);if(!r)return;let i=new RegExp(`\\b${n}="([^"]*)"`).exec(r[0]);return i?i[1]:void 0}function ke(e,t,n,r){let o=new RegExp(`<${t}\\b[^>]*?(/?)>`).exec(e);if(!o)return e;let a=o[0],l=o[1]==="/",d=a.slice(1,l?-2:-1),u=new RegExp(`\\b${n}="[^"]*"`).test(d)?d.replace(new RegExp(`\\b${n}="[^"]*"`),()=>`${n}="${r}"`):`${d} ${n}="${r}"`;return e.replace(a,()=>`<${u}${l?"/>":">"}`)}function cn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function pn(e,t){if(!e)return t;let n=parseInt(e,16);return Number.isNaN(n)||n<0||n>1114111||n>=55296&&n<=57343?t:String.fromCodePoint(n)}function fn(e,t,n){let[r,i,o]=e.slice(0,10).split("-").map(c=>parseInt(c,10));if(!it(r,i,o))return e;let a=t&&t.trim()?t:"M/d/yyyy",l=c=>String(c).padStart(2,"0"),d=new Date(Date.UTC(r,i-1,o)),m=c=>{try{return new Intl.DateTimeFormat(n||"en",{month:c,timeZone:"UTC"}).format(d)}catch{return new Intl.DateTimeFormat("en",{month:c,timeZone:"UTC"}).format(d)}},u={yyyy:String(r),yy:String(r).slice(-2),MMMM:m("long"),MMM:m("short"),MM:l(i),M:String(i),dd:l(o),d:String(o)};return a.replace(/yyyy|yy|MMMM|MMM|MM|M|dd|d/g,c=>u[c])}function it(e,t,n){if(!e||!t||!n)return false;let r=new Date(Date.UTC(e,t-1,n));return r.getUTCFullYear()===e&&r.getUTCMonth()===t-1&&r.getUTCDate()===n}function Se(e,t){return e?{type:"paragraph",content:[{type:"run",content:[{type:"text",text:e}],...t?{formatting:{fontFamily:{ascii:t,hAnsi:t,eastAsia:t,cs:t}}}:{}}]}:{type:"paragraph",content:[]}}function gn(e){return e&&e.replace(/<w:showingPlcHdr\b[^>]*\/>/g,"").replace(/<w:showingPlcHdr\b[^>]*>[\s\S]*?<\/w:showingPlcHdr>/g,"")}function Re(e,t){let n=gn(t);return {...e,showingPlaceholder:false,rawPropertiesXml:(n??t)||void 0}}function we(e,t){let n=e.rawPropertiesXml??"";switch(t.kind){case "dropdown":{if(e.sdtType!=="dropDownList"&&e.sdtType!=="comboBox")throw new W(`Control is '${e.sdtType}', not a dropdown/combo box.`);let r=e.listItems?.find(m=>m.value===t.value||m.displayText===t.value);if(!r&&e.sdtType==="dropDownList")throw new W(`'${t.value}' is not one of the control's list items.`);let i=r?.value??t.value,o=r?.displayText??t.value,a=r?e.listItems?.indexOf(r):void 0,l=e.sdtType==="comboBox"?"w:comboBox":"w:dropDownList",d=ke(n,l,"w:lastValue",cn(i));return {properties:{...Re(e,d),listLastValue:i,controlState:{...e.controlState,value:o,selectedValue:i,selectedIndex:a,placeholder:false}},content:[Se(o)]}}case "checkbox":{if(e.sdtType!=="checkbox")throw new W(`Control is '${e.sdtType}', not a checkbox.`);if(ae(n,"w14:checked","w14:val")==null)throw new W("Checkbox control has no <w14:checked> state to update (not a Word checkbox).");let r=t.checked?"w14:checkedState":"w14:uncheckedState",i=pn(ae(n,r,"w14:val"),t.checked?"\u2612":"\u2610"),o=ae(n,r,"w14:font"),a=ke(n,"w14:checked","w14:val",t.checked?"1":"0");return {properties:{...Re(e,a),checked:t.checked,controlState:{...e.controlState,checked:t.checked,value:i,placeholder:false}},content:[Se(i,o)]}}case "date":{if(e.sdtType!=="date")throw new W(`Control is '${e.sdtType}', not a date control.`);let r=t.date.slice(0,10),[i,o,a]=/^\d{4}-\d{2}-\d{2}$/.test(r)?r.split("-").map(Number):[];if(!it(i,o,a))throw new W(`Date must be ISO yyyy-mm-dd, got '${t.date}'.`);let l=`${r}T00:00:00`,d=ke(n,"w:date","w:fullDate",l),m=e.dateState?.format??e.dateFormat??ae(n,"w:dateFormat","w:val"),u=e.dateState?.language,c=fn(r,m,u);return {properties:{...Re(e,d),dateFormat:m,dateState:{...e.dateState,fullDate:l,format:m},controlState:{...e.controlState,value:r,placeholder:false}},content:[Se(c)]}}}}function st(e){return e.numPrFromStyle!=null&&e.numPr!=null&&JSON.stringify(e.numPr)===JSON.stringify(e.numPrFromStyle)}function dt(e){if(e._originalFormatting){let n=e._originalFormatting,r={...n};return e.alignment!==(n.alignment||void 0)&&(r.alignment=e.alignment||void 0),st(e)?(delete r.numPr,delete r.numPrFromStyle):e.numPr!==n.numPr&&JSON.stringify(e.numPr)!==JSON.stringify(n.numPr)&&(r.numPr=e.numPr||void 0,delete r.numPrFromStyle),e.styleId!==(n.styleId||void 0)&&(r.styleId=e.styleId||void 0),e.pageBreakBefore!==(n.pageBreakBefore||void 0)&&(r.pageBreakBefore=e.pageBreakBefore||void 0),e.widowControl!==(n.widowControl??void 0)&&(r.widowControl=e.widowControl??void 0),e.bidi!==(n.bidi||void 0)&&(r.bidi=e.bidi||void 0),r}if(e.alignment||e.spaceBefore!=null||e.spaceAfter!=null||e.spaceBeforeLines!=null||e.spaceAfterLines!=null||e.beforeAutospacing!=null||e.afterAutospacing!=null||e.lineSpacing||e.indentLeft||e.indentRight||e.indentFirstLine||e.numPr||e.styleId||e.borders||e.shading||e.tabs||e.outlineLevel!=null||e.contextualSpacing||e.pageBreakBefore||e.widowControl!=null||e.bidi)return {alignment:e.alignment||void 0,spaceBefore:e.spaceBefore??void 0,spaceAfter:e.spaceAfter??void 0,spaceBeforeLines:e.spaceBeforeLines??void 0,spaceAfterLines:e.spaceAfterLines??void 0,beforeAutospacing:e.beforeAutospacing??void 0,afterAutospacing:e.afterAutospacing??void 0,lineSpacing:e.lineSpacing||void 0,lineSpacingRule:e.lineSpacingRule||void 0,indentLeft:e.indentLeft||void 0,indentRight:e.indentRight||void 0,indentFirstLine:e.indentFirstLine||void 0,hangingIndent:e.hangingIndent||void 0,numPr:st(e)?void 0:e.numPr||void 0,styleId:e.styleId||void 0,borders:e.borders||void 0,shading:e.shading||void 0,tabs:e.tabs||void 0,outlineLevel:e.outlineLevel??void 0,contextualSpacing:e.contextualSpacing||void 0,pageBreakBefore:e.pageBreakBefore||void 0,widowControl:e.widowControl??void 0,bidi:e.bidi||void 0}}function ut(e){if(e._originalFormatting){let n=e._originalFormatting,r={...n};return e.styleId!==(n.styleId||void 0)&&(r.styleId=e.styleId||void 0),e.justification!==(n.justification||void 0)&&(r.justification=e.justification||void 0),e.floating!==(n.floating||void 0)&&(r.floating=e.floating||void 0),e.tableLayout!==(n.layout||void 0)&&(r.layout=e.tableLayout||void 0),e.look!==(n.look||void 0)&&(r.look=e.look||void 0),e.bidi!==(n.bidi||void 0)&&(r.bidi=e.bidi||void 0),(e.width!==n.width?.value||e.widthType!==n.width?.type)&&(r.width=e.width!=null||e.widthType?{value:e.width??0,type:e.widthType||"dxa"}:void 0),e.cellMargins&&(r.cellMargins=at(e.cellMargins)),r}if(e.styleId||e.width!=null||e.widthType||e.justification||e.tableLayout||e.floating||e.cellMargins||e.look||e.bidi)return {styleId:e.styleId||void 0,width:e.width!=null||e.widthType?{value:e.width??0,type:e.widthType||"dxa"}:void 0,justification:e.justification||void 0,layout:e.tableLayout||void 0,floating:e.floating||void 0,cellMargins:e.cellMargins?at(e.cellMargins):void 0,look:e.look||void 0,bidi:e.bidi||void 0}}function at(e){return {top:e.top!=null?{value:e.top,type:"dxa"}:void 0,bottom:e.bottom!=null?{value:e.bottom,type:"dxa"}:void 0,left:e.left!=null?{value:e.left,type:"dxa"}:void 0,right:e.right!=null?{value:e.right,type:"dxa"}:void 0}}function ct(e){if(e._originalFormatting){let t=e._originalFormatting,n={...t};return e.height!==(t.height?.value||void 0)&&(n.height=e.height?{value:e.height,type:"dxa"}:void 0),e.heightRule!==(t.heightRule||void 0)&&(n.heightRule=e.heightRule||void 0),e.isHeader!==(t.header||void 0)&&(n.header=e.isHeader||void 0),n}if(!(!e.height&&!e.isHeader))return {height:e.height?{value:e.height,type:"dxa"}:void 0,heightRule:e.heightRule||void 0,header:e.isHeader||void 0}}function pt(e){if(e._originalFormatting){let n=e._originalFormatting,r={...n};return e.colspan>1&&(r.gridSpan=e.colspan),e.width!=null&&(r.width={value:e.width,type:e.widthType||"dxa"}),e.verticalAlign!==(n.verticalAlign||void 0)&&(r.verticalAlign=e.verticalAlign||void 0),e.backgroundColor?r.shading=e._originalResolvedFill===e.backgroundColor&&n.shading?n.shading:{fill:{rgb:e.backgroundColor}}:n.shading&&(r.shading=void 0),e.borders&&(r.borders=e.borders),e.margins&&(r.margins=lt(e.margins)),e.textDirection!==(n.textDirection||void 0)&&(r.textDirection=e.textDirection||void 0),r}if(e.colspan>1||e.rowspan>1||e.width!=null||e.verticalAlign||e.backgroundColor||e.borders||e.margins||e.textDirection)return {gridSpan:e.colspan>1?e.colspan:void 0,width:e.width!=null?{value:e.width,type:e.widthType||"dxa"}:void 0,verticalAlign:e.verticalAlign||void 0,textDirection:e.textDirection||void 0,shading:e.backgroundColor?{fill:{rgb:e.backgroundColor}}:void 0,borders:e.borders,margins:e.margins?lt(e.margins):void 0}}function lt(e){let t={};return e.top!=null&&(t.top={value:e.top,type:"dxa"}),e.bottom!=null&&(t.bottom={value:e.bottom,type:"dxa"}),e.left!=null&&(t.left={value:e.left,type:"dxa"}),e.right!=null&&(t.right={value:e.right,type:"dxa"}),t}var mn={paraId:null,textId:null,alignment:null,spaceBefore:null,spaceAfter:null,lineSpacing:null,lineSpacingRule:null,spacingExplicit:null,indentLeft:null,indentRight:null,indentFirstLine:null,hangingIndent:false,numPr:null,numPrFromStyle:null,listNumFmt:null,listIsBullet:null,listMarker:null,listMarkerHidden:null,listMarkerFontFamily:null,listMarkerFontSize:null,listMarkerSuffix:null,listLevelNumFmts:null,listAbstractNumId:null,listStartOverride:null,styleId:null,borders:null,shading:null,tabs:null,pageBreakBefore:null,renderedPageBreakBefore:null,keepNext:null,keepLines:null,widowControl:null,contextualSpacing:null,defaultTextFormatting:null,sectionBreakType:null,bidi:null,outlineLevel:null,bookmarks:null,_originalFormatting:null,_originalRunBoundaries:null,_sectionProperties:null,pPrIns:null,pPrDel:null,pPrChange:null},hn={styleId:null,width:null,widthType:null,justification:null,columnWidths:null,tableLayout:null,floating:null,cellMargins:null,look:null,bidi:null,_originalFormatting:null,tblPrChange:null},yn={height:null,heightRule:null,isHeader:false,_originalFormatting:null,trIns:null,trDel:null,trPrChange:null},bn={colspan:1,rowspan:1,colwidth:null,width:null,widthType:null,verticalAlign:null,backgroundColor:null,borders:null,margins:null,textDirection:null,noWrap:false,_originalFormatting:null,_originalResolvedFill:null,cellMarker:null,tcPrChange:null},kn=new Set(["bold","italic","superscript","subscript","allCaps","smallCaps","emboss","imprint","textShadow","textOutline","hidden","rtl"]);function C(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function A(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function R(e){return typeof e=="string"?e:void 0}function de(e){if(Array.isArray(e))return e.map(de);let t=C(e);if(!t)return e;let n={};for(let[r,i]of Object.entries(t))i!=null&&(n[r]=de(i));return n}function j(e){if(e==null)return "null";if(Array.isArray(e))return `[${e.map(j).join(",")}]`;let t=C(e);return t?`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${j(t[n])}`).join(",")}}`:JSON.stringify(e)}function X(e){let t={...e};return delete t.hyperlink,delete t.ins,delete t.del,t}function te(e){let t={};e.bold&&(t.bold=true,t.boldCs=true),e.italic&&(t.italic=true,t.italicCs=true);let n=C(e.underline);n&&n.inheritedHyperlink!==true&&(t.underline={style:R(n.style)||"single",color:C(n.color)??null});let r=C(e.strike);r&&(r.double?t.doubleStrike=true:t.strike=true);let i=C(e.textColor);i&&i.inheritedHyperlink!==true&&(t.color={rgb:R(i.rgb)??null,themeColor:i.themeColor??null,themeTint:R(i.themeTint)??null,themeShade:R(i.themeShade)??null}),typeof e.highlight=="string"&&(t.highlight=e.highlight);let o=C(e.fontSize);if(o){let f=A(o.size),h=A(o.sizeCs)??f;f!==void 0&&(t.fontSize=f),h!==void 0&&(t.fontSizeCs=h);}let a=C(e.fontFamily);if(a){let f=R(a.ascii);t.fontFamily={ascii:f??null,hAnsi:R(a.hAnsi)??null,eastAsia:R(a.eastAsia),cs:R(a.cs)||f,asciiTheme:a.asciiTheme??null,hAnsiTheme:R(a.hAnsiTheme),eastAsiaTheme:R(a.eastAsiaTheme),csTheme:R(a.csTheme)};}e.superscript&&(t.vertAlign="superscript"),e.subscript&&(t.vertAlign="subscript"),e.allCaps&&(t.allCaps=true),e.smallCaps&&(t.smallCaps=true);let l=C(e.characterSpacing);if(l){let f=A(l.spacing),h=A(l.position),g=A(l.scale),k=A(l.kerning);f!==void 0&&(t.spacing=f),h!==void 0&&(t.position=h),g!==void 0&&(t.scale=g),k!==void 0&&(t.kerning=k);}e.emboss&&(t.emboss=true),e.imprint&&(t.imprint=true),e.textShadow&&(t.shadow=true);let d=C(e.emphasisMark);d&&(t.emphasisMark=R(d.type)||"dot"),e.textOutline&&(t.outline=true),e.hidden&&(t.hidden=true),e.rtl&&(t.rtl=true);let m=C(e.textEffect);m&&(t.effect=R(m.effect)||"blinkBackground");let u=C(e.modernTextEffects);u?.effects&&(t.modernEffects=u.effects);let c=C(e.runStyle),y=R(c?.styleId);return y&&(t.styleId=y),t}function mt(e,t){let n=[],r="",i=()=>{r&&(n.push({type:"text",text:r}),r="");},o=t.fontFamily?[t.fontFamily.ascii,t.fontFamily.hAnsi,t.fontFamily.eastAsia,t.fontFamily.cs].filter(l=>!!l):[],a=o.length>0&&o.every(l=>l===o[0])?o[0]:null;for(let l of e){let d=l.codePointAt(0)??0;l==="\xAD"?(i(),n.push({type:"softHyphen"})):l==="\u2011"?(i(),n.push({type:"noBreakHyphen"})):a&&d>=61440&&d<=63743?(i(),n.push({type:"symbol",font:a,char:d.toString(16).toUpperCase().padStart(4,"0")})):r+=l;}return i(),n}function Ie(e,t){let n=te(X(t));return {type:"run",formatting:Object.keys(n).length>0?n:void 0,content:mt(e,n)}}function Sn(e,t){for(let n of t.content){let r=e.content[e.content.length-1];r?.type==="text"&&n.type==="text"?r.text+=n.text:e.content.push(n);}}function Rn(e){let t=0xcbf29ce484222325n;for(let n of new TextEncoder().encode(e))t=(t^BigInt(n))*0x100000001b3n,t&=0xffffffffffffffffn;return Number(t&(1n<<53n)-1n)}function xe(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Number(e);return Number.isFinite(t)?t:Rn(e)}return 0}function V(e,t=false){let n=C(e);if(!n)return null;let r=R(n.author)||"Unknown",i=R(n.date);return {id:xe(n.revisionId??n.id),author:r,...i?{date:i}:{}}}function wn(e){let t=C(e.hyperlink);if(!t)return null;let n=R(t.href)||"";return n.startsWith("#")?{type:"hyperlink",anchor:n.slice(1),tooltip:R(t.tooltip)||void 0,children:[]}:{type:"hyperlink",href:n,tooltip:R(t.tooltip)||void 0,rId:R(t.rId)||void 0,children:[]}}function xn(e){let t=C(e.hyperlink);return t?R(t.href)||"":null}function ve(e,t){let n=R(e.fieldData);if(n&&n.length<=2e6)try{let u=JSON.parse(n),c=u.type==="simpleField"?u.content:u.fieldResult;if((u.type==="simpleField"||u.type==="complexField")&&typeof u.instruction=="string"&&Array.isArray(c)){let y=R(e.displayMode);return u.fieldTree&&y&&(u.fieldTree.displayMode=y),u}}catch{}let r=te(X(t)),i={type:"run",content:[{type:"text",text:R(e.displayText)||""}],...Object.keys(r).length>0?{formatting:r}:{}},o=R(e.instruction)||"",a=R(e.fieldType)||"UNKNOWN",l=e.fldLock===true||void 0,d=e.dirty===true||void 0,m=R(e.displayMode)||"result";return e.fieldKind==="complex"?{type:"complexField",instruction:o,fieldType:a,fieldCode:[],fieldResult:[i],fldLock:l,dirty:d,fieldTree:{version:1,displayMode:m}}:{type:"simpleField",instruction:o,fieldType:a,content:[i],fldLock:l,dirty:d,fieldTree:{version:1,displayMode:m}}}function ht(e){return {type:"mathEquation",display:R(e.display)||"inline",ommlXml:R(e.ommlXml)||"",plainText:R(e.plainText)||void 0}}function Ae(e,t){let n=C(e.rule),r=A(n?.height);if(!n||r===void 0||n.width!=null&&A(n.width)===void 0||n.widthPercent!=null&&A(n.widthPercent)===void 0||typeof n.alignment!="string"||typeof n.noShade!="boolean"||typeof n.color!="string"||typeof n.xml!="string")throw new Error("Malformed horizontalRule embed payload");let i={width:A(n.width)??null,widthPercent:A(n.widthPercent)??null,height:r,alignment:n.alignment,noShade:n.noShade,color:n.color,xml:n.xml},o=te(X(t));return {type:"run",content:[{type:"horizontalRule",rule:i}],...Object.keys(o).length>0?{formatting:o}:{}}}function yt(e){let t=e,n={type:R(t.wrapType)||"inline"};t.distTop!==void 0&&(n.distT=c$1(Number(t.distTop))),t.distBottom!==void 0&&(n.distB=c$1(Number(t.distBottom))),t.distLeft!==void 0&&(n.distL=c$1(Number(t.distLeft))),t.distRight!==void 0&&(n.distR=c$1(Number(t.distRight))),t.wrapText&&(n.wrapText=t.wrapText);let r={type:"image",rId:R(t.rId)||"",src:R(t.src)||"",alt:R(t.alt)||void 0,title:R(t.title)||void 0,shapeType:R(t.shapeType)||void 0,size:{width:c$1(Number(t.width)||0),height:c$1(Number(t.height)||0)},wrap:n};if(t.transform){let a={},l=t.transform.match(/rotate\(([-\d.]+)deg\)/)?.[1];l&&(a.rotation=Number.parseFloat(l)),t.transform.includes("scaleX(-1)")&&(a.flipH=true),t.transform.includes("scaleY(-1)")&&(a.flipV=true),(a.rotation||a.flipH||a.flipV)&&(r.transform=a);}if(t.position?.horizontal&&t.position.vertical&&(r.position={relativeHeight:t.position.relativeHeight,horizontal:{relativeTo:t.position.horizontal.relativeTo||"column",alignment:t.position.horizontal.align,posOffset:t.position.horizontal.posOffset},vertical:{relativeTo:t.position.vertical.relativeTo||"paragraph",alignment:t.position.vertical.align,posOffset:t.position.vertical.posOffset}}),t.borderWidth&&t.borderWidth>0){let a={solid:"solid",dotted:"dot",dashed:"dash",double:"solid",groove:"solid",ridge:"solid",inset:"solid",outset:"solid"};r.outline={width:c$1(t.borderWidth),color:t.borderColor?{rgb:t.borderColor.replace("#","")}:void 0,style:t.borderStyle&&a[t.borderStyle]||"solid"};}t.hlinkHref&&(r.hlinkHref=t.hlinkHref);let i={};t.cropTop!=null&&(i.top=t.cropTop),t.cropRight!=null&&(i.right=t.cropRight),t.cropBottom!=null&&(i.bottom=t.cropBottom),t.cropLeft!=null&&(i.left=t.cropLeft),Object.keys(i).length>0&&(r.crop=i),t.opacity!=null&&t.opacity<1&&(r.opacity=t.opacity),t.layoutInCell!=null&&(r.layoutInCell=t.layoutInCell),t.allowOverlap!=null&&(r.allowOverlap=t.allowOverlap);let o={};return t.effectExtentTop&&(o.top=c$1(t.effectExtentTop)),t.effectExtentBottom&&(o.bottom=c$1(t.effectExtentBottom)),t.effectExtentLeft&&(o.left=c$1(t.effectExtentLeft)),t.effectExtentRight&&(o.right=c$1(t.effectExtentRight)),Object.keys(o).length>0&&(r.padding=o),{type:"run",content:[{type:"drawing",image:r}]}}function Tn(e){let t=R(e);if(!(!t||t.length>2e6))try{let n=JSON.parse(t);return n?.type!=="shape"||typeof n.shapeType!="string"?void 0:(C(n.size)||(n.size={width:0,height:0}),n)}catch{return}}function bt(e){let t=R(e.chartJson);if(!t)return null;try{let n=JSON.parse(t);return n?.type!=="chart"||typeof n.chartType!="string"?null:{type:"run",content:[{type:"chart",chart:n}]}}catch{return null}}function kt(e){let t=Tn(e.shapeJson)??{type:"shape",shapeType:"rect",size:{width:0,height:0}},n=R(e.shapeType);n&&(t.shapeType=n);let r=R(e.shapeId);if(r&&(t.id=r),e.width&&(t.size={...t.size,width:c$1(Number(e.width))}),e.height&&(t.size={...t.size,height:c$1(Number(e.height))}),Array.isArray(e.geometryPath)&&e.geometryPath.length>0&&(t.geometryPath=e.geometryPath),e.fillType==="gradient"&&typeof e.gradientStops=="string")try{let o=JSON.parse(e.gradientStops);t.fill={type:"gradient",gradient:{type:R(e.gradientType)||"linear",angle:A(e.gradientAngle)||void 0,stops:o.map(a=>({position:a.position,color:{rgb:a.color.replace("#","")}}))}};}catch{t.fill={type:"solid",color:{rgb:(R(e.fillColor)||"000000").replace("#","")}};}else typeof e.fillColor=="string"?t.fill={type:R(e.fillType)||"solid",color:{rgb:e.fillColor.replace("#","")}}:e.fillType==="none"&&(t.fill={type:"none"});if(typeof e.outlineWidth=="number"&&e.outlineWidth>0){let o={solid:"solid",dotted:"dot",dashed:"dash"},a=R(e.outlineStyle);t.outline={width:c$1(e.outlineWidth),color:typeof e.outlineColor=="string"?{rgb:e.outlineColor.replace("#","")}:void 0,style:a&&o[a]||"solid"};}let i={};if(typeof e.rotation=="number")i.rotation=e.rotation;else if(typeof e.transform=="string"){let o=e.transform.match(/rotate\(([-\d.]+)deg\)/)?.[1];o&&(i.rotation=Number.parseFloat(o));}return (e.flipH||String(e.transform||"").includes("scaleX(-1)"))&&(i.flipH=true),(e.flipV||String(e.transform||"").includes("scaleY(-1)"))&&(i.flipV=true),(i.rotation||i.flipH||i.flipV)&&(t.transform=i),{type:"run",content:[{type:"shape",shape:t}]}}function Cn(e){let t=fe(e),n=R(e.propertiesJson);if(n&&n.length<=1e6)try{let a=JSON.parse(n);a&&typeof a=="object"&&typeof a.sdtType=="string"&&(t=a);}catch{}let r=[];for(let a of Array.isArray(e.content)?e.content:[]){let l=C(a),d=R(l?.kind);if(!l||!d)continue;let m=C(l.attrs)??{};if(d==="text"){let u=R(l.text);u!==void 0&&r.push({kind:"text",text:u,attributes:m});continue}r.push({kind:"embed",embedKind:d,payload:C(l.payload)??{},attributes:m});}let i=Te(ue(r)),o=St(e.value);if(o)try{let a=we(t,o);t=a.properties;let l=a.content[0];i=Te(l?.type==="paragraph"?l.content:[]);}catch{}return {type:"inlineSdt",properties:t,content:i}}function Te(e){return e.filter(t=>t.type==="run"||t.type==="hyperlink"||t.type==="simpleField"||t.type==="complexField"||t.type==="inlineSdt"||t.type==="mathEquation")}function St(e){let t=C(e);return t?.kind==="checkbox"&&typeof t.checked=="boolean"?{kind:"checkbox",checked:t.checked}:t?.kind==="dropdown"&&typeof t.value=="string"?{kind:"dropdown",value:t.value}:t?.kind==="date"&&typeof t.date=="string"?{kind:"date",date:t.date}:null}function Rt(e){if(e.modelKind!=="commentReference")return null;let t=A(e.commentId);return {type:"run",content:[{type:"commentReference",...t!==void 0?{id:t}:{}}]}}function ft(e){if(e.kind==="text")return Ie(e.text,e.attributes);switch(e.embedKind){case "break":return {type:"run",content:[{type:"break",breakType:"textWrapping"}]};case "tab":return {type:"run",content:[{type:"tab"}]};case "image":return yt(e.payload);case "horizontalRule":return Ae(e.payload,e.attributes);case "shape":return kt(e.payload);case "chart":return bt(e.payload);case "field":return Rt(e.payload)??ve(e.payload,e.attributes);case "math":return ht(e.payload);case "sdt":return Cn(e.payload);case "noteRef":{let t=e.payload.footnoteRefId,n=e.payload.endnoteRefId;return {type:"run",content:[t!==void 0?{type:"footnoteRef",id:xe(t)}:{type:"endnoteRef",id:xe(n)}]}}default:return null}}function Pn(e,t){let n;if(e.kind==="embed"&&e.embedKind==="image")n=yt(e.payload);else if(e.kind==="embed"&&e.embedKind==="horizontalRule")n=Ae(e.payload,e.attributes);else if(e.kind==="embed"&&e.embedKind==="shape")n=kt(e.payload);else if(e.kind==="embed"&&e.embedKind==="chart")n=bt(e.payload)??{type:"run",content:[]};else if(e.kind==="text"){let o=te(X(e.attributes));n={type:"run",content:[{type:"text",text:e.text}],...Object.keys(o).length>0?{formatting:o}:{}};}else n={type:"run",content:[]};let i=(C(e.attributes.ins)??C(e.attributes.del))?.isMovePair===true;return e.attributes.ins?i?{type:"moveTo",info:t,content:[n]}:{type:"insertion",info:t,content:[n]}:i?{type:"moveFrom",info:t,content:[n]}:{type:"deletion",info:t,content:[n]}}function In(e,t){if(t.kind==="text"){e.children.push(Ie(t.text,t.attributes));return}if(t.embedKind==="break")e.children.push({type:"run",content:[{type:"break",breakType:"textWrapping"}]});else if(t.embedKind==="tab")e.children.push({type:"run",content:[{type:"tab"}]});else if(t.embedKind==="horizontalRule")e.children.push(Ae(t.payload,t.attributes));else if(t.embedKind==="field"){let n=Rt(t.payload)??ve(t.payload,t.attributes);n.type==="run"?e.children.push(n):(e.structuredChildren??(e.structuredChildren=[...e.children])).push(n);}else t.embedKind==="math"&&(e.structuredChildren??(e.structuredChildren=[...e.children])).push(ht(t.payload));}function gt(e){let t=[];for(let n of e){let r={...n.attributes};delete r.fieldResult;let i=n.kind==="embed"&&n.embedKind==="tab"?{kind:"text",text:" ",attributes:r}:{...n,attributes:r},o=t.at(-1);i.kind==="text"&&o?.kind==="text"&&j(o.attributes)===j(r)?o.text+=i.text:t.push(i);}return j(t)}function vn(e){let t=[];for(let[i,o]of e.entries()){if(o.kind!=="embed"||o.embedKind!=="field")continue;let a=A(C(o.payload.resultProjection)?.id);a!==void 0&&t.push({id:a,owner:o,position:i});}if(t.length===0)return e;let n=new Map,r=e.filter((i,o)=>{let a=C(i.attributes.fieldResult),l=A(a?.id),d=A(a?.index),m=t.find(f=>f.id===l&&f.position>o)?.owner;if(d===void 0||!m)return true;let u=n.get(m)??new Map,c=u.get(d)??[],y={...i.attributes};return delete y.fieldResult,c.push({...i,attributes:y}),u.set(d,c),n.set(m,u),false});for(let{owner:i}of t){let o=ve(i.payload,i.attributes);if(o.type!=="complexField")continue;let a=C(i.payload.resultProjection),l=Array.isArray(a?.children)?a.children:[],d=new Map;for(let c of l){let y=C(c),f=A(y?.index);if(f===void 0||!Array.isArray(y?.items))continue;let h=n.get(i)?.get(f)??[];if(gt(h)===gt(y.items))continue;let g=Te(ue(h)),k=f<0?o.structuredCode?.inline?.[-f-1]:o.structuredResult?.inline?.[f];k?.type==="hyperlink"&&g.length===1&&g[0]?.type==="hyperlink"&&(g[0]={...k,...g[0],structuredChildren:g[0].structuredChildren}),d.set(f,g);}if(d.size===0)continue;let m=(o.structuredResult?.inline??[]).flatMap((c,y)=>d.get(y)??[c]),u=o.structuredCode?.inline?.flatMap((c,y)=>d.get(-y-1)??[c]);o.structuredResult={...o.structuredResult,inline:m},u&&(o.structuredCode={...o.structuredCode,inline:u}),o.fieldTree&&(o.fieldTree.result={...o.fieldTree.result,inline:m},u&&(o.fieldTree.code={...o.fieldTree.code,inline:u})),o.fieldResult=m.flatMap(c=>c.type==="run"?[c]:c.type==="hyperlink"?c.children.filter(y=>y.type==="run"):[]),i.payload={...i.payload,fieldData:JSON.stringify(o)};}return r}function ue(e){e=vn(e);let t=[],n=null,r=null,i=null,o=()=>{n&&t.push(n),n=null,r=null;},a=()=>{i&&t.push(i),i=null;};for(let l of e){if(l.kind==="embed"&&l.embedKind==="noteRef"){o(),a();let c=ft(l);c&&t.push(c);continue}let d=V(l.attributes.ins??l.attributes.del);if(d){o(),a(),t.push(Pn(l,d));continue}let m=xn(l.attributes);if(m!==null){o();let c=i?i.href||(i.anchor?`#${i.anchor}`:""):null;(!i||c!==m)&&(a(),i=wn(l.attributes)),i&&In(i,l);continue}if(a(),l.kind==="text"){let c=j(X(l.attributes)),y=Ie(l.text,l.attributes);n&&r===c?Sn(n,y):(o(),n=y,r=c);continue}o();let u=ft(l);u&&t.push(u);}return o(),a(),t}function An(e){if(!e)return {};let t={};for(let n of e.split("|")){let r=n.indexOf(":");if(r<=0)return null;let i=n.slice(0,r),o;try{o=JSON.parse(n.slice(r+1));}catch{return null}i==="comment"||i==="footnoteRef"||(kn.has(i)?t[i]=true:i==="highlight"?t.highlight=o.color:i==="insertion"||i==="deletion"?t[i==="insertion"?"ins":"del"]=de({id:o.revisionId,author:o.author,date:o.date,isMovePair:o.isMovePair}):t[i]=de(o));}return t}function Fn(e){return e.noteMarks?.length?e.noteMarks.map(t=>({type:t==="endnote"?"endnoteRefMark":"footnoteRefMark"})):null}function Yn(e,t,n){if(!n?.length||!e.every(l=>l.type==="run"&&l.content.every(d=>d.type==="text"))||t.some(l=>l.kind!=="text"||l.attributes.hyperlink)||n.some(l=>l.noteMarks?.length&&l.text.length>0)||t.map(l=>l.kind==="text"?l.text:"").join("")!==n.map(l=>l.text).join(""))return e;let i=0,o=0,a=[];for(let l of n){let d=An(l.marksKey);if(!d)return e;a.push(d);let m=l.text.length;for(;m>0;){let u=t[i];if(u?.kind!=="text"||j(X(u.attributes))!==j(d))return e;let c=u.text.length-o,y=Math.min(m,c);m-=y,o+=y,o===u.text.length&&(i+=1,o=0);}}return i!==t.length||o!==0?e:n.map((l,d)=>{let m=l.text.length===0?l.formatting:te(a[d]),u={type:"run",content:Fn(l)??mt(l.text,m??{})};return m&&Object.keys(m).length>0&&(u.formatting=m),l.propertyChanges?.length&&(u.propertyChanges=l.propertyChanges),u})}function le(e){return e.content.reduce((t,n)=>n.type==="text"||n.type==="instrText"?t+n.text.length:n.type==="symbol"?t+n.char.length:n.type==="tab"||n.type==="softHyphen"||n.type==="noBreakHyphen"||n.type==="footnoteRef"||n.type==="endnoteRef"||n.type==="horizontalRule"?t+1:t,0)}function K(e){switch(e.type){case "run":return le(e);case "hyperlink":return e.children.reduce((t,n)=>t+(n.type==="run"?le(n):0),0);case "simpleField":return e.content.reduce((t,n)=>t+K(n),0);case "complexField":return e.fieldResult.reduce((t,n)=>t+le(n),0);case "inlineSdt":return e.content.reduce((t,n)=>t+K(n),0);case "insertion":case "deletion":case "moveFrom":case "moveTo":return e.content.reduce((t,n)=>t+(n.type==="run"?le(n):0),0);case "mathEquation":return e.plainText?.length??0;default:return 0}}function Mn(e,t){if(!e.content.every(i=>i.type==="text"))return [e,null];let n=e.content.map(i=>i.type==="text"?i.text:"").join(""),r=i=>i?{type:"run",...e.formatting?{formatting:e.formatting}:{},...e.propertyChanges?{propertyChanges:e.propertyChanges}:{},content:[{type:"text",text:i}]}:null;return [r(n.slice(0,t)),r(n.slice(t))]}function Ce(e,t,n=r=>r.kind==="start"?{type:"commentRangeStart",id:r.id}:{type:"commentRangeEnd",id:r.id}){if(t.length===0)return e;let r=[...t].sort((d,m)=>d.offset-m.offset||(d.kind===m.kind?d.id-m.id:d.kind==="end"?-1:1)),i=[],o=0,a=0,l=d=>{for(;a<r.length&&r[a].offset===d;){let m=r[a++];i.push(n(m));}};l(0);for(let d of e){let m=K(d),u=r.slice(a).map(c=>c.offset).filter(c=>c>o&&c<o+m);if(d.type==="run"&&d.content.every(c=>c.type==="text")){let c=d,y=0;for(let f of u){if(!c)break;let[h,g]=Mn(c,f-o-y);h&&i.push(h),l(f),c=g,y=f-o;}c&&i.push(c);}else i.push(d);o+=m,l(o);}return l(o),i}function _n(e){if(!Array.isArray(e.bookmarks))return [];let t=[];for(let n of e.bookmarks){let r=C(n),i=A(r?.id);if(!r||i===void 0)continue;let o=A(r.offset)??0,a={name:R(r.name),colFirst:A(r.colFirst),colLast:A(r.colLast)};r.kind==="start"?t.push({id:i,kind:"start",offset:o,...a}):r.kind==="end"?t.push({id:i,kind:"end",offset:o,...a}):(t.push({id:i,kind:"start",offset:0,...a}),t.push({id:i,kind:"end",offset:Number.MAX_SAFE_INTEGER,...a}));}return t}function Bn(e,t){if(!t)return e;let n=e.reduce((o,a)=>o+K(a),0),r=[],i=0;for(let[o,a]of t.content.entries())a.type==="rawXml"&&r.push({id:o,kind:"start",offset:Math.min(i,n)}),i+=K(a);return Ce(e,r,o=>t.content[o.id])}function On(e){let t={...mn,...e};return t.styleId=e.pStyle??null,t._sectionProperties=e.sectPr??null,delete t.pStyle,delete t.sectPr,t}function Nn(e,t,n,r,i){let o=On(t),a=ue(n);a=Yn(a,n,Array.isArray(o._originalRunBoundaries)?o._originalRunBoundaries:void 0),a=Bn(a,i),a=Ce(a,r);let l=_n(t).map(c=>({...c,offset:c.offset===Number.MAX_SAFE_INTEGER?a.reduce((y,f)=>y+K(f),0):c.offset}));l.length>0&&(a=Ce(a,l,c=>{let y=c;return y.kind==="start"?{type:"bookmarkStart",id:y.id,name:y.name||"",...y.colFirst!==void 0?{colFirst:y.colFirst}:{},...y.colLast!==void 0?{colLast:y.colLast}:{},position:{offset:y.offset}}:{type:"bookmarkEnd",id:y.id,position:{offset:y.offset}}}));let d={type:"paragraph",paraId:e||void 0,textId:i?.textId,formatting:dt(o),content:a};i?.renderedPageBreakBefore&&(d.renderedPageBreakBefore=true);let m=V(t.pPrIns,true),u=V(t.pPrDel,true);return m&&(d.pPrIns=m),u&&(d.pPrDel=u),Array.isArray(t.pPrChange)&&t.pPrChange.length>0&&(d.propertyChanges=t.pPrChange),t.sectPr?d.sectionProperties=t.sectPr:t.sectionBreakType&&(d.sectionProperties={sectionStart:t.sectionBreakType}),d}function En(e){let t=e[0]?.cells,n=e[e.length-1]?.cells,r=t?.[0]?.formatting?.borders;if(!t||!n||!r)return;let i={top:r.top,left:r.left,bottom:n[0]?.formatting?.borders?.bottom,right:t[t.length-1]?.formatting?.borders?.right,insideH:e.length>1?r.bottom:void 0,insideV:t.length>1?r.right:void 0},o=Object.entries(i).filter(([,a])=>a!==void 0);return o.length>0?Object.fromEntries(o):void 0}function Ln(e){let t=new Map;e.forEach((r,i)=>{let o=0;for(let a of r.cells){let l=o;if(o+=a.formatting?.gridSpan??1,a.formatting?.vMerge){let d=t.get(l)??[];d.push({rowIndex:i,cell:a}),t.set(l,d);}}});let n=r=>{r.formatting&&(delete r.formatting.vMerge,Object.keys(r.formatting).length===0&&(r.formatting=void 0));};for(let r of t.values()){let i=null,o=0,a=-1,l=()=>{i&&o<2&&n(i),i=null,o=0;};for(let d of r){let m=d.cell.formatting?.vMerge;m==="restart"?(l(),i=d.cell,o=1,a=d.rowIndex):m==="continue"&&(i&&d.rowIndex===a+1?(o+=1,a=d.rowIndex):(l(),n(d.cell)));}l();}}function Dn(e,t){let n={...bn,...t.tcPr??{}},r=t.story&&e.storyIds.has(t.story)?e.storyToBlocks(t.story):[],i={type:"tableCell",formatting:pt(n),content:r},o=n.cellMarker;if(o){let a=V(o.info,true)??{id:0,author:"Unknown"};o.kind==="ins"?i.structuralChange={type:"tableCellInsertion",info:a}:o.kind==="del"?i.structuralChange={type:"tableCellDeletion",info:a}:i.structuralChange={type:"tableCellMerge",info:a,...o.vMerge?{vMerge:o.vMerge}:{},...o.vMergeOrig?{vMergeOrig:o.vMergeOrig}:{}};}return Array.isArray(n.tcPrChange)&&n.tcPrChange.length>0&&(i.propertyChanges=n.tcPrChange),i}function Jn(e,t){let n=Array.isArray(t.rows)?t.rows:[],r=[],i=[],o=0;n.forEach((f,h)=>{let g=0;for(let k of Array.isArray(f.cells)?f.cells:[]){for(;r[h]?.[g];)g+=1;let w=k.tcPr??{},T=A(w.rowspan)||1,v=A(w.colspan)||1;i.push({row:h,col:g,rowspan:T,colspan:v,cell:Dn(e,k)});for(let P=h;P<h+T;P+=1){r[P]??(r[P]=[]);for(let I=g;I<g+v;I+=1)r[P][I]=true;}g+=v,o=Math.max(o,g);}});let a=new Map(i.map(f=>[`${f.row}-${f.col}`,f])),l=new Map;for(let f of i)for(let h=f.row;h<f.row+f.rowspan;h+=1)for(let g=f.col;g<f.col+f.colspan;g+=1)l.set(`${h}-${g}`,f);let d=n.map((f,h)=>{let g=[];for(let P=0;P<o;){let I=a.get(`${h}-${P}`);if(I){let N={...I.cell.formatting??{}};I.colspan>1?N.gridSpan=I.colspan:delete N.gridSpan,I.rowspan>1?N.vMerge="restart":N.vMerge!=="restart"&&N.vMerge!=="continue"&&delete N.vMerge,g.push({...I.cell,formatting:Object.keys(N).length>0?N:void 0}),P+=I.colspan;continue}let M=l.get(`${h}-${P}`);if(!M){P+=1;continue}let S={...M.cell.formatting??{}};M.colspan>1?S.gridSpan=M.colspan:delete S.gridSpan,S.vMerge="continue",g.push({...M.cell,content:[],formatting:S}),P+=M.colspan;}let k={...yn,...f.trPr??{}},w={type:"tableRow",formatting:ct(k),cells:g},T=V(k.trIns,true),v=V(k.trDel,true);return T?w.structuralChange={type:"tableRowInsertion",info:T}:v&&(w.structuralChange={type:"tableRowDeletion",info:v}),Array.isArray(k.trPrChange)&&k.trPrChange.length>0&&(w.propertyChanges=k.trPrChange),w});Ln(d);let m=Array.isArray(t.grid)?t.grid.filter(f=>typeof f=="number"):[],u={...hn,...t.tblPr??{},columnWidths:m.length>0?m:void 0},c=ut(u);if(!c?.borders){let f=En(d);f&&(c={...c??{},borders:f});}let y={type:"table",columnWidths:u.columnWidths||void 0,formatting:c,rows:d};return Array.isArray(u.tblPrChange)&&u.tblPrChange.length>0&&(y.propertyChanges=u.tblPrChange),y}function Un(){return {type:"paragraph",content:[{type:"run",content:[{type:"break",breakType:"page"}]}]}}function Fe(e){return e.type==="insertion"||e.type==="deletion"||e.type==="moveFrom"||e.type==="moveTo"?e.content.length>0&&e.content.every(Fe):e.type==="run"&&e.content.length>0&&e.content.every(t=>t.type==="footnoteRefMark"||t.type==="endnoteRefMark")}function Wn(e){return e.some(t=>t.type==="paragraph"&&t.content.some(Fe))}function jn(e,t){if(Wn(e))return e;let n=t.find(d=>d.type==="paragraph")?.content??[],r=n.findIndex(d=>!Fe(d)),i=n.slice(0,r<0?n.length:r);if(i.length===0)return e;let o=e.findIndex(d=>d.type==="paragraph");if(o<0)return e;let a=e[o],l=[...e];return l[o]={...a,content:[...i,...a.content]},l}function zn(e){let t=new Map,n=r=>{for(let i of r)if(i.type==="paragraph")i.paraId&&!t.has(i.paraId)&&t.set(i.paraId,i);else if(i.type==="table")for(let o of i.rows)for(let a of o.cells)n(a.content);else i.type==="blockSdt"&&n(i.content);};n(e.package.document.content);for(let r of e.package.headers?.values()??[])n(r.content);for(let r of e.package.footers?.values()??[])n(r.content);for(let r of e.package.footnotes??[])n(r.content);for(let r of e.package.endnotes??[])n(r.content);return t}function $n(e){let t=new Map,n=(r,i)=>{t.set(r,i);let o=0,a=0;for(let l of i){if(l.type==="blockSdt"){n(`${r}:sdt${a++}`,l.content);continue}if(l.type!=="table")continue;let d=o++;l.rows.forEach((m,u)=>{m.cells.forEach((c,y)=>{n(`${r}:t${d}:r${u}c${y}`,c.content);});});}};n("body",e.package.document.content);for(let[r,i]of e.package.headers??[])n(`hf:${r}`,i.content);for(let[r,i]of e.package.footers??[])n(`hf:${r}`,i.content);for(let r of e.package.footnotes??[])n(`fn:${r.id}`,r.content);for(let r of e.package.endnotes??[])n(`en:${r.id}`,r.content);return t}function Hn(e,t){let n=new Map;for(let r of t??[]){let i;try{i=e.resolveComment(String(r.id));}catch{continue}let o=new Map;for(let a of i){let l=o.get(a.story)??[];l.push(a),o.set(a.story,l);}for(let[a,l]of o){if(l.length===0)continue;let d=Math.min(...l.map(c=>c.start)),m=Math.max(...l.map(c=>c.end)),u=n.get(a)??[];u.push({id:r.id,start:d,end:m}),n.set(a,u);}}return n}function Vn(e,t){let n=0;for(let r=0;r<t.length;r+=1){let i=t[r];if(!ne(i))continue;let o=t.slice(r+1).find(d=>d.type==="paragraph"&&d.paraId&&e.some(m=>m.type==="paragraph"&&m.paraId===d.paraId)),a=o?.type==="paragraph"?e.findIndex(d=>d.type==="paragraph"&&d.paraId===o.paraId):-1,l=a>=0?a:Math.min(r+n,e.length);e.splice(l,0,i),n=Math.max(0,l-r);}return e}var Pe=class{constructor(t,n){b(this,"session",t);b(this,"storyIds");b(this,"baseParagraphs");b(this,"baseStories");b(this,"comments");this.storyIds=new Set(t.storyIds()),this.baseParagraphs=zn(n),this.baseStories=$n(n),this.comments=Hn(t,n.package.document.comments);}storyToBlocks(t){let n=[],r=this.baseStories.get(t),i=r?.filter(f=>f.type==="paragraph"),o=this.session.storySegments(t),a=this.comments.get(t)??[],l=[],d=0,m=0,u=0,c=f=>{let h=[];for(let g of a)g.start>=d&&g.start<=f&&h.push({id:g.id,kind:"start",offset:g.start-d}),g.end>=d&&g.end<=f&&h.push({id:g.id,kind:"end",offset:g.end-d});return h},y=(f,h)=>{let g=0;for(let k=0;k<f.length;k+=1)f[k]===" "&&(k>g&&l.push({kind:"text",text:f.slice(g,k),attributes:h}),l.push({kind:"embed",embedKind:"tab",payload:{},attributes:h}),g=k+1);g<f.length&&l.push({kind:"text",text:f.slice(g),attributes:h});};for(let f of o){if(f.kind==="text"){y(f.text,f.attributes),u+=f.text.length;continue}if(f.kind==="pilcrow"){let h=`${t}:p${m}`,g=f.paraId===h&&!this.baseParagraphs.has(f.paraId)?"":f.paraId;n.push(Nn(g,f.properties,l,c(u),this.baseParagraphs.get(f.paraId)??(f.paraId===h?i?.[m]:void 0))),l=[],m+=1,u+=1,d=u;continue}if(f.embedKind==="table")n.push(Jn(this,f.payload));else if(f.embedKind==="blockSdt"){let h=R(f.payload.story),g=fe(f.payload),k=h&&this.storyIds.has(h)?this.storyToBlocks(h):[],w=St(f.payload.value);if(w)try{let T=we(g,w);g=T.properties,k=T.content;}catch{}n.push({type:"blockSdt",properties:g,content:k});}else if(f.embedKind==="opaque"){let h=C(f.payload.blob);if(h?.type==="pageBreak")n.push(Un());else {let g=r?.[n.length];h?.type==="blockSdt"&&g?.type==="blockSdt"&&n.push(g);}}else l.push(f);u+=1;}return l.length>0&&n.push({type:"paragraph",content:ue(l)}),Vn(n,r??[])}};function Kn(e,t,n={}){let r=new Pe(e,t),i=c=>n.storyIds===void 0||n.storyIds.has(c),o=r.storyIds.has("body")&&i("body")?r.storyToBlocks("body"):t.package.document.content,a=t.package.headers;a&&(n.storyIds===void 0||[...a.keys()].some(c=>i(`hf:${c}`)))&&(a=new Map([...a].map(([c,y])=>{let f=`hf:${c}`;return [c,r.storyIds.has(f)&&i(f)?{...y,content:r.storyToBlocks(f)}:y]})));let l=t.package.footers;l&&(n.storyIds===void 0||[...l.keys()].some(c=>i(`hf:${c}`)))&&(l=new Map([...l].map(([c,y])=>{let f=`hf:${c}`;return [c,r.storyIds.has(f)&&i(f)?{...y,content:r.storyToBlocks(f)}:y]})));let d=(c,y)=>n.storyIds===void 0||c?.some(h=>i(`${y}${h.id}`))?c?.map(h=>{let g=`${y}${h.id}`;return r.storyIds.has(g)&&i(g)?{...h,content:jn(r.storyToBlocks(g),h.content),verbatimXml:void 0}:h}):c,m=d(t.package.footnotes,"fn:"),u=d(t.package.endnotes,"en:");return {...t,package:{...t.package,document:{...t.package.document,content:o},...a?{headers:a}:{},...l?{footers:l}:{},...m?{footnotes:m}:{},...u?{endnotes:u}:{}}}}function Jr(e,t){return !e||!t?e===t:e.anchor.story===t.anchor.story&&e.anchor.paraId===t.anchor.paraId&&e.anchor.offset===t.anchor.offset&&e.head.story===t.head.story&&e.head.paraId===t.head.paraId&&e.head.offset===t.head.offset}function Xn(){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 wt(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 qn(e){return JSON.stringify(e.map(t=>({story:t.story,startPara:t.start.paraId,startOffset:t.start.offset,endPara:t.end.paraId,endOffset:t.end.offset})))}function xt(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function Gn(e,t){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 r=n;if(!Array.isArray(r.referencedFonts)||!r.referencedFonts.every(o=>typeof o=="string"))throw new TypeError("DOCX host referencedFonts must be a string array");let i=c(r.envelope,xt(t));return {document:i.document,referencedFonts:r.referencedFonts,embeddedFonts:i.embeddedFonts,...i.fontTableRelationshipsXml===void 0?{}:{fontTableRelationshipsXml:i.fontTableRelationshipsXml}}}function Zn(e,t){let n=new Map,r=[],i=false,o=false,a=0,l=0,d=false,m=false,u,c=null,y=[],f=new Map,h=new Map,g=null,k=false,w=0,T=0,v=false,P=null,I=()=>{u=void 0,c=null;},M=()=>{if(!(o||d||l!==0)){d=true;try{for(;!o&&r.length>0;){let s=r.shift();if(!s)break;for(let[p,b]of [...n]){if(o)return;if(n.get(p)===b)try{b(s.update.slice(),s.origin);}catch{}}}}finally{d=false,o&&(r.length=0);}}},S=s=>{I(),l+=1;try{return s()}finally{l-=1,l===0&&M();}},N=s=>s?{anchor:{...s.anchor},head:{...s.head}}:null,x=s=>{m||(e.track_undo(),m=true),s!==void 0&&e.select_story(s);},Tt=()=>{i||(e.set_update_observer((s,p)=>{p!==0&&p!==1||(r.push({update:s.slice(),origin:p===0?"local":"remote"}),M());}),i=true);},Ct=()=>{!i||n.size>0||o||(r.length=0,e.clear_update_observer(),i=false);},Ye=(s,p)=>{let b=s.slice(),F=S(()=>e.open_docx(b,p)),q=Gn(F,b);return P=b,q};return {clientId:t,registerFont:s=>{v||(e.clear_measure_fonts(),v=true);let p=e.register_measure_font(s);return y.push(s.slice()),T+=1,p},clearFonts:()=>{e.clear_measure_fonts(),y.length=0,h.clear(),T+=1,v=true;},measureParagraphJson:s=>{let p=e.measure_paragraph_json(s);return h.set(s,s),p},layoutDocumentJson:s=>{let p=e.layout_document_json(s);return g=s,k=false,w+=1,p},layoutFontRequirementsJson:s=>e.layout_font_requirements_json(s),layoutDocumentWithRegionsJson:s=>{let p=e.layout_document_with_regions_json(s);return g=s,k=true,w+=1,p},layoutDocumentWithRegionsRetainedJson:s=>{let p=e.layout_document_with_regions_retained_json(s);return g=s,k=true,w+=1,p},retainedKernelInputsJson:s=>{if(s!==w)throw new Error(`retained layout revision mismatch: expected ${s}, current ${w}`);return e.retained_kernel_inputs_json()},buildDisplayListJson:s=>e.build_display_list_json(s),buildDisplayListFrame:(s,p)=>e.build_display_list_frame(s,p),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),applyInput:(s,p)=>(x(),S(()=>e.apply_input(s,p))),applyDelete:(s,p)=>(x(),S(()=>e.apply_delete(s,p))),applyInputProfiled:(s,p)=>{x();let b=S(()=>e.apply_input_profiled(s,p)),F=JSON.parse(e.apply_input_profile_json());return {frame:b,profile:F}},applyDeleteProfiled:(s,p)=>{x();let b=S(()=>e.apply_delete_profiled(s,p)),F=JSON.parse(e.apply_input_profile_json());return {frame:b,profile:F}},residentWorkerSnapshot:s=>{if(!g||!k&&f.size===0)return null;let p=e.selection(),b=s?.knownFontsRevision===T,F=null;if(s?.knownStateVector)try{F=e.encode_diff(s.knownStateVector.slice());}catch{F=null;}return {clientId:t,state:F??e.encode_state(),selection:JSON.parse(p),fonts:b?[]:y.map(q=>q.slice()),fontsRevision:T,renderInputs:[...f].map(([q,Pt])=>({story:q,env:structuredClone(Pt)})),measureInputs:[...h.values()],layoutInput:g,layoutWithRegions:k,layoutRevision:w}},residentWorkerProbe:()=>!g||!k&&f.size===0?null:{layoutRevision:w},displayHitTestRegionsJson:(s,p,b)=>e.display_hit_test_regions_json(s,p,b),displayVerticalMoveJson:(s,p,b)=>e.display_vertical_move_json(s,p,b),displayRangeRectsJson:(s,p)=>e.display_range_rects_json(s,p),displayRangeRectsRegionJson:(s,p,b,F)=>e.display_range_rects_region_json(s,p,b,F),outlineGlyphJson:(s,p)=>e.outline_glyph_json(s,p),loadState:s=>S(()=>e.load(s)),seedFromDocx:s=>Ye(s,true),openDocx:Ye,materializeDocx:()=>{let s=P,p=e.materialize_docx();return !s||p===void 0?null:b$1(p,xt(s)).document},loadStories:s=>S(()=>JSON.parse(e.load_json(JSON.stringify(s)))),encodeState:()=>e.encode_state(),encodeStateVector:()=>e.encode_state_vector(),encodeStateAsUpdate:s=>s===void 0?e.encode_state():e.encode_diff(s.slice()),applyUpdate:s=>S(()=>JSON.parse(e.apply_update_with_inference(s))),applyLocalUpdate:s=>{x(),S(()=>e.apply_local_update(s));},onUpdate:s=>{if(o)throw new Error("yrs session is destroyed");if(typeof s!="function")throw new TypeError("update listener must be a function");let p=a++;n.set(p,s),Tt();let b=true;return ()=>{b&&(b=false,n.delete(p),Ct());}},encodeStickyPosition:s=>({story:s.story,encoded:e.encode_sticky_position(s.story,s.paraId,s.offset)}),resolveStickyPosition:s=>{try{return JSON.parse(e.resolve_sticky_position(s.story,s.encoded))}catch{return null}},setSelection:(s,p=s)=>{if(s.story!==p.story)throw new Error("yrs selection must stay inside one story");e.set_selection(s.story,s.paraId,s.offset,p.paraId,p.offset),u={anchor:{...s},head:{...p}};},selection:()=>(u!==void 0||(u=JSON.parse(e.selection())),N(u)),encodeSelection:()=>{let s=JSON.parse(e.encoded_selection());return s?{story:s.story,anchor:Uint8Array.from(s.anchor),head:Uint8Array.from(s.head)}:null},resolveSelection:s=>{try{return JSON.parse(e.resolve_encoded_selection(s.story,s.anchor,s.head))}catch{return null}},setCellSelection:s=>e.set_cell_selection(JSON.stringify(s)),cellSelection:()=>JSON.parse(e.cell_selection()),beginUndoCapture:x,historyStories:()=>e.history_stories(),undo:()=>S(()=>e.undo()),redo:()=>S(()=>e.redo()),canUndo:()=>e.can_undo(),canRedo:()=>e.can_redo(),createStory:(s,p,b="Normal",F="left")=>S(()=>JSON.parse(e.create_story(s,p,b,F))),deleteStory:s=>S(()=>e.delete_story(s)),insertTable:(s,p,b,F)=>(x(s.story),S(()=>JSON.parse(e.insert_table(s.story,s.paraId,s.offset,p,b,F?.name,F?.date)))),insertRow:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.insert_row(JSON.stringify(s),p==="below",b?.name,b?.date)))),insertColumn:(s,p)=>(x(s.story),S(()=>JSON.parse(e.insert_column(JSON.stringify(s),p==="right")))),deleteRow:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.delete_row(JSON.stringify(s),p?.name,p?.date)))),deleteColumn:s=>(x(s.anchor.story),S(()=>JSON.parse(e.delete_column(JSON.stringify(s))))),deleteTable:s=>(x(s.story),S(()=>JSON.parse(e.delete_table(JSON.stringify(s))))),mergeCells:s=>(x(s.anchor.story),S(()=>JSON.parse(e.merge_cells(JSON.stringify(s))))),splitCell:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.split_cell(JSON.stringify(s),p,b)))),setCellShading:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.set_cell_shading(JSON.stringify(s),p??void 0)))),setCellTextFormat:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.set_cell_text_format(JSON.stringify(s),JSON.stringify(p))))),setCellBorders:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.set_cell_borders(JSON.stringify(s),JSON.stringify(p))))),setColumnWidth:(s,p)=>(x(s.story),S(()=>JSON.parse(e.set_column_width(JSON.stringify(s),p)))),setTableWidth:(s,p)=>(x(s.story),S(()=>JSON.parse(e.set_table_width(JSON.stringify(s),p)))),insertText:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.insert_text(s.story,s.paraId,s.offset,p,b?.name,b?.date)))),deleteRange:(s,p)=>(x(s.story),S(()=>JSON.parse(e.delete_range(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,p?.name,p?.date)))),replaceRange:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.replace_range(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,p,b?.name,b?.date)))),splitParagraph:(s,p)=>(x(s.story),S(()=>JSON.parse(e.split_paragraph(s.story,s.paraId,s.offset,p?.name,p?.date)))),mergeParagraphs:(s,p,b)=>(x(s),S(()=>JSON.parse(e.merge_paragraphs(s,p,b?.name,b?.date)))),toggleMark:(s,p)=>{x(s.story),S(()=>e.toggle_mark(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p)));},formatRange:(s,p)=>{x(s.story),S(()=>e.format_range(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p)));},setHyperlink:(s,p)=>{x(s.story),S(()=>e.set_hyperlink(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p)));},clearFormatting:s=>{x(s.story),S(()=>e.clear_formatting(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset));},applyParagraphStyle:(s,p,b)=>{x(s.story),S(()=>e.apply_paragraph_style(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,p,b?.name,b?.date));},setParagraphAttrs:(s,p,b)=>{x(s.story),S(()=>e.set_paragraph_attrs(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p),b?.name,b?.date));},insertImage:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.insert_image(s.story,s.paraId,s.offset,JSON.stringify(p),b?.name,b?.date)))),setContentControlValue:(s,p)=>{x(),S(()=>e.set_content_control_value(s,JSON.stringify(p)));},setContentControlValueAt:(s,p)=>{x(s.story),S(()=>e.set_content_control_value_at(s.story,s.paraId,s.offset,JSON.stringify(p)));},clearContentControlValue:s=>{x(),S(()=>e.clear_content_control_value(s));},setImageGeometry:(s,p)=>{x(),S(()=>e.set_image_geometry(s,JSON.stringify(p)));},insertPageBreak:s=>{x(s.story),S(()=>e.insert_page_break(s.story,s.paraId,s.offset));},insertSectionBreak:(s,p)=>{x(s.story),S(()=>e.insert_section_break(s.story,s.paraId,s.offset,p));},insertWatermark:(s,p)=>{x(s.story),S(()=>e.insert_watermark(s.story,s.paraId,s.offset,JSON.stringify(p)));},applyRawOps:(s,p)=>S(()=>e.apply_raw_ops(s,JSON.stringify(p))),applySeedRawOps:(s,p)=>S(()=>e.apply_seed_raw_ops(s,JSON.stringify(p))),setParagraphAttr:(s,p,b)=>S(()=>e.set_paragraph_attr(s,p,JSON.stringify(b??null))),addComment:(s,p,b,F)=>S(()=>JSON.parse(e.add_comment(qn(s),p,b,JSON.stringify(F??null)))),acceptChange:s=>S(()=>JSON.parse(e.accept_change(wt(s)))),rejectChange:s=>S(()=>JSON.parse(e.reject_change(wt(s)))),selectionContext:s=>{let p=JSON.stringify(s);if(c?.key===p)return JSON.parse(c.json);let b=e.selection_context(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset),F=JSON.parse(b);return c={key:p,json:b},F},listRevisions:()=>JSON.parse(e.list_revisions()),resolveComment:s=>JSON.parse(e.resolve_comment(s)),storyIds:()=>e.story_ids(),storyLength:s=>e.story_len(s),storyChecksum:s=>BigInt(e.story_checksum(s)),yrsBlocksForStory:(s,p={})=>{let b=e.yrs_blocks_for_story(s,JSON.stringify(p)),F=JSON.parse(b);return f.set(s,structuredClone(p)),F},paragraphs:s=>JSON.parse(e.paragraphs(s)),paragraphSpans:s=>JSON.parse(e.paragraph_spans(s)),storySegments:s=>JSON.parse(e.story_segments(s)),locateParagraph:(s,p)=>JSON.parse(e.locate_paragraph(s,p)),destroy:()=>{o||(o=true,n.clear(),r.length=0,i&&e.clear_update_observer(),e.free());}}}async function Ur(e){let t=e?.clientId??Xn(),n=await import('../wasm-7SOSHNGP.mjs');return await n.preloadEditWasm(),Zn(n.createEditSession(t),t)}export{ce as ResidentEngineWorkerClient,J as ResidentWorkerFailureError,Mt as canUseResidentEngineWorker,tr as compareYrsLocs,Qn as createYrsInputPositionMap,Ur as createYrsSession,er as displayPositionToYrsLoc,un as documentToYrs,Jr as sameYrsSelection,De as yrsLocToDisplayPosition,Kn as yrsToDocument};
|
|
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,a as a$2}from'../chunk-J7LNO6SM.mjs';import {a as a$3,b as b$1}from'../chunk-GD4VNJ64.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$1(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 d of [...o])d(t,n===0?"local":"remote");}),r=true);};return {registerFont:t=>e.register_measure_font(t),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 d=e.apply_input_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:d,profile:s}},applyDeleteProfiled:(t,n)=>{c();let d=e.apply_delete_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:d,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(),f=null,D=null,h=new Map,k=new Map,S=new Set,w=new Set,B=1,U=1,O={color:"#000",width:2},v=null,y=null,P=null,J=null,C=new Set,Y=null;ae.onmessage=e=>{ee=ee.then(()=>{if(Y)throw Y;return pe(e.data)}).catch(o=>{if(o instanceof WebAssembly.RuntimeError){Y=o,_({id:e.data.id,ok:false,error:`Resident engine worker trapped: ${o.message}`,terminal:true});return}_({id:e.data.id,ok:false,error:o instanceof Error?o.message:String(o)});});};async function pe(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"){v=null,y!==null&&await M(false),_({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&&(B!==e.devicePixelRatio||U!==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),B=e.devicePixelRatio,U=e.zoom,O=e.caretStyle;for(let[l,c]of h)w.has(l)||(c.width=0,c.height=0,k.delete(l),oe(l));await M(r?true:i),_({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);_({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)a.registerFont(o);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,f=null,D=null,h.clear(),k.clear(),S.clear(),w.clear(),v=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){f=u$1(f,s(o));for(let p of f.damagedPageIds)S.add(p.toString());f={...f,pages:f.pages.map(p=>({...p,primitiveIds:p.primitiveIds.slice()}))};let n=a?.residentCaretSnapshot();if(!n||!b(n,f))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 d=a?.selection()??null;v=t?n.caretRect??null:null;let s$1=new Set(f.pages.map(p=>p.pageId.toString()));for(let p of S)s$1.has(p)||S.delete(p);for(let p of h.keys())s$1.has(p)||(h.delete(p),k.delete(p),oe(p));let F=performance.now(),{replayedPages:W,caretPainted:A}=await M(false),b$1=performance.now()-F,I=j(o),g=i.map(j),m=a?j(a.encodeStateVector()):void 0;_({id:e,ok:true,frame:I,updates:g,engineMs:r,workerTotalMs:performance.now()-c,engineProfile:l,caret:n,selection:d,caretPainted:A,replayMs:b$1,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(!f||h.size===0)return {replayedPages:0,caretPainted:false};!D&&a&&(D=new a$1({provider:(n,d)=>a.outlineGlyphJson(n,d)}));let r=v&&w.has(v.pageId)?v:null,i$1=r?a$2(r,O,B,U):null,l=r&&i$1?`${r.pageId}|${i$1.x}|${i$1.y}|${i$1.width}|${i$1.height}|${O.color}`:null,c=[];for(let n=0;n<f.pages.length;n+=1){let s=f.pages[n].pageId.toString();if(!w.has(s))continue;let F=S.has(s),W=s===r?.pageId&&!(y===s&&P===l),A=s===y&&s!==r?.pageId;if(!F&&!W&&!A)continue;let b=h.get(s),I=f.displayList.pages[n];if(!b||!I)continue;let g$1=s,m=k.get(g$1);m||(m=new OffscreenCanvas(1,1),k.set(g$1,m));let p=m;if(!F&&C.has(g$1)){c.push(Promise.resolve({canvas:b,buffer:p,pageId:g$1}));continue}c.push(g(p,I,{glyphCache:D??void 0},B,U).then(()=>({canvas:b,buffer:p,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:d,pageId:s}of R)r&&i$1&&s===r.pageId?(J||(J=new OffscreenCanvas(1,1)),j$1(n,d,J,{...i$1,color:O.color}),C.add(s),y=s,P=l,t=true):(i(n,d),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 _(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",
|