@ember-lattice/collab 0.0.0-stage → 1.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # @ember-lattice/collab
2
+
3
+ ## 1.1.0
4
+
5
+ ### Patch Changes
6
+
7
+ - @ember-lattice/sheet@1.1.0
8
+ - @ember-lattice/formula@1.1.0
9
+
10
+ ## 1.0.0
11
+
12
+ ### Major Changes
13
+
14
+ - 7ce4af2: Lattice 1.0: one grid for every collection in Ember. Lists, feeds, tables, boards and
15
+ spreadsheets come from one headless engine, a port of TanStack Table. It has 80 of the 81
16
+ AG Grid features in the parity matrix; the external filter runs after grouping. The release has the client row models, the Lattice wire protocol with servers for Node,
17
+ Rails and Python, an IronCalc spreadsheet with live collaboration, themes, test harnesses, Jig
18
+ stories and Marquetry catalog entries.
19
+
20
+ ### Patch Changes
21
+
22
+ - Updated dependencies [7ce4af2]
23
+ - @ember-lattice/formula@1.0.0
24
+ - @ember-lattice/sheet@1.0.0
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Gaudet
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.
package/NOTICE ADDED
@@ -0,0 +1,30 @@
1
+ Lattice
2
+ Copyright (c) 2026 Joe Gaudet. MIT licensed; see LICENSE.md.
3
+
4
+ Lattice ports code from two MIT-licensed TanStack projects into Ember-native code. Lattice does
5
+ not depend on either package. PORT_MAP.md names each ported file and its source.
6
+
7
+ TanStack Table (@tanstack/table-core 9.3.1)
8
+ https://github.com/TanStack/table
9
+ Copyright (c) 2016 Tanner Linsley
10
+
11
+ TanStack Virtual (@tanstack/virtual-core 3.19.16)
12
+ https://github.com/TanStack/virtual
13
+ Copyright (c) 2021-present Tanner Linsley
14
+
15
+ Both are licensed under the MIT License:
16
+
17
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
18
+ and associated documentation files (the "Software"), to deal in the Software without
19
+ restriction, including without limitation the rights to use, copy, modify, merge, publish,
20
+ distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
21
+ Software is furnished to do so, subject to the following conditions:
22
+
23
+ The above copyright notice and this permission notice shall be included in all copies or
24
+ substantial portions of the Software.
25
+
26
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
27
+ BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
29
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,95 @@
1
- # Temporary Holding Version
1
+ # @ember-lattice/collab
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Live collaboration for Lattice sheets: an op log client with rebase, presence, cursors,
4
+ selections, soft locks and undo. The server part is in `@ember-lattice/server`
5
+ (`createDocServer`). The design is in [ADR 0016](https://joegaudet.com/ember-lattice/docs/adr/0016-collaboration/index.html).
6
+
7
+ Part of [Lattice](https://joegaudet.com/ember-lattice/). Not released yet.
8
+
9
+ ## How it works
10
+
11
+ - The server holds the truth. It gives each submit a sequence number (`seq`), applies each op
12
+ that still fits the doc, recalculates with the engine, and sends the applied ops and the
13
+ changed values to every client.
14
+ - The client applies each local op to the `Workbook` at once, and sends it.
15
+ - The client keeps a shadow model with only the server state. When a server op conflicts with
16
+ a local op that waits, the view loads the shadow again and applies the waiting ops on top.
17
+ - Every op names rows, columns and sheets by ID. Thus, only two conflicts remain:
18
+ - Two writes to one cell: the last write in server order wins.
19
+ - An edit to a deleted row or column: the server drops it, and `onDrop` tells the user.
20
+
21
+ ## Server
22
+
23
+ ```ts
24
+ import { WebSocketServer } from 'ws'
25
+ import { attachSocket, createDocServer, createMemoryStore } from '@ember-lattice/server'
26
+ import { createIronCalcEngine } from '@ember-lattice/formula-ironcalc'
27
+
28
+ const server = createDocServer({
29
+ store: createMemoryStore(),
30
+ engine: () => createIronCalcEngine({ wasm }),
31
+ snapshotEvery: 100,
32
+ })
33
+ await server.create('budget', doc)
34
+
35
+ const wss = new WebSocketServer({ port: 8080, maxPayload: 1_000_000 })
36
+ wss.on('connection', socket => attachSocket(server, socket))
37
+ ```
38
+
39
+ Authenticate each socket before you attach it. The server trusts the client ID of the
40
+ `join` message. Each message goes through `parseClientMessage` first: it never throws, it
41
+ rejects unknown keys, and it limits the counts and the lengths (`COLLAB_LIMITS`).
42
+
43
+ ## Client
44
+
45
+ ```ts
46
+ import { CollabSession } from '@ember-lattice/collab'
47
+
48
+ const session = new CollabSession({
49
+ doc: workbook,
50
+ docId: 'budget',
51
+ clientId: crypto.randomUUID(),
52
+ name: 'Ann',
53
+ transport: { send: message => socket.send(JSON.stringify(message)) },
54
+ onDrop: ops => notify(`${ops.length} edits were lost: another user deleted the row`),
55
+ onPresence: peers => (this.peers = peers),
56
+ })
57
+ socket.onopen = () => session.open()
58
+ socket.onclose = () => session.close()
59
+ socket.onmessage = event => session.receive(JSON.parse(event.data))
60
+ await session.ready
61
+
62
+ await session.apply([{ type: 'setCell', sheet: 's1', row: 'r1', col: 'c1', value: 2 }])
63
+ ```
64
+
65
+ - Call `open()` after each connect. The session sends `join` with the last `seq`, and sends the
66
+ waiting ops again. The server applies a resent op one time only.
67
+ - Without the `seq` option, the session loads a snapshot from the server into the `Workbook`.
68
+ If the app loaded the `Workbook` itself, give the `seq` of that doc.
69
+ - The ops are `CollabOp`: the `SheetOp` of the engine, `setNote` and `freeze`. The engine does
70
+ not see `setNote` and `freeze`. Conditional formats and data validation are local only.
71
+ - `onRemote(ops)` tells the view about the ops of another user, after they are in the
72
+ `Workbook`. The Sheet surface uses it to refresh an open cell editor.
73
+
74
+ ## Presence and soft locks
75
+
76
+ - `setPresence({ cursor, selection })` sends the cursor cell and the selection range.
77
+ - `setEditing(cell)` marks the cell that the user edits now. Use `setEditing(null)` at the end.
78
+ - `peers` gives the other users, each with a color, a name, a cursor, a selection and the cell
79
+ in edit mode. `lockAt(sheet, row, col)` gives the user who edits that cell.
80
+ - Presence is not stored. A peer without a message for `presenceTimeout` (30 s) goes away. The
81
+ session sends its presence again each half timeout.
82
+
83
+ ## Undo
84
+
85
+ `undo()` undoes the last local change, and `redo()` applies the last undone change again. A
86
+ later write of another user to the same cell stays: the undo and the redo skip that cell. A new
87
+ local change clears the redo list. Each gives the applied ops. In this part, undo has no inverse
88
+ for a row, column or sheet delete.
89
+
90
+ ## Tests
91
+
92
+ - `pnpm vitest run packages/collab` runs the session tests and the convergence test.
93
+ - The convergence test (fast-check) runs 10 clients with random ops, random delivery order and
94
+ lost links. After all messages arrive, each client and the server must hold the same rows,
95
+ columns, merges, frozen panes, values, formulas, notes and computed values.
package/addon-main.cjs ADDED
@@ -0,0 +1,4 @@
1
+ 'use strict'
2
+
3
+ const { addonV1Shim } = require('@embroider/addon-shim')
4
+ module.exports = addonV1Shim(__dirname)
@@ -0,0 +1,4 @@
1
+ export { CollabSession, toDoc } from './session.ts';
2
+ export type { CollabSessionOptions, Peer, Transport } from './session.ts';
3
+ export type * from './wire.ts';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AACnD,YAAY,EAAE,oBAAoB,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACzE,mBAAmB,WAAW,CAAA"}
@@ -0,0 +1,89 @@
1
+ import { Workbook } from '@ember-lattice/sheet';
2
+ import type { CellRef, RangeRef } from '@ember-lattice/formula';
3
+ import type { ClientMessage, CollabDoc, CollabOp, Presence, ServerMessage } from './wire.ts';
4
+ /** Sends client messages. The app gives server messages to `session.receive`. */
5
+ export interface Transport {
6
+ send(message: ClientMessage): void;
7
+ }
8
+ /** Another user on the doc. */
9
+ export interface Peer extends Presence {
10
+ clientId: string;
11
+ name: string;
12
+ color: string;
13
+ /** The time of the last presence message, from `now()`. */
14
+ seen: number;
15
+ }
16
+ export interface CollabSessionOptions {
17
+ /** The view: the sheet model that the user sees and edits. */
18
+ doc: Workbook;
19
+ transport: Transport;
20
+ docId: string;
21
+ clientId: string;
22
+ name?: string;
23
+ /** The seq of `doc` when the app loaded it itself. Without it, the session loads a snapshot. */
24
+ seq?: number;
25
+ /** A peer without a presence message for this time (ms) goes away. Default 30 s. */
26
+ presenceTimeout?: number;
27
+ now?: () => number;
28
+ /** The server or a rebase dropped these local ops (for example, an edit to a deleted row). */
29
+ onDrop?: (ops: CollabOp[], reason: string) => void;
30
+ /** The ops of another user are in the view now. */
31
+ onRemote?: (ops: CollabOp[]) => void;
32
+ /** The peers changed. Put them in tracked state to render cursors and lock hints. */
33
+ onPresence?: (peers: Peer[]) => void;
34
+ onError?: (error: unknown) => void;
35
+ }
36
+ /** The model as a doc, with the computed values. */
37
+ export declare function toDoc(book: Workbook): CollabDoc;
38
+ /**
39
+ * A live link from a `Workbook` to the collab server (plan 8.4). Local ops change the view at
40
+ * once and go to the server. The session keeps a shadow model that holds only the server
41
+ * state. When a server op conflicts with a pending local op, the view loads the shadow again
42
+ * and applies the pending ops on top: the result is what the server makes when the pending
43
+ * ops arrive.
44
+ */
45
+ export declare class CollabSession {
46
+ #private;
47
+ readonly doc: Workbook;
48
+ onDrop: ((ops: CollabOp[], reason: string) => void) | undefined;
49
+ onRemote: ((ops: CollabOp[]) => void) | undefined;
50
+ onPresence: ((peers: Peer[]) => void) | undefined;
51
+ onError: (error: unknown) => void;
52
+ /** Ends when the view holds the server doc. */
53
+ readonly ready: Promise<void>;
54
+ constructor(options: CollabSessionOptions);
55
+ /** The last server seq that the view holds, or null before the first snapshot. */
56
+ get seq(): number | null;
57
+ /** The count of local submits that the server did not sequence yet. */
58
+ get pending(): number;
59
+ get canUndo(): boolean;
60
+ get canRedo(): boolean;
61
+ /** The other users with a presence that did not expire. */
62
+ get peers(): Peer[];
63
+ /** The user in edit mode on this cell, if there is one: a soft lock hint. */
64
+ lockAt(sheet: string, row: string, col: string): Peer | undefined;
65
+ /** Waits for the engine work of the view and the shadow. */
66
+ settled(): Promise<void>;
67
+ /** Call when the transport connects (also after a reconnect). */
68
+ open(): void;
69
+ /** Call when the transport disconnects. Local ops wait for the next `open`. */
70
+ close(): void;
71
+ /** Applies local ops at once and sends them. Ops that do not fit the view now are skipped. */
72
+ apply(ops: CollabOp[]): Promise<void>;
73
+ /**
74
+ * Undoes the last local change that still has an effect. Later writes of others stay. Gives
75
+ * the applied ops, so the view can show the cells again.
76
+ */
77
+ undo(): Promise<CollabOp[]>;
78
+ /** Applies the last undone change again. A later write of another user wins over it. */
79
+ redo(): Promise<CollabOp[]>;
80
+ setPresence(state: {
81
+ cursor: CellRef | null;
82
+ selection: RangeRef | null;
83
+ }): void;
84
+ /** Marks the cell that this user edits now, or null when the edit ends. */
85
+ setEditing(cell: CellRef | null): void;
86
+ /** Takes one server message. */
87
+ receive(m: ServerMessage): void;
88
+ }
89
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAE/C,OAAO,KAAK,EAAc,OAAO,EAAiB,QAAQ,EAAW,MAAM,wBAAwB,CAAA;AACnG,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAE5F,iFAAiF;AACjF,MAAM,WAAW,SAAS;IACxB,IAAI,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI,CAAA;CACnC;AAED,+BAA+B;AAC/B,MAAM,WAAW,IAAK,SAAQ,QAAQ;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,2DAA2D;IAC3D,IAAI,EAAE,MAAM,CAAA;CACb;AAED,MAAM,WAAW,oBAAoB;IACnC,8DAA8D;IAC9D,GAAG,EAAE,QAAQ,CAAA;IACb,SAAS,EAAE,SAAS,CAAA;IACpB,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,gGAAgG;IAChG,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,oFAAoF;IACpF,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,GAAG,CAAC,EAA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IAAI,IAAI,EAAE,CAGlB;IAOD,6EAA6E;IAC7E,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;IAMjE,4DAA4D;IACtD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA0B9B,iEAAiE;IACjE,IAAI,IAAI,IAAI;IAuBZ,+EAA+E;IAC/E,KAAK,IAAI,IAAI;IAMb,8FAA8F;IACxF,KAAK,CAAC,GAAG,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAM3C;;;OAGG;IACH,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;IAI3B,wFAAwF;IACxF,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;IAuC3B,WAAW,CAAC,KAAK,EAAE;QAAE,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC;QAAC,SAAS,EAAE,QAAQ,GAAG,IAAI,CAAA;KAAE,GAAG,IAAI;IAKhF,2EAA2E;IAC3E,UAAU,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,GAAG,IAAI;IAStC,gCAAgC;IAChC,OAAO,CAAC,CAAC,EAAE,aAAa,GAAG,IAAI;CAsIhC"}
@@ -0,0 +1,133 @@
1
+ import type { CellChange, CellRef, CellStyle, CellValue, RangeRef, SheetOp } from '@ember-lattice/formula';
2
+ /**
3
+ * An op on the wire: a `SheetOp` (the engine ops), or a model op that the engine does not see.
4
+ * `freeze` keeps the counts of frozen rows and columns; 0 and 0 removes the panes.
5
+ */
6
+ export type CollabOp = SheetOp | {
7
+ type: 'setNote';
8
+ sheet: string;
9
+ row: string;
10
+ col: string;
11
+ note: string | null;
12
+ } | {
13
+ type: 'freeze';
14
+ sheet: string;
15
+ rows: number;
16
+ cols: number;
17
+ };
18
+ /** A cell, a selection or a cell in edit mode, as presence. */
19
+ export interface Presence {
20
+ cursor: CellRef | null;
21
+ selection: RangeRef | null;
22
+ /** The cell that the user edits now: a soft lock hint for the other users. */
23
+ editing: CellRef | null;
24
+ }
25
+ export type ClientMessage =
26
+ /** Opens a doc. `sinceSeq` null asks for a snapshot; a number asks for the ops after it. */
27
+ {
28
+ v: 1;
29
+ type: 'join';
30
+ docId: string;
31
+ clientId: string;
32
+ sinceSeq: number | null;
33
+ name?: string;
34
+ } | {
35
+ v: 1;
36
+ type: 'submit';
37
+ docId: string;
38
+ clientId: string;
39
+ opId: string;
40
+ baseSeq: number;
41
+ ops: CollabOp[];
42
+ } | ({
43
+ v: 1;
44
+ type: 'presence';
45
+ docId: string;
46
+ } & Presence);
47
+ /** A doc as the server sends it: the `WorkbookDoc` form, with the computed values. */
48
+ export interface CollabCell {
49
+ row: string;
50
+ col: string;
51
+ value?: CellValue;
52
+ formula?: string;
53
+ computed?: CellValue;
54
+ format?: string;
55
+ style?: string;
56
+ note?: string;
57
+ }
58
+ export interface CollabArea {
59
+ start: {
60
+ row: string;
61
+ col: string;
62
+ };
63
+ end: {
64
+ row: string;
65
+ col: string;
66
+ };
67
+ }
68
+ export interface CollabDoc {
69
+ sheets: {
70
+ id: string;
71
+ name: string;
72
+ rows: string[];
73
+ cols: string[];
74
+ cells: CollabCell[];
75
+ merges?: CollabArea[];
76
+ /** Not there when no row and no column is frozen. */
77
+ frozen?: {
78
+ rows: number;
79
+ cols: number;
80
+ };
81
+ }[];
82
+ names?: {
83
+ name: string;
84
+ ref: string;
85
+ }[];
86
+ styles?: Record<string, CellStyle>;
87
+ }
88
+ export type ServerMessage = {
89
+ v: 1;
90
+ type: 'snapshot';
91
+ docId: string;
92
+ seq: number;
93
+ doc: CollabDoc;
94
+ }
95
+ /** The ops as the server applied them, to every client (the sender too). */
96
+ | {
97
+ v: 1;
98
+ type: 'ops';
99
+ docId: string;
100
+ seq: number;
101
+ clientId: string;
102
+ opId: string;
103
+ ops: CollabOp[];
104
+ changes: CellChange[];
105
+ }
106
+ /** A submit that the server sequenced before (a resend after a reconnect). */
107
+ | {
108
+ v: 1;
109
+ type: 'ack';
110
+ docId: string;
111
+ opId: string;
112
+ seq: number;
113
+ }
114
+ /** The server applied no op of the submit. `opId` is null when the message did not parse. */
115
+ | {
116
+ v: 1;
117
+ type: 'reject';
118
+ docId: string;
119
+ opId: string | null;
120
+ reason: string;
121
+ } | ({
122
+ v: 1;
123
+ type: 'presence';
124
+ docId: string;
125
+ clientId: string;
126
+ name: string;
127
+ } & Presence) | {
128
+ v: 1;
129
+ type: 'leave';
130
+ docId: string;
131
+ clientId: string;
132
+ };
133
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,UAAU,EACV,OAAO,EACP,SAAS,EACT,SAAS,EACT,QAAQ,EACR,OAAO,EACR,MAAM,wBAAwB,CAAA;AAE/B;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAChB,OAAO,GACP;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GACjF;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAA;AAEjE,+DAA+D;AAC/D,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE,OAAO,GAAG,IAAI,CAAA;IACtB,SAAS,EAAE,QAAQ,GAAG,IAAI,CAAA;IAC1B,8EAA8E;IAC9E,OAAO,EAAE,OAAO,GAAG,IAAI,CAAA;CACxB;AAED,MAAM,MAAM,aAAa;AACvB,4FAA4F;AAC1F;IACE,CAAC,EAAE,CAAC,CAAA;IACJ,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,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CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,CAAC,GACtF;IAAE,CAAC,EAAE,CAAC,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,627 @@
1
+ import is from '@sindresorhus/is';
2
+ import { Workbook } from '@ember-lattice/sheet';
3
+
4
+ /** Sends client messages. The app gives server messages to `session.receive`. */
5
+
6
+ /** Another user on the doc. */
7
+
8
+ const COLORS = ['#d1495b', '#2e86ab', '#3b8b3b', '#c77d0a', '#7b4fa8', '#a1533f', '#16808a', '#b5397b'];
9
+ function colorOf(clientId) {
10
+ let h = 0;
11
+ for (const ch of clientId) h = h * 31 + ch.charCodeAt(0) | 0;
12
+ return COLORS[Math.abs(h) % COLORS.length];
13
+ }
14
+ const nullEngine = {
15
+ load: async () => {},
16
+ apply: async () => [],
17
+ evaluate: async () => null,
18
+ functions: () => []
19
+ };
20
+ function equal(a, b) {
21
+ if (a === b) return true;
22
+ if (is.array(a) && is.array(b)) return a.length === b.length && a.every((x, i) => equal(x, b[i]));
23
+ if (is.plainObject(a) && is.plainObject(b)) {
24
+ const keys = Object.keys(a).filter(k => a[k] !== undefined);
25
+ const other = Object.keys(b).filter(k => b[k] !== undefined);
26
+ return keys.length === other.length && keys.every(k => equal(a[k], b[k]));
27
+ }
28
+ return false;
29
+ }
30
+ const STRUCTURAL = new Set(['insertRows', 'deleteRows', 'insertCols', 'deleteCols', 'addSheet', 'removeSheet', 'renameSheet']);
31
+
32
+ /** The cell that a `setCell` op writes, as a key, or nothing for another op. */
33
+ const cellKey = op => op.type === 'setCell' ? [`${op.sheet} ${op.row} ${op.col}`] : [];
34
+
35
+ /** The model as a doc, with the computed values. */
36
+ function toDoc(book) {
37
+ return {
38
+ sheets: book.sheets.map(s => ({
39
+ id: s.id,
40
+ name: s.name,
41
+ rows: [...s.rows],
42
+ cols: [...s.cols],
43
+ cells: [...s.entries()].map(([row, col, c]) => ({
44
+ row,
45
+ col,
46
+ ...c
47
+ })),
48
+ merges: s.merges.map(m => structuredClone(m)),
49
+ frozen: {
50
+ ...s.frozen
51
+ }
52
+ })),
53
+ names: Object.entries(book.names).map(([name, ref]) => ({
54
+ name,
55
+ ref
56
+ })),
57
+ styles: Object.fromEntries(book.styles)
58
+ };
59
+ }
60
+
61
+ /** Loads the model at once; the engine loads after. Sets the computed values of the doc. */
62
+ function load(book, doc) {
63
+ const done = book.load(doc);
64
+ for (const s of doc.sheets) {
65
+ const sheet = book.sheet(s.id);
66
+ for (const c of s.cells) {
67
+ if (c.formula && c.computed !== undefined) sheet.updateCell(c.row, c.col, {
68
+ computed: c.computed
69
+ });
70
+ }
71
+ }
72
+ return done;
73
+ }
74
+ function take(book, changes) {
75
+ for (const {
76
+ sheet,
77
+ row,
78
+ col,
79
+ value
80
+ } of changes) {
81
+ const s = book.sheets.find(x => x.id === sheet);
82
+ if (s?.cell(row, col)) s.updateCell(row, col, {
83
+ computed: value
84
+ });
85
+ }
86
+ }
87
+
88
+ /** The op if it fits the model now, else null. The server uses the same rules. */
89
+ function fits(book, op) {
90
+ const sheet = id => book.sheets.find(s => s.id === id);
91
+ const nameUsed = (name, except) => book.sheets.some(s => s.id !== except && s.name.toLowerCase() === name.toLowerCase());
92
+ switch (op.type) {
93
+ case 'setCell':
94
+ case 'setNote':
95
+ {
96
+ const s = sheet(op.sheet);
97
+ return s?.rows.includes(op.row) && s.cols.includes(op.col) ? op : null;
98
+ }
99
+ case 'freeze':
100
+ return sheet(op.sheet) ? op : null;
101
+ case 'insertRows':
102
+ case 'insertCols':
103
+ {
104
+ const ids = op.type === 'insertRows' ? sheet(op.sheet)?.rows : sheet(op.sheet)?.cols;
105
+ if (!ids || op.ids.some(id => ids.includes(id))) return null;
106
+ return op.before === null || ids.includes(op.before) ? op : null;
107
+ }
108
+ case 'deleteRows':
109
+ case 'deleteCols':
110
+ {
111
+ const ids = op.type === 'deleteRows' ? sheet(op.sheet)?.rows : sheet(op.sheet)?.cols;
112
+ const keep = [...new Set(op.ids)].filter(id => ids?.includes(id));
113
+ if (keep.length === 0) return null;
114
+ return keep.length === op.ids.length ? op : {
115
+ ...op,
116
+ ids: keep
117
+ };
118
+ }
119
+ case 'setFormat':
120
+ case 'setStyle':
121
+ case 'merge':
122
+ case 'unmerge':
123
+ return sheet(op.range.sheet)?.bounds(op.range) ? op : null;
124
+ case 'setName':
125
+ return op;
126
+ case 'addSheet':
127
+ return sheet(op.id) || nameUsed(op.name) ? null : op;
128
+ case 'removeSheet':
129
+ return sheet(op.id) && book.sheets.length > 1 ? op : null;
130
+ case 'renameSheet':
131
+ return sheet(op.id) && !nameUsed(op.name, op.id) ? op : null;
132
+ }
133
+ }
134
+ const sameRange = (a, b) => a.start.row === b.start.row && a.start.col === b.start.col && a.end.row === b.end.row && a.end.col === b.end.col;
135
+
136
+ /** The ops that undo `op` on the model as it is now. A delete has no inverse in this part. */
137
+ function inverseOf(book, op) {
138
+ switch (op.type) {
139
+ case 'setNote':
140
+ {
141
+ const note = book.sheet(op.sheet).cell(op.row, op.col)?.note ?? null;
142
+ return [{
143
+ ...op,
144
+ note
145
+ }];
146
+ }
147
+ case 'freeze':
148
+ return [{
149
+ type: 'freeze',
150
+ sheet: op.sheet,
151
+ ...book.sheet(op.sheet).frozen
152
+ }];
153
+ case 'setCell':
154
+ {
155
+ const c = book.sheet(op.sheet).cell(op.row, op.col);
156
+ const back = {
157
+ type: 'setCell',
158
+ sheet: op.sheet,
159
+ row: op.row,
160
+ col: op.col
161
+ };
162
+ if (c?.formula) back.formula = c.formula;else if (c?.value !== undefined) back.value = c.value;
163
+ return [back];
164
+ }
165
+ case 'insertRows':
166
+ return [{
167
+ type: 'deleteRows',
168
+ sheet: op.sheet,
169
+ ids: op.ids
170
+ }];
171
+ case 'insertCols':
172
+ return [{
173
+ type: 'deleteCols',
174
+ sheet: op.sheet,
175
+ ids: op.ids
176
+ }];
177
+ case 'merge':
178
+ case 'unmerge':
179
+ {
180
+ const same = book.sheet(op.range.sheet).merges.filter(m => sameRange(op.range, m)).length;
181
+ const remerge = Array.from({
182
+ length: same
183
+ }, () => ({
184
+ type: 'merge',
185
+ range: op.range
186
+ }));
187
+ return op.type === 'merge' ? [{
188
+ type: 'unmerge',
189
+ range: op.range
190
+ }, ...remerge] : remerge;
191
+ }
192
+ case 'setFormat':
193
+ case 'setStyle':
194
+ {
195
+ const sheet = book.sheet(op.range.sheet);
196
+ return [...sheet.cellsOf(op.range)].map(([row, col]) => {
197
+ const range = {
198
+ sheet: sheet.id,
199
+ start: {
200
+ row,
201
+ col
202
+ },
203
+ end: {
204
+ row,
205
+ col
206
+ }
207
+ };
208
+ const c = sheet.cell(row, col);
209
+ if (op.type === 'setFormat') return {
210
+ type: 'setFormat',
211
+ range,
212
+ format: c?.format ?? null
213
+ };
214
+ return {
215
+ type: 'setStyle',
216
+ range,
217
+ style: c?.style && book.styles.get(c.style) || null
218
+ };
219
+ });
220
+ }
221
+ case 'setName':
222
+ return [{
223
+ type: 'setName',
224
+ name: op.name,
225
+ ref: book.names[op.name] ?? null
226
+ }];
227
+ case 'addSheet':
228
+ return [{
229
+ type: 'removeSheet',
230
+ id: op.id
231
+ }];
232
+ case 'renameSheet':
233
+ return [{
234
+ type: 'renameSheet',
235
+ id: op.id,
236
+ name: book.sheet(op.id).name
237
+ }];
238
+ case 'deleteRows':
239
+ case 'deleteCols':
240
+ case 'removeSheet':
241
+ return [];
242
+ }
243
+ }
244
+
245
+ /**
246
+ * A live link from a `Workbook` to the collab server (plan 8.4). Local ops change the view at
247
+ * once and go to the server. The session keeps a shadow model that holds only the server
248
+ * state. When a server op conflicts with a pending local op, the view loads the shadow again
249
+ * and applies the pending ops on top: the result is what the server makes when the pending
250
+ * ops arrive.
251
+ */
252
+ class CollabSession {
253
+ doc;
254
+ /** The server state only. Its engine computes nothing: it takes the server values. */
255
+ #shadow = new Workbook(nullEngine);
256
+ #transport;
257
+ #docId;
258
+ #clientId;
259
+ #name;
260
+ #timeout;
261
+ #now;
262
+ onDrop;
263
+ onRemote;
264
+ onPresence;
265
+ onError;
266
+ #seq = null;
267
+ #pending = [];
268
+ #undo = [];
269
+ #redo = [];
270
+ /** The view can have computed values that differ from the shadow. */
271
+ #dirty = false;
272
+ #online = false;
273
+ #me = {
274
+ cursor: null,
275
+ selection: null,
276
+ editing: null
277
+ };
278
+ #timer;
279
+ #work = new Set();
280
+ #opPrefix = Math.random().toString(36).slice(2, 8);
281
+ #opCount = 0;
282
+ #ready;
283
+ /** Ends when the view holds the server doc. */
284
+ ready = new Promise(resolve => this.#ready = resolve);
285
+ #peerMap = new Map();
286
+ constructor(options) {
287
+ this.doc = options.doc;
288
+ this.#transport = options.transport;
289
+ this.#docId = options.docId;
290
+ this.#clientId = options.clientId;
291
+ this.#name = options.name;
292
+ this.#timeout = options.presenceTimeout ?? 30_000;
293
+ this.#now = options.now ?? Date.now;
294
+ this.onDrop = options.onDrop;
295
+ this.onRemote = options.onRemote;
296
+ this.onPresence = options.onPresence;
297
+ this.onError = options.onError ?? (e => console.error(e));
298
+ if (options.seq !== undefined) {
299
+ this.#seq = options.seq;
300
+ this.#track(load(this.#shadow, toDoc(this.doc)));
301
+ this.#ready();
302
+ }
303
+ }
304
+
305
+ /** The last server seq that the view holds, or null before the first snapshot. */
306
+ get seq() {
307
+ return this.#seq;
308
+ }
309
+
310
+ /** The count of local submits that the server did not sequence yet. */
311
+ get pending() {
312
+ return this.#pending.length;
313
+ }
314
+ get canUndo() {
315
+ return this.#undo.some(ops => ops.length > 0);
316
+ }
317
+ get canRedo() {
318
+ return this.#redo.some(ops => ops.length > 0);
319
+ }
320
+
321
+ /** The other users with a presence that did not expire. */
322
+ get peers() {
323
+ const now = this.#now();
324
+ return [...this.#peerMap.values()].filter(p => now - p.seen <= this.#timeout);
325
+ }
326
+ #setPeers(peers) {
327
+ this.#peerMap = peers;
328
+ this.onPresence?.(this.peers);
329
+ }
330
+
331
+ /** The user in edit mode on this cell, if there is one: a soft lock hint. */
332
+ lockAt(sheet, row, col) {
333
+ return this.peers.find(p => p.editing?.sheet === sheet && p.editing.row === row && p.editing.col === col);
334
+ }
335
+
336
+ /** Waits for the engine work of the view and the shadow. */
337
+ async settled() {
338
+ while (this.#work.size) await Promise.all([...this.#work]);
339
+ }
340
+ #track(p) {
341
+ const done = p.catch(this.onError).finally(() => this.#work.delete(done));
342
+ this.#work.add(done);
343
+ return done;
344
+ }
345
+ #send(message) {
346
+ if (this.#online) this.#transport.send(message);
347
+ }
348
+ #submit(p) {
349
+ this.#send({
350
+ v: 1,
351
+ type: 'submit',
352
+ docId: this.#docId,
353
+ clientId: this.#clientId,
354
+ opId: p.opId,
355
+ baseSeq: this.#seq ?? 0,
356
+ ops: p.ops
357
+ });
358
+ }
359
+
360
+ /** Call when the transport connects (also after a reconnect). */
361
+ open() {
362
+ this.#online = true;
363
+ const join = {
364
+ v: 1,
365
+ type: 'join',
366
+ docId: this.#docId,
367
+ clientId: this.#clientId,
368
+ sinceSeq: this.#seq
369
+ };
370
+ if (this.#name !== undefined) join.name = this.#name;
371
+ this.#send(join);
372
+ for (const p of this.#pending) this.#submit(p);
373
+ if (this.#me.cursor || this.#me.selection || this.#me.editing) this.#sendPresence();
374
+ clearInterval(this.#timer);
375
+ // A heartbeat, so the presence of this user does not expire for the others.
376
+ this.#timer = setInterval(() => {
377
+ if (this.#me.cursor || this.#me.selection || this.#me.editing) this.#sendPresence();
378
+ this.#setPeers(new Map([...this.#peerMap].filter(([, p]) => this.#now() - p.seen <= this.#timeout)));
379
+ }, this.#timeout / 2);
380
+ }
381
+
382
+ /** Call when the transport disconnects. Local ops wait for the next `open`. */
383
+ close() {
384
+ this.#online = false;
385
+ clearInterval(this.#timer);
386
+ this.#setPeers(new Map());
387
+ }
388
+
389
+ /** Applies local ops at once and sends them. Ops that do not fit the view now are skipped. */
390
+ async apply(ops) {
391
+ const {
392
+ work,
393
+ applied
394
+ } = this.#local(ops, this.#undo);
395
+ if (applied.length) this.#redo = [];
396
+ await work;
397
+ }
398
+
399
+ /**
400
+ * Undoes the last local change that still has an effect. Later writes of others stay. Gives
401
+ * the applied ops, so the view can show the cells again.
402
+ */
403
+ undo() {
404
+ return this.#step(this.#undo, this.#redo);
405
+ }
406
+
407
+ /** Applies the last undone change again. A later write of another user wins over it. */
408
+ redo() {
409
+ return this.#step(this.#redo, this.#undo);
410
+ }
411
+ async #step(from, to) {
412
+ while (from.length) {
413
+ const ops = from.pop();
414
+ if (ops.length === 0) continue;
415
+ const {
416
+ work,
417
+ applied
418
+ } = this.#local(ops, to);
419
+ await work;
420
+ return applied;
421
+ }
422
+ return [];
423
+ }
424
+
425
+ /** Applies and sends local ops, and pushes their inverse on `history`. */
426
+ #local(ops, history) {
427
+ if (this.#seq === null) throw new Error('Lattice: wait for `session.ready` before you apply ops');
428
+ const applied = [];
429
+ const inverse = [];
430
+ const work = [];
431
+ // shortcut: one engine call for each op, so each inverse sees the state before its op.
432
+ // Batch the engine calls when large local batches are common.
433
+ for (const op of ops) {
434
+ const fit = fits(this.doc, op);
435
+ if (!fit) continue;
436
+ inverse.unshift(...inverseOf(this.doc, fit));
437
+ work.push(this.#track(this.doc.apply([fit])));
438
+ applied.push(fit);
439
+ }
440
+ if (applied.length === 0) return {
441
+ work: Promise.resolve(),
442
+ applied
443
+ };
444
+ history.push(inverse);
445
+ const p = {
446
+ opId: `${this.#clientId}.${this.#opPrefix}.${++this.#opCount}`,
447
+ ops: applied
448
+ };
449
+ this.#pending.push(p);
450
+ this.#submit(p);
451
+ return {
452
+ work: Promise.all(work),
453
+ applied
454
+ };
455
+ }
456
+ setPresence(state) {
457
+ this.#me = {
458
+ ...this.#me,
459
+ ...state
460
+ };
461
+ this.#sendPresence();
462
+ }
463
+
464
+ /** Marks the cell that this user edits now, or null when the edit ends. */
465
+ setEditing(cell) {
466
+ this.#me = {
467
+ ...this.#me,
468
+ editing: cell
469
+ };
470
+ this.#sendPresence();
471
+ }
472
+ #sendPresence() {
473
+ this.#send({
474
+ v: 1,
475
+ type: 'presence',
476
+ docId: this.#docId,
477
+ ...this.#me
478
+ });
479
+ }
480
+
481
+ /** Takes one server message. */
482
+ receive(m) {
483
+ if (m.docId !== this.#docId && m.docId !== '') return;
484
+ switch (m.type) {
485
+ case 'snapshot':
486
+ this.#track(load(this.#shadow, m.doc));
487
+ this.#seq = m.seq;
488
+ this.#rebuild();
489
+ this.#ready();
490
+ return;
491
+ case 'ops':
492
+ return this.#ops(m);
493
+ case 'ack':
494
+ // A resent op that a snapshot already holds.
495
+ if (this.#pending[0]?.opId === m.opId && this.#seq !== null && m.seq <= this.#seq) {
496
+ this.#pending.shift();
497
+ this.#rebuild();
498
+ }
499
+ return;
500
+ case 'reject':
501
+ {
502
+ const head = this.#pending[0];
503
+ if (m.opId !== null && head?.opId === m.opId) {
504
+ this.#pending.shift();
505
+ this.onDrop?.(head.ops, m.reason);
506
+ this.#rebuild();
507
+ } else this.onError(new Error(`Lattice: the collab server rejected a message: ${m.reason}`));
508
+ return;
509
+ }
510
+ case 'presence':
511
+ {
512
+ const {
513
+ v: _v,
514
+ type: _t,
515
+ docId: _d,
516
+ ...peer
517
+ } = m;
518
+ const peers = new Map(this.#peerMap);
519
+ peers.set(m.clientId, {
520
+ ...peer,
521
+ color: colorOf(m.clientId),
522
+ seen: this.#now()
523
+ });
524
+ this.#setPeers(peers);
525
+ return;
526
+ }
527
+ case 'leave':
528
+ {
529
+ const peers = new Map(this.#peerMap);
530
+ peers.delete(m.clientId);
531
+ this.#setPeers(peers);
532
+ }
533
+ }
534
+ }
535
+ #ops(m) {
536
+ if (this.#seq === null || m.seq <= this.#seq) return;
537
+ if (m.seq !== this.#seq + 1) {
538
+ this.onError(new Error(`Lattice: collab seq ${m.seq} after ${this.#seq}`));
539
+ return;
540
+ }
541
+ this.#seq = m.seq;
542
+ this.#track(this.#shadow.apply(m.ops));
543
+ take(this.#shadow, m.changes);
544
+ const head = this.#pending[0];
545
+ if (m.clientId === this.#clientId && head?.opId === m.opId) {
546
+ this.#pending.shift();
547
+ if (!equal(head.ops, m.ops)) {
548
+ const kept = m.ops;
549
+ const lost = head.ops.filter(op => !kept.some(k => equal(k, op)));
550
+ if (lost.length) this.onDrop?.(lost, 'conflict');
551
+ this.#rebuild();
552
+ } else if (this.#pending.length === 0) this.#settle(m.changes);
553
+ // The shadow took the changes; the view takes them when no op waits.
554
+ else this.#dirty = true;
555
+ return;
556
+ }
557
+ this.#transformUndo(m.ops);
558
+ if (this.#pending.length === 0) {
559
+ this.#track(this.doc.apply(m.ops));
560
+ this.#settle(m.changes);
561
+ } else if (this.#commutes(m.ops)) {
562
+ this.#track(this.doc.apply(m.ops));
563
+ this.#dirty = true;
564
+ } else this.#rebuild();
565
+ this.onRemote?.(m.ops);
566
+ }
567
+
568
+ /** True when the server ops touch nothing that the pending ops touch. */
569
+ #commutes(ops) {
570
+ const pending = this.#pending.flatMap(p => p.ops);
571
+ if (pending.some(op => STRUCTURAL.has(op.type))) return false;
572
+ const mine = new Set(pending.flatMap(cellKey));
573
+ return ops.every(op => op.type === 'setCell' && !mine.has(cellKey(op)[0]));
574
+ }
575
+
576
+ /** The view now has no pending op: it must show the server values. */
577
+ #settle(changes) {
578
+ if (this.#dirty) this.#copyComputed();else take(this.doc, changes);
579
+ this.#dirty = false;
580
+ // The engine of the view writes its values later. The server values win when no op waits.
581
+ // shortcut: a copy of all cells after each settle, O(cells). Copy only the changed cells
582
+ // when large sheets with a local engine get slow.
583
+ const work = [...this.#work];
584
+ if (work.length) {
585
+ this.#track(Promise.all(work).then(() => {
586
+ if (this.#pending.length === 0) this.#copyComputed();
587
+ }));
588
+ }
589
+ }
590
+ #copyComputed() {
591
+ for (const s of this.#shadow.sheets) {
592
+ const view = this.doc.sheets.find(x => x.id === s.id);
593
+ for (const [row, col, c] of s.entries()) {
594
+ if (view?.cell(row, col) && !equal(view.cell(row, col)?.computed, c.computed)) {
595
+ view.updateCell(row, col, {
596
+ computed: c.computed
597
+ });
598
+ }
599
+ }
600
+ }
601
+ }
602
+
603
+ /** Loads the shadow into the view, then applies the pending ops that still fit. */
604
+ #rebuild() {
605
+ this.#track(load(this.doc, toDoc(this.#shadow)));
606
+ for (const p of this.#pending) {
607
+ for (const op of p.ops) {
608
+ const fit = fits(this.doc, op);
609
+ if (fit) this.#track(this.doc.apply([fit]));
610
+ }
611
+ }
612
+ this.#dirty = this.#pending.length > 0;
613
+ if (!this.#dirty) this.#settle([]);
614
+ }
615
+
616
+ /** A later write of another user wins over the undo or redo of an earlier local write. */
617
+ #transformUndo(ops) {
618
+ const written = new Set(ops.flatMap(cellKey));
619
+ if (written.size === 0) return;
620
+ const keep = entry => entry.filter(op => op.type !== 'setCell' || !written.has(cellKey(op)[0]));
621
+ this.#undo = this.#undo.map(keep);
622
+ this.#redo = this.#redo.map(keep);
623
+ }
624
+ }
625
+
626
+ export { CollabSession, toDoc };
627
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/session.ts"],"sourcesContent":["import is from '@sindresorhus/is'\nimport { Workbook } from '@ember-lattice/sheet'\nimport type { WorkbookDoc } from '@ember-lattice/sheet'\nimport type { CellChange, CellRef, FormulaEngine, RangeRef, SheetOp } from '@ember-lattice/formula'\nimport type { ClientMessage, CollabDoc, CollabOp, Presence, ServerMessage } from './wire.ts'\n\n/** Sends client messages. The app gives server messages to `session.receive`. */\nexport interface Transport {\n send(message: ClientMessage): void\n}\n\n/** Another user on the doc. */\nexport interface Peer extends Presence {\n clientId: string\n name: string\n color: string\n /** The time of the last presence message, from `now()`. */\n seen: number\n}\n\nexport interface CollabSessionOptions {\n /** The view: the sheet model that the user sees and edits. */\n doc: Workbook\n transport: Transport\n docId: string\n clientId: string\n name?: string\n /** The seq of `doc` when the app loaded it itself. Without it, the session loads a snapshot. */\n seq?: number\n /** A peer without a presence message for this time (ms) goes away. Default 30 s. */\n presenceTimeout?: number\n now?: () => number\n /** The server or a rebase dropped these local ops (for example, an edit to a deleted row). */\n onDrop?: (ops: CollabOp[], reason: string) => void\n /** The ops of another user are in the view now. */\n onRemote?: (ops: CollabOp[]) => void\n /** The peers changed. Put them in tracked state to render cursors and lock hints. */\n onPresence?: (peers: Peer[]) => void\n onError?: (error: unknown) => void\n}\n\ninterface Pending {\n opId: string\n ops: CollabOp[]\n}\n\nconst COLORS = [\n '#d1495b',\n '#2e86ab',\n '#3b8b3b',\n '#c77d0a',\n '#7b4fa8',\n '#a1533f',\n '#16808a',\n '#b5397b',\n]\n\nfunction colorOf(clientId: string): string {\n let h = 0\n for (const ch of clientId) h = (h * 31 + ch.charCodeAt(0)) | 0\n return COLORS[Math.abs(h) % COLORS.length]!\n}\n\nconst nullEngine: FormulaEngine = {\n load: async () => {},\n apply: async () => [],\n evaluate: async () => null,\n functions: () => [],\n}\n\nfunction equal(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (is.array(a) && is.array(b)) return a.length === b.length && a.every((x, i) => equal(x, b[i]))\n if (is.plainObject(a) && is.plainObject(b)) {\n const keys = Object.keys(a).filter(k => a[k] !== undefined)\n const other = Object.keys(b).filter(k => b[k] !== undefined)\n return keys.length === other.length && keys.every(k => equal(a[k], b[k]))\n }\n return false\n}\n\nconst STRUCTURAL = new Set([\n 'insertRows',\n 'deleteRows',\n 'insertCols',\n 'deleteCols',\n 'addSheet',\n 'removeSheet',\n 'renameSheet',\n])\n\n/** The cell that a `setCell` op writes, as a key, or nothing for another op. */\nconst cellKey = (op: CollabOp): string[] =>\n op.type === 'setCell' ? [`${op.sheet} ${op.row} ${op.col}`] : []\n\n/** The model as a doc, with the computed values. */\nexport function toDoc(book: Workbook): CollabDoc {\n return {\n sheets: book.sheets.map(s => ({\n id: s.id,\n name: s.name,\n rows: [...s.rows],\n cols: [...s.cols],\n cells: [...s.entries()].map(([row, col, c]) => ({ row, col, ...c })),\n merges: s.merges.map(m => structuredClone(m)),\n frozen: { ...s.frozen },\n })),\n names: Object.entries(book.names).map(([name, ref]) => ({ name, ref })),\n styles: Object.fromEntries(book.styles),\n }\n}\n\n/** Loads the model at once; the engine loads after. Sets the computed values of the doc. */\nfunction load(book: Workbook, doc: CollabDoc): Promise<void> {\n const done = book.load(doc as WorkbookDoc)\n for (const s of doc.sheets) {\n const sheet = book.sheet(s.id)\n for (const c of s.cells) {\n if (c.formula && c.computed !== undefined)\n sheet.updateCell(c.row, c.col, { computed: c.computed })\n }\n }\n return done\n}\n\nfunction take(book: Workbook, changes: CellChange[]) {\n for (const { sheet, row, col, value } of changes) {\n const s = book.sheets.find(x => x.id === sheet)\n if (s?.cell(row, col)) s.updateCell(row, col, { computed: value })\n }\n}\n\n/** The op if it fits the model now, else null. The server uses the same rules. */\nfunction fits(book: Workbook, op: CollabOp): CollabOp | null {\n const sheet = (id: string) => book.sheets.find(s => s.id === id)\n const nameUsed = (name: string, except?: string) =>\n book.sheets.some(s => s.id !== except && s.name.toLowerCase() === name.toLowerCase())\n switch (op.type) {\n case 'setCell':\n case 'setNote': {\n const s = sheet(op.sheet)\n return s?.rows.includes(op.row) && s.cols.includes(op.col) ? op : null\n }\n case 'freeze':\n return sheet(op.sheet) ? op : null\n case 'insertRows':\n case 'insertCols': {\n const ids = op.type === 'insertRows' ? sheet(op.sheet)?.rows : sheet(op.sheet)?.cols\n if (!ids || op.ids.some(id => ids.includes(id))) return null\n return op.before === null || ids.includes(op.before) ? op : null\n }\n case 'deleteRows':\n case 'deleteCols': {\n const ids = op.type === 'deleteRows' ? sheet(op.sheet)?.rows : sheet(op.sheet)?.cols\n const keep = [...new Set(op.ids)].filter(id => ids?.includes(id))\n if (keep.length === 0) return null\n return keep.length === op.ids.length ? op : { ...op, ids: keep }\n }\n case 'setFormat':\n case 'setStyle':\n case 'merge':\n case 'unmerge':\n return sheet(op.range.sheet)?.bounds(op.range) ? op : null\n case 'setName':\n return op\n case 'addSheet':\n return sheet(op.id) || nameUsed(op.name) ? null : op\n case 'removeSheet':\n return sheet(op.id) && book.sheets.length > 1 ? op : null\n case 'renameSheet':\n return sheet(op.id) && !nameUsed(op.name, op.id) ? op : null\n }\n}\n\nconst sameRange = (a: RangeRef, b: { start: CellRef | RangeRef['start']; end: RangeRef['end'] }) =>\n a.start.row === b.start.row &&\n a.start.col === b.start.col &&\n a.end.row === b.end.row &&\n a.end.col === b.end.col\n\n/** The ops that undo `op` on the model as it is now. A delete has no inverse in this part. */\nfunction inverseOf(book: Workbook, op: CollabOp): CollabOp[] {\n switch (op.type) {\n case 'setNote': {\n const note = book.sheet(op.sheet).cell(op.row, op.col)?.note ?? null\n return [{ ...op, note }]\n }\n case 'freeze':\n return [{ type: 'freeze', sheet: op.sheet, ...book.sheet(op.sheet).frozen }]\n case 'setCell': {\n const c = book.sheet(op.sheet).cell(op.row, op.col)\n const back: SheetOp = { type: 'setCell', sheet: op.sheet, row: op.row, col: op.col }\n if (c?.formula) back.formula = c.formula\n else if (c?.value !== undefined) back.value = c.value\n return [back]\n }\n case 'insertRows':\n return [{ type: 'deleteRows', sheet: op.sheet, ids: op.ids }]\n case 'insertCols':\n return [{ type: 'deleteCols', sheet: op.sheet, ids: op.ids }]\n case 'merge':\n case 'unmerge': {\n const same = book.sheet(op.range.sheet).merges.filter(m => sameRange(op.range, m)).length\n const remerge = Array.from({ length: same }, (): SheetOp => ({\n type: 'merge',\n range: op.range,\n }))\n return op.type === 'merge' ? [{ type: 'unmerge', range: op.range }, ...remerge] : remerge\n }\n case 'setFormat':\n case 'setStyle': {\n const sheet = book.sheet(op.range.sheet)\n return [...sheet.cellsOf(op.range)].map(([row, col]): SheetOp => {\n const range = { sheet: sheet.id, start: { row, col }, end: { row, col } }\n const c = sheet.cell(row, col)\n if (op.type === 'setFormat') return { type: 'setFormat', range, format: c?.format ?? null }\n return { type: 'setStyle', range, style: (c?.style && book.styles.get(c.style)) || null }\n })\n }\n case 'setName':\n return [{ type: 'setName', name: op.name, ref: book.names[op.name] ?? null }]\n case 'addSheet':\n return [{ type: 'removeSheet', id: op.id }]\n case 'renameSheet':\n return [{ type: 'renameSheet', id: op.id, name: book.sheet(op.id).name }]\n case 'deleteRows':\n case 'deleteCols':\n case 'removeSheet':\n return []\n }\n}\n\n/**\n * A live link from a `Workbook` to the collab server (plan 8.4). Local ops change the view at\n * once and go to the server. The session keeps a shadow model that holds only the server\n * state. When a server op conflicts with a pending local op, the view loads the shadow again\n * and applies the pending ops on top: the result is what the server makes when the pending\n * ops arrive.\n */\nexport class CollabSession {\n readonly doc: Workbook\n /** The server state only. Its engine computes nothing: it takes the server values. */\n readonly #shadow = new Workbook(nullEngine)\n readonly #transport: Transport\n readonly #docId: string\n readonly #clientId: string\n readonly #name: string | undefined\n readonly #timeout: number\n readonly #now: () => number\n onDrop: ((ops: CollabOp[], reason: string) => void) | undefined\n onRemote: ((ops: CollabOp[]) => void) | undefined\n onPresence: ((peers: Peer[]) => void) | undefined\n onError: (error: unknown) => void\n #seq: number | null = null\n #pending: Pending[] = []\n #undo: CollabOp[][] = []\n #redo: CollabOp[][] = []\n /** The view can have computed values that differ from the shadow. */\n #dirty = false\n #online = false\n #me: Presence = { cursor: null, selection: null, editing: null }\n #timer: ReturnType<typeof setInterval> | undefined\n #work = new Set<Promise<unknown>>()\n #opPrefix = Math.random().toString(36).slice(2, 8)\n #opCount = 0\n #ready!: () => void\n /** Ends when the view holds the server doc. */\n readonly ready: Promise<void> = new Promise(resolve => (this.#ready = resolve))\n #peerMap = new Map<string, Peer>()\n\n constructor(options: CollabSessionOptions) {\n this.doc = options.doc\n this.#transport = options.transport\n this.#docId = options.docId\n this.#clientId = options.clientId\n this.#name = options.name\n this.#timeout = options.presenceTimeout ?? 30_000\n this.#now = options.now ?? Date.now\n this.onDrop = options.onDrop\n this.onRemote = options.onRemote\n this.onPresence = options.onPresence\n this.onError = options.onError ?? (e => console.error(e))\n if (options.seq !== undefined) {\n this.#seq = options.seq\n this.#track(load(this.#shadow, toDoc(this.doc)))\n this.#ready()\n }\n }\n\n /** The last server seq that the view holds, or null before the first snapshot. */\n get seq(): number | null {\n return this.#seq\n }\n\n /** The count of local submits that the server did not sequence yet. */\n get pending(): number {\n return this.#pending.length\n }\n\n get canUndo(): boolean {\n return this.#undo.some(ops => ops.length > 0)\n }\n\n get canRedo(): boolean {\n return this.#redo.some(ops => ops.length > 0)\n }\n\n /** The other users with a presence that did not expire. */\n get peers(): Peer[] {\n const now = this.#now()\n return [...this.#peerMap.values()].filter(p => now - p.seen <= this.#timeout)\n }\n\n #setPeers(peers: Map<string, Peer>) {\n this.#peerMap = peers\n this.onPresence?.(this.peers)\n }\n\n /** The user in edit mode on this cell, if there is one: a soft lock hint. */\n lockAt(sheet: string, row: string, col: string): Peer | undefined {\n return this.peers.find(\n p => p.editing?.sheet === sheet && p.editing.row === row && p.editing.col === col,\n )\n }\n\n /** Waits for the engine work of the view and the shadow. */\n async settled(): Promise<void> {\n while (this.#work.size) await Promise.all([...this.#work])\n }\n\n #track(p: Promise<unknown>) {\n const done = p.catch(this.onError).finally(() => this.#work.delete(done))\n this.#work.add(done)\n return done\n }\n\n #send(message: ClientMessage) {\n if (this.#online) this.#transport.send(message)\n }\n\n #submit(p: Pending) {\n this.#send({\n v: 1,\n type: 'submit',\n docId: this.#docId,\n clientId: this.#clientId,\n opId: p.opId,\n baseSeq: this.#seq ?? 0,\n ops: p.ops,\n })\n }\n\n /** Call when the transport connects (also after a reconnect). */\n open(): void {\n this.#online = true\n const join: ClientMessage = {\n v: 1,\n type: 'join',\n docId: this.#docId,\n clientId: this.#clientId,\n sinceSeq: this.#seq,\n }\n if (this.#name !== undefined) join.name = this.#name\n this.#send(join)\n for (const p of this.#pending) this.#submit(p)\n if (this.#me.cursor || this.#me.selection || this.#me.editing) this.#sendPresence()\n clearInterval(this.#timer)\n // A heartbeat, so the presence of this user does not expire for the others.\n this.#timer = setInterval(() => {\n if (this.#me.cursor || this.#me.selection || this.#me.editing) this.#sendPresence()\n this.#setPeers(\n new Map([...this.#peerMap].filter(([, p]) => this.#now() - p.seen <= this.#timeout)),\n )\n }, this.#timeout / 2)\n }\n\n /** Call when the transport disconnects. Local ops wait for the next `open`. */\n close(): void {\n this.#online = false\n clearInterval(this.#timer)\n this.#setPeers(new Map())\n }\n\n /** Applies local ops at once and sends them. Ops that do not fit the view now are skipped. */\n async apply(ops: CollabOp[]): Promise<void> {\n const { work, applied } = this.#local(ops, this.#undo)\n if (applied.length) this.#redo = []\n await work\n }\n\n /**\n * Undoes the last local change that still has an effect. Later writes of others stay. Gives\n * the applied ops, so the view can show the cells again.\n */\n undo(): Promise<CollabOp[]> {\n return this.#step(this.#undo, this.#redo)\n }\n\n /** Applies the last undone change again. A later write of another user wins over it. */\n redo(): Promise<CollabOp[]> {\n return this.#step(this.#redo, this.#undo)\n }\n\n async #step(from: CollabOp[][], to: CollabOp[][]): Promise<CollabOp[]> {\n while (from.length) {\n const ops = from.pop()!\n if (ops.length === 0) continue\n const { work, applied } = this.#local(ops, to)\n await work\n return applied\n }\n return []\n }\n\n /** Applies and sends local ops, and pushes their inverse on `history`. */\n #local(ops: CollabOp[], history: CollabOp[][]) {\n if (this.#seq === null)\n throw new Error('Lattice: wait for `session.ready` before you apply ops')\n const applied: CollabOp[] = []\n const inverse: CollabOp[] = []\n const work: Promise<unknown>[] = []\n // shortcut: one engine call for each op, so each inverse sees the state before its op.\n // Batch the engine calls when large local batches are common.\n for (const op of ops) {\n const fit = fits(this.doc, op)\n if (!fit) continue\n inverse.unshift(...inverseOf(this.doc, fit))\n work.push(this.#track(this.doc.apply([fit])))\n applied.push(fit)\n }\n if (applied.length === 0) return { work: Promise.resolve(), applied }\n history.push(inverse)\n const p = { opId: `${this.#clientId}.${this.#opPrefix}.${++this.#opCount}`, ops: applied }\n this.#pending.push(p)\n this.#submit(p)\n return { work: Promise.all(work), applied }\n }\n\n setPresence(state: { cursor: CellRef | null; selection: RangeRef | null }): void {\n this.#me = { ...this.#me, ...state }\n this.#sendPresence()\n }\n\n /** Marks the cell that this user edits now, or null when the edit ends. */\n setEditing(cell: CellRef | null): void {\n this.#me = { ...this.#me, editing: cell }\n this.#sendPresence()\n }\n\n #sendPresence() {\n this.#send({ v: 1, type: 'presence', docId: this.#docId, ...this.#me })\n }\n\n /** Takes one server message. */\n receive(m: ServerMessage): void {\n if (m.docId !== this.#docId && m.docId !== '') return\n switch (m.type) {\n case 'snapshot':\n this.#track(load(this.#shadow, m.doc))\n this.#seq = m.seq\n this.#rebuild()\n this.#ready()\n return\n case 'ops':\n return this.#ops(m)\n case 'ack':\n // A resent op that a snapshot already holds.\n if (this.#pending[0]?.opId === m.opId && this.#seq !== null && m.seq <= this.#seq) {\n this.#pending.shift()\n this.#rebuild()\n }\n return\n case 'reject': {\n const head = this.#pending[0]\n if (m.opId !== null && head?.opId === m.opId) {\n this.#pending.shift()\n this.onDrop?.(head.ops, m.reason)\n this.#rebuild()\n } else this.onError(new Error(`Lattice: the collab server rejected a message: ${m.reason}`))\n return\n }\n case 'presence': {\n const { v: _v, type: _t, docId: _d, ...peer } = m\n const peers = new Map(this.#peerMap)\n peers.set(m.clientId, { ...peer, color: colorOf(m.clientId), seen: this.#now() })\n this.#setPeers(peers)\n return\n }\n case 'leave': {\n const peers = new Map(this.#peerMap)\n peers.delete(m.clientId)\n this.#setPeers(peers)\n }\n }\n }\n\n #ops(m: Extract<ServerMessage, { type: 'ops' }>) {\n if (this.#seq === null || m.seq <= this.#seq) return\n if (m.seq !== this.#seq + 1) {\n this.onError(new Error(`Lattice: collab seq ${m.seq} after ${this.#seq}`))\n return\n }\n this.#seq = m.seq\n this.#track(this.#shadow.apply(m.ops))\n take(this.#shadow, m.changes)\n const head = this.#pending[0]\n if (m.clientId === this.#clientId && head?.opId === m.opId) {\n this.#pending.shift()\n if (!equal(head.ops, m.ops)) {\n const kept = m.ops\n const lost = head.ops.filter(op => !kept.some(k => equal(k, op)))\n if (lost.length) this.onDrop?.(lost, 'conflict')\n this.#rebuild()\n } else if (this.#pending.length === 0) this.#settle(m.changes)\n // The shadow took the changes; the view takes them when no op waits.\n else this.#dirty = true\n return\n }\n this.#transformUndo(m.ops)\n if (this.#pending.length === 0) {\n this.#track(this.doc.apply(m.ops))\n this.#settle(m.changes)\n } else if (this.#commutes(m.ops)) {\n this.#track(this.doc.apply(m.ops))\n this.#dirty = true\n } else this.#rebuild()\n this.onRemote?.(m.ops)\n }\n\n /** True when the server ops touch nothing that the pending ops touch. */\n #commutes(ops: CollabOp[]): boolean {\n const pending = this.#pending.flatMap(p => p.ops)\n if (pending.some(op => STRUCTURAL.has(op.type))) return false\n const mine = new Set(pending.flatMap(cellKey))\n return ops.every(op => op.type === 'setCell' && !mine.has(cellKey(op)[0]!))\n }\n\n /** The view now has no pending op: it must show the server values. */\n #settle(changes: CellChange[]) {\n if (this.#dirty) this.#copyComputed()\n else take(this.doc, changes)\n this.#dirty = false\n // The engine of the view writes its values later. The server values win when no op waits.\n // shortcut: a copy of all cells after each settle, O(cells). Copy only the changed cells\n // when large sheets with a local engine get slow.\n const work = [...this.#work]\n if (work.length) {\n this.#track(\n Promise.all(work).then(() => {\n if (this.#pending.length === 0) this.#copyComputed()\n }),\n )\n }\n }\n\n #copyComputed() {\n for (const s of this.#shadow.sheets) {\n const view = this.doc.sheets.find(x => x.id === s.id)\n for (const [row, col, c] of s.entries()) {\n if (view?.cell(row, col) && !equal(view.cell(row, col)?.computed, c.computed)) {\n view.updateCell(row, col, { computed: c.computed })\n }\n }\n }\n }\n\n /** Loads the shadow into the view, then applies the pending ops that still fit. */\n #rebuild() {\n this.#track(load(this.doc, toDoc(this.#shadow)))\n for (const p of this.#pending) {\n for (const op of p.ops) {\n const fit = fits(this.doc, op)\n if (fit) this.#track(this.doc.apply([fit]))\n }\n }\n this.#dirty = this.#pending.length > 0\n if (!this.#dirty) this.#settle([])\n }\n\n /** A later write of another user wins over the undo or redo of an earlier local write. */\n #transformUndo(ops: CollabOp[]) {\n const written = new Set(ops.flatMap(cellKey))\n if (written.size === 0) return\n const keep = (entry: CollabOp[]) =>\n entry.filter(op => op.type !== 'setCell' || !written.has(cellKey(op)[0]!))\n this.#undo = this.#undo.map(keep)\n this.#redo = this.#redo.map(keep)\n }\n}\n"],"names":["COLORS","colorOf","clientId","h","ch","charCodeAt","Math","abs","length","nullEngine","load","apply","evaluate","functions","equal","a","b","is","array","every","x","i","plainObject","keys","Object","filter","k","undefined","other","STRUCTURAL","Set","cellKey","op","type","sheet","row","col","toDoc","book","sheets","map","s","id","name","rows","cols","cells","entries","c","merges","m","structuredClone","frozen","names","ref","styles","fromEntries","doc","done","formula","computed","updateCell","take","changes","value","find","cell","fits","nameUsed","except","some","toLowerCase","includes","ids","before","keep","range","bounds","sameRange","start","end","inverseOf","note","back","same","remerge","Array","from","cellsOf","format","style","get","CollabSession","Workbook","onDrop","onRemote","onPresence","onError","cursor","selection","editing","random","toString","slice","ready","Promise","resolve","Map","constructor","options","transport","docId","presenceTimeout","now","Date","e","console","error","seq","pending","canUndo","ops","canRedo","peers","values","p","seen","#setPeers","lockAt","settled","size","all","#track","catch","finally","delete","add","#send","message","send","#submit","v","opId","baseSeq","open","join","sinceSeq","clearInterval","setInterval","close","work","applied","undo","redo","#step","to","pop","#local","history","Error","inverse","fit","unshift","push","setPresence","state","setEditing","#sendPresence","receive","shift","head","reason","_v","_t","_d","peer","set","color","#ops","kept","lost","#commutes","flatMap","has","mine","#settle","then","#copyComputed","view","#rebuild","#transformUndo","written","entry"],"mappings":";;;AAMA;;AAKA;;AAmCA,MAAMA,MAAM,GAAG,CACb,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,CACV;AAED,SAASC,OAAOA,CAACC,QAAgB,EAAU;EACzC,IAAIC,CAAC,GAAG,CAAC;AACT,EAAA,KAAK,MAAMC,EAAE,IAAIF,QAAQ,EAAEC,CAAC,GAAIA,CAAC,GAAG,EAAE,GAAGC,EAAE,CAACC,UAAU,C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K,CAACnC,GAAG,CAACmC,IAAI,CAAC;AACnC,EAAA;AACF;;"}
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "@ember-lattice/collab",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.1.0",
4
+ "description": "Live collaboration for Lattice sheets and grids: an op log client with rebase, presence, cursors and selections.",
5
+ "keywords": [
6
+ "ember-addon",
7
+ "ember",
8
+ "data-grid",
9
+ "table",
10
+ "virtual-scroll"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "Joe Gaudet <joe@joegaudet.com>",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/joegaudet/ember-lattice.git",
17
+ "directory": "packages/collab"
18
+ },
19
+ "homepage": "https://joegaudet.com/ember-lattice/",
20
+ "bugs": "https://github.com/joegaudet/ember-lattice/issues",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./declarations/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "./addon-main.js": "./addon-main.cjs"
27
+ },
28
+ "typesVersions": {
29
+ "*": {
30
+ "*": [
31
+ "declarations/*"
32
+ ]
33
+ }
34
+ },
35
+ "files": [
36
+ "addon-main.cjs",
37
+ "declarations",
38
+ "dist",
39
+ "README.md",
40
+ "CHANGELOG.md",
41
+ "LICENSE.md",
42
+ "NOTICE"
43
+ ],
44
+ "dependencies": {
45
+ "@embroider/addon-shim": "^1.10.3",
46
+ "decorator-transforms": "^2.4.0",
47
+ "@ember-lattice/formula": "1.1.0",
48
+ "@ember-lattice/sheet": "1.1.0",
49
+ "@sindresorhus/is": "^7.2.0"
50
+ },
51
+ "peerDependencies": {
52
+ "@glimmer/component": ">= 2.0.0",
53
+ "ember-source": ">= 6.12.0"
54
+ },
55
+ "devDependencies": {
56
+ "@babel/core": "^7.29.7",
57
+ "@babel/plugin-transform-typescript": "^7.29.7",
58
+ "@babel/runtime": "^7.29.7",
59
+ "@ember/library-tsconfig": "^3.0.0",
60
+ "@embroider/addon-dev": "^8.4.2",
61
+ "@glimmer/component": "^2.2.1",
62
+ "@glimmer/tracking": "^1.1.2",
63
+ "@glint/ember-tsc": "^1.14.2",
64
+ "@glint/template": "^1.9.0",
65
+ "@rollup/plugin-babel": "^7.1.0",
66
+ "babel-plugin-ember-template-compilation": "^4.0.1",
67
+ "ember-source": "~7.3.0",
68
+ "rollup": "^4.64.6",
69
+ "typescript": "~6.0.3"
70
+ },
71
+ "publishConfig": {
72
+ "access": "public"
73
+ },
74
+ "engines": {
75
+ "node": ">=22.12.0"
76
+ },
77
+ "ember": {
78
+ "edition": "octane"
79
+ },
80
+ "ember-addon": {
81
+ "version": 2,
82
+ "type": "addon",
83
+ "main": "addon-main.cjs"
84
+ },
85
+ "scripts": {
86
+ "build": "rm -rf declarations && rollup --config",
87
+ "start": "rm -rf declarations && rollup --config --watch",
88
+ "typecheck": "ember-tsc --noEmit"
89
+ }
6
90
  }