@betteroffice/xlsx 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,129 +1,151 @@
1
1
  # @betteroffice/xlsx
2
2
 
3
- Framework-free core for the BetterOffice XLSX editor — the Rust engine (parse,
4
- calc, render) compiled to WebAssembly, plus display-list, viewport, hit-test,
5
- and accessibility helpers.
3
+ Framework-free XLSX parsing, formula calculation, editing, and rendering through a Rust/WebAssembly
4
+ engine. Includes canvas painting, viewport, hit-testing, accessibility, and clipboard helpers.
5
+
6
+ ## Install
6
7
 
7
8
  ```bash
8
9
  bun add @betteroffice/xlsx
9
10
  ```
10
11
 
11
- Most apps want the turnkey React component in
12
- [`@betteroffice/xlsx-react`](https://www.npmjs.com/package/@betteroffice/xlsx-react).
13
- Reach for this package directly to render a spreadsheet onto your own canvas or
14
- to drive a workbook headlessly.
15
-
16
- ## Open, render, edit, save
17
-
18
- ```ts
19
- import { initWasm, openWorkbook, paintDisplayList } from "@betteroffice/xlsx";
12
+ No peer dependencies.
20
13
 
21
- await initWasm();
22
- const workbook = openWorkbook(new Uint8Array(await file.arrayBuffer()));
14
+ ## Usage
23
15
 
24
- const ctx = canvas.getContext("2d")!;
25
- const dpr = devicePixelRatio;
26
- canvas.width = 800 * dpr;
27
- canvas.height = 600 * dpr;
28
- const frame = workbook.displayList({ x: 0, y: 0, width: 800, height: 600 });
29
- paintDisplayList(ctx, frame, dpr);
16
+ Sheet, row and column indices are zero-based, so `editCell(0, 9, 2, ...)` writes cell C10 on the
17
+ first sheet.
30
18
 
31
- workbook.editCell(0, 9, 2, "=SUM(C1:C9)"); // recalcs dependents
32
- const bytes = workbook.save();
19
+ ```ts
20
+ import { initWasm, openWorkbook } from '@betteroffice/xlsx';
21
+
22
+ export async function updateWorkbook(bytes: Uint8Array): Promise<Uint8Array> {
23
+ await initWasm();
24
+ const workbook = openWorkbook(bytes);
25
+ try {
26
+ workbook.editCell(0, 9, 2, '=SUM(C1:C9)');
27
+ return workbook.save();
28
+ } finally {
29
+ workbook.dispose();
30
+ }
31
+ }
33
32
  ```
34
33
 
35
- `initWasm()` fetches the packaged wasm asset once in browsers. Pass wasm bytes
36
- or a precompiled `WebAssembly.Module` explicitly in runtimes that cannot fetch
37
- the asset URL.
34
+ Cell input parses text, numbers, booleans, and formulas;
35
+ formulas start with `=`. Editing a cell recalculates its dependents.
38
36
 
39
- Around the handle, the package exports the helpers a custom grid needs:
40
- `cellAtPoint` / `cellRect` / `rangeRect` (hit-testing), the viewport math,
41
- `buildA11yGrid` (accessibility tree), and `toTsv` / `fromTsv` (clipboard). The
42
- handle itself covers styling (`patchRangeStyle`, `setNumberFormat`), undo/redo,
43
- and PNG export (`renderPng` / `renderRangePng`; guard with
44
- `isPngExportAvailable`).
37
+ ## Entry points
45
38
 
46
- ## Print a range
39
+ These entry points are exported from `@betteroffice/xlsx`:
47
40
 
48
- `workbook.printDisplayList(sheet, range, metrics, gridlines)` renders a range
49
- without changing workbook data, the active sheet, or screen geometry. Pass
50
- `PrintMetrics` measured from the workbook's normal font: `dpi`, `maxDigitWidth`,
51
- `fontAscent`, and `fontDescent` use the layout device's pixels; `fontSizePt` and
52
- `defaultRowHeightPt` use points. `fontFamily` supplies the default face, and
53
- optional `defaultColumnWidth` uses the stored OOXML character width.
41
+ | entry point | description |
42
+ | --- | --- |
43
+ | `initWasm(input?)` | Initialize the engine; concurrent calls share initialization. |
44
+ | `openWorkbook(bytes, options?)` | Open XLSX bytes as a synchronous `WorkbookHandle` after initialization. |
45
+ | `openWorkbookSession(bytes, options?)` | Open a workbook in a dedicated worker with asynchronous access. |
46
+ | `paintDisplayList(ctx, frame, dpr, origin?)` | Paint a display list onto a canvas 2D context. |
47
+ | `isPngExportAvailable()` | Check whether the initialized engine supports PNG export. |
48
+ | `isProposalsAvailable()` | Check whether the initialized engine supports edit proposals. |
49
+ | `exportXlsxStructured(bytes, options?)` | Asynchronously export stored workbook content from bytes. |
50
+ | `exportXlsxMarkdown(bytes, options?, markdownOptions?)` | Asynchronously export Markdown from bytes. |
54
51
 
55
- The result uses 96-DPI logical coordinates. Paint it with `paintDisplayList(ctx,
56
- frame, scale, { x, y })`; the optional origin uses backing-store pixels, so page
57
- margins need no intermediate image. Cell ranges, paper size, and pagination are
58
- chosen by the caller. See the [Office comparison harness](../../scripts/office-quality).
52
+ `initWasm()` loads the packaged WASM asset by default. Pass WASM bytes or a compiled
53
+ `WebAssembly.Module` in runtimes that cannot fetch that URL. Dispose workbook handles when finished.
59
54
 
60
- ## AI agents / human-in-the-loop
55
+ ## Canvas rendering and grid helpers
61
56
 
62
- An agent stages edits as a proposal instead of applying them; a human reviews
63
- per-cell before/after previews and accepts or rejects. Accepting applies the
64
- proposal as one undo step and recalcs dependents, and throws
65
- `StaleProposalError` if the workbook drifted under the proposal since it was
66
- staged.
57
+ `WorkbookHandle.displayList(viewport)` returns the active sheet's display list. Size the backing store
58
+ for the device pixel ratio and give the canvas its logical CSS dimensions:
67
59
 
68
60
  ```ts
69
- import { isProposalsAvailable } from "@betteroffice/xlsx";
70
-
71
- if (isProposalsAvailable()) {
72
- const proposal = workbook.propose("copilot", "add totals", [
73
- { sheet: 0, row: 9, col: 2, input: "=SUM(C1:C9)" },
74
- ]);
75
- workbook.listProposals(); // pending proposals, oldest first
76
- workbook.acceptProposal(proposal.id); // or workbook.rejectProposal(proposal.id)
61
+ import { paintDisplayList, type WorkbookHandle } from '@betteroffice/xlsx';
62
+
63
+ export function drawWorkbook(workbook: WorkbookHandle, canvas: HTMLCanvasElement) {
64
+ const dpr = window.devicePixelRatio || 1;
65
+ canvas.width = 800 * dpr;
66
+ canvas.height = 600 * dpr;
67
+ canvas.style.width = '800px';
68
+ canvas.style.height = '600px';
69
+ const ctx = canvas.getContext('2d');
70
+ if (!ctx) throw new Error('Canvas 2D is unavailable');
71
+ const frame = workbook.displayList({ x: 0, y: 0, width: 800, height: 600 });
72
+ paintDisplayList(ctx, frame, dpr);
77
73
  }
78
74
  ```
79
75
 
80
- The React editor paints pending proposals as in-cell tracked-change ghosts with
81
- an accept/reject panel. Guard with `isProposalsAvailable()` against cores built
82
- without the feature.
76
+ For a custom grid, use `cellAtPoint`, `cellRect`, and `rangeRect` for hit-testing and geometry,
77
+ `buildA11yGrid` for accessibility data, and `toTsv` / `fromTsv` for clipboard text.
78
+ The `@betteroffice/xlsx/headless` entry exports pure grid helpers and types without the canvas painter
79
+ or WASM loader.
83
80
 
84
- ## Collaboration
81
+ ## Range moves
85
82
 
86
- Open a collaborative replica, then connect it to any reliable binary transport:
83
+ `workbook.moveRange(sheet, source, destination)` moves an A1 range within a sheet and rewrites
84
+ references in one undo step; the destination is the new top-left cell. Surface errors when a move is
85
+ refused rather than discarding the source workbook.
87
86
 
88
- ```ts
89
- import { initWasm, openWorkbook } from "@betteroffice/xlsx";
90
- import {
91
- CollaborationProvider,
92
- type CollaborationTransport,
93
- } from "@betteroffice/xlsx/collaboration";
94
-
95
- await initWasm();
96
- const workbook = openWorkbook(bytes, { collaborative: true });
97
- const transport: CollaborationTransport = createTransport();
98
- const provider = new CollaborationProvider(workbook, transport, {
99
- user: { name: "Ada" }, // identity for this peer's selection flag
100
- });
101
- provider.connect();
102
-
103
- function dispose() {
104
- provider.destroy();
105
- workbook.dispose();
106
- }
107
- ```
87
+ ## Printing and PNG export
88
+
89
+ `workbook.printDisplayList(sheet, range, metrics, gridlines)` renders an A1 range using `PrintMetrics`
90
+ measured from the workbook's normal font. The caller chooses paper size, margins, and pagination;
91
+ `paintDisplayList` accepts an optional origin in backing-store pixels for positioning the result.
92
+
93
+ `workbook.renderPng(viewport)` exports the active sheet's viewport. `workbook.renderRangePng()` exports
94
+ its used range, or accepts `{ range, scale }` to select an A1 range and raster scale. Both return PNG
95
+ bytes synchronously; check `isPngExportAvailable()` before calling them.
96
+
97
+ ## Worker sessions
98
+
99
+ The low-level `openWorkbookSession` API (also exported from `@betteroffice/xlsx/worker`) is
100
+ experimental. It returns a `WorkbookSession` with
101
+ promise-returning operations through `session.call`, plus asynchronous `session.save()` and
102
+ `session.dispose()` methods.
103
+
104
+ The React editor uses a worker by default and exposes its own asynchronous API. Use
105
+ [`@betteroffice/xlsx-react`](https://www.npmjs.com/package/@betteroffice/xlsx-react) for the editor UI.
106
+
107
+ ## Edit proposals
108
+
109
+ `workbook.propose(agentId, note, edits)` stages cell edits for review without applying them.
110
+ `listProposals`, `acceptProposal`, and `rejectProposal` manage that queue; acceptance applies the
111
+ proposal as one undo step and recalculates dependents. Check `isProposalsAvailable()` first;
112
+ acceptance throws `StaleProposalError` if targeted cells have changed since staging.
113
+
114
+ ## Version-checked edit batches
115
+
116
+ `readCells` returns cells with their version; `validateEdits` checks a batch without committing it,
117
+ and `applyEdits` applies all steps or returns a typed refusal without changing the workbook.
118
+ See [Edit XLSX in version-checked batches](https://docs.betteroffice.dev/docs/javascript#edit-xlsx-in-version-checked-batches)
119
+ for targets, guards, supported steps, and limits.
120
+
121
+ ## Structured export
122
+
123
+ `exportStructured` and `exportMarkdown` read committed content with positional anchors and diagnostics
124
+ without recalculating formulas. See
125
+ [Export XLSX content with anchors](https://docs.betteroffice.dev/docs/javascript#export-xlsx-content-with-anchors)
126
+ for scopes, hidden content, limits, and byte-based exports.
127
+
128
+ ## Collaboration
129
+
130
+ The `@betteroffice/xlsx/collaboration` entry exports `CollaborationProvider` for connecting replicas
131
+ to a binary transport. See the [collaboration guide](https://docs.betteroffice.dev/docs/collaboration)
132
+ for provider lifecycle, transport setup, and shared starting state.
108
133
 
109
- The provider speaks the Yjs sync-v1 protocol used by y-websocket. WebSocket room
110
- routing, authentication, WebRTC signaling, reconnection policy, and awareness
111
- remain transport concerns; document updates flow directly between the connection
112
- and the Rust/WASM Yrs replica without a second JavaScript `Y.Doc`.
113
- After a close, the transport may reopen itself or the caller may invoke
114
- `provider.connect()` for another connection attempt.
115
- Call `provider.destroy()` before discarding its transport or workbook.
134
+ Open the workbook with `openWorkbook(bytes, { collaborative: true })`. Collaborative workbooks
135
+ synchronize cell content, formulas, styles, column widths and row heights, with local undo and
136
+ redo whose effects synchronize.
137
+ Structural edits throw: inserting or deleting rows and columns, adding, removing, moving or renaming
138
+ sheets, and changing charts or defined names.
116
139
 
117
- Collaborative sessions currently support cell content, formulas, styles, column
118
- widths, and row heights. Structural edits and inverse-op undo are rejected until
119
- they have stable axis identities and a Yrs-aware undo manager.
140
+ ## Operation profiles
120
141
 
121
- ## Development
142
+ `editCellProfiled`, `applyOpsProfiled`, and `displayListProfiled` return engine stage durations in
143
+ milliseconds alongside their results. See
144
+ [Operation profiles](https://docs.betteroffice.dev/docs/javascript#operation-profiles).
122
145
 
123
- The generated `.wasm` binary is intentionally not committed. From the repository
124
- root, install `wasm-pack` 0.15.0 and `binaryen`, then run
125
- `bun run build:xlsx-wasm`. Package builds, tests, demo startup, and CI run this
126
- step automatically.
146
+ ## Documentation
127
147
 
128
- [JavaScript guide](https://docs.betteroffice.dev/docs/javascript) ·
129
- [Changelog](https://github.com/openooxml/betteroffice/blob/main/packages/xlsx/CHANGELOG.md) · Apache-2.0.
148
+ - [JavaScript guide](https://docs.betteroffice.dev/docs/javascript)
149
+ - [Package guide](https://docs.betteroffice.dev/docs/packages)
150
+ - [React editor on npm](https://www.npmjs.com/package/@betteroffice/xlsx-react)
151
+ - [Repository](https://github.com/openooxml/betteroffice)
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Wire format between a main-thread collaboration facade and the provider its document worker runs.
3
+ * Main owns the host transport's lifecycle and forwards its bytes untouched; the worker runs the protocol and
4
+ * answers with frames to send, state and the transport calls its own failures need.
5
+ */
6
+ type PipeErrorCode = 'backpressure' | 'protocol' | 'replica' | 'transport';
7
+ interface PipeError {
8
+ code: PipeErrorCode;
9
+ message: string;
10
+ }
11
+ interface PipeUser {
12
+ name: string;
13
+ color?: string;
14
+ }
15
+ interface PipeProviderOptions {
16
+ maxFrameBytes?: number;
17
+ maxMessagesPerFrame?: number;
18
+ syncChunkBytes?: number;
19
+ maxSyncBytes?: number;
20
+ user?: PipeUser;
21
+ }
22
+ /** The docx cursor; the default cursor type `C` of the pipe types. */
23
+ interface PipeCursor {
24
+ story: string;
25
+ anchor: Uint8Array;
26
+ head: Uint8Array;
27
+ }
28
+ type PipeTransportEvent = {
29
+ type: 'open';
30
+ } | {
31
+ type: 'message';
32
+ data: ArrayBuffer;
33
+ } | {
34
+ type: 'close';
35
+ reason?: string;
36
+ };
37
+ /**
38
+ * Main to worker, in order; `seq` increases. `connect`, `disconnect`, `destroy` and `fail` replay what main already
39
+ * did to the host transport, so the worker sends nothing and asks for no transport call while it runs them.
40
+ */
41
+ type PipeOp<C = PipeCursor> = {
42
+ op: 'create';
43
+ seq: number;
44
+ options: PipeProviderOptions;
45
+ } | {
46
+ op: 'connect';
47
+ seq: number;
48
+ } | {
49
+ op: 'disconnect';
50
+ seq: number;
51
+ } | {
52
+ op: 'destroy';
53
+ seq: number;
54
+ } | {
55
+ op: 'fail';
56
+ seq: number;
57
+ error: PipeError;
58
+ } | {
59
+ op: 'cursor';
60
+ seq: number;
61
+ cursor: C | null;
62
+ broadcast: boolean;
63
+ } | {
64
+ op: 'event';
65
+ seq: number;
66
+ event: PipeTransportEvent;
67
+ };
68
+ /** The docx peer; the default peer type `P` of the pipe types. */
69
+ interface PipePeer {
70
+ clientId: number;
71
+ clock: number;
72
+ user: {
73
+ name: string;
74
+ color: string;
75
+ };
76
+ cursor: PipeCursor | null;
77
+ lastSeenAt: number;
78
+ cursorMovedAt: number;
79
+ inferredCursor: {
80
+ clientId: number;
81
+ story: string;
82
+ paraId: string;
83
+ endOffset: number;
84
+ } | null;
85
+ }
86
+ /**
87
+ * Worker to main, in order. `through` is the last op the worker had run; main drops output older than its own
88
+ * latest lifecycle call.
89
+ */
90
+ type PipeOutput<P = PipePeer> = {
91
+ do: 'unsubscribe';
92
+ through: number;
93
+ } | {
94
+ do: 'disconnect';
95
+ through: number;
96
+ } | {
97
+ do: 'send';
98
+ data: ArrayBuffer;
99
+ through: number;
100
+ }
101
+ /** The awareness leave main sends when the host disconnects first; null while there is none to send. */
102
+ | {
103
+ do: 'leave';
104
+ data: ArrayBuffer | null;
105
+ through: number;
106
+ } | {
107
+ do: 'status';
108
+ status: 'disconnected' | 'connecting' | 'connected' | 'destroyed';
109
+ synced: boolean;
110
+ through: number;
111
+ } | {
112
+ do: 'peers';
113
+ peers: P[];
114
+ timeOrigin: number;
115
+ through: number;
116
+ } | {
117
+ do: 'error';
118
+ error: PipeError;
119
+ through: number;
120
+ }
121
+ /** The worker has no provider under this id. */
122
+ | {
123
+ do: 'lost';
124
+ };
125
+ interface PipeCommandPayload<C = PipeCursor> {
126
+ provider: number;
127
+ ops: PipeOp<C>[];
128
+ }
129
+
130
+ type CollaborationUpdateOrigin = 'local' | 'remote';
131
+ interface CollaborationReplica {
132
+ readonly clientId: number;
133
+ encodeStateVector(): Uint8Array;
134
+ encodeStateAsUpdate(remoteStateVector?: Uint8Array): Uint8Array;
135
+ applyUpdate(update: Uint8Array): unknown;
136
+ onUpdate(listener: (update: Uint8Array, origin: CollaborationUpdateOrigin) => void): () => void;
137
+ }
138
+ type CollaborationTransportEvent = {
139
+ type: 'open';
140
+ } | {
141
+ type: 'message';
142
+ data: Uint8Array;
143
+ } | {
144
+ type: 'close';
145
+ reason?: string;
146
+ } | {
147
+ type: 'error';
148
+ error: unknown;
149
+ } | {
150
+ type: 'drain';
151
+ };
152
+ interface CollaborationTransport {
153
+ /** Starts one attempt; after close, reopen internally or require another provider.connect(). */
154
+ connect(): void | Promise<void>;
155
+ disconnect(): void | Promise<void>;
156
+ /** Returns true only when the owned frame was accepted; false requires a later drain event. */
157
+ send(data: Uint8Array): boolean;
158
+ onEvent(listener: (event: CollaborationTransportEvent) => void): () => void;
159
+ }
160
+ type CollaborationStatus = 'disconnected' | 'connecting' | 'connected' | 'destroyed';
161
+ interface CollaborationStatusChange {
162
+ status: CollaborationStatus;
163
+ synced: boolean;
164
+ }
165
+ interface CollaborationUser {
166
+ name: string;
167
+ color: string;
168
+ }
169
+ interface CollaborationUserOptions {
170
+ name: string;
171
+ color?: string;
172
+ }
173
+ interface AwarenessCell {
174
+ row: number;
175
+ col: number;
176
+ }
177
+ interface AwarenessCursor {
178
+ sheet: string;
179
+ anchor: AwarenessCell;
180
+ head: AwarenessCell;
181
+ }
182
+ interface AwarenessPayload {
183
+ user: CollaborationUser;
184
+ cursor: AwarenessCursor | null;
185
+ }
186
+ interface AwarenessState extends AwarenessPayload {
187
+ clientId: number;
188
+ clock: number;
189
+ }
190
+ interface AwarenessUpdate {
191
+ clientId: number;
192
+ clock: number;
193
+ state: AwarenessPayload | null;
194
+ }
195
+ interface AwarenessPeer extends AwarenessState {
196
+ lastSeen: number;
197
+ cursorMovedAt: number;
198
+ }
199
+ interface CollaborationAwareness {
200
+ readonly peers: readonly AwarenessPeer[];
201
+ setCursor(cursor: AwarenessCursor | null): void;
202
+ onAwareness(listener: AwarenessListener): () => void;
203
+ }
204
+ type CollaborationErrorCode = 'backpressure' | 'protocol' | 'replica' | 'transport';
205
+ declare class CollaborationError extends Error {
206
+ readonly code: CollaborationErrorCode;
207
+ readonly cause: unknown;
208
+ constructor(code: CollaborationErrorCode, message: string, cause?: unknown);
209
+ }
210
+ interface CollaborationProviderOptions {
211
+ maxFrameBytes?: number;
212
+ maxMessagesPerFrame?: number;
213
+ maxPendingBytes?: number;
214
+ user?: CollaborationUserOptions;
215
+ }
216
+ type CollaborationStatusListener = (change: CollaborationStatusChange) => void;
217
+ type CollaborationErrorListener = (error: CollaborationError) => void;
218
+ type AwarenessListener = (peers: readonly AwarenessPeer[]) => void;
219
+
220
+ /** One provider's line to the worker that runs it. */
221
+ interface CollaborationPipeEndpoint<C = PipeCursor> {
222
+ /** Runs `ops` in the worker, in order after earlier posts; settles once the worker has run them. */
223
+ post(ops: PipeOp<C>[], transfer: ArrayBuffer[]): Promise<unknown>;
224
+ close(): void;
225
+ }
226
+ /** What a worker replica offers a provider that can run in its worker. */
227
+ interface CollaborationPipeChannel<C = PipeCursor, P = PipePeer> {
228
+ /** `receive` takes the worker's output for this provider; `lost` reports the worker is gone for it. */
229
+ open(receive: (out: readonly PipeOutput<P>[]) => void, lost: (reason: string) => void): CollaborationPipeEndpoint<C>;
230
+ }
231
+
232
+ /** @experimental */
233
+ interface AsyncCollaborationReplica {
234
+ readonly clientId: number;
235
+ encodeStateVector(): Promise<Uint8Array>;
236
+ encodeStateAsUpdate(remoteStateVector?: Uint8Array): Promise<Uint8Array>;
237
+ applyUpdate(update: Uint8Array): Promise<unknown>;
238
+ /** Applies updates in order as one merge; rejects at the first refused update, keeping the ones before it. */
239
+ applyUpdateChunks?(updates: readonly Uint8Array[]): Promise<unknown>;
240
+ onUpdate(listener: (update: Uint8Array, origin: CollaborationUpdateOrigin) => void): () => void;
241
+ }
242
+ /** @experimental */
243
+ interface AsyncReplicaAdapter extends CollaborationReplica {
244
+ readonly async: AsyncCollaborationReplica;
245
+ }
246
+ /** @internal */
247
+ declare function attachCollaborationPipe(adapter: AsyncReplicaAdapter, channel: CollaborationPipeChannel<AwarenessCursor, AwarenessPeer> | undefined): void;
248
+ /** @internal */
249
+ declare function collaborationPipeFor(replica: CollaborationReplica): CollaborationPipeChannel<AwarenessCursor, AwarenessPeer> | undefined;
250
+ /** @experimental */
251
+ declare function createAsyncCollaborationReplica(replica: AsyncCollaborationReplica): AsyncReplicaAdapter;
252
+
253
+ export { type AwarenessPeer as A, type CollaborationReplica as C, type PipeCommandPayload as P, type CollaborationTransport as a, type CollaborationProviderOptions as b, type CollaborationStatus as c, type CollaborationStatusListener as d, type CollaborationErrorListener as e, type AwarenessListener as f, type AwarenessCursor as g, type AwarenessPayload as h, type AwarenessUpdate as i, type CollaborationUserOptions as j, type CollaborationUser as k, type AsyncCollaborationReplica as l, type AsyncReplicaAdapter as m, type AwarenessCell as n, type AwarenessState as o, type CollaborationAwareness as p, CollaborationError as q, type CollaborationErrorCode as r, type CollaborationStatusChange as s, type CollaborationTransportEvent as t, type CollaborationUpdateOrigin as u, attachCollaborationPipe as v, collaborationPipeFor as w, createAsyncCollaborationReplica as x };
@@ -0,0 +1 @@
1
+ import {I,u,v,o,K as K$1,r,t,F,x,B,H,p,C,w,G as G$1,D,y,A,z as z$1,q,a as a$1,d as d$1}from'./chunk-JGTBRHCP.js';import {a}from'./chunk-O2XFH626.js';var h=class extends Error{constructor(t,s,r){super(s);a(this,"code");a(this,"cause");this.name="CollaborationError",this.code=t,this.cause=r;}};function G(o){return o instanceof Error&&o.message?o.message:typeof o=="string"&&o?o:"Unknown error"}var Y=["backpressure","protocol","replica","transport"],E=64,j=250;function K(o){if(o[0]!==0||o[1]!==2)return false;let e=0;for(let t=2,s=0;t<Math.min(o.byteLength,7);t++,s+=7)if(e+=(o[t]&127)*2**s,o[t]<128)return t+1+e===o.byteLength;return false}var b=class{constructor(e,t,s){a(this,"transport",t);a(this,"options",s);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(r=>this.receive(r),r=>this.lose(r)),this.enqueue({op:"create",seq:++this.seq,options:s.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,s;try{if(s=this.transport.onEvent(r=>this.forward(t,r)),typeof s!="function")throw new TypeError("Transport event subscription must return a function")}catch(r){this.subscription+=1,this.fail(this.transportError("Failed to subscribe to transport events",r));return}if(!this.wantsConnection||this.isDestroyed||e!==this.connectAttempt||t!==this.subscription){try{s();}catch(r){this.isDestroyed||this.report(this.transportError("Failed to unsubscribe from stale transport events",r));}return}this.unsubscribeTransport=s;}try{let t=this.transport.connect();t&&t.catch(s=>{!this.isDestroyed&&this.wantsConnection&&this.connectAttempt===e&&this.fail(this.transportError("Transport connect failed",s));});}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 s of t)this.report(s);}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 s of t)this.report(s);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=[],s=this.unsubscribeTransport;if(this.unsubscribeTransport=null,this.subscription+=1,s)try{s();}catch(r){t.push(this.transportError("Failed to unsubscribe from transport events",r));}if(!e)return t;try{let r=this.transport.disconnect();r&&r.catch(a=>{this.isDestroyed||this.report(this.transportError("Transport disconnect failed",a));});}catch(r){t.push(this.transportError("Transport disconnect failed",r));}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"&&Y.includes(t)?t:"transport",message:e.message}});let s=this.release(true);this.setStatus("disconnected",false),this.report(e);for(let r of s)this.report(r);}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();},j));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(a=>a.op==="destroy"),s=e.reduce((a,n)=>n.op==="event"&&n.event.type==="message"?a+n.event.data.byteLength+E:a,0),r;try{r=this.endpoint.post(e,a$1(e));}catch(a){r=Promise.reject(a);}r.then(()=>{this.posting=false,this.inboundBytes-=s,t?this.close():this.urgent?this.flush():this.queue.length>0&&this.schedule(true);},a=>{this.posting=false,this.inboundBytes-=s,this.lose(G(a));});}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+E>this.options.maxPendingBytes-this.inboundBytes){this.fail(this.options.makeError("backpressure","Pending replica data exceeds the byte limit"));return}this.inboundBytes+=t.data.byteLength+E,this.enqueue({op:"event",seq:++this.seq,event:{type:"message",data:t.data.slice().buffer}},!this.isSynced&&K(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 s=this.release(false);for(let r of s)this.report(r);break}case "disconnect":{this.wantsConnection=false;let s=this.release(true);for(let r of s)this.report(r);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 s=this.options.rebasePeer,r=t.timeOrigin-d$1();this.peerList=s?t.peers.map(a=>s(a,r)):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,s;try{s=this.transport.send(e.slice());}catch(r){this.fail(this.transportError("Transport send failed",r));return}if(typeof s!="boolean"){this.fail(this.options.makeError("transport","Transport send must return a boolean"));return}!s&&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(s){this.fail(this.transportError("Transport send failed",s));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 s of t)this.report(s);}},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[s,r]of [...this.statusListeners])if(this.statusListeners.get(s)===r)try{r({status:e,synced:t});}catch{}}}emitPeers(){let e=this.peers;for(let[t,s]of [...this.peerListeners])if(this.peerListeners.get(t)===s)try{s(e);}catch{}}report(e){for(let[t,s]of [...this.errorListeners])if(this.errorListeners.get(t)===s)try{s(e);}catch{}}};var Z=u,ee=1e3;function T(o,e,t){if(!Number.isSafeInteger(e)||e<(t?0:1))throw new RangeError(`${o} must be ${t?"a non-negative":"a positive"} integer`);return e}function te(o){return o instanceof Error&&o.message?o.message:typeof o=="string"&&o?o:"Unknown error"}function c(o,e,t){return t instanceof h?t:new h(o,`${e}: ${te(t)}`,t)}function d(o,e){if(!(o instanceof Uint8Array))throw new TypeError(`${e} must return a Uint8Array`);return o.slice()}function P(o){o.unref?.();}var X=new WeakMap,z=new WeakMap;function le(o){return X.get(o)()}function de(o){return z.get(o)()}var W=class{constructor(e,t,s={}){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=I(e),this.transport=t,this.maxFrameBytes=T("maxFrameBytes",s.maxFrameBytes??u,false),this.maxMessagesPerFrame=T("maxMessagesPerFrame",s.maxMessagesPerFrame??v,false),this.maxPendingBytes=T("maxPendingBytes",s.maxPendingBytes??Z,true),this.awarenessUser=o(s.user,e.clientId),X.set(this,()=>this.beginArrival()),z.set(this,()=>this.leaveFrame());let r=K$1(e);if(r){this.unsubscribeReplica=()=>{};let a;this.piped=new b(r,{connect:()=>this.connectPipedTransport(()=>a?.()),disconnect:()=>{this.wantsConnection=false,this.connectAttempt+=1;let n=this.cleanupTransport(()=>{},true);if(n.length)throw n[0]},send:n=>t.send(n),onEvent:n=>{if(!this.transportCleanup)return t.onEvent(n);let p=true,l=()=>{},u=()=>{a=void 0;try{let y=t.onEvent(n);if(typeof y!="function")throw new TypeError("Transport event subscription must return a function");p?l=y:y();}catch(y){throw c("transport","Failed to subscribe to transport events",y)}};return a=u,()=>{p=false,a===u&&(a=void 0),l();}}},{worker:{maxFrameBytes:this.maxFrameBytes,maxMessagesPerFrame:this.maxMessagesPerFrame,user:{...this.awarenessUser}},maxPendingBytes:this.maxPendingBytes,hasUser:true,makeError:(n,p,l)=>new h(n,p,l),normalize:c});return}try{this.unsubscribeReplica=e.onUpdate((a,n)=>{n==="local"&&this.forwardLocalUpdate(a);});}catch(a){throw c("replica","Failed to observe replica updates",a)}}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:r(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 s;try{if(s=this.transport.onEvent(r=>this.handleTransportEvent(e,r)),typeof s!="function")throw new TypeError("Transport event subscription must return a function")}catch(r){this.failConnection(e,c("transport","Failed to subscribe to transport events",r));return}if(!this.isCurrent(e)){try{s();}catch(r){this.isDestroyed||this.report(c("transport","Failed to unsubscribe from stale transport events",r));}return}this.unsubscribeTransport=s,this.hasTransportSubscription=true;}try{let s=this.transport.connect();s&&s.catch(r=>{this.isCurrent(e)&&this.connectAttempt===t&&this.failConnection(e,c("transport","Transport connect failed",r));});}catch(s){this.failConnection(e,c("transport","Transport connect failed",s));}}}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(),s=this.cleanupTransport(t,true);this.setStatus("disconnected",false);for(let r of s)this.report(r);}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(),s=this.cleanupTransport(t,e);this.setStatus("destroyed",false);for(let r of s)this.report(r);try{this.unsubscribeReplica();}catch(r){this.report(c("replica","Failed to unsubscribe from replica updates",r));}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),s=this.nextListenerId++;return this.errorListeners.set(s,e),()=>{t?.(),this.errorListeners.delete(s);}}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(s=>{try{e(s);}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$1=e?t(e):false;if(this.awarenessCursor=e&&t$1?{sheet:e.sheet,anchor:{...e.anchor},head:{...e.head}}:null,e&&!t$1&&this.report(new h("protocol",`Awareness cursor needs a sheet identifier of 1 to ${256} characters and non-negative cell coordinates; cursor dropped`)),this.piped){this.piped.setCursor(this.awarenessCursor,true);return}if(!this.isOpen||!this.wantsConnection)return;let s=80-(Date.now()-this.lastAwarenessSentAt);if(s<=0){this.publishAwareness();return}this.awarenessBroadcastTimer||(this.awarenessBroadcastTimer=setTimeout(()=>{this.awarenessBroadcastTimer=void 0,this.publishAwareness();},s),P(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 s=this.takeTransportSubscription();this.clearPending();let r=this.cleanupTransport(s,true);this.setStatus("disconnected",false),this.report(t);for(let a of r)this.report(a);}takeTransportSubscription(){let e=this.unsubscribeTransport;return this.unsubscribeTransport=()=>{},this.hasTransportSubscription=false,e}cleanupTransport(e,t){let s=[];try{e();}catch(r){s.push(c("transport","Failed to unsubscribe from transport events",r));}if(!t||this.transportCleanup)return s;try{let r=this.transport.disconnect();if(r){let a=!1,n=Promise.resolve(r).catch(p=>{a=!0,this.isDestroyed||this.report(c("transport","Transport disconnect failed",p));}).finally(()=>{this.transportCleanup===n&&(a&&!this.isDestroyed&&(this.wantsConnection=!1,this.piped?.disconnect()),this.transportCleanup=void 0,!this.isDestroyed&&(a?this.piped||this.setStatus("disconnected",!1):this.wantsConnection&&!this.piped&&this.startConnection()));});this.transportCleanup=n;}}catch(r){s.push(c("transport","Transport disconnect failed",r));}return s}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,c("transport","Transport error",t.error));break;case "drain":this.isOpen&&this.flushPending();break;default:this.failConnection(e,new h("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(a=>{this.isCurrentOpen(e,t)&&this.sendHandshake(e,d(a,"encodeStateVector"),t);}).catch(a=>{this.isCurrentOpen(e,t)&&this.failConnection(e,c("replica","Failed to encode replica state vector",a));});return}let s;try{s=d(this.replica.encodeStateVector(),"encodeStateVector");}catch(r){this.failConnection(e,c("replica","Failed to encode replica state vector",r));return}this.sendHandshake(e,s,t);}sendHandshake(e,t,s){if(!this.isCurrentOpen(e,s))return;let r;try{r=F(t),this.sendFrame(x(r??t,this.maxFrameBytes));}catch(a){this.failConnection(e,c("protocol","Failed to encode collaboration handshake",a));return}if(!r&&this.isCurrentOpen(e,s)&&this.sendFullUpdate(e,s),!!this.isCurrentOpen(e,s)){try{this.sendFrame(B(this.maxFrameBytes));}catch(a){this.report(c("protocol","Failed to encode awareness query",a));}this.isCurrentOpen(e,s)&&(this.hasPublishedAwarenessForOpen||this.publishAwareness(),this.isCurrentOpen(e,s)&&this.startAwarenessTimers());}}sendFullUpdate(e,t){let s=n=>{if(this.isCurrentOpen(e,t))try{this.sendFrame(z$1(n,this.maxFrameBytes));}catch(p){this.failConnection(e,c("protocol","Failed to encode collaboration handshake",p));}},r=n=>{this.isCurrentOpen(e,t)&&this.failConnection(e,c("replica","Failed to encode replica update",n));};if(this.asyncReplica){this.asyncReplica.encodeStateAsUpdate().then(n=>d(n,"encodeStateAsUpdate")).then(s,r);return}let a;try{a=d(this.replica.encodeStateAsUpdate(),"encodeStateAsUpdate");}catch(n){r(n);return}s(a);}handleMessage(e,t,s){let r;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`);r=s??H(t,this.maxFrameBytes,this.maxMessagesPerFrame);}catch(a){this.failConnection(e,c("protocol","Invalid collaboration frame",a));return}if(this.asyncReplica&&!s){let a=[];for(let n of r){if(!this.isCurrent(e)||!this.isOpen)return;n.type==="sync-step-1"||n.type==="sync-step-2"||n.type==="update"?a.push(n):this.handleMessage(e,new Uint8Array,[n]);}a.length&&this.isCurrent(e)&&this.isOpen&&(this.asyncReplica.applyUpdateChunks&&a.every(n=>n.type==="update")?this.enqueueRemoteUpdates(e,t.byteLength,a.map(n=>n.update)):this.enqueueReplicaMessages(e,t.byteLength,a));return}for(let a of r){if(!this.isCurrent(e)||!this.isOpen)return;switch(a.type){case "sync-step-1":this.respondToSyncStep1(e,a.stateVector);break;case "sync-step-2":{let n=this.syncArrival,p=this.syncArrival={deferred:false};try{this.applyRemoteUpdate(e,a.update)&&this.isCurrent(e)&&!p.deferred&&this.setStatus("connected",!0);}finally{this.syncArrival=n;}break}case "update":this.applyRemoteUpdate(e,a.update);break;case "awareness":try{let n=[],p$1=0,l=p(this.awarenessStore,C(a.update,w,u=>n.push(u)),this.replica.clientId,Date.now(),{onPeersDiscarded:u=>{p$1=u;}});for(let u of n)this.report(c("protocol","Invalid awareness update",u));if(p$1>0&&this.report(new h("protocol",`${p$1} awareness ${p$1===1?"entry was":"entries were"} discarded because the tracked peer limit of ${1024} was reached`)),!this.isCurrent(e)||!this.isOpen)return;l&&this.emitAwareness();}catch(n){this.report(c("protocol","Invalid awareness update",n));}break;case "auth":this.failConnection(e,new h("protocol",a.reason?`Authentication denied: ${a.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,s){if(t>this.maxPendingBytes-this.replicaBytes){this.failConnection(e,new h("backpressure","Pending replica data exceeds the byte limit"));return}this.replicaBytes+=t,this.updateBatch=null;let r=this.openEpoch,a=this.replicaTail.then(async()=>{for(let n of s){if(!this.isCurrentOpen(e,r))return;try{if(n.type==="sync-step-1"){let p=G$1(n.stateVector),l=await this.asyncReplica.encodeStateAsUpdate(D(p.stateVector).slice());if(!this.isCurrentOpen(e,r))return;if(this.sendFrame(y(d(l,"encodeStateAsUpdate"),this.maxFrameBytes)),p.open&&this.isCurrentOpen(e,r)){let u=d(await this.asyncReplica.encodeStateVector(),"encodeStateVector");this.isCurrentOpen(e,r)&&this.sendFrame(x(u,this.maxFrameBytes));}}else (n.type==="sync-step-2"||n.type==="update")&&(await this.asyncReplica.applyUpdate(D(n.update).slice()),n.type==="sync-step-2"&&this.isCurrentOpen(e,r)&&this.setStatus("connected",!0));}catch(p){this.isCurrentOpen(e,r)&&this.failConnection(e,c("replica","Async replica operation failed",p));return}}}).finally(()=>{r===this.openEpoch&&(this.replicaBytes-=t);});this.replicaTail=a.catch(()=>{});}enqueueRemoteUpdates(e,t,s){if(t>this.maxPendingBytes-this.replicaBytes){this.failConnection(e,new h("backpressure","Pending replica data exceeds the byte limit"));return}this.replicaBytes+=t;let r=this.openEpoch,a=s.map(u=>D(u).slice()),n=this.updateBatch;if(n?.connection===r){n.updates.push(...a),n.bytes+=t;return}let p={connection:r,bytes:t,updates:a};this.updateBatch=p;let l=this.replicaTail.then(async()=>{if(this.updateBatch===p&&(this.updateBatch=null),!!this.isCurrentOpen(e,r))try{p.updates.length===1?await this.asyncReplica.applyUpdate(p.updates[0]):await this.asyncReplica.applyUpdateChunks(p.updates);}catch(u){this.isCurrentOpen(e,r)&&this.failConnection(e,c("replica","Async replica operation failed",u));}}).finally(()=>{r===this.openEpoch&&(this.replicaBytes-=p.bytes);});this.replicaTail=l.catch(()=>{});}respondToSyncStep1(e,t){let s=G$1(t),r;try{r=d(this.replica.encodeStateAsUpdate(D(s.stateVector).slice()),"encodeStateAsUpdate");}catch(n){this.failConnection(e,c("replica","Failed to encode replica update",n));return}try{this.sendFrame(y(r,this.maxFrameBytes));}catch(n){this.failConnection(e,c("protocol","Failed to encode SyncStep2",n));return}if(!s.open||!this.isCurrent(e)||!this.isOpen)return;let a;try{a=d(this.replica.encodeStateVector(),"encodeStateVector");}catch(n){this.failConnection(e,c("replica","Failed to encode replica state vector",n));return}try{this.sendFrame(x(a,this.maxFrameBytes));}catch(n){this.failConnection(e,c("protocol","Failed to encode collaboration handshake",n));}}beginArrival(){let e=this.epoch,t=this.openEpoch,s=this.syncArrival;s&&(s.deferred=true);let r=false,a=n=>{r||(r=true,this.isCurrentOpen(e,t)&&n());};return {settle:()=>a(()=>{s&&this.setStatus("connected",true);}),fail:n=>a(()=>this.failConnection(e,c("replica","Failed to apply remote update",n)))}}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:A([{clientId:this.replica.clientId,clock:e,state:null}],this.maxFrameBytes)}}catch{return null}}applyRemoteUpdate(e,t){try{return this.replica.applyUpdate(D(t).slice()),!0}catch(s){return this.failConnection(e,c("replica","Failed to apply remote update",s)),false}}forwardLocalUpdate(e){if(this.isDestroyed||!this.isOpen||!this.wantsConnection)return;let t=this.epoch,s;try{s=d(e,"Replica update");}catch(r){this.failConnection(t,c("replica","Invalid replica update",r));return}try{this.sendFrame(z$1(s,this.maxFrameBytes));}catch(r){this.failConnection(t,c("protocol","Failed to encode update",r));}}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 h("protocol","Awareness clock exhausted")));return}this.awarenessClock+=1;try{this.hasPublishedAwarenessForOpen=!0;let s=A([{clientId:this.replica.clientId,clock:this.awarenessClock,state:e===null?null:{user:this.awarenessUser,cursor:this.awarenessCursor}}],this.maxFrameBytes);t==="best-effort"?this.sendBestEffort(s):this.sendFrame(s),this.lastAwarenessSentAt=Date.now();}catch(s){t==="queued"&&this.report(c("protocol","Failed to encode awareness update",s));}}}startAwarenessTimers(){this.stopAwarenessTimers(),this.awarenessHeartbeatTimer=setInterval(()=>{this.publishAwareness();},2e4),this.awarenessExpiryTimer=setInterval(()=>{q(this.awarenessStore,Date.now(),45e3)&&this.emitAwareness();},ee),P(this.awarenessHeartbeatTimer),P(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,s]of [...this.awarenessListeners])if(this.awarenessListeners.get(t)===s)try{s(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 s;try{s=this.transport.send(e.slice());}catch(r){this.failConnection(t,c("transport","Transport send failed",r));return}if(typeof s!="boolean"){this.failConnection(t,new h("transport","Transport send must return a boolean"));return}!s&&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 h("backpressure",`Pending collaboration data exceeds ${this.maxPendingBytes} bytes`));return}let s=t.slice();this.pendingFrames.push(s),this.queuedBytes+=s.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],s;try{s=this.transport.send(t.slice());}catch(r){this.failConnection(e,c("transport","Transport send failed",r));return}if(typeof s!="boolean"){this.failConnection(e,new h("transport","Transport send must return a boolean"));return}if(!s||!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 s=++this.statusRevision,r={status:e,synced:t};for(let[a,n]of [...this.statusListeners]){if(this.statusRevision!==s)return;if(this.statusListeners.get(a)===n)try{n(r);}catch{}}}report(e){for(let[t,s]of [...this.errorListeners])if(this.errorListeners.get(t)===s)try{s(e);}catch{}}};export{h as a,le as b,de as c,W as d};