@betteroffice/xlsx 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSES/MIT-ruzstd.txt +21 -0
- package/LICENSES/MIT-twox-hash.txt +21 -0
- package/LICENSES/MIT-wuff.txt +20 -0
- package/README.md +45 -10
- package/dist/chunk-3HDY7PGX.js +1 -0
- package/dist/chunk-4YUSZI3G.js +2 -0
- package/dist/chunk-6OSHYRMV.js +1 -0
- package/dist/chunk-AZDGFDN2.js +1 -0
- package/dist/chunk-B5K4E4KI.js +1 -0
- package/dist/chunk-E4HKBJOP.js +7 -0
- package/dist/chunk-FEO7P5TH.js +1 -0
- package/dist/chunk-GHET7GIK.js +1 -0
- package/dist/chunk-JABP2QRG.js +1 -0
- package/dist/chunk-K2GIAESV.js +2 -0
- package/dist/chunk-KNQOCV7P.js +1 -0
- package/dist/chunk-OUNTNO7R.js +1 -0
- package/dist/chunk-QUHWI3QK.js +1 -0
- package/dist/chunk-S6UYP4BX.js +1 -0
- package/dist/chunk-T4GUPT57.js +1 -0
- package/dist/chunk-VJDPZ75R.js +1 -0
- package/dist/chunk-X5HR6GJB.js +4 -0
- package/dist/collaboration.js +1 -1
- package/dist/{editPeer-DN6JDr8Z.d.ts → editPeer-CVhOkqsr.d.ts} +732 -365
- package/dist/generated/preflight/xlsx_preflight_bg.wasm +0 -0
- package/dist/generated/xlsx_wasm_bg.wasm +0 -0
- package/dist/generated/xlsx_wasm_lean_bg.wasm +0 -0
- package/dist/headless.d.ts +8 -2
- package/dist/headless.js +1 -1
- package/dist/index.d.ts +27 -5
- package/dist/index.js +1 -4
- package/dist/sessionWorker.missing.d.ts +3 -0
- package/dist/sessionWorker.missing.js +1 -0
- package/dist/sessionWorker.node.d.ts +3 -0
- package/dist/sessionWorker.node.js +1 -0
- package/dist/{types-DdoEoFSX.d.ts → types-BXjmeL2E.d.ts} +71 -3
- package/dist/wasm-preflight.d.ts +26 -0
- package/dist/wasm-preflight.js +1 -0
- package/dist/worker.d.ts +3 -3
- package/dist/worker.js +1 -1
- package/dist/xlsxSessionWorker.mjs +7 -1
- package/dist/xlsxSessionWorker.node.mjs +1 -0
- package/dist/xlsxWorkerStart.d.ts +11 -0
- package/dist/xlsxWorkerStart.js +1 -0
- package/package.json +20 -6
- package/dist/chunk-DIDVDN7H.js +0 -1
- package/dist/chunk-HJJEOLPD.js +0 -1
- package/dist/chunk-JGTBRHCP.js +0 -1
- package/dist/chunk-K7TMSGNA.js +0 -1
- package/dist/chunk-SXM2HKJL.js +0 -4
- /package/dist/{xlsxSessionWorker.d.ts → xlsxSessionWorker.node.d.ts} +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 Moritz Borcherding
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2015 Jake Goulding
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Copyright (c) 2013-2017 by the WOFF2 Authors.
|
|
2
|
+
Copyright (c) 2025 by Nico Burns.
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in
|
|
12
|
+
all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
16
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
17
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
18
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
19
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
20
|
+
THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -34,6 +34,11 @@ export async function updateWorkbook(bytes: Uint8Array): Promise<Uint8Array> {
|
|
|
34
34
|
Cell input parses text, numbers, booleans, and formulas;
|
|
35
35
|
formulas start with `=`. Editing a cell recalculates its dependents.
|
|
36
36
|
|
|
37
|
+
On a protected sheet, `editCell`, `editCells`, `patchRangeStyle`, `setNumberFormat`,
|
|
38
|
+
`applyFormat`, `moveChart` and `resizeChart` throw for locked cells, formats and chart moves and resizes the protection
|
|
39
|
+
forbids, as Excel does. Pass `{ protectedSheets: 'allow' }` as their last argument to write
|
|
40
|
+
through the protection, which stays in the file; a collaborative workbook refuses it.
|
|
41
|
+
|
|
37
42
|
## Entry points
|
|
38
43
|
|
|
39
44
|
These entry points are exported from `@betteroffice/xlsx`:
|
|
@@ -41,6 +46,7 @@ These entry points are exported from `@betteroffice/xlsx`:
|
|
|
41
46
|
| entry point | description |
|
|
42
47
|
| --- | --- |
|
|
43
48
|
| `initWasm(input?)` | Initialize the engine; concurrent calls share initialization. |
|
|
49
|
+
| `decodeFontFace(bytes, { codec, dict?, maxOutput? })` | Asynchronously decode a packed font with the selected engine into `{ font, payload? }` ArrayBuffers; rejects on invalid options or decode errors without retrying another decoder. |
|
|
44
50
|
| `openWorkbook(bytes, options?)` | Open XLSX bytes as a synchronous `WorkbookHandle` after initialization. |
|
|
45
51
|
| `openWorkbookSession(bytes, options?)` | Open a workbook in a dedicated worker with asynchronous access. |
|
|
46
52
|
| `paintDisplayList(ctx, frame, dpr, origin?)` | Paint a display list onto a canvas 2D context. |
|
|
@@ -84,20 +90,42 @@ or WASM loader.
|
|
|
84
90
|
references in one undo step; the destination is the new top-left cell. Surface errors when a move is
|
|
85
91
|
refused rather than discarding the source workbook.
|
|
86
92
|
|
|
93
|
+
## Filling a range
|
|
94
|
+
|
|
95
|
+
`workbook.fillRange(sheet, source, destination)` copies the A1 source block over the complete
|
|
96
|
+
destination rectangle as one undo step. `destination` includes the source and must start at its
|
|
97
|
+
top-left corner; cells outside the source are filled by tiling the source block. Values, cached
|
|
98
|
+
formula results, and styles are copied, and formulas are translated by their relative offset with
|
|
99
|
+
`$` references kept. This is copy tiling only — there is no series or trend detection. Array
|
|
100
|
+
formulas, merged cells, Excel tables, charts anchored in either rectangle, hyperlinks, conditional
|
|
101
|
+
formats covering only part of the filled cells, and sheets whose file keeps comments, data
|
|
102
|
+
validations or extension rules are refused before the workbook changes, so surface the error and
|
|
103
|
+
keep the selection where it was.
|
|
104
|
+
|
|
87
105
|
## Printing and PNG export
|
|
88
106
|
|
|
89
107
|
`workbook.printDisplayList(sheet, range, metrics, gridlines)` renders an A1 range using `PrintMetrics`
|
|
90
108
|
measured from the workbook's normal font. The caller chooses paper size, margins, and pagination;
|
|
91
109
|
`paintDisplayList` accepts an optional origin in backing-store pixels for positioning the result.
|
|
92
110
|
|
|
93
|
-
`workbook.renderPng(viewport)`
|
|
94
|
-
|
|
95
|
-
|
|
111
|
+
`await workbook.renderPng({ sheet, viewport })` draws a viewport of a sheet, and
|
|
112
|
+
`await workbook.renderPng({ sheet, range })` a cell range, as PNG bytes. `sheet` is a zero-based index or
|
|
113
|
+
a tab name; `range` is an A1 string, `{ kind: 'a1', a1 }`, zero-based `{ kind: 'rowCol', start, end }`, or `'used'`
|
|
114
|
+
for the sheet's used range at call time.
|
|
115
|
+
Options are `{ scale, maxWidth, maxHeight, signal, fonts }`. The editor's painter draws on a canvas. Without
|
|
116
|
+
`fonts`, it loads the bundled faces `@betteroffice/xlsx-native` draws the sheet's fonts with, so both engines
|
|
117
|
+
match, and rejects if one fails to load. A `fonts` list, even an empty one, replaces the bundled faces: a family it
|
|
118
|
+
does not cover is painted with the engine's built-in substitute, whose pixels differ between the canvas and native
|
|
119
|
+
engines. A supplied face that fails to load rejects with `PngExportError` code `font-unavailable`. Without a canvas, it rejects with
|
|
120
|
+
code `canvas-unavailable`; use `@betteroffice/xlsx-native` for PNG export in that environment.
|
|
121
|
+
`isPngExportAvailable()` reports whether PNG export can run.
|
|
96
122
|
|
|
97
123
|
## Worker sessions
|
|
98
124
|
|
|
99
|
-
|
|
100
|
-
|
|
125
|
+
Node.js >= 20.16 / 22.3 runs worker sessions on `worker_threads`, keeping the process alive until the session is disposed.
|
|
126
|
+
|
|
127
|
+
The low-level `openWorkbookSession` API (also exported from `@betteroffice/xlsx/worker`) can
|
|
128
|
+
change in minor releases. It returns a `WorkbookSession` with
|
|
101
129
|
promise-returning operations through `session.call`, plus asynchronous `session.save()` and
|
|
102
130
|
`session.dispose()` methods.
|
|
103
131
|
|
|
@@ -109,7 +137,8 @@ The React editor uses a worker by default and exposes its own asynchronous API.
|
|
|
109
137
|
`workbook.propose(agentId, note, edits)` stages cell edits for review without applying them.
|
|
110
138
|
`listProposals`, `acceptProposal`, and `rejectProposal` manage that queue; acceptance applies the
|
|
111
139
|
proposal as one undo step and recalculates dependents. Check `isProposalsAvailable()` first;
|
|
112
|
-
acceptance throws `StaleProposalError` if targeted cells have changed since staging.
|
|
140
|
+
acceptance throws `StaleProposalError` if targeted cells have changed since staging. Listed proposals
|
|
141
|
+
name those cells in `staleTargets`, so a host can warn before accepting.
|
|
113
142
|
|
|
114
143
|
## Version-checked edit batches
|
|
115
144
|
|
|
@@ -132,10 +161,16 @@ to a binary transport. See the [collaboration guide](https://docs.betteroffice.d
|
|
|
132
161
|
for provider lifecycle, transport setup, and shared starting state.
|
|
133
162
|
|
|
134
163
|
Open the workbook with `openWorkbook(bytes, { collaborative: true })`. Collaborative workbooks
|
|
135
|
-
synchronize cell content, formulas, styles, column widths and row heights,
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
164
|
+
synchronize cell content, formulas, styles, column widths and row heights, row and column
|
|
165
|
+
visibility, freeze panes, merged cells, single hyperlinks, chart positions, defined names,
|
|
166
|
+
conditional formats, auto filters and sheets added at the end, with local undo and redo whose
|
|
167
|
+
effects synchronize.
|
|
168
|
+
|
|
169
|
+
Other structural edits are refused without changing the workbook: `applyOps` throws and editor
|
|
170
|
+
sessions report the command as refused with reason `unsupported`. That covers inserting or deleting
|
|
171
|
+
rows and columns, adding a sheet anywhere but the end, removing, moving or renaming sheets and chart
|
|
172
|
+
edits beyond moving a chart. See the
|
|
173
|
+
[collaboration guide](https://docs.betteroffice.dev/docs/collaboration#xlsx-limits) for the reasons.
|
|
139
174
|
|
|
140
175
|
## Operation profiles
|
|
141
176
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {h,d,k as k$1,a}from'./chunk-E4HKBJOP.js';import'./chunk-VJDPZ75R.js';import'./chunk-S6UYP4BX.js';import'./chunk-JABP2QRG.js';import'./chunk-O2XFH626.js';function S(t){return t instanceof Error&&t.diagnostic?.reason==="cdn-unavailable"}function k({diagnostic:t}){typeof globalThis.dispatchEvent=="function"&&typeof CustomEvent=="function"&&globalThis.dispatchEvent(new CustomEvent("betteroffice:font-pack-diagnostic",{detail:{...t}}));}var E,A=()=>E??(E=d().catch(t=>{throw E=void 0,t}));async function I(t,n,e){let l=await n(t.resolveBundledFamilyFace(e.family,e.bold,e.italic));if(l)return l;let s=await n(t.resolveGlyphFallbackFace(e.family,e.bold,e.italic,"word"));return s||(await n(t.resolveLastResortChoice(e.family,e.bold,e.italic,"word").face)??t.BASE_LATIN_FONTS.find(r=>r.weight===700===e.bold&&r.style==="italic"===e.italic))}var C=(t,n)=>t.family===n.family&&t.weight===n.weight&&t.style===n.style;async function L(t,n,{font:e,scripts:l}){let s=[],o=d=>{d&&!s.some(u=>C(u,d))&&s.push(d);},r=await n(t.resolveBundledFamilyFace(e.family,e.bold,e.italic));o(r);for(let d of l)o(await n(t.resolveScriptFallbackFace(d,e.bold,e.italic,e.family)));o(await n(t.resolveGlyphFallbackFace(e.family,e.bold,e.italic,"word")));let c=t.resolveLastResortChoice(e.family,e.bold,e.italic,"word");return (!c.onlyIfPrimaryFails||!r)&&o(await n(c.face)),s}async function M(t,n,e){let l=new Set(e.filter(o=>o.scripts.length).map(o=>h(o.font))),s=new Map;for(let o of e){let r=h(o.font),c=s.get(r)??{font:o.font,faces:[]};if(s.set(r,c),!l.has(r)){c.faces.length||c.faces.push(await I(t,n,o.font));continue}for(let d of await L(t,n,o))c.faces.some(u=>C(u,d))||c.faces.push(d);}for(let o of s.values())o.faces.length||o.faces.push(await I(t,n,o.font));return s}async function N(t,n,e=new Set){n?.throwIfAborted();let l=A().then(async r=>{let c=new Set,d=async i=>i&&!c.has(i.file)&&await r.bundledFaceInstalled(i).catch(()=>true)?i:void 0,u=async(i,f)=>{try{let a=new Uint8Array(await r.loadBundledFontBytes(i,void 0,{decoder:k$1,strict:!0})),F={bold:i.weight===700,italic:i.style==="italic"};return {family:i.family,...F,bytes:a,face:F}}catch(a$1){if(S(a$1)&&(a$1.diagnostic.pack==="cjk"||a$1.diagnostic.pack==="intl")){c.add(i.file),e.has(a$1)||(e.add(a$1),k(a$1));return}let F=a$1 instanceof Error?a$1.message:String(a$1);throw new a("font-unavailable",`${i.family} for ${f} could not load: ${F}`)}},g=new Map,R=(i,f)=>{let a=g.get(i.file);return a||(a=u(i,f),g.set(i.file,a)),a};for(;;){let i=await M(r,d,t),f=c.size,a=[],F=new Map;if(await Promise.all([...i].map(async([y,{font:p,faces:D}])=>{let[w,...x]=await Promise.all(D.map(h=>R(h,p.family)));w&&a.push({...w,family:p.family,bold:p.bold,italic:p.italic});let b=x.filter(h=>h!==void 0);b.length&&F.set(y,b);})),c.size===f)return {faces:a,fallbacks:y=>[...F.get(h(y))??[]]};n?.throwIfAborted();}});if(!n)return l;let s,o=new Promise((r,c)=>{s=()=>c(n.reason),n.addEventListener("abort",s,{once:true});});l.catch(()=>{});try{return await Promise.race([l,o])}finally{n.removeEventListener("abort",s);}}export{N as defaultSheetFaces};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {l,h,o,L,r,e,d,a,G as G$1,c as c$1,K,i,t,w as w$1,v,u as u$1,J,f,g as g$1,B as B$1,H,x as x$1,D,z as z$1,C as C$1,I,A as A$1,y,F}from'./chunk-K2GIAESV.js';import {c,g,C,o as o$1,u,A,z,s,w,k,p,l as l$1,B,n,x,j,v as v$1,e as e$1}from'./chunk-E4HKBJOP.js';import {b,a as a$1}from'./chunk-VJDPZ75R.js';import {a as a$4}from'./chunk-S6UYP4BX.js';import {a as a$3,c as c$2,d as d$1}from'./chunk-JABP2QRG.js';import {a as a$2}from'./chunk-O2XFH626.js';async function Xe(t){let e=await fetch(t);if(typeof WebAssembly.compileStreaming=="function")try{return await WebAssembly.compileStreaming(e.clone())}catch(o){if(!e.ok||!["basic","cors","default"].includes(e.type)||e.headers.get("Content-Type")==="application/wasm")throw o}return WebAssembly.compile(await e.arrayBuffer())}async function Yt(t){let e=a$4(t);return e?WebAssembly.compile(e):Xe(t)}function Je(t){return typeof Worker=="function"?Xe(t):Yt(t)}async function Et(t){let e=new Response(t,{headers:{"Content-Type":"application/wasm"}});return typeof WebAssembly.compileStreaming=="function"?WebAssembly.compileStreaming(e):WebAssembly.compile(await e.arrayBuffer())}function Qe(t,e,o,c=Xe){let a,s,r=false;function d(){return a||(a=c(e),a.catch(()=>{})),a}return t.listen(u=>{if(!h(u)||u.kind!=="wasm-compile")return;if(u.pending){if(!a){a=new Promise(y=>{s=y;}),a.catch(()=>{});try{t.post({protocol:1,kind:"wasm-accept"});}catch{}}return}let S=s;if(s=void 0,S){let y=u.stream?Et(u.stream):u.bytes?WebAssembly.compile(u.bytes):c(e);y.catch(()=>{}),S(y);}else u.stream||u.bytes?a?u.stream?.cancel().catch(()=>{}):(a=u.stream?Et(u.stream):WebAssembly.compile(u.bytes),a.catch(()=>{})):d();}),async u=>{if(u!==void 0)return o(u);let S=d(),y;try{y=await S;}catch(b){throw a===S&&(a=void 0),b}if(await o(y),!r){r=true;let b={protocol:1,kind:"wasm-module",url:e.href,module:y};try{t.post(b);}catch{}}}}function xt(t){for(;;){let e=t();if(!JSON.parse(e).conditionalPending)return e}}var eo=256,to=64,oo=128,ke={cells:1e5},Te=1048576,At=16*1024*1024;function pe(t,e,o,c=false){let a=r=>{let d=o[e.indexOf(r)];if(c&&d===void 0)throw new J("target-sheet-missing");return d??r},s=r=>Array.isArray(r)?r.map(s):!r||typeof r!="object"?r:Object.fromEntries(Object.entries(r).map(([d,u])=>[d,d==="sheetId"&&typeof u=="string"?a(u):(d==="sheetIds"||d==="changedSheets")&&Array.isArray(u)?u.map(a):s(u)]));return s(t)}function ro(t){let e="";for(let o=t+1;o>0;o=Math.floor((o-1)/26))e=String.fromCharCode(65+(o-1)%26)+e;return e}function fe(t){if(!Number.isSafeInteger(t.row)||t.row<0||t.row>=1048576||!Number.isSafeInteger(t.col)||t.col<0||t.col>=16384)throw new J("missing-target");return `${ro(t.col)}${t.row+1}`}function qe(t){if(t.kind==="rowCol"){if(fe(t.start),fe(t.end),t.start.row>t.end.row||t.start.col>t.end.col)throw new J("missing-target");return {start:t.start,end:t.end}}let e=/^\$?([A-Za-z]+)\$?([1-9]\d*)(?::\$?([A-Za-z]+)\$?([1-9]\d*))?$/.exec(t.a1);if(!e)throw new J("missing-target");let o=(c,a)=>{let s=0;for(let d of c.toUpperCase())s=s*26+d.charCodeAt(0)-64;let r={row:Number(a)-1,col:s-1};return fe(r),r};return qe({kind:"rowCol",start:o(e[1],e[2]),end:o(e[3]??e[1],e[4]??e[2])})}function G(t,e,o=t.sheetInfo().sheetIds){let c=o.indexOf(e.sheetId);if(c<0)throw new J("target-sheet-missing");let{start:a,end:s}=qe(e.range);return {sheet:c,start:a,end:s,range:`${fe(a)}:${fe(s)}`}}function It(t,e,o){let{start:c,end:a}=G(t,o,e.sheetIds);if(o.activeCell&&(fe(o.activeCell),o.activeCell.row<c.row||o.activeCell.row>a.row||o.activeCell.col<c.col||o.activeCell.col>a.col))throw new J("missing-target")}function Re(t,e,o,c=t.sheetInfo().sheetIds){let a=c[e];if(a===void 0)throw new J("missing-target");let s={sheetId:a,range:o};return G(t,s,c),s}function Ot(t,e,o,c,a=t.sheetInfo().sheetIds){return Re(t,e,{kind:"rowCol",start:{row:o,col:c},end:{row:o,col:c}},a)}function Ge(t,e,o){if(!e.editableSheets||e.catalogDirty){let b=t.readCells({ranges:[]});if(!b.ok)throw new Error(b.failure.message);e.editableSheets=b.sheets.map(q=>q.editable);}let c=t.version(),a=new TextEncoder,s=a.encode(JSON.stringify({expectVersion:c,steps:[]})).length,r=[],d=0,u=0,S=s,y=()=>{if(r.length===0)return;let b=t.validateEdits({expectVersion:c,steps:r});if(!b.ok)throw new J(b.failure.code,b);r=[],d=u=0,S=s;};for(let b of o){let{start:q,end:v}=qe(b.target.range),l=(v.row-q.row+1)*(v.col-q.col+1),m=b.op==="setCellInputs"?b.inputs.flat().reduce((R,P)=>R+P.length,0):0,H=e.editableSheets[G(t,b.target,e.info?.sheetIds).sheet]?{op:"patchStyle",target:b.target,patch:{}}:b,A=a.encode(JSON.stringify(H)).length+1;if((r.length===oo||d+l>ke.cells||u+m>Te||S+A>At)&&y(),l>ke.cells||m>Te||S+A>At)throw new J("limit-exceeded");r.push(H),d+=l,u+=m,S+=A;}y();}function Pt(t,e,o=t.sheetInfo().sheetIds){let c=new Map;for(let d of e)Ot(t,d.sheet,d.row,d.col,o),c.set(`${d.sheet}:${d.row}:${d.col}`,d);let a=[...c.values()].sort((d,u)=>d.sheet-u.sheet||d.row-u.row||d.col-u.col),s=[],r=new Map;for(let d=0;d<a.length;){let u=a[d++],S=u,y=[u.input],b=u.input.length;for(;d<a.length&&a[d].sheet===u.sheet&&a[d].row===u.row&&a[d].col===S.col+1&&y.length<ke.cells&&b+a[d].input.length<=Te;)S=a[d++],y.push(S.input),b+=S.input.length;let q=`${u.sheet}:${u.col}:${S.col}`,v=r.get(q);if(v?.step.target.range.kind==="rowCol"&&v.step.target.range.end.row===u.row-1&&v.cells+y.length<=ke.cells&&v.text+b<=Te)v.step.target.range.end.row=u.row,v.step.inputs.push(y),v.cells+=y.length,v.text+=b;else {let l={op:"setCellInputs",target:Re(t,u.sheet,{kind:"rowCol",start:{row:u.row,col:u.col},end:{row:u.row,col:S.col}},o),inputs:[y]};s.push(l),r.set(q,{step:l,cells:y.length,text:b});}}return s}function Ze(t,e,o){try{return t.captureFormat(e,o)}catch(c){throw c instanceof Error&&!a$1(c)&&/^sheet \d+ is not an editable worksheet$/.test(c.message)?new J("unsupported"):c}}function Me(t,e,o){let c=G(t,Re(t,e,{kind:"a1",a1:o})),a=t.readCells({ranges:[]});if(!a.ok)throw new Error(a.failure.message);if(!a.sheets[e].editable)throw Ze(t,e,"A1"),new J("locked-target");if((c.end.row-c.start.row+1)*(c.end.col-c.start.col+1)>1e5)throw new J("limit-exceeded")}function so(t,e){if(e.end.row<c$2-1&&e.end.col<d$1-1)return e;let o=t.selectionData(e.sheet,0,0,"usedRange").usedRange;if(!o)return null;let c={row:Math.max(e.start.row,o.top),col:Math.max(e.start.col,o.left)},a={row:Math.min(e.end.row,o.bottom),col:Math.min(e.end.col,o.right)};return c.row>a.row||c.col>a.col?null:{...e,start:c,end:a,range:`${fe(c)}:${fe(a)}`}}function no(t,e,o){if(o.kind==="select"||o.kind==="setReadOnly"||o.kind==="applyUpdate"||o.kind==="collabPipe")throw new J("invalid-command");let c=o.payload;if(o.kind==="applyOps"&&"toolbar"in c){let{toolbar:r}=c;if(!r.target)throw new J("invalid-command");let d=G(t,r.target,e.sheetIds),u=r.id==="clear"?so(t,d):d;if(!u)return {method:"editCells",args:[d.sheet,[]]};if(r.id==="clear"&&(u.end.row-u.start.row+1)*(u.end.col-u.start.col+1)>ke.cells)throw new J("limit-exceeded");r.id!=="clear"&&Me(t,u.sheet,u.range);let S=r.id==="clear"?{}:t.selectionFormatting(u.sheet,u.range),y=r.id==="merge"?t.mergedRanges(u.sheet,u.range):[],b=F(r,u,S,y);if(!b)throw new J("invalid-command");return b}if(o.kind==="applyFormat"&&"formatToken"in c){let r=e.formats.get(c.formatToken);if(!r)throw new J("invalid-command");let d=G(t,c.target,e.sheetIds);return {method:"applyFormat",args:[d.sheet,d.range,r]}}if(o.kind==="applyFormat"&&"capturedFrom"in c){let r=G(t,c.target,e.sheetIds),d=G(t,c.capturedFrom,e.sheetIds);if((d.end.row-d.start.row+1)*(d.end.col-d.start.col+1)>1e5)throw new J("limit-exceeded");return {method:"applyFormat",args:[r.sheet,r.range,Ze(t,d.sheet,d.range)]}}if(!("args"in c))throw new J("invalid-command");let a={method:o.kind,args:[...c.args],calculation:c.calculation},s=()=>{if(e.bases.get(o.basis.version)!==e.sheetRevision)throw new J("stale-target")};if(a.method==="applyOps"){let r=[...e.sheetIds],d=e.nextSheetId;return a.args[0]=a.args[0].map(u=>{let{target:S=c.target,...y}=u;if(S){let b=G(t,S,r);if(y.type==="removeSheet")y.index=b.sheet;else if(y.type==="moveSheet")y.from=b.sheet;else if("sheet"in y)y.sheet=b.sheet;else throw new J("invalid-command")}else if(("sheet"in y||"index"in y||typeof y.scope=="number"||y.type==="moveSheet"||y.type==="setDefinedNames"||y.type==="restoreSheet"||y.type==="setTables")&&(s(),r.length!==e.sheetIds.length||r.some((b,q)=>b!==e.sheetIds[q])))throw new J("stale-target");if(y.type==="addSheet")r.splice(y.index,0,`command-sheet:${d++}`);else if(y.type==="removeSheet")r.splice(y.index,1);else if(y.type==="moveSheet"){let[b]=r.splice(y.from,1);r.splice(y.to,0,b);}return y}),a}if(a.method==="propose")return a.args[2]=a.args[2].map(r=>{let{target:d=c.target,...u}=r;return d?u.sheet=G(t,d,e.sheetIds).sheet:s(),u}),a;if(c.target){let r=G(t,c.target,e.sheetIds);switch(a.method){case "editCell":if(r.start.row!==r.end.row||r.start.col!==r.end.col)throw new J("invalid-command");a.args=[r.sheet,r.start.row,r.start.col,a.args[3]];break;case "editCells":a.args[0]=r.sheet;break;case "patchRangeStyle":case "setNumberFormat":case "applyFormat":a.args[0]=r.sheet,a.args[1]=r.range;break;case "setActiveSheet":a.args[0]=r.sheet;break;case "moveChart":case "resizeChart":case "moveRange":case "fillRange":a.args[0]=r.sheet;break;default:throw new J("invalid-command")}}else ["editCell","editCells","patchRangeStyle","setNumberFormat","applyFormat","setActiveSheet","moveChart","resizeChart","moveRange","fillRange"].includes(a.method)&&s();return a}function io(t,e,o){switch(o.method){case "applyEdits":if(o.args[0].expectVersion!==t.version())throw new J("stale-version");for(let c of o.args[0].steps)G(t,c.target,e.sheetIds);o.args[0]=pe(o.args[0],e.sheetIds,t.sheetInfo().sheetIds);break;case "editCell":{let[c,a,s,r]=o.args;Ge(t,e,[{op:"setCellInputs",target:Ot(t,c,a,s,e.info?.sheetIds),inputs:[[r]]}]);break}case "editCells":{let[c,a]=o.args;Ge(t,e,Pt(t,a.map(s=>({...s,sheet:c})),e.info?.sheetIds));break}case "applyOps":for(let c of o.args[0]){let a=c,s=a.type==="setColWidth"?a.width:a.type==="setRowHeight"?a.height:void 0,r=a.type==="setColWidth"?255:409.5;if(s!=null&&(typeof s!="number"||!Number.isFinite(s)||s<0||s>r))throw new J("invalid-step")}break;case "patchRangeStyle":case "setNumberFormat":Me(t,o.args[0],o.args[1]);break;case "propose":if(!t.isProposalsAvailable())throw new J("unsupported");Ge(t,e,Pt(t,o.args[2],e.info?.sheetIds));break;case "acceptProposal":if(!t.isProposalsAvailable())throw new J("unsupported");if(!t.listProposals().some(c=>c.id===o.args[0]))throw new J("missing-target");break;case "applyFormat":if(Me(t,o.args[0],o.args[1]),o.args[2].rows===0||o.args[2].columns===0||o.args[2].formats.length!==o.args[2].rows*o.args[2].columns)throw new J("invalid-command");break;case "setActiveSheet":case "moveChart":case "resizeChart":case "moveRange":Re(t,o.args[0],{kind:"a1",a1:"A1"});break;case "fillRange":{let[c,a,s]=o.args,r=Re(t,c,{kind:"a1",a1:a});G(t,{sheetId:r.sheetId,range:{kind:"a1",a1:s}},e.sheetIds);let d=qe({kind:"a1",a1:a}),u=qe({kind:"a1",a1:s});if(d.start.row!==u.start.row||d.start.col!==u.start.col||u.end.row<d.end.row||u.end.col<d.end.col)throw new J("invalid-step");if((u.end.row-u.start.row+1)*(u.end.col-u.start.col+1)>ke.cells)throw new J("limit-exceeded");break}}}function ao(t){if(/^(?:chart |anchor \d+ of )/.test(t)||t==="range move cannot safely preserve charts"||t==="fill cannot safely preserve charts anchored in the filled range")return "chart";if(t==="range move cannot safely preserve Excel tables"||t==="fill cannot safely preserve Excel tables"||/^cannot move sheet \d+ tracks: table .+ covers the moved tracks$/.test(t))return "table";if(t==="fill cannot safely preserve hyperlinks"||t==="fill cannot safely preserve comments"||t==="fill cannot safely preserve data validations"||t==="fill cannot safely preserve conditional formats")return "fill";let e=/^(.+?) references cells this (?:edit would move|move would relocate), and it cannot be rewritten$/.exec(t)?.[1].toLowerCase().replace(/^\//,"");return e?e.startsWith("xl/charts/")||e.startsWith("xl/drawings/")?"chart":e.startsWith("xl/tables/")?"table":e.startsWith("xl/pivottables/")||e.startsWith("xl/pivotcache/")?"pivot":"other":"other"}function Fe(t){let e={failure:{code:"unsupported",cause:ao(t),message:t}};return new J("unsupported",e)}function Ft(t,e){if(t instanceof J)return t;if(e==="acceptProposal"&&t instanceof l$1)return new J("stale-proposal",{cells:t.cells,targets:t.targets});if(!(!(t instanceof Error)||a$1(t))){if(/^(?:[A-Z]+[1-9]\d* is locked on protected sheet |sheet [\s\S]+ is protected$)/.test(t.message))return new J("locked-target",{ok:false,failure:{code:"locked-target",message:t.message}});if(e==="applyOps"&&(t.message==="structural operations are unavailable in collaborative mode"||t.message==="collaborative sheets can only be added at the end of the workbook"))return new J("unsupported");if(t.message==="calculation context is unavailable for collaborative workbooks")return new J("unsupported");if(e==="undo"&&t.message==="undo would remove a sheet that holds collaborators' edits")return new J("unsupported");if(["applyOps","patchRangeStyle","setNumberFormat","applyFormat","propose","acceptProposal"].includes(e??"")&&t.message==="number format table is full")return new J("limit-exceeded");if(e==="applyOps"&&(t.message==="invalid collaborative workbook state: too many sheet merge edits"||t.message==="invalid collaborative workbook state: too many sheet hyperlink edits"))return new J("limit-exceeded");if(e==="applyOps"&&(/^formula at sheet \d+, [A-Z]+[1-9]\d* cannot be safely rewritten$/.test(t.message)||/^(?:defined name|chart reference in) .+ cannot be safely rewritten$/.test(t.message)||/^.+ references cells this edit would move, and it cannot be rewritten$/.test(t.message)||/^anchor \d+ of .+ is held by two sheets that disagree on where it sits$/.test(t.message)||/^chart .+ cannot change how it follows a grid edit$/.test(t.message)||/^chart .+ cannot be resized: a one-cell extent is not written back$/.test(t.message)||/^chart .+ cannot change its anchor kind$/.test(t.message)||/^cannot move sheet \d+ tracks: .+$/.test(t.message))||e==="resizeChart"&&/^(?:chart .+ is pinned to the sheet and cannot be resized|chart .+ cannot be resized: a one-cell extent is not written back|chart .+ cannot be resized to that size)$/.test(t.message)||e==="moveRange"&&(/^range move cannot safely preserve .+$/.test(t.message)||/^.+ contains worksheet features a cell move cannot safely preserve$/.test(t.message)||/^.+ references cells this move would relocate, and it cannot be rewritten$/.test(t.message))||e==="fillRange"&&/^fill cannot safely preserve .+$/.test(t.message))return Fe(t.message);if(e==="applyOps"&&/^chart frame .+ does not hold the chart part and anchor this op was recorded against; its drawing has changed$/.test(t.message))return new J("stale-target");if((e==="editCell"||e==="editCells"||e==="propose"||e==="acceptProposal"||e==="moveRange")&&/^(?:cell number must be finite|cell text exceeds Excel's length limit|formula exceeds the length limit)$/.test(t.message))return new J("invalid-step");if(e==="fillRange"&&/^(?:fill destination must start at the source's top-left cell and contain it|fill cannot copy a formula above the length limit)$/.test(t.message))return new J("invalid-step");if((e==="applyOps"||e==="patchRangeStyle"||e==="setNumberFormat"||e==="applyFormat")&&(/^(?:font family must not be empty|font size must be between 1 and 400|captured format dimensions do not match its cells)$/.test(t.message)||/^invalid color .*; expected #rrggbb$/.test(t.message)))return new J("invalid-step");if(e==="applyOps"&&(/^the anchor of .+ would leave the sheet grid$/.test(t.message)||/^defined name .+ has a formula above the length limit$/.test(t.message)||/^(?:chart reference exceeds the supported length|chart reference contains a character xml cannot carry|sheet name contains a character xml cannot carry, and the workbook references the sheet)$/.test(t.message)||/^the (?:data validation|extension data validation|extension conditional format|sparkline|extension) formulas on sheet .+ cannot follow the sheet (?:rename|removal)$/.test(t.message)))return new J("invalid-step");if((e==="applyOps"||e==="moveChart"||e==="resizeChart")&&/^(?:anchor offset is out of range|anchor extent is not positive|anchor corners are inverted or coincident|anchor cell is outside the worksheet grid|anchor extends beyond the worksheet grid)$/.test(t.message))return new J("invalid-step");if(e==="applyOps"&&/^bad ops: /.test(t.message)||e==="resizeChart"&&/^bad chart resize args: /.test(t.message)||e==="applyFormat"&&/^bad format args: /.test(t.message)||e==="editCells"&&/^bad edit args: /.test(t.message)||e==="moveRange"&&/^bad (?:move range args|range|move destination): /.test(t.message)||e==="fillRange"&&/^bad (?:fill args|range): /.test(t.message)||e==="applyEdits"&&/^malformed request: /.test(t.message))return new J("invalid-command");if((e==="applyOps"||e==="moveChart"||e==="resizeChart"||e==="moveRange"||e==="fillRange")&&(/^(?:sheet(?: index)?|row|column) \d+ (?:is )?out of range$/.test(t.message)||/^cell row \d+, column \d+ is out of range$/.test(t.message)||/^sheet \d+ is not an editable worksheet$/.test(t.message)||/^invalid sheet name: /.test(t.message)||/^duplicate sheet name: /.test(t.message)||/^(?:row|column) operation (?:count must be positive|exceeds sheet bounds)$/.test(t.message)||/^range \d+x\d+ exceeds the \d+-cell copy cap$/.test(t.message)||/^(?:workbook has no sheets|sheet contains too many hyperlinks|hyperlink must have a destination|hyperlink field exceeds its length limit)$/.test(t.message)||/^workbook contains (?:a non-finite cell number|cell text above Excel's length limit|a formula above the length limit|an invalid cell style index|an invalid column width|an invalid row height|overlapping merged ranges)$/.test(t.message)||/^no chart frame on this sheet is named /.test(t.message)||/^chart .+ is pinned to the sheet and cannot be moved$/.test(t.message)||/^(?:row|column) insertion would (?:discard content at|push a chart anchor past) the sheet boundary$/.test(t.message)||/^(?:freeze pane is out of range|range start must be above and left of range end|restore sheet operations are internal)$/.test(t.message)))return new J("invalid-step")}}function He(t,e,o,c,a=null){return {identity:t,epoch:e.epoch,throughSeq:0,selection:o,readOnly:false,statuses:new Map,bases:new Map([[e.version,0]]),sheetRevision:0,historySelections:[],sheetIds:[...c],nextSheetId:c.length,calculation:a,formats:new Map}}function Ee(t,e){let o=e.editState,c=!o||e.catalogDirty;(!e.info||c)&&(e.info=t.sheetInfo());let a=e.info;if(!e.editableSheets||c){let l=t.readCells({ranges:[]});if(!l.ok)throw new Error(l.failure.message);e.editableSheets=l.sheets.map(m=>m.editable);}let s=t.historyState(),r=JSON.stringify(e.selection),d=e.formattingSelection!==r,u=o?.formatting,S=o?.mergedRanges,y=o?.formattingAvailable??false,b=o?.selectionEditable??false;if(!u||e.formattingDirty||d){let l=G(t,e.selection,e.sheetIds),{sheet:m,start:H,end:A}=l;b=e.editableSheets[m],y=b&&(A.row-H.row+1)*(A.col-H.col+1)<=1e5,u=y?t.selectionFormatting(m,l.range):{};}if(!S||e.mergesDirty||d){let l=G(t,e.selection,e.sheetIds);S=t.mergedRanges(l.sheet,l.range);}e.formattingSelection=r,e.formattingDirty=e.mergesDirty=e.catalogDirty=false;let q={canUndo:s.canUndo,canRedo:s.canRedo,formatting:u,formattingAvailable:y,selectionEditable:b,mergedRanges:S??[],calculation:t.calculationStatus(),sheets:c?e.sheetIds.map((l,m)=>({id:l,index:m,name:a.sheetNames[m]})):o.sheets,activeSheet:a.activeSheet,readOnly:e.readOnly,...e.historyReset?{historyReset:true}:{}},v={};for(let l of Object.keys(q))(!o||o[l]!==q[l]&&JSON.stringify(o[l])!==JSON.stringify(q[l]))&&Object.assign(v,{[l]:q[l]});return e.editState=q,Object.keys(v).length>0?v:void 0}function Ke(t,e,o){let c=t.sheetInfo();if(c.sheetIds.length===o.length&&c.sheetIds.every((s,r)=>s===o[r]))return;let a=new Map(o.map((s,r)=>[s,e.sheetIds[r]]));e.sheetIds=c.sheetIds.map(s=>a.get(s)??s),e.sheetRevision+=1,e.sheetIds.includes(e.selection.sheetId)||(e.selection={sheetId:e.sheetIds[c.activeSheet],range:{kind:"a1",a1:"A1"}});}function lo(t,e,o,c){if(I(o,e.pipeFrameBytes),o.frame&&o.frame.sheet>=t.sheetCount())throw new J("missing-target");if(o.kind==="collabPipe"){if(!c)throw new J("unsupported");let R=t.version(),P=t.sheetInfo().sheetIds;c(o.payload),Ke(t,e,P);let T=e.pipeFrameBytes??(e.pipeFrameBytes=new Map);for(let $ of o.payload.ops)if($.op==="create")T.has(o.payload.provider)||T.set(o.payload.provider,$.options.maxFrameBytes??a$3);else if(T.has(o.payload.provider))$.op==="destroy"&&T.delete(o.payload.provider);else break;let U=t.version()!==R;return U&&(e.formattingDirty=e.mergesDirty=e.catalogDirty=true),{seq:o.seq,status:U?"applied":"noop",committed:U,...U?{result:{remoteUpdate:true,proposals:t.listProposals()}}:{}}}if(o.kind==="applyUpdate"){let R=t.version(),P=t.sheetInfo().sheetIds,T=false;for(let U of [o.payload.update,...o.payload.updates??[]]){let $=t.version();try{t.applyUpdate(U);}catch(re){if(!(re instanceof Error)||a$1(re)||t.version()!==$)throw re;if($===R)throw new J("invalid-update");T=true;break}}return Ke(t,e,P),e.formattingDirty=e.mergesDirty=e.catalogDirty=true,{seq:o.seq,status:t.version()===R?"noop":"applied",committed:t.version()!==R,result:{remoteUpdate:true,proposals:t.listProposals(),...T?{refusedUpdate:"invalid-update"}:{}}}}if(o.kind==="select"){It(t,e,o.payload.selection);let R=JSON.stringify(e.selection)!==JSON.stringify(o.payload.selection);return e.selection=structuredClone(o.payload.selection),{seq:o.seq,status:R?"applied":"noop",committed:false}}if(o.kind==="setReadOnly"){let R=e.readOnly!==o.payload.readOnly||!!e.allowHostProposals!=!!o.payload.allowHostProposals;return e.readOnly=o.payload.readOnly,e.allowHostProposals=o.payload.allowHostProposals===true,{seq:o.seq,status:R?"applied":"noop",committed:false}}let a$2=o.kind==="applyOps"&&"toolbar"in o.payload&&o.payload.toolbar.id==="refreshProposals";if(o.kind==="setActiveSheet"&&o.payload.expectVersion!==void 0&&o.payload.expectVersion!==t.version())throw new J("stale-version");let s=e.allowHostProposals&&(o.kind==="propose"||o.kind==="acceptProposal"||o.kind==="rejectProposal");if(e.readOnly&&!s&&o.kind!=="setActiveSheet"&&!a$2)throw new J("read-only");if(o.payload.selection&&It(t,e,o.payload.selection),a$2)return {seq:o.seq,status:"applied",committed:false,result:{proposals:t.listProposals()}};if(o.kind==="applyOps"&&"toolbar"in o.payload&&o.payload.toolbar.id==="paintFormat"){let{target:R}=o.payload.toolbar;if(!R)throw new J("invalid-command");let P=G(t,R,e.sheetIds);Me(t,P.sheet,P.range);let T=Ze(t,P.sheet,P.range),U=globalThis.crypto.getRandomValues(new Uint8Array(16)),$=`format:${Array.from(U,ae=>ae.toString(16).padStart(2,"0")).join("")}`;e.formats.set($,T),e.formats.size>to&&e.formats.delete(e.formats.keys().next().value),o.payload.selection&&(e.selection=structuredClone(o.payload.selection));let re={formatToken:$};return {seq:o.seq,status:"applied",committed:false,result:re}}let r=no(t,e,o);if(io(t,e,r),r.method==="setActiveSheet"&&o.payload.selection&&e.sheetIds[r.args[0]]!==o.payload.selection.sheetId)throw new J("invalid-command");let d=t.version(),u=e.info?.activeSheet??t.sheetInfo().activeSheet,S=t.historyState(),y=structuredClone(e.selection),b=[...e.sheetIds],q=e.collaborative&&(r.method==="undo"||r.method==="redo"||r.method==="applyOps"&&r.args[0].some(R=>R.type==="addSheet"))?t.sheetInfo().sheetIds:void 0,v$1;try{r.calculation&&t.setCalculationContext(r.calculation),v$1=v(t,r);}catch(R){let P=Ft(R,r.method);throw P&&t.version()===d?(r.calculation&&t.setCalculationContext(e.calculation),P):new a(a$1(R)?"trap":"crash",`Workbook command failed at sequence ${o.seq} (${o.kind})`,R instanceof Error?R.message:String(R))}if(u$1(v$1)){if(r.method!=="applyEdits"||t.version()!==d)throw new a("crash","Workbook command failed after dispatch");let R=v$1;throw r.calculation&&t.setCalculationContext(e.calculation),new J(R.failure.code,R)}r.calculation&&(e.calculation={...r.calculation});let l=t.version()!==d,m=t.historyState();if(l&&q)Ke(t,e,q);else if(l&&r.method==="applyOps")for(let R of r.args[0]){let P=R;if(P.type==="addSheet")e.sheetIds.splice(P.index,0,`command-sheet:${e.nextSheetId++}`);else if(P.type==="removeSheet")e.sheetIds.splice(P.index,1);else if(P.type==="moveSheet"){let[T]=e.sheetIds.splice(P.from,1);e.sheetIds.splice(P.to,0,T);}}if(r.method==="undo"||r.method==="redo"){if(l){let R=r.method==="undo"?S.undoDepth:m.undoDepth,P=e.historySelections[R];if(P){q||(e.sheetIds=[...r.method==="undo"?P.beforeSheets:P.afterSheets]),e.selection=structuredClone(r.method==="undo"?P.before:P.after);let T=e.sheetIds.indexOf(e.selection.sheetId);T>=0&&t.setActiveSheet(T);}}}else o.payload.selection&&(e.selection=structuredClone(o.payload.selection));if(l){if(r.method==="undo"||r.method==="redo")e.formattingDirty=e.mergesDirty=true,e.catalogDirty=true;else if(r.method==="applyOps"){let R=r.args[0].map(T=>T.type),P=R.some(T=>["insertRows","deleteRows","insertCols","deleteCols","addSheet","removeSheet","moveSheet"].includes(T));e.formattingDirty=P||R.some(T=>["setCell","patchRangeStyle","setRangeNumberFormat","applyRangeFormat","restoreColStyles"].includes(T)),e.mergesDirty=P||R.some(T=>["mergeCells","unmergeCells"].includes(T)),e.catalogDirty=R.some(T=>["addSheet","removeSheet","moveSheet","renameSheet"].includes(T));}else (r.method==="patchRangeStyle"||r.method==="setNumberFormat"||r.method==="applyFormat"||r.method==="acceptProposal"||r.method==="moveRange"||r.method==="fillRange"||r.method==="applyEdits"&&r.args[0].steps.some(R=>R.op==="patchStyle"||R.op==="setNumberFormat"))&&(e.formattingDirty=true);(b.length!==e.sheetIds.length||b.some((R,P)=>R!==e.sheetIds[P]))&&(e.sheetRevision+=1);}let H=!e.info||e.catalogDirty||r.method==="setActiveSheet"||r.method==="undo"||r.method==="redo"?t.sheetInfo():e.info;if(e.info=H,(!e.sheetIds.includes(e.selection.sheetId)||r.method==="setActiveSheet"&&!o.payload.selection&&u!==H.activeSheet)&&(e.selection={sheetId:e.sheetIds[H.activeSheet],range:{kind:"a1",a1:"A1"}}),r.method!=="undo"&&r.method!=="redo"&&l&&m.undoDepth>S.undoDepth){e.historySelections.length>S.undoDepth+1&&(e.historySelections.length=S.undoDepth+1);let R=structuredClone(e.selection);if(r.method==="editCell"){let[P,T,U]=r.args;R={sheetId:e.sheetIds[P],activeCell:{row:T,col:U},range:{kind:"rowCol",start:{row:T,col:U},end:{row:T,col:U}}};}e.historySelections[m.undoDepth]={before:y,after:R,beforeSheets:b,afterSheets:[...e.sheetIds]};}let A=r.method==="setActiveSheet"?u!==H.activeSheet||JSON.stringify(y)!==JSON.stringify(e.selection):r.method==="propose"||r.method==="acceptProposal"||r.method==="rejectProposal"&&v$1===true;return {seq:o.seq,status:l||A?"applied":"noop",committed:l,...v$1===void 0?{}:{result:pe(v$1,H.sheetIds,e.sheetIds)}}}function Tt(t,e,o,c,a$2=false,s){let r,d=o.kind==="applyUpdate"||o.kind==="collabPipe";try{if(c&&!d)throw new J(c);if(a$2&&!d)r={seq:o.seq,status:"cancelled",reason:"dependency-refused",committed:!1,affectedSeqs:[o.seq]};else {if(!d&&!e.bases.has(o.basis.version))throw new J("stale-basis");r=lo(t,e,o,s);}}catch(q){let v=Ft(q);if(!v)throw q instanceof a?q:new a(a$1(q)?"trap":"crash","Workbook command failed",q instanceof Error?q.message:String(q));r={seq:o.seq,status:"refused",reason:v.reason,committed:false,affectedSeqs:[o.seq],...v.result===void 0?{}:{result:pe(v.result,t.sheetInfo().sheetIds,e.sheetIds)}};}let u=t.version();if(e.bases.has(o.basis.version)){let q=e.bases.get(o.basis.version);e.bases.delete(o.basis.version),e.bases.set(o.basis.version,q);}e.bases.set(u,e.sheetRevision),e.bases.size>eo&&e.bases.delete(e.bases.keys().next().value);let S=JSON.stringify(e.selection),y=S!==e.publishedSelection||r.status==="refused"||r.status==="cancelled"?structuredClone(e.selection):void 0;r.status!=="refused"&&r.status!=="cancelled"&&(e.publishedSelection=S);let b;try{b=Ee(t,e);}catch(q){throw new a(a$1(q)?"trap":"crash","Workbook command state projection failed",q instanceof Error?q.message:String(q))}return {throughSeq:o.seq,version:u,statuses:[r],...y?{selection:y}:{},...b?{editState:b}:{}}}var co=4096,Mt=4096;function Ht(t,e){let o=new WeakMap,c=4096;function a(s,r,d){if(--c<0||d>32)return false;if(Object.is(s,r))return true;if(s===null||r===null||typeof s!="object"||typeof r!="object")return false;if(o.has(s))return o.get(s)===r;if(o.set(s,r),s instanceof Date||r instanceof Date)return s instanceof Date&&r instanceof Date&&Object.is(s.getTime(),r.getTime());if(s instanceof RegExp||r instanceof RegExp)return s instanceof RegExp&&r instanceof RegExp&&s.source===r.source&&s.flags===r.flags;if(s instanceof Number||r instanceof Number||s instanceof Boolean||r instanceof Boolean||s instanceof String||r instanceof String)return s.constructor===r.constructor&&Object.is(s.valueOf(),r.valueOf());if(s instanceof ArrayBuffer||r instanceof ArrayBuffer||ArrayBuffer.isView(s)||ArrayBuffer.isView(r)){let b=l=>l instanceof ArrayBuffer?new Uint8Array(l):ArrayBuffer.isView(l)?new Uint8Array(l.buffer,l.byteOffset,l.byteLength):void 0,q=b(s),v=b(r);if(!q||!v||s.constructor!==r.constructor||q.byteLength!==v.byteLength||q.byteLength>c)return false;c-=q.byteLength;for(let l=0;l<q.length;l+=1)if(q[l]!==v[l])return false;return true}if(s instanceof Map||r instanceof Map||s instanceof Set||r instanceof Set){if(s.constructor!==r.constructor||!(s instanceof Map||s instanceof Set)||!(r instanceof Map||r instanceof Set)||s.size!==r.size||s.size>c)return false;let b=s.entries(),q=r.entries();for(let v=0;v<s.size;v+=1)if(!a(b.next().value,q.next().value,d+1))return false;return true}if(Array.isArray(s)!==Array.isArray(r)||Array.isArray(s)&&Array.isArray(r)&&s.length!==r.length||Object.getPrototypeOf(s)!==Object.getPrototypeOf(r)||!Array.isArray(s)&&Object.getPrototypeOf(s)!==Object.prototype&&Object.getPrototypeOf(s)!==null)return false;let u=Object.keys(s);if(u.length>c||u.length!==Object.keys(r).length)return false;let S=s,y=r;return u.every(b=>g$1(r,b)&&a(S[b],y[b],d+1))}return a(t,e,0)}function uo(t=[]){let e=[];function o(a){let s=0,r=e.length;for(;s<r;){let d=Math.floor((s+r)/2),u=e[d];if(a<u[0])r=d;else if(a>u[1])s=d+1;else return true}return false}function c(a$1){if(!Number.isSafeInteger(a$1)||a$1<=0)throw new TypeError("Invalid replay sequence");let s=0;for(;s<e.length&&e[s][1]<a$1-1;)s+=1;let r=e[s];if(r&&r[0]<=a$1+1){r[0]=Math.min(r[0],a$1),r[1]=Math.max(r[1],a$1);let d=e[s+1];d&&d[0]<=r[1]+1&&(r[1]=Math.max(r[1],d[1]),e.splice(s+1,1));return}if(e.length===co)throw new a("out-of-memory","Command replay ledger exhausted: 4096 disjoint ranges per epoch");e.splice(s,0,[a$1,a$1]);}for(let a of t)c(a);return {contains:o,add:c}}function _t(t){return {...t,...t.affectedSeqs===void 0?{}:{affectedSeqs:[...t.affectedSeqs]}}}function Nt(t,e){let o=e instanceof Error?e.message:String(e),c={name:y,refusal:{seq:t}},a=Object.assign(new Error(`Command ${t} has an unknown outcome: ${o}`),c);return Object.defineProperty(a,"cause",{value:e,writable:true,configurable:true}),a}function fo(t){return t instanceof Error&&!(t instanceof a)&&!a$1(t)}function ge(t){if(t instanceof a)return t;let e=a$1(t);return new a(e?"trap":"crash",t instanceof Error?t.message:String(t))}function Ut(t){let e$1=t.retainedOutcomes??256,{session:o,incarnation:c,epoch:a$2,getVersion:s,apply:r,frame:d$1,snapshot:u,prunedDuplicateReason:S}=t,y=t.throughSeq??0,b=s();if(!Number.isSafeInteger(e$1)||e$1<0||!Number.isSafeInteger(y)||y<0||!Number.isFinite(b)||S!==void 0&&(typeof S!="string"||S.length===0))throw new TypeError("Invalid command host ledger");let q=new Map,v=uo(t.refusedSeqs),l=new Set(t.replayAppliedSeqs);for(let i of l)if(!Number.isSafeInteger(i)||i<=0)throw new TypeError("Invalid replay sequence");let m,H=Promise.resolve(),A=0,R=0,P=0,T=0,U=0,$=new Map,re,ae,F=false,de=false,J=y,k=0,E=t.queries?_():0,O=new Map;function _(){let i=t.layoutRevision?.()??0;if(!Number.isSafeInteger(i)||i<0)throw new TypeError("Invalid layout revision");return i}function B(i,g=[]){if(!(!t.checkRefusals||C$1.includes(i)||g.includes(i)||["stale-epoch","stale-incarnation","wrong-session","stale-version","dependency-refused","unknown-outcome","disposed"].includes(i)))throw M(new TypeError(`Undeclared refusal: ${i}`))}function M(i){return m=i,j(),i}function z(i){if(P===Mt&&!m&&M(new a("out-of-memory","Command handler capacity exceeded")),m)return Promise.reject(m);P+=1;let I=H.then(()=>{if(m)throw m;return i()}).finally(()=>{P-=1,j();});return H=I.then(()=>{},()=>{}),I}function ne(i){let g=$.get(i);if(g){$.delete(i);for(let I of g)I();}}function j(){if(!m)return;let i=m,g=[...$.values()],I=[...O.values()];$.clear(),O.clear();for(let W of g)for(let X of W)X();for(let W of I)for(let X of W)X.reject(i);}async function se(){try{let i=await d$1({coversThroughSeq:y,version:b});if(i===void 0)return;let g=f(i)?i.value:i;if(!A$1({session:o,incarnation:c,epoch:a$2,throughSeq:y,version:b,outcomes:[],frame:g})||g.coversThroughSeq!==y)throw new Error("Frame does not cover the settled command boundary");return i}catch(i){throw M(ge(i))}}async function V(){let i=await se();if(i===void 0)throw new Error("No frame is available at the settled command boundary");return i}function Y(i){if(i.status==="refused"||i.status==="cancelled")try{v.add(i.seq);}catch(g){throw M(ge(g))}if(y=i.seq,e$1>0&&(q.set(i.seq,_t(i)),q.size>e$1&&q.delete(q.keys().next().value)),O.size)for(let g of [...O.keys()].sort((I,W)=>I-W)){if(g>y)break;let I=O.get(g);if(I){O.delete(g);for(let W of I)W.start();}}return i}function ee(i,g,I=false){return {seq:i,status:I?"cancelled":"refused",reason:g,committed:false}}function D$1(i,g){let I={session:o,incarnation:c,epoch:a$2,throughSeq:y,version:b,outcomes:i?[_t(i)]:[]};try{g&&g$1(g,"selection")&&(!F||!(t.selectionEquals??Ht)(re,g.selection))&&(re=x$1(g.selection),F=!0,I.selection=x$1(re),t.queries&&(k+=1)),g&&g$1(g,"editState")&&(!de||!(t.editStateEquals??Ht)(ae,g.editState))&&(ae=x$1(g.editState),de=!0,I.editState=x$1(ae)),t.queries&&(E=_(),I.revisions={selection:k,layout:E});}catch(W){throw M(ge(W))}return I}async function p(i){if(A>0||R>1)return i;try{let g=await se();if(g===void 0)return i;if(f(g)){if(i.frame=g.value,!A$1(i)||i.frame.coversThroughSeq!==y)throw new Error("Frame does not cover the settled command boundary");return e(i,g.transfer)}if(i.frame=g,!A$1(i)||g.coversThroughSeq!==y)throw new Error("Frame does not cover the settled command boundary");return i}catch(g){throw M(ge(g))}}function n(i){try{let g=s();if(!Number.isFinite(g)||g!==b)throw new Error("Version changed outside a command");return g}catch(g){throw M(Nt(i,g))}}function f$1(i){return z$1(i)&&i.session===o&&i.incarnation===c&&i.basis.epoch===a$2}async function h(i){if(!z$1(i))throw new TypeError("Invalid command envelope");if(i.session!==o)return D$1(ee(i.seq,"wrong-session"));if(i.incarnation!==c)return D$1(ee(i.seq,"stale-incarnation"));if(i.basis.epoch!==a$2){let K=ee(i.seq,"stale-epoch");return D$1(i.seq>y?Y(K):K)}if(i.seq<=y)return p(D$1(q.get(i.seq)??(S===void 0?{seq:i.seq,status:"duplicate"}:ee(i.seq,S))));if(v.contains(i.seq))return p(D$1(Y(ee(i.seq,"unknown-outcome"))));if(i.afterSeq!==void 0&&v.contains(i.afterSeq))return p(D$1(Y(ee(i.seq,"dependency-refused",true))));let g=i.replay===true&&l.has(i.seq);if(t.commands){if(!g$1(t.commands,i.kind))return p(D$1(Y(ee(i.seq,"unsupported"))));if(t.commands[i.kind].admission==="local-write"&&!g&&t.readOnly?.())return p(D$1(Y(ee(i.seq,"read-only"))))}let I=n(i.seq);if(i.expectVersion&&!g&&i.basis.version!==I)return p(D$1(Y(ee(i.seq,"stale-version"))));let W;try{if(W=await r(i,{basis:i.basis,currentVersion:I,replayPreviouslyApplied:g}),!W||typeof W!="object"||W.status!=="applied"&&W.status!=="noop"&&W.status!=="cancelled"&&W.status!=="refused"||W.status==="applied"&&W.committed!==void 0&&W.committed!==!1||W.status==="cancelled"&&W.reason!==void 0&&typeof W.reason!="string")throw new Error("Invalid format apply result");let K=s();if(!Number.isFinite(K)||(W.status==="applied"&&W.committed!==!1?K<=I:K!==I))throw new Error(`${W.status} violated the command version contract`);b=K;}catch(K){throw M(Nt(i.seq,K))}W.status==="refused"&&B(W.reason,t.commands?.[i.kind]?.refusals);let X=W.status==="refused"?{...ee(i.seq,W.reason),...W.affectedSeqs===void 0?{}:{affectedSeqs:W.affectedSeqs}}:W.status==="cancelled"?{seq:i.seq,status:"cancelled",committed:false,...W.reason===void 0?{}:{reason:W.reason}}:W.status==="applied"&&W.committed===false?{seq:i.seq,status:"applied",committed:false}:{seq:i.seq,status:W.status},te=D$1(Y(X),W);return W.status==="noop"&&t.deferFrame?.(i,W)?te:p(te)}let w={lane:"input",mutates:true,reframes:true,reorderable:false};function C(i,g){return {ok:false,refusal:{code:i,...g===void 0?{}:{detail:g}}}}function Z(i){return !!i&&typeof i=="object"&&typeof i.session=="string"&&[i.incarnation,i.epoch,i.afterSeq].every(g=>Number.isSafeInteger(g)&&g>=0)}function N(i,g,I){return z(async()=>{let W;try{W=await t.queries.handlers[g](I,i);}catch(te){if(te instanceof a||a$1(te))throw M(ge(te));return C("invalid-payload",te instanceof Error?te.message:String(te))}if(D(W))return B(W.refusal.code,t.queries.specs[g].refusals),{ok:false,refusal:W.refusal};let X={ok:true,value:f(W)?W.value:W,at:{incarnation:c,epoch:a$2,throughSeq:y,doc:b,selection:k,layout:_()}};return f(W)?e(X,W.transfer):X})}return {handler(i,g){let I=f$1(g),W=I&&A>0;I&&(J=Math.max(J,g.seq),A=Math.max(0,A-1),R+=1);let X=z(()=>h(g));return W&&ne(++T),j(),X.finally(()=>{I&&(R-=1),j();})},policy(i){return f$1(i)&&(A+=1,J=Math.max(J,i.seq)),{...w}},query(i,g,I,W){return m?Promise.reject(m):!Z(g)||typeof I!="string"||!Array.isArray(W)?Promise.resolve(C("invalid-payload")):g.session!==o||g.incarnation!==c||g.epoch!==a$2||g.afterSeq>J?Promise.resolve(C("stale")):!t.queries||!g$1(t.queries.specs,I)||!g$1(t.queries.handlers,I)?Promise.resolve(C("unsupported")):y>=g.afterSeq?N(i,I,W):d(new Promise((X,te)=>{let K=O.get(g.afterSeq);K||O.set(g.afterSeq,K=[]),K.push({start:()=>{N(i,I,W).then(X,te);},reject:te});}))},queryPolicy(i,g,I){return {lane:"interactive",reorderable:(t.queries&&g$1(t.queries.specs,g)?t.queries.specs[g]:void 0)?.stale!=="answer-at-fence"}},revise(i){if(m)throw m;let g=b,I=E;b=s();let W=D$1(void 0,i);return b!==g||E!==I||g$1(W,"selection")||g$1(W,"editState")?W:void 0},checkpoint(i){return z(async()=>{let g;try{let I=s();if(I!==b)throw new Error("Version changed before checkpoint");let W;try{W=(await u()).slice();}catch(X){throw s()===I&&fo(X)&&(g=X),X}if(s()!==I)throw new Error("Snapshot changed the command version");return e({state:W,epoch:a$2,version:b,throughSeq:y},[W.buffer])}catch(I){throw g||M(ge(I))}})},checkpointPolicy(){return {lane:"input",reorderable:false}},frame(){return U===Mt&&!m&&M(new a("out-of-memory","Command frame capacity exceeded")),m?(j(),Promise.reject(m)):A===0?z(V):(U+=1,new Promise((i,g)=>{let I=T+A,W=$.get(I);W||$.set(I,W=[]),W.push(()=>{U-=1,z(V).then(i,g);});}))}}}var $t={capture:()=>{},restore:()=>{}},Ye=new Uint8Array([88,76,83,88,82,69,67,86]),Dt=3,ce=21,po=8;function zt(t){let e=()=>{throw new TypeError("Unsupported workbook recovery checkpoint")};return t.length<42||!Ye.every((o,c)=>t[c]===o)||t[8]!==po||t[41]>1?e():t[41]===1}function _e(t,e=2166136261){for(let o of t)e=Math.imul(e^o,16777619);return e>>>0}function Lt(t,e,o,c,a=[],s={version:o,dirty:o>0},r=$t,d={}){r.capture(e);let u=[];for(let v of [...a].sort((l,m)=>l-m)){let l=u[u.length-1];l&&v<=l[1]+1?l[1]=Math.max(l[1],v):u.push([v,v]);}let S={session:e.identity.session,epoch:e.epoch,throughSeq:e.throughSeq,revision:o,engineVersion:c.find(([v])=>v===o)[1],versions:c,bases:[...e.bases],refusedSeqs:a,refusedRanges:d.refusedRanges??u,refusedOutcomes:d.refusedOutcomes??[],statuses:[...e.statuses],selection:e.selection,readOnly:e.readOnly,allowHostProposals:e.allowHostProposals===true,sheetIds:e.sheetIds,nextSheetId:e.nextSheetId,sheetRevision:e.sheetRevision,calculation:e.calculation,formats:[...e.formats],hostVersion:s.version,dirty:s.dirty,...d.historySelections?{historySelections:d.historySelections}:{}},y=new TextEncoder().encode(JSON.stringify(S));if(y.length>4294967295||t.length===0||t.length>4294967295)throw new RangeError("Workbook recovery checkpoint size is out of range");let b=new Uint8Array(ce+y.length+t.length),q=new DataView(b.buffer);return b.set(Ye),q.setUint8(8,Dt),q.setUint32(9,y.length,true),q.setUint32(13,t.length,true),b.set(y,ce),b.set(t,ce+y.length),q.setUint32(17,_e(b.subarray(ce),_e(b.subarray(0,17))),true),b}function Bt(t){let e=()=>{throw new TypeError("Invalid workbook recovery checkpoint")};(t.length<ce||!Ye.every((l,m)=>t[m]===l))&&e();let o=new DataView(t.buffer,t.byteOffset,t.byteLength),c=o.getUint32(9,true),a=o.getUint32(13,true);(o.getUint8(8)!==Dt||c===0||a===0||ce+c+a!==t.length||_e(t.subarray(ce),_e(t.subarray(0,17)))!==o.getUint32(17,true))&&e();let s=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(t.subarray(ce,ce+c))),r=t.subarray(ce+c),d=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>=0,u=(l,m,H)=>Array.isArray(l)&&l.length<=256&&l.every(A=>Array.isArray(A)&&A.length===2&&m(A[0])&&H(A[1]))&&new Set(l.map(A=>A[0])).size===l.length,S=l=>typeof l=="string"&&l.length>0,y=l=>{if(l===null)return true;if(!l||typeof l!="object")return false;let m=l,H=(A,R)=>A&&A.range&&Array.isArray(R)&&R.length>0&&R.every(S)&&new Set(R).size===R.length&&R.includes(A.sheetId);return !!(H(m.before,m.beforeSheets)&&H(m.after,m.afterSheets))},b=l=>{if(!l||typeof l!="object")return false;let m=l;return d(m.seq)&&m.seq>0&&(m.status==="refused"||m.status==="cancelled")&&S(m.reason)&&m.committed===false&&(m.affectedSeqs===void 0||Array.isArray(m.affectedSeqs)&&m.affectedSeqs.every(H=>d(H)&&H>0))},q=l=>{if(!l||typeof l!="object")return false;let m=l;return d(m.seq)&&m.seq>0&&["applied","noop","refused","cancelled"].includes(m.status??"")&&typeof m.committed=="boolean"&&(m.affectedSeqs===void 0||Array.isArray(m.affectedSeqs)&&m.affectedSeqs.every(d))&&(m.reason===void 0||S(m.reason))},v=l=>{if(!l||typeof l!="object")return false;let m=l;return d(m.rows)&&m.rows>0&&d(m.columns)&&m.columns>0&&m.rows*m.columns<=1e5&&Array.isArray(m.formats)&&m.formats.length===m.rows*m.columns};return (!s||!S(s.session)||!S(s.engineVersion)||!d(s.epoch)||s.epoch===0||![s.throughSeq,s.revision,s.hostVersion,s.sheetRevision,s.nextSheetId].every(d)||typeof s.readOnly!="boolean"||typeof s.dirty!="boolean"||s.allowHostProposals!==void 0&&typeof s.allowHostProposals!="boolean"||!Array.isArray(s.sheetIds)||s.sheetIds.length===0||!s.sheetIds.every(S)||new Set(s.sheetIds).size!==s.sheetIds.length||s.sheetIds.some(l=>l.startsWith("command-sheet:")&&(!d(Number(l.slice(14)))||Number(l.slice(14))>=s.nextSheetId))||!u(s.versions,d,S)||!u(s.bases,S,d)||!s.versions.some(([l,m])=>l===s.revision&&m===s.engineVersion)||!s.bases.some(([l])=>l===s.engineVersion)||!Array.isArray(s.refusedSeqs)||s.refusedSeqs.length>256||new Set(s.refusedSeqs).size!==s.refusedSeqs.length||!s.refusedSeqs.every(l=>d(l)&&l>0&&l<=s.throughSeq)||!Array.isArray(s.refusedRanges)||s.refusedRanges.length>4096||!s.refusedRanges.every((l,m,H)=>{if(!Array.isArray(l)||l.length!==2||!d(l[0])||!d(l[1])||l[0]===0||l[0]>l[1]||l[1]>s.throughSeq)return false;let A=H[m-1];return m===0||Array.isArray(A)&&A[1]<l[0]-1})||!s.refusedSeqs.every(l=>s.refusedRanges.some(([m,H])=>l>=m&&l<=H))||!u(s.statuses,d,q)||!s.statuses.every(([l,m])=>l===m.seq&&l<=s.throughSeq&&s.refusedSeqs.includes(l)===(m.status==="refused"||m.status==="cancelled"))||!s.statuses.every(([l,m])=>s.refusedRanges.some(([H,A])=>l>=H&&l<=A)===(m.status==="refused"||m.status==="cancelled"))||!u(s.refusedOutcomes,d,b)||!s.refusedOutcomes.every(([l,m])=>l===m.seq&&s.statuses.some(([H,A])=>H===l&&A.status===m.status&&A.reason===m.reason)&&(m.affectedSeqs??[]).every(H=>s.statuses.some(([A,R])=>A===H&&R.status===m.status&&R.reason===m.reason&&R.committed===false)))||!u(s.formats,S,v)||s.formats.length>64||s.historySelections!==void 0&&(!Array.isArray(s.historySelections)||!s.historySelections.every(y))||!s.selection||!s.sheetIds.includes(s.selection.sheetId)||r.length===0)&&e(),s.calculation!==null&&(!s.calculation||!Number.isFinite(s.calculation.nowSerial)||!d(s.calculation.randSeed)||s.calculation.randSeed>4294967295)&&e(),{...s,allowHostProposals:s.allowHostProposals===true,engine:r}}function jt(t,e,o,c=$t){if(t.version()!==e.engineVersion||t.sheetCount()!==e.sheetIds.length||o.session!==e.session)throw new TypeError("Workbook recovery boundary mismatch");let a=He(o,{epoch:e.epoch,version:e.engineVersion},e.selection,e.sheetIds,e.calculation),s=G(t,e.selection,e.sheetIds),r=e.selection.activeCell;if(r&&(!Number.isSafeInteger(r.row)||!Number.isSafeInteger(r.col)||r.row<s.start.row||r.row>s.end.row||r.col<s.start.col||r.col>s.end.col))throw new TypeError("Invalid recovery selection");return Object.assign(a,{throughSeq:e.throughSeq,readOnly:e.readOnly,allowHostProposals:e.allowHostProposals===true,nextSheetId:e.nextSheetId,sheetRevision:e.sheetRevision,bases:new Map(e.bases),formats:new Map(e.formats),historyReset:e.historySelections===void 0,historySelections:structuredClone(e.historySelections??[]).map(d=>d??void 0)}),a.statuses=new Map(e.statuses),c.restore(t),Ee(t,a),a}function Vt(t,e){return t===e||JSON.stringify(t)===JSON.stringify(e)}function Xt(t){let{handle:e$1,state:o}=t,c=t.now??(()=>performance.now()),a$2=new Map,s=t.revision??0,r=0,d=new Map(t.versions??[[s,e$1.version()]]),u=new Set(t.refusedSeqs),S=t.refusedRanges?.map(([k,E])=>[k,E])??[],y=new Map(t.refusedOutcomes);if(!t.refusedRanges)for(let k of [...u].sort((E,O)=>E-O))U(k);let b=new Map,q,v=false,l,m,H$1=Promise.resolve(),A,R=o.historyReset===true,P=new Set,T=[];function U(k){let E=S[S.length-1];if(E&&k<=E[1]+1)E[1]=Math.max(E[1],k);else {if(S.length===4096)throw new a("out-of-memory","Workbook refusal ledger exhausted");S.push([k,k]);}}function $(k,E){o.statuses.set(k,structuredClone(E)),o.statuses.size>256&&o.statuses.delete(o.statuses.keys().next().value);for(let O of u)o.statuses.has(O)||u.delete(O);for(let O of a$2.keys())o.statuses.has(O)||a$2.delete(O);for(let O of y.keys())o.statuses.has(O)||y.delete(O);}function re(k){return k.payload.compatibility?k.payload.compatibility:{...o.identity,seq:k.seq,basis:{epoch:k.basis.epoch,version:d.get(k.basis.version)??""},afterSeq:k.afterSeq,kind:k.kind,payload:k.payload.payload,...G$1(k.payload.frame)?{frame:k.payload.frame}:{}}}function ae(k){if(H(k),k.session!==o.identity.session||k.incarnation!==o.identity.incarnation||k.basis.epoch!==o.epoch)throw new Error("Workbook command identity or epoch mismatch")}let F=Ut({session:o.identity.session,incarnation:1,epoch:o.epoch,throughSeq:o.throughSeq,refusedSeqs:S.map(([,k])=>k),getVersion:()=>s-r,selectionEquals:Vt,editStateEquals:Vt,apply(k){let E=re({...k,basis:{...k.basis,version:k.basis.version+r}}),O;if(k.payload.compatibility){if(ae(E),E.seq!==k.seq||E.seq!==o.throughSeq+1)throw new Error(`Expected workbook command sequence ${o.throughSeq+1}`);E.kind!=="applyUpdate"&&E.kind!=="collabPipe"&&E.afterSeq!==void 0&&!o.statuses.has(E.afterSeq)&&(O="dependency-expired");}let _=se=>{try{return se()}catch(V){throw A=V instanceof a?V:new a(a$1(V)?"trap":"crash","Workbook command failed",V instanceof Error?V.message:String(V)),A}},B=_(()=>e$1.version()),M=_(()=>Tt(e$1,o,E,O,!1,t.applyPipe)),z=M.statuses[0];k.kind!=="collabPipe"&&G$1(b.get(k.seq)?.frame)&&(v=true),R&&(M.selection=structuredClone(o.selection),M.editState=o.editState,R=false);let ne=_(()=>e$1.version());ne!==B&&(s+=1,d.set(s,ne),d.size>256&&d.delete(d.keys().next().value),t.onCommit?.()),a$2.set(k.seq,M),$(k.seq,z),o.throughSeq=k.seq;let j={...M.selection?{selection:M.selection}:{},...M.editState?{editState:M.editState}:{}};return z.status==="refused"?{status:"refused",reason:z.reason,affectedSeqs:z.affectedSeqs,...j}:z.status==="cancelled"?{status:"cancelled",reason:z.reason,...j}:z.status==="applied"?{status:"applied",...z.committed?{}:{committed:false},...j}:{status:"noop",...j}},frame({coversThroughSeq:k}){let E=b.get(k),O=l??E?.frame;if(!G$1(O)||O.sheet>=e$1.sheetCount())return;let _=q?.request;if(!l&&!v&&E?.pipe&&q?.version===e$1.version()&&_&&_.sheet===O.sheet&&_.zoom===O.zoom&&_.dpr===O.dpr&&_.viewport.x===O.viewport.x&&_.viewport.y===O.viewport.y&&_.viewport.width===O.viewport.width&&_.viewport.height===O.viewport.height)return;let B=t.frame(O,k);return q={version:B.version,request:structuredClone(O)},v=false,e({coversThroughSeq:k,revision:B.epoch,payload:B},[B.displayList])},snapshot:async()=>{let k=T.shift();await Promise.all(k?.settled??[]);let E=k?.preserveHistory===true,O=c();try{return Lt(t.captureRecovery?.()??v$1(e$1,o.throughSeq,E),o,s,[...d],[...u],t.sessionState?.(),void 0,{refusedRanges:S,refusedOutcomes:[...y],...E?{historySelections:o.historySelections}:{}})}finally{k&&(k.encodeMs=Math.max(0,c()-O));}}});async function de(k,E){if(A)throw A;E.payload.compatibility&&ae(E.payload.compatibility);let O=o.throughSeq,_,B=new Promise(M=>{_=M;});P.add(B),b.set(E.seq,{frame:E.payload.frame??(E.kind==="applyUpdate"||E.kind==="collabPipe"?m:void 0),pipe:E.kind==="collabPipe"}),E.payload.frame&&(m=E.payload.frame),b.size>256&&b.delete(b.keys().next().value);try{let M=E.afterSeq,z=M===void 0?void 0:S.find(([n,f])=>M>=n&&M<=f),ne=await F.handler(k,{...E,basis:{...E.basis,version:E.basis.version-r},...z?{afterSeq:z[1]}:{}}),j=f(ne)?ne.value:ne;o.throughSeq=Math.max(o.throughSeq,j.throughSeq);let se=j.outcomes.map(n=>{let f=(n.status==="refused"||n.status==="cancelled")&&E.session===o.identity.session&&E.incarnation===1&&(E.basis.epoch===o.epoch||n.seq===j.throughSeq&&!o.statuses.has(n.seq)&&!a$2.has(n.seq))&&n.seq>O&&n.seq<=j.throughSeq;f&&(u.add(n.seq),U(n.seq),y.set(n.seq,{...n,...n.affectedSeqs?{affectedSeqs:[...n.affectedSeqs]}:{}}));let h=E.session===o.identity.session&&E.incarnation===1&&E.basis.epoch===o.epoch,w=h?a$2.get(n.seq):void 0,C=h?o.statuses.get(n.seq):void 0,Z=w?.statuses[0]??C??{...n,status:n.status==="duplicate"?"noop":n.status,committed:!1,affectedSeqs:n.affectedSeqs??[n.seq]};!w&&f&&$(n.seq,Z);let N=h&&n.status==="duplicate"?y.get(n.seq)??(C&&(C.status==="refused"||C.status==="cancelled")?{seq:C.seq,status:C.status,committed:!1,...C.reason?{reason:C.reason}:{},...C.status==="refused"&&C.affectedSeqs?{affectedSeqs:C.affectedSeqs}:{}}:void 0):void 0;return {...N??n,...N?.affectedSeqs?{affectedSeqs:[...N.affectedSeqs]}:{},workbook:!w&&C?structuredClone(Z):Z}}),V=a$2.get(E.seq),Y=j.version+r,ee=d.get(Y)??e$1.version(),D={throughSeq:j.throughSeq,version:ee,statuses:se.map(n=>n.workbook),...V?.selection?{selection:V.selection}:{},...V?.editState?{editState:V.editState}:{}};!V&&se.some(n=>n.status==="refused"||n.status==="cancelled")&&(D.selection=structuredClone(o.selection),D.editState=o.editState);let p={...j,version:Y,engineVersion:ee,outcomes:se,compatibility:D};return f(ne)?e(p,ne.transfer):p}catch(M){throw A||(B$1(M)?(A=new a("crash",M.message),A):M)}finally{P.delete(B),_();}}function J(k){let E=H$1.then(async()=>{l=k??m,k&&(m=k);try{return await F.frame()}finally{l=void 0;}});return H$1=E.then(()=>{},()=>{}),E}return {validateDirectEdits(){if(o.throughSeq!==0||P.size!==0)throw new Error("Direct edits require an unused command host");if(A)throw A},synchronizeDirectEdits(k=e$1.version()){return s+=1,r+=1,d.set(s,k),d.size>256&&d.delete(d.keys().next().value),o.bases.set(k,o.sheetRevision),o.bases.size>256&&o.bases.delete(o.bases.keys().next().value),o.formattingDirty=true,{revision:s,versions:[...d],refusedSeqs:[...u]}},handler:de,policy:k=>({...F.policy(k),lane:k.kind==="applyUpdate"||k.kind==="collabPipe"?"collab":"input",userInput:k.kind!=="applyUpdate"&&k.kind!=="collabPipe"}),async checkpoint(k,E=false){let O={settled:[...P],preserveHistory:E,encodeMs:0};T.push(O);let _=await F.checkpoint(k),B=f(_)?_.value:_,M={...B,version:B.version+r,encodeMs:O.encodeMs};return f(_)?e(M,_.transfer):M},checkpointPolicy:F.checkpointPolicy,frame:()=>J(),rememberFrame(k){m=k,q={version:e$1.version(),request:structuredClone(k)};},requestFrame:J,async command(k){ae(k);let E=k.seq<=o.throughSeq;if(E){let M=o.statuses.get(k.seq);if(!M)throw new Error(`Expected workbook command sequence ${o.throughSeq+1}`);let z={throughSeq:o.throughSeq,version:e$1.version(),statuses:[structuredClone(M)]};return {...z,shared:{session:o.identity.session,incarnation:1,epoch:o.epoch,throughSeq:o.throughSeq,version:s,engineVersion:e$1.version(),compatibility:z,outcomes:[{seq:M.seq,status:M.status,workbook:structuredClone(M),...M.committed?{}:{committed:false}}]}}}let O=await de(null,{session:k.session,incarnation:1,seq:k.seq,basis:{epoch:k.basis.epoch,version:s},afterSeq:k.afterSeq,kind:k.kind,payload:{payload:k.payload,compatibility:k,frame:E?void 0:k.frame}}),_=f(O)?O.value:O,B={..._.compatibility,shared:_,..._.frame?{frame:_.frame.payload}:{}};return f(O)?e(B,O.transfer):B}}}var mo={load:()=>import('./chunk-B5K4E4KI.js')},et=class extends Error{constructor(o){super(`Preview refused: ${JSON.stringify(o)}`);a$2(this,"refusal",o);a$2(this,"code");this.name="WorkbookPreviewRefusal";let c=o.failure;this.code=typeof c?.code=="string"?c.code:"refused";}};function Jt(t){return t.sheetIds.map((e,o)=>({id:e,index:o,name:t.sheetNames[o]}))}function Qt(){let t=globalThis.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Gt(t$1,e$1={}){let o$2,c$2=false,a$2,s$1=0,r$1=false,d$1=0,u$2=0,S=0,y=false,b=false,q={session:Qt(),incarnation:Qt()},v$1,l,m=false,H=()=>{},A$1,R,P,T,U=[],$=new TextEncoder;function re(){c$2||R!==void 0||(R=setTimeout(()=>{R=void 0;let p=A$1?.drain();p&&D.emit("collaborationPipe",p.batches,p.transfer);},0));}function ae(p){if(!A$1)throw new J("unsupported");A$1.run(p);}function F(){if(c$2)throw new Error("Workbook session is disposed");if(!o$2)throw new Error("Workbook session is not open");return o$2}function de(){c$2=true,R!==void 0&&clearTimeout(R),R=void 0,A$1?.dispose(),A$1=void 0;let p=o$2;o$2=void 0,H(),H=()=>{},p?.dispose(),P=void 0,T=void 0,U.length=0,v$1=void 0,l=void 0;}function J$1(p,n){if(!Number.isInteger(n)||n<0||n>=p.sheetCount())throw new RangeError("Sheet index is out of range")}function k$1(p,n){let f=F();if(!v$1?.throughSeq)return n(p);let h=f.sheetInfo().sheetIds,w;try{w=pe(p,v$1.sheetIds,h,!0);}catch(C){if(!(C instanceof J))throw C;return {ok:false,version:f.version(),failure:{code:"missing-target",message:"The command sheet no longer exists"}}}return pe(n(w),h,v$1.sheetIds)}function E(p,n$1){let f=F();J$1(f,n$1);let h=$.encode(n(f,p,n$1)).buffer;return d$1+=1,{displayList:h,version:f.version(),epoch:d$1,sequence:v$1?.throughSeq||u$2,sheet:n$1,viewport:p,mergedRanges:f.visibleMergedRanges(n$1,p)}}function O(p,n){let f=F();if(!s())throw j();return d(f.renderPng(p,n).then(_))}function _(p){let n=p.buffer instanceof ArrayBuffer&&p.byteOffset===0&&p.byteLength===p.buffer.byteLength?p.buffer:new Uint8Array(p).buffer;return e(n,[n])}function B$1(p){let n=F(),f=n.exportStructured(p);if(!v$1?.throughSeq)return f;let h=p?.maxBytes,w=h!==void 0&&Number.isFinite(h)?h:8*1024*1024,C=pe(f,n.sheetInfo().sheetIds,v$1.sheetIds);return C.ok&&$.encode(JSON.stringify(C.content)).byteLength>w?{ok:false,version:C.version,failure:{code:"limit-exceeded",target:null,message:"The exported content exceeds maxBytes"}}:C}function M(p){let n=F();J$1(n,p);let{contentWidth:f,contentHeight:h,frozenRows:w,frozenCols:C,initialScrollX:Z,initialScrollY:N}=n.sheetInfoFor(p),i=n.cellRect(p,Math.max(0,w-1),Math.max(0,C-1));return {sheet:p,version:n.version(),contentWidth:f,contentHeight:h,frozenRows:w,frozenCols:C,initialScrollX:Z,initialScrollY:N,frozenWidth:C===0?0:i.x+i.w,frozenHeight:w===0?0:i.y+i.h}}function z$1(p){l=Xt({handle:F(),state:v$1,applyPipe:ae,...p?{revision:p.revision,versions:p.versions,refusedSeqs:p.refusedSeqs,refusedRanges:p.refusedRanges,refusedOutcomes:p.refusedOutcomes}:{},sessionState:()=>({version:s$1,dirty:r$1}),frame:(n,f)=>({...E(n.viewport,n.sheet),...q,sequence:f,coversThroughSeq:f,requestGeneration:n.requestGeneration??n.generation,zoom:n.zoom,dpr:n.dpr}),onCommit(){s$1+=1,r$1=true,D.emit("changed",{version:s$1,dirty:r$1});}});}let ne={beginPeerSnapshot(p,n,f){let h=F();if(T=void 0,!y||b)throw new Error("Worker peer snapshot requires pending retained hydration");try{return x(h).begin(n,f),T={version:h.version(),sequence:u$2,records:n,bytes:f},{version:T.version,sequence:u$2}}catch(w){try{x(h).end();}catch{}throw new Error(w instanceof Error?w.message:String(w))}},pullPeerSnapshot(){let p=F();try{let n=j$1(p),f=[],h=0;for(;f.length<n.records&&h<n.bytes;){let w=n.pending??x(p).next();if(n.pending=void 0,w===void 0)break;let C=w.buffer;if(!(C instanceof ArrayBuffer)||w.byteOffset!==0||w.byteLength!==C.byteLength)throw new Error("Worker peer snapshot chunk is not transferable");if(f.length>0&&h+w.byteLength>n.bytes){n.pending=w;break}f.push(C),h+=w.byteLength;}return f.length===0?void 0:e(f,f)}catch(n){T=void 0;try{x(p).end();}catch{}throw new Error(n instanceof Error?n.message:String(n))}},endPeerSnapshot(p,n){let f=F();try{n||j$1(f),x(f).end();}catch(h){try{x(f).end();}catch{}throw new Error(h instanceof Error?h.message:String(h))}finally{T=void 0;}},preview(p,n$1,f,h){let w=F();if(J$1(w,f),!P)throw new Error("Worker preview requires retained hydration");let C=B(P.bytes,{},P.hydration);try{for(let N of U){C.setCalculationContext(N.calculation);try{v(C,N.op);}catch(i){if(!(i instanceof l$1)||!N.staleProposal)throw i}}for(let N of h){t({sequence:1,calculation:{nowSerial:0,randSeed:0},op:N}),N.calculation&&C.setCalculationContext(N.calculation);let i=v(C,N);if(u$1(i))throw new et(i)}let Z=$.encode(xt(()=>n(C,n$1,f))).buffer;return e({displayList:Z,version:C.version(),epoch:0,sequence:u$2,sheet:f,viewport:n$1,mergedRanges:C.visibleMergedRanges(f,n$1)},[Z])}finally{C.dispose();}},attachPeer(p,n,f){if(b=false,n!==F().version()||f!==u$2)throw new w$1("version-mismatch","Workbook worker state differs from retained peer hydration");b=true,P=void 0,U.length=0;},detachPeer(){b=false;},replay(p,n){if(t(n),y&&!b)throw new w$1("mutation-outside-replay","Workbook replay requires an attached edit peer");let f=F();if(n.sequence!==u$2+1){let w=new Error(`Expected workbook replay sequence ${u$2+1}, got ${n.sequence}`);throw w.name="WorkbookReplayOrderError",w}let h=n.op;try{let w=f.version();f.setCalculationContext(n.calculation);let C;try{if(C=v(f,!y&&h.method==="applyEdits"?{method:"applyEdits",args:[{...h.args[0],expectVersion:w}]}:h),n.staleProposal)throw new Error("Expected a stale proposal refresh")}catch(N){if(!(N instanceof l$1)||!n.staleProposal||JSON.stringify({cells:N.cells,targets:N.targets})!==JSON.stringify(n.staleProposal))throw N}if(u$1(C))throw new Error(`Engine refused replay: ${JSON.stringify(C)}`);let Z=f.version()!==w;return u$2=n.sequence,P&&U.push(structuredClone(n)),Z&&(S+=1,s$1+=1,r$1=!0,D.emit("changed",{version:s$1,dirty:r$1})),{sequence:u$2,revision:S,version:s$1,result:C}}catch(w){let C=`Workbook replay diverged at sequence ${n.sequence} (${h.method})`;throw new a(a$1(w)?"trap":"crash",C,`${C}: ${w instanceof Error?w.message:String(w)}`)}}};function j$1(p){if(!T)throw new Error("Worker peer snapshot is not active");if(T.version!==p.version()||T.sequence!==u$2)throw new Error("Workbook changed during peer snapshot");return T}let se={async decodeFontFace(p,n,f,h){if(c$2)throw new Error("Workbook session is disposed");if(await(e$1.initWasm??o$1)(h,a$2===void 0?void 0:{png:a$2}),c$2)throw new Error("Workbook session is disposed");let w=await k(n,f);return e(w,w.payload===void 0?[w.font]:[w.font,w.payload])},async openRecovery(p,n,f={}){if(c$2)throw new Error("Workbook session is disposed");if(o$2)throw new Error("Workbook session is already open");let h=Bt(n.state);if(n.epoch!==h.epoch||n.version!==h.revision||n.throughSeq!==h.throughSeq)throw new TypeError("Workbook recovery envelope mismatch");if(zt(h.engine))throw new Error("Recovery is unavailable for collaborative workbooks");if(c$1(f.fontCdn),a$2=f.png,await(e$1.initWasm??o$1)(f.wasm,{png:f.png}),c$2)throw new Error("Workbook session is disposed");let w$1=w(h.engine,h.throughSeq);try{q.session=h.session,v$1=jt(w$1,h,q),s$1=h.hostVersion,r$1=h.dirty,o$2=w$1,z$1(h);let C=w$1.sheetInfo();return {format:"xlsx",stage:"ready",version:s$1,dirty:r$1,sheets:v$1.sheetIds.map((Z,N)=>({id:Z,index:N,name:C.sheetNames[N]})),activeSheet:C.activeSheet,commandContext:{...q,basis:{epoch:v$1.epoch,version:w$1.version()}},throughSeq:v$1.throughSeq,revision:h.revision,historyReset:v$1.historyReset===!0,pngExport:s(),selection:v$1.selection,editState:v$1.editState}}catch(C){throw o$2=void 0,v$1=void 0,l=void 0,w$1.dispose(),C}},async open(p,n,f={}){if(c$2)throw new Error("Workbook session is disposed");if(o$2)throw new Error("Workbook session is already open");let h=f.initialViewport;if(h&&!G$1({sheet:h.sheet??0,viewport:{x:0,y:0,width:h.width,height:h.height},zoom:h.zoom,dpr:h.dpr,generation:h.requestGeneration}))throw new TypeError("Invalid workbook initial paint request");let w="retainPeerHydration"in f&&f.retainPeerHydration===true;y=w;let C=f.wasm;if(w&&C instanceof ArrayBuffer&&(C=await WebAssembly.compile(C)),c$1(f.fontCdn),a$2=f.png,await(e$1.initWasm??o$1)(C,{png:f.png}),C??(C=e$1.wasmModule?.()),c$2)throw new Error("Workbook session is disposed");let Z=f.collaborative&&!w?await mo.load():void 0;if(c$2)throw new Error("Workbook session is disposed");let N=f.calculation??(w&&!f.collaborative?{nowSerial:K(Date.now()),randSeed:globalThis.crypto.getRandomValues(new Uint32Array(1))[0]>>>0}:void 0),i=u(new Uint8Array(n),{collaborative:f.collaborative,clientId:f.clientId,calculation:N,recalculate:f.recalculate});m=f.collaborative===true;try{if(f.initialUpdate){if(!m||w)throw new Error("Initial updates require a collaborative worker replica");i.applyUpdate(f.initialUpdate);}f.recoveryVersion!==void 0&&A(i,f.recoveryVersion),h?.sheet!==void 0&&(J$1(i,h.sheet),i.setActiveSheet(h.sheet));let g;if(w&&(P={bytes:new Uint8Array(n).slice(),hydration:z(i)}),P){let he=JSON.parse(P.hydration);g=he.calculation_context===void 0?void 0:he.calculation_context===null?null:{nowSerial:he.calculation_context.now_serial,randSeed:he.workbook.rand_seed};}w&&C instanceof WebAssembly.Module&&t$1.post({protocol:1,kind:"wasm-module",url:c(f.png!==!1).href,module:C,hydration:P.hydration,version:i.version(),sequence:u$2});let I=i.sheetInfo(),W=Jt(I);o$2=i,m&&!w&&(H=i.onUpdate((he,Zt)=>{D.emit("collaborationUpdate",{update:he,origin:Zt});})),m&&!w&&(A$1=Z.createWorkbookCollaborationHost(i,re)),v$1=He(q,{epoch:1,version:i.version()},{sheetId:I.sheetIds[I.activeSheet],range:{kind:"a1",a1:"A1"}},I.sheetIds,N??null),v$1.collaborative=m&&!w,z$1(),w&&D.emit("peerOpened",{version:i.version(),initialCalculation:g});let X={...v$1};(h||!w&&f.includeEditState)&&Ee(i,X);let te={format:"xlsx",stage:"ready",version:s$1,dirty:r$1,...m&&!w?{clientId:i.clientId}:{},sheets:W,activeSheet:I.activeSheet,pngExport:s(),commandContext:{...q,basis:{epoch:v$1.epoch,version:i.version()}},...!w&&X.editState?{editState:X.editState,selection:v$1.selection}:{}};if(!h)return te;let K=M(I.activeSheet),Ne={...E({x:K.initialScrollX,y:K.initialScrollY,width:h.width/h.zoom,height:h.height/h.zoom},I.activeSheet),...q,coversThroughSeq:0,requestGeneration:h.requestGeneration,zoom:h.zoom,dpr:h.dpr};return l.rememberFrame({sheet:I.activeSheet,viewport:Ne.viewport,zoom:h.zoom,dpr:h.dpr,generation:h.requestGeneration}),e({...te,initialPaint:{sheetView:K,frame:Ne,editState:X.editState}},[Ne.displayList])}catch(g){throw o$2=void 0,v$1=void 0,l=void 0,P=void 0,A$1?.dispose(),A$1=void 0,H(),H=()=>{},i.dispose(),g}},version:()=>F().version(),collaborationStateVector(){return Y(),F().encodeStateVector()},collaborationStateAsUpdate(p,n){return Y(),F().encodeStateAsUpdate(n)},listDefinedNames:(p,n)=>F().listDefinedNames(n),readCells:(p,n)=>k$1(n,f=>F().readCells(f)),findText:(p,n)=>k$1(n,f=>F().findText(f)),validateEdits:(p,n)=>n.expectVersion!==F().version()?F().validateEdits(n):k$1(n,f=>F().validateEdits(f)),applyEdits(p,n){if(v$1?.throughSeq)throw new Error("Workbook command sessions require command batches");l?.validateDirectEdits();let f=F().applyEdits(n);return f.ok&&f.applied&&(l?.synchronizeDirectEdits(f.version),s$1+=1,r$1=true,D.emit("changed",{version:s$1,dirty:r$1})),f},async command(p,n){V(),(n.kind==="applyUpdate"||n.kind==="collabPipe")&&Y();let f=F().version(),h=await l.command(n);return F().version()!==f&&D.scheduler.bump({version:true,generation:true}),h},edit(p,n){return V(),(n.kind==="applyUpdate"||n.kind==="collabPipe")&&Y(),l.handler(null,n)},checkpoint(p,n=false){return V(),l.checkpoint(null,n)},commandFrame(p,n){V();let f=n?l.requestFrame(n):l.frame();return d(f.catch(h=>{if(!(h instanceof Error&&!(h instanceof a)&&h.message==="No frame is available at the settled command boundary"))throw h}))},frame(p,n,f={}){let h=E(n,f.sheet??F().sheetInfo().activeSheet);return e(h,[h.displayList])},sheetView(p,n){return M(n)},cellGeometry(p,n,f,h){let w=F();return J$1(w,n),{sheet:n,version:w.version(),rect:w.cellRect(n,f,h),scrollPosition:w.cellPosition(n,f,h)}},selectionData(p,n,f,h,w){let C=F();return J$1(C,n),C.selectionData(n,f,h,w)},cellInputs(p,n,f){let h=F();return J$1(h,n),{sheet:n,version:h.version(),cells:h.rangeCells(n,f)}},translateFormulas:(p,n)=>C(F(),n),captureFormat(p,n,f){let h=F();return J$1(h,n),h.captureFormat(n,f)},sheets:()=>Jt({...F().sheetInfo(),...v$1?.throughSeq?{sheetIds:v$1.sheetIds}:{}}),calculationStatus:()=>F().calculationStatus(),renderPng:(p,n,f={})=>O(n,f),renderPngFonts:(p,n,f={})=>g(F(),n,{...f,fonts:void 0}),exportStructured:(p,n)=>B$1(n),exportMarkdown(p,n,f){let h=F(),w=h.exportMarkdown(n,f);if(!v$1?.throughSeq)return w;if(w.ok){let C=B$1(n);if(!C.ok)return C}return pe(w,h.sheetInfo().sheetIds,v$1.sheetIds)},printDisplayList(p,n,f,h,w){let C=F();return J$1(C,n),_($.encode(JSON.stringify(C.printDisplayList(n,f,h,w))))},save(){let p=F().save(),n=p.buffer instanceof ArrayBuffer&&p.byteOffset===0&&p.byteLength===p.buffer.byteLength?p.buffer:new Uint8Array(p).buffer;return e(n,[n])},saveWithWarnings(){let{bytes:p,warnings:n}=F().saveWithWarnings(),f=p.buffer instanceof ArrayBuffer&&p.byteOffset===0&&p.byteLength===p.buffer.byteLength?p.buffer:new Uint8Array(p).buffer;return e({bytes:f,warnings:n},[f])},dispose(){F(),de();}};function V(){if(F(),!l)throw new Error("Workbook commands are not open");if(y||b||u$2>0)throw new Error("Workbook commands require a session without an edit peer")}function Y(){if(V(),!m)throw new Error("Workbook session is not collaborative")}for(let p of Object.keys(se)){let n=o[p],f=se[p];Object.defineProperty(se,p,{enumerable:true,value:(...h)=>{let w=typeof n=="function"?n(...h.slice(1)):n;if(y&&w.mutates)throw new w$1("mutation-outside-replay",`Cannot call ${p} outside workbook edit-peer replay in retained hydration mode`);return f(...h)}});}let ee={...t$1,post(p,n){let f=i(p)&&p.kind==="reply"?A$1?.drain():void 0,h=f?{collabPipe:f.batches}:void 0;t$1.post(h?{...p,...h}:p,f?[...n??[],...f.transfer]:n);}},D=L(ee,{handlers:{...se,...ne},policies:{...o,...r,edit:p=>l?.policy(p)??{lane:"input",reorderable:false},checkpoint:()=>l?.checkpointPolicy()??{lane:"input",reorderable:false}},context:null,onDispose:de,trapFailure:ho});return D}function ho(t){let e=b(t.message)??b(t.diagnostics),o=e?{bytes:e.bytes,memoryBytes:e.budgetBytes}:p();return o?new a("out-of-memory","The workbook is too large: the spreadsheet engine ran out of memory",`An allocation of ${o.bytes} bytes failed with ${Math.round(o.memoryBytes/2**20)} MiB of engine memory; ${t.message}${t.diagnostics?`: ${t.diagnostics}`:""}`):void 0}var Kt=Symbol.for("betteroffice.xlsx.worker.started");function wr(t){let e=t;if(e[Kt])return;e[Kt]=true;let o=l(t),c$1,a=false;o.listen(S=>{h(S)&&S.kind==="call"&&S.method==="open"&&(a=S.args[1]?.retainPeerHydration===true);});let s={...o,post:(...S)=>{a&&i(S[0])&&S[0].kind==="wasm-module"||o.post(...S);}},r=Qe(s,c(),o$1,async S=>(c$1=await Je(S),c$1)),d,u=Gt(o,{initWasm:e$1==="native"?o$1:(S,y)=>y?.png!==false?r(S):(d??(d=Qe(s,c(false),o$1,async b=>(c$1=await Je(b),c$1))),d(S)),wasmModule:()=>c$1});Object.assign(globalThis,{__betterofficeEngineProgress:()=>u.progress()});}
|
|
2
|
+
export{wr as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1,c}from'./chunk-T4GUPT57.js';import {a as a$3,d as d$1}from'./chunk-GHET7GIK.js';import {b,a as a$2,e}from'./chunk-JABP2QRG.js';import {a}from'./chunk-O2XFH626.js';var z=80,j=2e4,F=45e3,De=3e3,ge=1048576,Ee=16384,S=128,g=256,L=1024,Q=["#0B57D0","#B3261E","#146C2E","#6B4EFF","#8E24AA","#00639B","#8E4E00","#7D5260"];function J(s){return s?{sheet:s.sheet,anchor:{...s.anchor},head:{...s.head}}:null}function Ce(s){return {user:{...s.user},cursor:J(s.cursor)}}function K(s,e){return !s||!e?s===e:s.sheet===e.sheet&&s.anchor.row===e.anchor.row&&s.anchor.col===e.anchor.col&&s.head.row===e.head.row&&s.head.col===e.head.col}function Se(s,e){return !s||!e?s===e:s.user.name===e.user.name&&s.user.color===e.user.color&&K(s.cursor,e.cursor)}function Te(s){return Q[s%Q.length]}function _(s,e){if(typeof s!="string"||!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(s))return Te(e);let t=s.slice(1).toUpperCase();return t.length===6?`#${t}`:`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`}function Z(s,e){return {name:s?.name.trim().slice(0,S)||"Anonymous",color:_(s?.color,e)}}function ee(s,e,t,r,n={}){let i=n.maxPeers??L;if(!Number.isSafeInteger(i)||i<1)throw new RangeError("Awareness peer limit must be a positive integer");let o=false,c=0;for(let h of e){if(h.clientId===t)continue;let l=s.get(h.clientId);if(l&&h.clock<l.clock)continue;if(l&&h.clock===l.clock){l.lastSeen=r;continue}if(!l&&s.size>=i){c+=1;continue}let m=h.state?.cursor!=null&&(!l?.state||!K(l.state.cursor,h.state.cursor)),y=h.state?Ce(h.state):null;o||(o=!Se(l?.state??null,y)),s.set(h.clientId,{clock:h.clock,state:y,lastSeen:r,cursorMovedAt:m?r:l?.cursorMovedAt??0});}return c>0&&n.onPeersDiscarded?.(c),o}function te(s,e,t=F){let r=false;for(let[n,i]of s)e-i.lastSeen<t||(r||(r=i.state!==null),s.delete(n));return r}function re(s){let e=[];for(let[t,r]of s)r.state&&e.push({clientId:t,clock:r.clock,user:{...r.state.user},cursor:J(r.state.cursor),lastSeen:r.lastSeen,cursorMovedAt:r.cursorMovedAt});return e.sort((t,r)=>t.clientId-r.clientId),e}function Ve(s,e,t=ge,r=Ee){let n=e.indexOf(s.sheet);return n<0||t<1||r<1||[s.anchor,s.head].some(({row:o,col:c})=>!Number.isSafeInteger(o)||!Number.isSafeInteger(c)||o<0||c<0||o>=t||c>=r)?null:{sheetIndex:n,range:{top:Math.min(s.anchor.row,s.head.row),left:Math.min(s.anchor.col,s.head.col),bottom:Math.max(s.anchor.row,s.head.row),right:Math.max(s.anchor.col,s.head.col)}}}function se(s,e$1){return e(s,e$1)}var d=class extends Error{constructor(t,r,n){super(r);a(this,"code");a(this,"cause");this.name="CollaborationError",this.code=t,this.cause=n;}};function Pe(s){return s instanceof Error&&s.message?s.message:typeof s=="string"&&s?s:"Unknown error"}var Ue=["backpressure","protocol","replica","transport"],R=64,xe=250;function Fe(s){if(s[0]!==0||s[1]!==2)return false;let e=0;for(let t=2,r=0;t<Math.min(s.byteLength,7);t++,r+=7)if(e+=(s[t]&127)*2**r,s[t]<128)return t+1+e===s.byteLength;return false}var T=class{constructor(e,t,r){a(this,"transport",t);a(this,"options",r);a(this,"endpoint");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"peerListeners",new Map);a(this,"nextListenerId",0);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"peerList",[]);a(this,"seq",0);a(this,"floor",0);a(this,"sendFloor",0);a(this,"inboundBytes",0);a(this,"flushingFrames",false);a(this,"queue",[]);a(this,"posting",false);a(this,"flushQueued",false);a(this,"heldTimer",null);a(this,"urgent",false);a(this,"unsubscribeTransport",null);a(this,"subscription",0);a(this,"wantsConnection",false);a(this,"connectAttempt",0);a(this,"leaveFrame",null);a(this,"pendingFrames",[]);a(this,"queuedBytes",0);a(this,"isDestroyed",false);a(this,"closed",false);this.endpoint=e.open(n=>this.receive(n),n=>this.lose(n)),this.enqueue({op:"create",seq:++this.seq,options:r.worker});}get status(){return this.connectionStatus}get synced(){return this.isSynced}get pendingBytes(){return this.queuedBytes}get peers(){return this.peerList}setCursor(e,t){this.isDestroyed||this.enqueue({op:"cursor",seq:++this.seq,cursor:e,broadcast:t});}onPeers(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.peerListeners.set(t,e),e(this.peers),()=>this.peerListeners.delete(t)}onStatus(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};let t=this.nextListenerId++;return this.errorListeners.set(t,e),()=>this.errorListeners.delete(t)}connect(){if(this.isDestroyed||this.connectionStatus==="connected"||this.connectionStatus==="connecting")return;if(this.closed){this.report(this.options.makeError("replica","Collaboration replica is retired"));return}this.wantsConnection=true,this.floor=++this.seq,this.enqueue({op:"connect",seq:this.floor});let e=++this.connectAttempt;if(this.setStatus("connecting",false),!(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt)){if(!this.unsubscribeTransport){let t=++this.subscription,r;try{if(r=this.transport.onEvent(n=>this.forward(t,n)),typeof r!="function")throw new TypeError("Transport event subscription must return a function")}catch(n){this.subscription+=1,this.fail(this.transportError("Failed to subscribe to transport events",n));return}if(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt||t!==this.subscription){try{r();}catch(n){this.isDestroyed||this.report(this.transportError("Failed to unsubscribe from stale transport events",n));}return}this.unsubscribeTransport=r;}try{let t=this.transport.connect();t&&t.catch(r=>{!this.isDestroyed&&this.wantsConnection&&this.connectAttempt===e&&this.fail(this.transportError("Transport connect failed",r));});}catch(t){this.fail(this.transportError("Transport connect failed",t));}}}disconnect(){if(this.isDestroyed)return;if(this.closed){this.setStatus("disconnected",false);return}if(!(this.wantsConnection||this.unsubscribeTransport!==null||this.connectionStatus!=="disconnected"))return;this.sendLeave(),this.floor=++this.seq,this.enqueue({op:"disconnect",seq:this.floor});let t=this.release(true);this.setStatus("disconnected",false);for(let r of t)this.report(r);}destroy(){if(this.isDestroyed)return;let e=!this.closed&&(this.wantsConnection||this.unsubscribeTransport!==null||this.connectionStatus==="connecting"||this.connectionStatus==="connected");e&&this.sendLeave(),this.floor=++this.seq,this.enqueue({op:"destroy",seq:this.floor});let t=this.closed?[]:this.release(e);this.isDestroyed=true,this.setStatus("destroyed",false);for(let r of t)this.report(r);this.statusListeners.clear(),this.errorListeners.clear(),this.peerListeners.clear();}transportError(e,t){return this.options.normalize("transport",e,t)}release(e){this.wantsConnection=false,this.connectAttempt+=1,this.leaveFrame=null,this.clearQueue(),this.clearPeers();let t=[],r=this.unsubscribeTransport;if(this.unsubscribeTransport=null,this.subscription+=1,r)try{r();}catch(n){t.push(this.transportError("Failed to unsubscribe from transport events",n));}if(!e)return t;try{let n=this.transport.disconnect();n&&n.catch(i=>{this.isDestroyed||this.report(this.transportError("Transport disconnect failed",i));});}catch(n){t.push(this.transportError("Transport disconnect failed",n));}return t}fail(e){if(this.isDestroyed||!this.wantsConnection)return;let t=e.code;this.floor=++this.seq,this.enqueue({op:"fail",seq:this.floor,error:{code:typeof t=="string"&&Ue.includes(t)?t:"transport",message:e.message}});let r=this.release(true);this.setStatus("disconnected",false),this.report(e);for(let n of r)this.report(n);}sendLeave(){let e=this.leaveFrame;if(this.leaveFrame=null,!(!e||!this.options.hasUser||!this.unsubscribeTransport||this.connectionStatus!=="connected"))try{this.transport.send(e);}catch(t){this.report(this.transportError("Failed to send awareness leave",t));}}enqueue(e,t=false){this.closed||(this.queue.push(e),this.schedule(t));}schedule(e){if(e||(this.urgent=true),!(this.posting||this.flushQueued)){if(e){this.heldTimer??(this.heldTimer=setTimeout(()=>{this.heldTimer=null,this.flush();},xe));return}this.flushQueued=true,queueMicrotask(()=>{this.flushQueued=false,this.flush();});}}flush(){if(this.posting||this.closed||this.queue.length===0)return;this.heldTimer!==null&&(clearTimeout(this.heldTimer),this.heldTimer=null);let e=this.queue;this.queue=[],this.urgent=false,this.posting=true;let t=e.some(i=>i.op==="destroy"),r=e.reduce((i,o)=>o.op==="event"&&o.event.type==="message"?i+o.event.data.byteLength+R:i,0),n;try{n=this.endpoint.post(e,a$3(e));}catch(i){n=Promise.reject(i);}n.then(()=>{this.posting=false,this.inboundBytes-=r,t?this.close():this.urgent?this.flush():this.queue.length>0&&this.schedule(true);},i=>{this.posting=false,this.inboundBytes-=r,this.lose(Pe(i));});}forward(e,t){if(!(this.closed||this.isDestroyed||e!==this.subscription))switch(t.type){case "message":if(this.inboundBytes===0?t.data.byteLength>this.options.maxPendingBytes:t.data.byteLength+R>this.options.maxPendingBytes-this.inboundBytes){this.fail(this.options.makeError("backpressure","Pending replica data exceeds the byte limit"));return}this.inboundBytes+=t.data.byteLength+R,this.enqueue({op:"event",seq:++this.seq,event:{type:"message",data:t.data.slice().buffer}},!this.isSynced&&Fe(t.data)&&this.inboundBytes<=this.options.maxPendingBytes/2);return;case "open":case "close":this.clearQueue(),t.type==="close"&&(this.connectAttempt+=1,this.leaveFrame=null),this.sendFloor=++this.seq,this.enqueue({op:"event",seq:this.sendFloor,event:t.type==="open"?{type:"open"}:{type:"close",...t.reason!==void 0&&{reason:t.reason}}}),t.type==="close"&&(this.clearPeers(),this.setStatus("disconnected",false));return;case "drain":this.flushPending();return;case "error":this.fail(this.transportError("Transport error",t.error));return;default:this.fail(this.options.makeError("transport","Unknown transport event"));}}receive(e){for(let t of e){if(this.closed||this.isDestroyed)return;if(t.do==="lost"){this.lose("Collaboration replica is retired");return}if(!(t.through<this.floor))switch(t.do){case "unsubscribe":{let r=this.release(false);for(let n of r)this.report(n);break}case "disconnect":{this.wantsConnection=false;let r=this.release(true);for(let n of r)this.report(n);break}case "send":t.through>=this.sendFloor&&this.send(new Uint8Array(t.data));break;case "leave":t.through>=this.sendFloor&&(this.leaveFrame=t.data?new Uint8Array(t.data):null);break;case "status":t.through>=this.sendFloor&&this.setStatus(t.status,t.synced);break;case "peers":{if(t.through<this.sendFloor||t.peers.length===0&&this.peerList.length===0)break;let r=this.options.rebasePeer,n=t.timeOrigin-d$1();this.peerList=r?t.peers.map(i=>r(i,n)):t.peers,this.emitPeers();break}case "error":this.report(this.options.makeError(t.error.code,t.error.message));break}}}send(e){if(!this.unsubscribeTransport)return;if(this.pendingFrames.length>0){this.queueFrame(e);return}let t=this.sendFloor,r;try{r=this.transport.send(e.slice());}catch(n){this.fail(this.transportError("Transport send failed",n));return}if(typeof r!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}!r&&this.unsubscribeTransport!==null&&t===this.sendFloor&&this.queueFrame(e);}queueFrame(e){if(e.byteLength>this.options.maxPendingBytes-this.queuedBytes){this.fail(this.options.makeError("backpressure",`Pending collaboration data exceeds ${this.options.maxPendingBytes} bytes`));return}this.pendingFrames.push(e),this.queuedBytes+=e.byteLength;}flushPending(){if(!this.flushingFrames){this.flushingFrames=true;try{for(;this.unsubscribeTransport&&this.pendingFrames.length>0;){let e=this.pendingFrames[0],t;try{t=this.transport.send(e.slice());}catch(r){this.fail(this.transportError("Transport send failed",r));return}if(typeof t!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}if(!t||this.pendingFrames[0]!==e)return;this.pendingFrames.shift(),this.queuedBytes-=e.byteLength;}}finally{this.flushingFrames=false;}}}clearQueue(){this.pendingFrames.length=0,this.queuedBytes=0;}lose(e){if(this.closed||(this.close(),this.isDestroyed))return;this.sendLeave();let t=this.release(this.wantsConnection||this.connectionStatus!=="disconnected");setTimeout(()=>{if(!this.isDestroyed){this.setStatus("disconnected",false),this.report(this.options.makeError("replica",e));for(let r of t)this.report(r);}},0);}close(){this.closed||(this.closed=true,this.queue=[],this.heldTimer!==null&&(clearTimeout(this.heldTimer),this.heldTimer=null),this.endpoint.close());}clearPeers(){this.peerList.length!==0&&(this.peerList=[],this.emitPeers());}setStatus(e,t){if(!(this.connectionStatus===e&&this.isSynced===t)){this.connectionStatus=e,t&&!this.isSynced&&this.queue.length>0&&this.schedule(false),this.isSynced=t;for(let[r,n]of [...this.statusListeners])if(this.statusListeners.get(r)===n)try{n({status:e,synced:t});}catch{}}}emitPeers(){let e=this.peers;for(let[t,r]of [...this.peerListeners])if(this.peerListeners.get(t)===r)try{r(e);}catch{}}report(e){for(let[t,r]of [...this.errorListeners])if(this.errorListeners.get(t)===r)try{r(e);}catch{}}};var B=4096,E=1024,ie=0,oe=1,Le=2,ae=3,ce=0,ue=1,pe=2,_e=0,Re=Number.MAX_SAFE_INTEGER,Oe=10,O=new TextEncoder().encode("\0betteroffice-document-fingerprint-v1\0"),u=class extends Error{constructor(e){super(e),this.name="ProtocolError";}},U=class{constructor(e){a(this,"bytes",e);a(this,"offset",0);}get done(){return this.offset===this.bytes.byteLength}readVarUint(){let e=0,t=1,r=0;for(;;){if(this.offset>=this.bytes.byteLength)throw new u("Truncated varUint");let n=this.bytes[this.offset++],i=n&127;if(i>Math.floor((Re-e)/t))throw new u("varUint exceeds Number.MAX_SAFE_INTEGER");if(e+=i*t,r+=1,(n&128)===0){if(r>1&&i===0)throw new u("Non-canonical varUint");return e}if(r>=8)throw new u("varUint exceeds Number.MAX_SAFE_INTEGER");t*=128;}}readVarUint8Array(){let e=this.readVarUint(),t=this.bytes.byteLength-this.offset;if(e>t)throw new u("Truncated varUint8Array");let r=this.bytes.slice(this.offset,this.offset+e);return this.offset+=e,r}readVarString(){let e=this.readVarUint8Array();try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(t){throw new u(`Invalid UTF-8 string${t instanceof Error?`: ${t.message}`:""}`)}}};function f(s){if(!Number.isSafeInteger(s)||s<0)throw new u("varUint value must be a non-negative safe integer");let e=[],t=s;for(;t>=128;)e.push(t%128|128),t=Math.floor(t/128);return e.push(t),Uint8Array.from(e)}function v(s,e){let t=0;for(let i of s)if(t+=i.byteLength,t>e)throw new u(`Frame exceeds ${e} bytes`);let r=new Uint8Array(t),n=0;for(let i of s)r.set(i,n),n+=i.byteLength;return r}function Be(s){let e=new TextEncoder().encode(s);return [f(e.byteLength),e]}function P(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function ne(s){if(!P(s))throw new u("Awareness cell must be an object");let{row:e,col:t}=s;if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0)throw new u("Awareness cell coordinates must be non-negative safe integers");return {row:e,col:t}}function he(s,e){if(s===null)return null;if(!P(s)||!P(s.user))throw new u("Awareness state must contain a user");let{name:t,color:r}=s.user;if(typeof t!="string"||t.length===0||t.length>S)throw new u(`Awareness user name must contain 1 to ${S} characters`);let n=_(r,e),i=s.cursor;if(i==null)return {user:{name:t,color:n},cursor:null};if(!P(i)||typeof i.sheet!="string")throw new u("Awareness cursor must contain a sheet identifier");if(i.sheet.length===0||i.sheet.length>g)throw new u(`Awareness sheet identifier must contain 1 to ${g} characters`);return {user:{name:t,color:n},cursor:{sheet:i.sheet,anchor:ne(i.anchor),head:ne(i.head)}}}function M(s,e,t){return v([f(ie),f(s),f(e.byteLength),e],t)}function x(s,e=a$2){return M(ce,s,e)}function I(s,e=a$2){return M(ue,s,e)}function N(s,e=a$2){return M(pe,s,e)}function k(s,e=a$2){if(s.length>E)throw new u(`Awareness update exceeds ${E} states`);let t=[f(s.length)];for(let n of s){if(!Number.isSafeInteger(n.clientId)||n.clientId<=0)throw new u("Awareness clientId must be a positive safe integer");if(!Number.isSafeInteger(n.clock)||n.clock<0)throw new u("Awareness clock must be a non-negative safe integer");let i=he(n.state,n.clientId);t.push(f(n.clientId),f(n.clock),...Be(JSON.stringify(i)));}let r=v(t,e);return v([f(oe),f(r.byteLength),r],e)}function le(s=a$2){return v([f(ae)],s)}function de(s,e=E,t){if(!(s instanceof Uint8Array))throw new u("Awareness update must be a Uint8Array");if(!Number.isSafeInteger(e)||e<1)throw new u("Awareness state limit must be a positive integer");let r=new U(s),n=r.readVarUint();if(n>e){let c=new u(`Awareness update exceeds ${e} states`);if(!t)throw c;t(c);}let i=[],o=Math.min(n,e);for(let c=0;c<o;c++){let h,l,m;try{h=r.readVarUint(),l=r.readVarUint(),m=r.readVarString();}catch(y){if(!t)throw y;return t(new u(`Awareness entry ${c+1} could not be decoded: ${y instanceof Error?y.message:"Unknown error"}`)),i}try{if(h<=0)throw new u("Awareness clientId must be a positive safe integer");let y=JSON.parse(m);i.push({clientId:h,clock:l,state:he(y,h)});}catch(y){let $=y instanceof u?y:new u(`Invalid awareness JSON${y instanceof Error?`: ${y.message}`:""}`);if(!t)throw $;t(new u(`Awareness entry ${c+1} discarded: ${$.message}`));}}if(n<=e&&!r.done){let c=new u("Trailing awareness update data");if(!t)throw c;t(c);}return i}function A(s){let e=O.byteLength+32,t=s.byteLength-e;if(t<0)return s;for(let r=0;r<O.byteLength;r+=1)if(s[t+r]!==O[r])return s;return s.subarray(0,t)}var fe=BigInt(b),Me=65536;function ye(s){let e=0,t=()=>{let o=0n;for(let c=0;c<Oe&&e<s.byteLength;c+=1){let h=s[e++];if(o|=BigInt(h&127)<<BigInt(7*c),h<128)return o}},r=t();if(r===void 0)return;let n=e,i=[];for(let o=r;o>0n;o-=1n){let c=e,h=t(),l=t();if(h===void 0||l===void 0)return;i.push({client:h,clock:l,start:c,end:e});}return e===s.byteLength?{header:n,entries:i}:void 0}function be(s){let e=A(s),t=ye(e);if(!t)return s;let{header:r,entries:n}=t;if(!(n.length>=Me||n.some(({client:i})=>i===fe)))return v([f(n.length+1),e.subarray(r),f(b),f(0),s.subarray(e.byteLength)],Number.MAX_SAFE_INTEGER)}function q(s){let e=A(s),t=ye(e);if(!t)return {stateVector:s,open:false};let r=t.entries.filter(({client:n,clock:i})=>n!==fe||i!==0n);return r.length===t.entries.length?{stateVector:s,open:false}:{stateVector:v([f(r.length),...r.map(({start:n,end:i})=>e.subarray(n,i)),s.subarray(e.byteLength)],Number.MAX_SAFE_INTEGER),open:true}}function me(s,e=a$2,t=B){if(!(s instanceof Uint8Array))throw new u("Frame must be a Uint8Array");if(s.byteLength===0)throw new u("Frame is empty");if(s.byteLength>e)throw new u(`Frame exceeds ${e} bytes`);if(!Number.isSafeInteger(t)||t<1)throw new u("Message limit must be a positive integer");let r=new U(s),n=[];for(;!r.done;){if(n.length>=t)throw new u(`Frame exceeds ${t} messages`);let i=r.readVarUint();switch(i){case ie:{let o=r.readVarUint(),c=r.readVarUint8Array();if(o===ce)n.push({type:"sync-step-1",stateVector:c});else if(o===ue)n.push({type:"sync-step-2",update:c});else if(o===pe)n.push({type:"update",update:c});else throw new u(`Unknown sync message type ${o}`);break}case oe:n.push({type:"awareness",update:r.readVarUint8Array()});break;case Le:{let o=r.readVarUint();if(o!==_e)throw new u(`Unknown auth message type ${o}`);n.push({type:"auth",reason:r.readVarString()});break}case ae:n.push({type:"query-awareness"});break;default:throw new u(`Unknown top-level message type ${i}`)}}return n}var Ie=a$2,Ne=1e3;function D(s,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${s} must be ${t?"a non-negative":"a positive"} integer`);return e}function ke(s){return s instanceof Error&&s.message?s.message:typeof s=="string"&&s?s:"Unknown error"}function p(s,e,t){return t instanceof d?t:new d(s,`${e}: ${ke(t)}`,t)}function w(s,e){if(!(s instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return s.slice()}function V(s){s.unref?.();}var Ae=new WeakMap,ve=new WeakMap;function nt(s){return Ae.get(s)()}function it(s){return ve.get(s)()}var we=class{constructor(e,t,r={}){a(this,"replica");a(this,"piped");a(this,"asyncReplica");a(this,"replicaTail",Promise.resolve());a(this,"replicaBytes",0);a(this,"updateBatch",null);a(this,"syncArrival");a(this,"openEpoch",0);a(this,"transport");a(this,"maxFrameBytes");a(this,"maxMessagesPerFrame");a(this,"maxPendingBytes");a(this,"statusListeners",new Map);a(this,"errorListeners",new Map);a(this,"awarenessListeners",new Map);a(this,"awarenessStore",new Map);a(this,"awarenessUser");a(this,"pendingFrames",[]);a(this,"unsubscribeReplica");a(this,"unsubscribeTransport",()=>{});a(this,"hasTransportSubscription",false);a(this,"connectionStatus","disconnected");a(this,"isSynced",false);a(this,"wantsConnection",false);a(this,"isOpen",false);a(this,"isDestroyed",false);a(this,"epoch",0);a(this,"connectAttempt",0);a(this,"nextListenerId",0);a(this,"queuedBytes",0);a(this,"isFlushing",false);a(this,"transportCleanup");a(this,"statusRevision",0);a(this,"awarenessClock",0);a(this,"reportedClockExhaustion",false);a(this,"awarenessCursor",null);a(this,"lastAwarenessSentAt",Number.NEGATIVE_INFINITY);a(this,"awarenessBroadcastTimer");a(this,"awarenessHeartbeatTimer");a(this,"awarenessExpiryTimer");a(this,"hasPublishedAwarenessForOpen",false);this.replica=e,this.asyncReplica=a$1(e),this.transport=t,this.maxFrameBytes=D("maxFrameBytes",r.maxFrameBytes??a$2,false),this.maxMessagesPerFrame=D("maxMessagesPerFrame",r.maxMessagesPerFrame??B,false),this.maxPendingBytes=D("maxPendingBytes",r.maxPendingBytes??Ie,true),this.awarenessUser=Z(r.user,e.clientId),Ae.set(this,()=>this.beginArrival()),ve.set(this,()=>this.leaveFrame());let n=c(e);if(n){this.unsubscribeReplica=()=>{};let i;this.piped=new T(n,{connect:()=>this.connectPipedTransport(()=>i?.()),disconnect:()=>{this.wantsConnection=false,this.connectAttempt+=1;let o=this.cleanupTransport(()=>{},true);if(o.length)throw o[0]},send:o=>t.send(o),onEvent:o=>{if(!this.transportCleanup)return t.onEvent(o);let c=true,h=()=>{},l=()=>{i=void 0;try{let m=t.onEvent(o);if(typeof m!="function")throw new TypeError("Transport event subscription must return a function");c?h=m:m();}catch(m){throw p("transport","Failed to subscribe to transport events",m)}};return i=l,()=>{c=false,i===l&&(i=void 0),h();}}},{worker:{maxFrameBytes:this.maxFrameBytes,maxMessagesPerFrame:this.maxMessagesPerFrame,user:{...this.awarenessUser}},maxPendingBytes:this.maxPendingBytes,hasUser:true,makeError:(o,c,h)=>new d(o,c,h),normalize:p});return}try{this.unsubscribeReplica=e.onUpdate((i,o)=>{o==="local"&&this.forwardLocalUpdate(i);});}catch(i){throw p("replica","Failed to observe replica updates",i)}}get status(){return this.piped?this.piped.status:this.connectionStatus}get synced(){return this.piped?this.piped.synced:this.isSynced}get pendingBytes(){return this.piped?this.piped.pendingBytes:this.queuedBytes}get peers(){return this.piped?this.piped.peers:re(this.awarenessStore)}connect(){if(this.piped)return this.piped.connect();this.isDestroyed||this.isOpen||this.connectionStatus==="connecting"||(this.wantsConnection=true,this.setStatus("connecting",false),!(this.transportCleanup||this.isDestroyed||!this.wantsConnection)&&this.startConnection());}connectPipedTransport(e){this.wantsConnection=true;let t=++this.connectAttempt;return this.transportCleanup?this.transportCleanup.then(()=>{if(!(this.isDestroyed||!this.wantsConnection||t!==this.connectAttempt)&&(e(),!(this.isDestroyed||!this.wantsConnection||t!==this.connectAttempt)))return this.transport.connect()}):this.transport.connect()}startConnection(){if(this.isDestroyed||!this.wantsConnection||this.isOpen||this.transportCleanup)return;let e=this.hasTransportSubscription?this.epoch:++this.epoch,t=++this.connectAttempt;if(this.setStatus("connecting",false),!!this.isCurrent(e)){if(!this.hasTransportSubscription){let r;try{if(r=this.transport.onEvent(n=>this.handleTransportEvent(e,n)),typeof r!="function")throw new TypeError("Transport event subscription must return a function")}catch(n){this.failConnection(e,p("transport","Failed to subscribe to transport events",n));return}if(!this.isCurrent(e)){try{r();}catch(n){this.isDestroyed||this.report(p("transport","Failed to unsubscribe from stale transport events",n));}return}this.unsubscribeTransport=r,this.hasTransportSubscription=true;}try{let r=this.transport.connect();r&&r.catch(n=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,p("transport","Transport connect failed",n));});}catch(r){this.failConnection(e,p("transport","Transport connect failed",r));}}}disconnect(){if(this.piped)return this.piped.disconnect();if(this.isDestroyed||!(this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus!=="disconnected"))return;this.clearPending(),this.resetReplicaQueue(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),r=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let n of r)this.report(n);}destroy(){if(this.piped){this.isDestroyed=true,this.piped.destroy(),this.errorListeners.clear();return}if(this.isDestroyed)return;let e=this.wantsConnection||this.isOpen||this.hasTransportSubscription||this.connectionStatus==="connecting"||this.connectionStatus==="connected";this.clearPending(),this.resetReplicaQueue(),this.publishAwareness(null,"best-effort"),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isDestroyed=true,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let t=this.takeTransportSubscription(),r=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let n of r)this.report(n);try{this.unsubscribeReplica();}catch(n){this.report(p("replica","Failed to unsubscribe from replica updates",n));}this.unsubscribeReplica=()=>{},this.statusListeners.clear(),this.errorListeners.clear(),this.awarenessListeners.clear();}onStatus(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("status listener must be a function");if(this.piped)return this.piped.onStatus(e);let t=this.nextListenerId++;return this.statusListeners.set(t,e),()=>this.statusListeners.delete(t)}onError(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("error listener must be a function");let t=this.piped?.onError(e),r=this.nextListenerId++;return this.errorListeners.set(r,e),()=>{t?.(),this.errorListeners.delete(r);}}onAwareness(e){if(this.isDestroyed)return ()=>{};if(typeof e!="function")throw new TypeError("awareness listener must be a function");if(this.piped)return this.piped.onPeers(r=>{try{e(r);}catch{}});let t=this.nextListenerId++;this.awarenessListeners.set(t,e);try{e(this.peers);}catch{}return ()=>this.awarenessListeners.delete(t)}setCursor(e){if(this.isDestroyed)return;let t=e?se(e):false;if(this.awarenessCursor=e&&t?{sheet:e.sheet,anchor:{...e.anchor},head:{...e.head}}:null,e&&!t&&this.report(new d("protocol",`Awareness cursor needs a sheet identifier of 1 to ${g} characters and non-negative cell coordinates; cursor dropped`)),this.piped){this.piped.setCursor(this.awarenessCursor,true);return}if(!this.isOpen||!this.wantsConnection)return;let r=z-(Date.now()-this.lastAwarenessSentAt);if(r<=0){this.publishAwareness();return}this.awarenessBroadcastTimer||(this.awarenessBroadcastTimer=setTimeout(()=>{this.awarenessBroadcastTimer=void 0,this.publishAwareness();},r),V(this.awarenessBroadcastTimer));}isCurrent(e){return !this.isDestroyed&&this.wantsConnection&&e===this.epoch}failConnection(e,t){if(!this.isCurrent(e))return;this.resetReplicaQueue(),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.wantsConnection=false,this.isOpen=false,this.epoch+=1,this.connectAttempt+=1;let r=this.takeTransportSubscription();this.clearPending();let n=this.cleanupTransport(r,true);this.setStatus("disconnected",false),this.report(t);for(let i of n)this.report(i);}takeTransportSubscription(){let e=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,e}cleanupTransport(e,t){let r=[];try{e();}catch(n){r.push(p("transport","Failed to unsubscribe from transport events",n));}if(!t||this.transportCleanup)return r;try{let n=this.transport.disconnect();if(n){let i=!1,o=Promise.resolve(n).catch(c=>{i=!0,this.isDestroyed||this.report(p("transport","Transport disconnect failed",c));}).finally(()=>{this.transportCleanup===o&&(i&&!this.isDestroyed&&(this.wantsConnection=!1,this.piped?.disconnect()),this.transportCleanup=void 0,!this.isDestroyed&&(i?this.piped||this.setStatus("disconnected",!1):this.wantsConnection&&!this.piped&&this.startConnection()));});this.transportCleanup=o;}}catch(n){r.push(p("transport","Transport disconnect failed",n));}return r}handleTransportEvent(e,t){if(this.isCurrent(e))switch(t.type){case "open":this.handleOpen(e);break;case "message":this.isOpen&&this.handleMessage(e,t.data);break;case "close":this.resetReplicaQueue(),this.stopAwarenessTimers(),this.clearAwarenessPeers(),this.hasPublishedAwarenessForOpen=false,this.isOpen=false,this.connectAttempt+=1,this.clearPending(),this.setStatus("disconnected",false);break;case "error":this.failConnection(e,p("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new d("transport","Unknown transport event"));}}handleOpen(e){if(this.isOpen)return;let t=++this.openEpoch;if(this.replicaTail=Promise.resolve(),this.replicaBytes=0,this.updateBatch=null,this.isOpen=true,this.hasPublishedAwarenessForOpen=false,this.clearPending(),this.setStatus("connected",false),!this.isCurrent(e)||!this.isOpen)return;if(this.asyncReplica){Promise.resolve().then(()=>{if(this.isCurrentOpen(e,t))return this.asyncReplica.encodeStateVector()}).then(i=>{this.isCurrentOpen(e,t)&&this.sendHandshake(e,w(i,"encodeStateVector"),t);}).catch(i=>{this.isCurrentOpen(e,t)&&this.failConnection(e,p("replica","Failed to encode replica state vector",i));});return}let r;try{r=w(this.replica.encodeStateVector(),"encodeStateVector");}catch(n){this.failConnection(e,p("replica","Failed to encode replica state vector",n));return}this.sendHandshake(e,r,t);}sendHandshake(e,t,r){if(!this.isCurrentOpen(e,r))return;let n;try{n=be(t),this.sendFrame(x(n??t,this.maxFrameBytes));}catch(i){this.failConnection(e,p("protocol","Failed to encode collaboration handshake",i));return}if(!n&&this.isCurrentOpen(e,r)&&this.sendFullUpdate(e,r),!!this.isCurrentOpen(e,r)){try{this.sendFrame(le(this.maxFrameBytes));}catch(i){this.report(p("protocol","Failed to encode awareness query",i));}this.isCurrentOpen(e,r)&&(this.hasPublishedAwarenessForOpen||this.publishAwareness(),this.isCurrentOpen(e,r)&&this.startAwarenessTimers());}}sendFullUpdate(e,t){let r=o=>{if(this.isCurrentOpen(e,t))try{this.sendFrame(N(o,this.maxFrameBytes));}catch(c){this.failConnection(e,p("protocol","Failed to encode collaboration handshake",c));}},n=o=>{this.isCurrentOpen(e,t)&&this.failConnection(e,p("replica","Failed to encode replica update",o));};if(this.asyncReplica){this.asyncReplica.encodeStateAsUpdate().then(o=>w(o,"encodeStateAsUpdate")).then(r,n);return}let i;try{i=w(this.replica.encodeStateAsUpdate(),"encodeStateAsUpdate");}catch(o){n(o);return}r(i);}handleMessage(e,t,r){let n;try{if(!(t instanceof Uint8Array))throw new TypeError("Frame must be a Uint8Array");if(t.byteLength>this.maxFrameBytes)throw new RangeError(`Frame exceeds ${this.maxFrameBytes} bytes`);n=r??me(t,this.maxFrameBytes,this.maxMessagesPerFrame);}catch(i){this.failConnection(e,p("protocol","Invalid collaboration frame",i));return}if(this.asyncReplica&&!r){let i=[];for(let o of n){if(!this.isCurrent(e)||!this.isOpen)return;o.type==="sync-step-1"||o.type==="sync-step-2"||o.type==="update"?i.push(o):this.handleMessage(e,new Uint8Array,[o]);}i.length&&this.isCurrent(e)&&this.isOpen&&(this.asyncReplica.applyUpdateChunks&&i.every(o=>o.type==="update")?this.enqueueRemoteUpdates(e,t.byteLength,i.map(o=>o.update)):this.enqueueReplicaMessages(e,t.byteLength,i));return}for(let i of n){if(!this.isCurrent(e)||!this.isOpen)return;switch(i.type){case "sync-step-1":this.respondToSyncStep1(e,i.stateVector);break;case "sync-step-2":{let o=this.syncArrival,c=this.syncArrival={deferred:false};try{this.applyRemoteUpdate(e,i.update)&&this.isCurrent(e)&&!c.deferred&&this.setStatus("connected",!0);}finally{this.syncArrival=o;}break}case "update":this.applyRemoteUpdate(e,i.update);break;case "awareness":try{let o=[],c=0,h=ee(this.awarenessStore,de(i.update,E,l=>o.push(l)),this.replica.clientId,Date.now(),{onPeersDiscarded:l=>{c=l;}});for(let l of o)this.report(p("protocol","Invalid awareness update",l));if(c>0&&this.report(new d("protocol",`${c} awareness ${c===1?"entry was":"entries were"} discarded because the tracked peer limit of ${L} was reached`)),!this.isCurrent(e)||!this.isOpen)return;h&&this.emitAwareness();}catch(o){this.report(p("protocol","Invalid awareness update",o));}break;case "auth":this.failConnection(e,new d("protocol",i.reason?`Authentication denied: ${i.reason}`:"Authentication denied"));return;case "query-awareness":this.publishAwareness();break}}}isCurrentOpen(e,t){return this.isCurrent(e)&&this.isOpen&&t===this.openEpoch}resetReplicaQueue(){this.openEpoch+=1,this.replicaTail=Promise.resolve(),this.replicaBytes=0,this.updateBatch=null;}enqueueReplicaMessages(e,t,r){if(t>this.maxPendingBytes-this.replicaBytes){this.failConnection(e,new d("backpressure","Pending replica data exceeds the byte limit"));return}this.replicaBytes+=t,this.updateBatch=null;let n=this.openEpoch,i=this.replicaTail.then(async()=>{for(let o of r){if(!this.isCurrentOpen(e,n))return;try{if(o.type==="sync-step-1"){let c=q(o.stateVector),h=await this.asyncReplica.encodeStateAsUpdate(A(c.stateVector).slice());if(!this.isCurrentOpen(e,n))return;if(this.sendFrame(I(w(h,"encodeStateAsUpdate"),this.maxFrameBytes)),c.open&&this.isCurrentOpen(e,n)){let l=w(await this.asyncReplica.encodeStateVector(),"encodeStateVector");this.isCurrentOpen(e,n)&&this.sendFrame(x(l,this.maxFrameBytes));}}else (o.type==="sync-step-2"||o.type==="update")&&(await this.asyncReplica.applyUpdate(A(o.update).slice()),o.type==="sync-step-2"&&this.isCurrentOpen(e,n)&&this.setStatus("connected",!0));}catch(c){this.isCurrentOpen(e,n)&&this.failConnection(e,p("replica","Async replica operation failed",c));return}}}).finally(()=>{n===this.openEpoch&&(this.replicaBytes-=t);});this.replicaTail=i.catch(()=>{});}enqueueRemoteUpdates(e,t,r){if(t>this.maxPendingBytes-this.replicaBytes){this.failConnection(e,new d("backpressure","Pending replica data exceeds the byte limit"));return}this.replicaBytes+=t;let n=this.openEpoch,i=r.map(l=>A(l).slice()),o=this.updateBatch;if(o?.connection===n){o.updates.push(...i),o.bytes+=t;return}let c={connection:n,bytes:t,updates:i};this.updateBatch=c;let h=this.replicaTail.then(async()=>{if(this.updateBatch===c&&(this.updateBatch=null),!!this.isCurrentOpen(e,n))try{c.updates.length===1?await this.asyncReplica.applyUpdate(c.updates[0]):await this.asyncReplica.applyUpdateChunks(c.updates);}catch(l){this.isCurrentOpen(e,n)&&this.failConnection(e,p("replica","Async replica operation failed",l));}}).finally(()=>{n===this.openEpoch&&(this.replicaBytes-=c.bytes);});this.replicaTail=h.catch(()=>{});}respondToSyncStep1(e,t){let r=q(t),n;try{n=w(this.replica.encodeStateAsUpdate(A(r.stateVector).slice()),"encodeStateAsUpdate");}catch(o){this.failConnection(e,p("replica","Failed to encode replica update",o));return}try{this.sendFrame(I(n,this.maxFrameBytes));}catch(o){this.failConnection(e,p("protocol","Failed to encode SyncStep2",o));return}if(!r.open||!this.isCurrent(e)||!this.isOpen)return;let i;try{i=w(this.replica.encodeStateVector(),"encodeStateVector");}catch(o){this.failConnection(e,p("replica","Failed to encode replica state vector",o));return}try{this.sendFrame(x(i,this.maxFrameBytes));}catch(o){this.failConnection(e,p("protocol","Failed to encode collaboration handshake",o));}}beginArrival(){let e=this.epoch,t=this.openEpoch,r=this.syncArrival;r&&(r.deferred=true);let n=false,i=o=>{n||(n=true,this.isCurrentOpen(e,t)&&o());};return {settle:()=>i(()=>{r&&this.setStatus("connected",true);}),fail:o=>i(()=>this.failConnection(e,p("replica","Failed to apply remote update",o)))}}leaveFrame(){if(!this.isOpen||this.isDestroyed||!this.wantsConnection||this.awarenessClock>=Number.MAX_SAFE_INTEGER)return null;try{let e=this.awarenessClock+1;return {clock:e,frame:k([{clientId:this.replica.clientId,clock:e,state:null}],this.maxFrameBytes)}}catch{return null}}applyRemoteUpdate(e,t){try{return this.replica.applyUpdate(A(t).slice()),!0}catch(r){return this.failConnection(e,p("replica","Failed to apply remote update",r)),false}}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,r;try{r=w(e,"Replica update");}catch(n){this.failConnection(t,p("replica","Invalid replica update",n));return}try{this.sendFrame(N(r,this.maxFrameBytes));}catch(n){this.failConnection(t,p("protocol","Failed to encode update",n));}}publishAwareness(e="current",t="queued"){if(!(!this.isOpen||this.isDestroyed||!this.wantsConnection)){if(this.awarenessBroadcastTimer&&(clearTimeout(this.awarenessBroadcastTimer),this.awarenessBroadcastTimer=void 0),this.awarenessClock>=Number.MAX_SAFE_INTEGER){t==="queued"&&!this.reportedClockExhaustion&&(this.reportedClockExhaustion=true,this.report(new d("protocol","Awareness clock exhausted")));return}this.awarenessClock+=1;try{this.hasPublishedAwarenessForOpen=!0;let r=k([{clientId:this.replica.clientId,clock:this.awarenessClock,state:e===null?null:{user:this.awarenessUser,cursor:this.awarenessCursor}}],this.maxFrameBytes);t==="best-effort"?this.sendBestEffort(r):this.sendFrame(r),this.lastAwarenessSentAt=Date.now();}catch(r){t==="queued"&&this.report(p("protocol","Failed to encode awareness update",r));}}}startAwarenessTimers(){this.stopAwarenessTimers(),this.awarenessHeartbeatTimer=setInterval(()=>{this.publishAwareness();},j),this.awarenessExpiryTimer=setInterval(()=>{te(this.awarenessStore,Date.now(),F)&&this.emitAwareness();},Ne),V(this.awarenessHeartbeatTimer),V(this.awarenessExpiryTimer);}stopAwarenessTimers(){this.awarenessBroadcastTimer&&clearTimeout(this.awarenessBroadcastTimer),this.awarenessHeartbeatTimer&&clearInterval(this.awarenessHeartbeatTimer),this.awarenessExpiryTimer&&clearInterval(this.awarenessExpiryTimer),this.awarenessBroadcastTimer=void 0,this.awarenessHeartbeatTimer=void 0,this.awarenessExpiryTimer=void 0;}clearAwarenessPeers(){if(this.awarenessStore.size===0)return;let e=this.peers.length>0;this.awarenessStore.clear(),e&&this.emitAwareness();}emitAwareness(){let e=this.peers;for(let[t,r]of [...this.awarenessListeners])if(this.awarenessListeners.get(t)===r)try{r(e);}catch{}}sendFrame(e){if(!this.isOpen||this.isDestroyed||!this.wantsConnection)return;let t=this.epoch;if(this.pendingFrames.length>0){this.queueFrame(t,e);return}let r;try{r=this.transport.send(e.slice());}catch(n){this.failConnection(t,p("transport","Transport send failed",n));return}if(typeof r!="boolean"){this.failConnection(t,new d("transport","Transport send must return a boolean"));return}!r&&this.isCurrent(t)&&this.isOpen&&this.queueFrame(t,e);}sendBestEffort(e){try{this.transport.send(e.slice());}catch{}}queueFrame(e,t){if(t.byteLength>this.maxPendingBytes-this.queuedBytes){this.failConnection(e,new d("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let r=t.slice();this.pendingFrames.push(r),this.queuedBytes+=r.byteLength;}flushPending(){if(!this.isFlushing){this.isFlushing=true;try{for(;this.isOpen&&!this.isDestroyed&&this.pendingFrames.length>0;){let e=this.epoch,t=this.pendingFrames[0],r;try{r=this.transport.send(t.slice());}catch(n){this.failConnection(e,p("transport","Transport send failed",n));return}if(typeof r!="boolean"){this.failConnection(e,new d("transport","Transport send must return a boolean"));return}if(!r||!this.isOpen||this.pendingFrames[0]!==t)return;this.pendingFrames.shift(),this.queuedBytes-=t.byteLength;}}finally{this.isFlushing=false;}}}clearPending(){this.pendingFrames.length=0,this.queuedBytes=0;}setStatus(e,t){if(this.connectionStatus===e&&this.isSynced===t)return;this.connectionStatus=e,this.isSynced=t;let r=++this.statusRevision,n={status:e,synced:t};for(let[i,o]of [...this.statusListeners]){if(this.statusRevision!==r)return;if(this.statusListeners.get(i)===o)try{o(n);}catch{}}}report(e){for(let[t,r]of [...this.errorListeners])if(this.errorListeners.get(t)===r)try{r(e);}catch{}}};export{z as a,j as b,F as c,De as d,ge as e,Ee as f,L as g,Q as h,Te as i,_ as j,Z as k,ee as l,te as m,re as n,Ve as o,d as p,nt as q,it as r,we as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-OUNTNO7R.js';function t(e){let o=globalThis.process;if(typeof o?.getBuiltinModule!="function")throw a(e);let n=o.getBuiltinModule("node:worker_threads");if(!n)throw a(e);return n}function i(){let e=t("the in-thread API").parentPort;if(!e)throw a("the in-thread API");return e}export{t as a,i as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {p,r,q,s}from'./chunk-6OSHYRMV.js';import'./chunk-T4GUPT57.js';import {a as a$1}from'./chunk-VJDPZ75R.js';import {b,d}from'./chunk-GHET7GIK.js';import'./chunk-JABP2QRG.js';import {a}from'./chunk-O2XFH626.js';var y=class{constructor(s){a(this,"emit",s);a(this,"listener",null);}connect(){}disconnect(){this.emit("disconnect");}send(s){return this.emit(s),true}onEvent(s){return this.listener=s,()=>{this.listener===s&&(this.listener=null,this.emit("unsubscribe"));}}deliver(s){this.listener?.(s);}};function E(n){let s=new Map,a=[],l=false,c=false,i=null,u=(e,t)=>{if(c)return;let r=!l&&a.length===0,o=a[a.length-1];o?.provider===e?o.out.push(t):a.push({provider:e,out:[t]}),r&&n.onOutput?.();},v=()=>{let e=i;if(!e||e.updates.length===0)return;i={updates:[],arrivals:[],single:true};let t=n.merge(e.updates,e.single&&e.updates.length===1);if("failed"in t){for(let r of e.arrivals)r.fail(t.failed);return}e.arrivals.forEach((r,o)=>r.settle(o===e.arrivals.length-1?t.applied:null));},b$1=(e,t,r)=>{if(!i)throw new Error("Collaboration updates merge only within a pipe burst");return i.updates.push(...t),i.arrivals.push(n.arrive(e)),i.single&&(i.single=r),null},S=e=>({clientId:n.clientId,encodeStateVector:()=>(v(),n.read.encodeStateVector()),encodeStateAsUpdate:t=>(v(),n.read.encodeStateAsUpdate(t)),...n.read.encodeStateAsUpdateChunks&&{encodeStateAsUpdateChunks:(t,r)=>(v(),n.read.encodeStateAsUpdateChunks(t,r))},applyUpdate:t=>b$1(e(),[t],true),applyUpdateChunks:t=>b$1(e(),t,false),onUpdate:n.onUpdate}),O=(e,t)=>{let r,o=new y(d=>{r.echo||u(e,typeof d=="string"?{do:d,through:r.through}:{do:"send",data:b(d),through:r.through});}),p=n.createProvider(S(()=>r.provider),o,t);r={id:e,provider:p,transport:o,through:0,echo:false,leaveClock:null,stop:[]};let g=false;return r.stop.push(p.onStatus(({status:d,synced:T})=>u(e,{do:"status",status:d,synced:T,through:r.through})),p.onError(d=>{r.echo||u(e,{do:"error",error:{code:d.code,message:d.message},through:r.through});}),p.onPeers(d$1=>{g&&u(e,{do:"peers",peers:[...d$1],timeOrigin:d(),through:r.through});})),g=true,s.set(e,r),r},P=(e,t)=>{e.echo=true;try{t();}finally{e.echo=false;}},x=e=>{let t=s.get(e.provider);for(let r of e.ops){if(r.op==="create"){t??(t=O(e.provider,r.options)),t.through=r.seq;continue}if(!t){u(e.provider,{do:"lost"});return}let o=t;switch(o.through=r.seq,r.op){case "connect":P(o,()=>o.provider.connect());break;case "disconnect":P(o,()=>o.provider.disconnect());break;case "fail":P(o,()=>o.transport.deliver({type:"error",error:n.transportError(r.error)}));break;case "destroy":P(o,()=>o.provider.destroy());for(let p of o.stop)p();s.delete(o.id),t=void 0;break;case "cursor":o.provider.setCursor(r.cursor,r.broadcast);break;case "event":{let{event:p}=r;o.transport.deliver(p.type==="message"?{type:"message",data:new Uint8Array(p.data)}:p);break}}}},H=()=>{for(let e of s.values()){let t=n.leave(e.provider),r=t?.clock??null;r!==e.leaveClock&&(e.leaveClock=r,u(e.id,{do:"leave",data:t?b(t.frame):null,through:e.through}));}};return {run(e){if(!c){l=true,i={updates:[],arrivals:[],single:true};try{x(e),v();}finally{i=null,l=false;}}},drain(){l=true;try{H();}finally{l=false;}if(a.length===0)return;let e=a;a=[];let t=[];for(let r of e)for(let o of r.out)(o.do==="send"||o.do==="leave"&&o.data)&&t.push(o.data);return {batches:e,transfer:t}},dispose(){if(!c){c=true;for(let e of s.values()){for(let t of e.stop)t();e.echo=true;try{e.provider.destroy();}catch{}}s.clear(),a=[];}}}}function L(n,s$1){return E({clientId:n.clientId,read:{encodeStateVector:()=>n.encodeStateVector(),encodeStateAsUpdate:a=>n.encodeStateAsUpdate(a)},onUpdate:a=>n.onUpdate(a),merge(a){for(let l of a){let c=n.version();try{n.applyUpdate(l);}catch(i){if(!(i instanceof Error)||a$1(i)||n.version()!==c)throw i;return {failed:i}}}return {applied:null}},createProvider:(a,l,c)=>{let i=new s(a,l,c);return Object.assign(i,{onPeers:u=>i.onAwareness(u)})},arrive:q,leave:r,transportError:a=>new p(a.code,a.message),onOutput:s$1})}export{L as createWorkbookCollaborationHost};
|