@classcad/client 0.0.0-stage → 3.0.0-beta.20261119100608

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.
Files changed (108) hide show
  1. package/README.md +20 -2
  2. package/bin/buerli-classcad.cjs +23 -0
  3. package/build/cjs/BuerliCadFacade.js +718 -0
  4. package/build/cjs/cclass/utils/assembly.js +687 -0
  5. package/build/cjs/cclass/utils/base.js +136 -0
  6. package/build/cjs/cclass/utils/index.js +99 -0
  7. package/build/cjs/cclass/utils/part.js +153 -0
  8. package/build/cjs/classcadEngine.js +33 -0
  9. package/build/cjs/createApi.js +71 -0
  10. package/build/cjs/createUnwrappedApi.js +43 -0
  11. package/build/cjs/facade.js +103 -0
  12. package/build/cjs/globals.js +157 -0
  13. package/build/cjs/index.js +102 -0
  14. package/build/cjs/io/AwvNodeClient.js +290 -0
  15. package/build/cjs/io/SocketIOClient.js +339 -0
  16. package/build/cjs/io/Transaction.js +134 -0
  17. package/build/cjs/io/WASMClient.js +433 -0
  18. package/build/cjs/io/WSClient.js +646 -0
  19. package/build/cjs/io/engineKey.js +202 -0
  20. package/build/cjs/re-export.js +35 -0
  21. package/build/cjs/session/host.js +479 -0
  22. package/build/cjs/session/identity.js +38 -0
  23. package/build/cjs/session/selection.js +283 -0
  24. package/build/cjs/session/share.js +229 -0
  25. package/build/cjs/session/types.js +23 -0
  26. package/build/cjs/test/SocketIOClient.spec.js +178 -0
  27. package/build/cjs/types/ComClient.js +10 -0
  28. package/build/cjs/utils/createRecursiveBufferGeometry.js +55 -0
  29. package/build/cjs/utils/createRecursiveScene.js +140 -0
  30. package/build/cjs/utils/getDifferentColoredMeshesFromEntity.js +24 -0
  31. package/build/cjs/utils/index.js +20 -0
  32. package/build/cjs/utils/polyline.js +65 -0
  33. package/build/cjs/utils/waitForSelect.js +29 -0
  34. package/build/esm/BuerliCadFacade.js +714 -0
  35. package/build/esm/cclass/utils/assembly.js +665 -0
  36. package/build/esm/cclass/utils/base.js +127 -0
  37. package/build/esm/cclass/utils/index.js +62 -0
  38. package/build/esm/cclass/utils/part.js +144 -0
  39. package/build/esm/classcadEngine.js +30 -0
  40. package/build/esm/createApi.js +66 -0
  41. package/build/esm/createUnwrappedApi.js +39 -0
  42. package/build/esm/facade.js +98 -0
  43. package/build/esm/globals.js +150 -0
  44. package/build/esm/index.js +80 -0
  45. package/build/esm/io/AwvNodeClient.js +286 -0
  46. package/build/esm/io/SocketIOClient.js +332 -0
  47. package/build/esm/io/Transaction.js +130 -0
  48. package/build/esm/io/WASMClient.js +429 -0
  49. package/build/esm/io/WSClient.js +642 -0
  50. package/build/esm/io/engineKey.js +196 -0
  51. package/build/esm/re-export.js +3 -0
  52. package/build/esm/session/host.js +474 -0
  53. package/build/esm/session/identity.js +34 -0
  54. package/build/esm/session/selection.js +277 -0
  55. package/build/esm/session/share.js +221 -0
  56. package/build/esm/session/types.js +20 -0
  57. package/build/esm/test/SocketIOClient.spec.js +178 -0
  58. package/build/esm/types/ComClient.js +7 -0
  59. package/build/esm/utils/createRecursiveBufferGeometry.js +51 -0
  60. package/build/esm/utils/createRecursiveScene.js +136 -0
  61. package/build/esm/utils/getDifferentColoredMeshesFromEntity.js +20 -0
  62. package/build/esm/utils/index.js +4 -0
  63. package/build/esm/utils/polyline.js +60 -0
  64. package/build/esm/utils/waitForSelect.js +23 -0
  65. package/build/types/BuerliCadFacade.d.ts +410 -0
  66. package/build/types/cclass/utils/assembly.d.ts +180 -0
  67. package/build/types/cclass/utils/base.d.ts +55 -0
  68. package/build/types/cclass/utils/index.d.ts +46 -0
  69. package/build/types/cclass/utils/part.d.ts +46 -0
  70. package/build/types/classcadEngine.d.ts +40 -0
  71. package/build/types/createApi.d.ts +65 -0
  72. package/build/types/createUnwrappedApi.d.ts +36 -0
  73. package/build/types/facade.d.ts +9 -0
  74. package/build/types/globals.d.ts +79 -0
  75. package/build/types/index.d.ts +82 -0
  76. package/build/types/io/AwvNodeClient.d.ts +182 -0
  77. package/build/types/io/SocketIOClient.d.ts +84 -0
  78. package/build/types/io/Transaction.d.ts +56 -0
  79. package/build/types/io/WASMClient.d.ts +239 -0
  80. package/build/types/io/WSClient.d.ts +242 -0
  81. package/build/types/io/engineKey.d.ts +137 -0
  82. package/build/types/re-export.d.ts +6 -0
  83. package/build/types/session/host.d.ts +108 -0
  84. package/build/types/session/identity.d.ts +46 -0
  85. package/build/types/session/selection.d.ts +164 -0
  86. package/build/types/session/share.d.ts +131 -0
  87. package/build/types/session/types.d.ts +113 -0
  88. package/build/types/test/SocketIOClient.spec.d.ts +0 -0
  89. package/build/types/types/ComClient.d.ts +307 -0
  90. package/build/types/utils/createRecursiveBufferGeometry.d.ts +8 -0
  91. package/build/types/utils/createRecursiveScene.d.ts +24 -0
  92. package/build/types/utils/getDifferentColoredMeshesFromEntity.d.ts +14 -0
  93. package/build/types/utils/index.d.ts +4 -0
  94. package/build/types/utils/polyline.d.ts +43 -0
  95. package/build/types/utils/waitForSelect.d.ts +4 -0
  96. package/doc/api/advanced/connection.md +488 -0
  97. package/doc/api/clients.md +2045 -0
  98. package/doc/api/engine-keys.md +230 -0
  99. package/doc/api/index.md +58 -0
  100. package/doc/api/modeling.md +682 -0
  101. package/doc/api/other.md +33 -0
  102. package/doc/api/session-sharing.md +706 -0
  103. package/package.json +60 -4
  104. package/test/classcadEngine.test.cjs +44 -0
  105. package/test/connect.test.cjs +81 -0
  106. package/test/engineKey.test.cjs +80 -0
  107. package/test/onClient.test.cjs +82 -0
  108. package/typedoc.json +8 -0
@@ -0,0 +1,642 @@
1
+ import { getDrawing } from '@classcad/sdkjs';
2
+ import { decode } from 'base64-arraybuffer';
3
+ import { inflate } from 'pako';
4
+ import { v4 as uuidv4 } from 'uuid';
5
+ import { BuerliCadFacade } from '../BuerliCadFacade';
6
+ import { MessageLevel } from '../re-export';
7
+ import { AwvNodeClient } from './AwvNodeClient';
8
+ import { CLIENT_CHANNEL } from '../session/identity';
9
+ /**
10
+ * How long graphic frames are collected before they are added to the drawing in one batch. Short enough to
11
+ * keep an interactive change immediate, long enough to merge the thousands of frames of a large model.
12
+ */
13
+ const GRAPHIC_BATCH_MS = 30;
14
+ /**
15
+ * Startup emission config of this connection, sent ONCE with SetEmissionConfig when
16
+ * the socket opens (the engine keeps the config per connection; nothing is
17
+ * attached to individual requests any more). Change it at any time with
18
+ * `setEmissionConfig()` - e.g. suppress graphics around a script and restore
19
+ * afterwards (see BuerliCadFacade.utils.withEmissionConfig).
20
+ *
21
+ * The server's WS default is full CONTENT in the neutral bundled form
22
+ * (snapshot + JSON graphic + messages on the Result frame). This set opts
23
+ * the interactive client INTO streaming - structure patches, immediate push,
24
+ * binary/compressed/multipackage graphics - which is what a live UI wants.
25
+ */
26
+ const DEFAULT_COMMAND_CONFIG = {
27
+ sendStructure: true,
28
+ sendStructure_Patch: true,
29
+ sendStructure_Immediately: true,
30
+ sendGraphic_Kernel: true,
31
+ sendGraphic_StructureObj: true,
32
+ sendGraphic_Sketch: true,
33
+ sendGraphic_Invisible: true,
34
+ sendGraphic_Compressed: true,
35
+ sendGraphic_Immediately: true,
36
+ sendGraphic_ImmediatelyBinary: true,
37
+ sendGraphic_Multipackage: true,
38
+ sendMessages: true,
39
+ sendMessages_Immediately: true,
40
+ };
41
+ /*
42
+ * Protocol (verified against ClassCAD 21.0.1-dev on localhost:9094):
43
+ * - Outgoing: raw JSON `{command, commandVersion, transactionID, ...}`
44
+ * - Incoming text: JSON frames with `{command, _from_, _transactionID_, ...}`
45
+ * May be multi-frame per request (Message, Structure, Patch frames before final Result)
46
+ * - Incoming binary: compressed SCG graphic packages (deflate-raw)
47
+ * - No Socket.IO envelopes, no BeginFrame/EndFrame wrapping
48
+ */
49
+ /**
50
+ * Connects the SDK to a native ClassCAD engine through the engine's own WebSocket server (`classcad-cli worker`).
51
+ *
52
+ * The server owns the session. Without an invite it creates one for this connection, which lasts as long as the
53
+ * connection; others join it with an invite from {@link WSClient.createInvite}, passed as `config.invite`. A URL
54
+ * without a scheme (`/session`) is on the server the page came from.
55
+ *
56
+ * Connection flow:
57
+ * 1. WebSocket handshake (server auto-creates session)
58
+ * 2. SetEmissionConfig command stores this connection's emission flags on the server
59
+ * 3. `fetchTree()` retrieves initial object tree
60
+ * 4. Connection promise resolves
61
+ *
62
+ * Undo and redo: `undo()` / `redo()` send the engine's `Undo` / `Redo` commands, and the `UndoStack` frames the
63
+ * server sends after every undoable command and every undo / redo fill `cad.states` (see {@link WSClient.undo}).
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { init, WSClient } from '@classcad/client'
68
+ *
69
+ * // The native engine's own WebSocket server (classcad-cli worker)
70
+ * init(drawingId => new WSClient('ws://localhost:9094', drawingId))
71
+ * ```
72
+ * @example
73
+ * ```ts
74
+ * import { BuerliCadFacade, buildShareUrl, init, WSClient } from '@classcad/client'
75
+ * import type { SessionPeer } from '@classcad/client'
76
+ *
77
+ * // The host: a session of its own on the engine, and an invite to it
78
+ * let host!: WSClient
79
+ * init(drawingId => (host = new WSClient('ws://localhost:9094', drawingId, { identity: { app: 'my-app' } })))
80
+ * await new BuerliCadFacade().connect()
81
+ *
82
+ * host.on('peers_changed', (_client, peers: SessionPeer[]) => {
83
+ * console.log(peers.map(peer => `${peer.inviteName}: ${peer.role}`))
84
+ * })
85
+ * const invite = await host.createInvite('view', 'review')
86
+ * console.log('Join at', buildShareUrl(invite))
87
+ * // Later: the token stops working, its guests are cut off
88
+ * await host.revokeInvite(invite.invite)
89
+ * ```
90
+ * Its events (`connected`, `conn_error`, …) and the members all clients share are on {@link AwvNodeClient}.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * import { BuerliCadFacade, init, WSClient } from '@classcad/client'
95
+ * import type { PresenceMessage } from '@classcad/client'
96
+ *
97
+ * // A guest: joins the host's session with its token
98
+ * let guest!: WSClient
99
+ * init(drawingId => (guest = new WSClient('ws://localhost:9094', drawingId, { invite: token })))
100
+ * await new BuerliCadFacade().connect()
101
+ * // With a 'view' invite the app keeps the guest from changing the model
102
+ * setReadOnly(guest.role === 'view')
103
+ *
104
+ * // The cameras follow each other
105
+ * guest.on('presence', (_client, msg: PresenceMessage) => {
106
+ * if (msg.channel === 'view') moveCamera(msg.data)
107
+ * })
108
+ * guest.sendPresence('view', myCamera())
109
+ * ```
110
+ * @category Clients
111
+ */
112
+ export class WSClient extends AwvNodeClient {
113
+ /** Snapshot of the guests currently sharing this session (main connection only). */
114
+ get peers() {
115
+ return Array.from(this._peers.values());
116
+ }
117
+ /** The address the client was given; one without a scheme (`/session`) is on the server the page came from. */
118
+ get url() {
119
+ return this._url;
120
+ }
121
+ /**
122
+ * @param _url - The server's WebSocket address, e.g. `ws://localhost:9094`, or a path on the page's own server.
123
+ * @param drawingId - The drawing the client serves (the factory given to {@link init} is called with it).
124
+ * @param config - Sub-path, invite, identity and emission config ({@link WSClientConfig}).
125
+ */
126
+ constructor(_url, drawingId, config) {
127
+ super();
128
+ this._url = _url;
129
+ this._pending = new Map();
130
+ this._connected = false;
131
+ /**
132
+ * Graphic packages waiting to be added to the drawing. The server sends the graphic of a model as many small
133
+ * frames (thousands for a large assembly); adding each on its own updated the store once per frame. They are
134
+ * collected for a moment and added in one batch (@see flushGraphic).
135
+ */
136
+ this._graphicQueue = [];
137
+ /** The server owns the session: invites are honoured by joining with `?invite=` on the server URL. */
138
+ this.shareKind = 'invite';
139
+ // `role` and `inviteName` (from AwvNodeClient) are set from the server's
140
+ // `SessionJoined` frame when connecting with an invite. Enforcement is
141
+ // client-side for now — apps should suppress mutating commands for 'view'.
142
+ /** Guests currently sharing this session (main connection only), keyed by peerId. */
143
+ this._peers = new Map();
144
+ /** True while a full-tree resync (after a failed structure patch) is in flight. */
145
+ this._resyncing = false;
146
+ this.setDrawingId(drawingId);
147
+ this._config = config !== null && config !== void 0 ? config : {};
148
+ }
149
+ /**
150
+ * Opens the WebSocket, sets the connection's emission config, loads the structure tree and publishes `identity`.
151
+ * Rejects when the socket fails before that, or when the engine predates SetEmissionConfig.
152
+ */
153
+ connect() {
154
+ return new Promise((resolve, reject) => {
155
+ try {
156
+ const wsUrl = this.buildUrl();
157
+ this._ws = new WebSocket(wsUrl);
158
+ this._ws.binaryType = 'arraybuffer';
159
+ this._ws.onopen = () => {
160
+ this._connected = true;
161
+ // Store this connection's emission config on the server (per-connection
162
+ // config model: the engine keeps it for every following command), then
163
+ // fetch the initial object tree - the connection is not valid until
164
+ // both completed. SetEmissionConfig is a tracked request, so its reply settles
165
+ // like any other Result.
166
+ this.setEmissionConfig(Object.assign(Object.assign({}, DEFAULT_COMMAND_CONFIG), this._config.commandConfig))
167
+ .then(() => BuerliCadFacade.utils.fetchTree(this._drawingId))
168
+ .then(() => {
169
+ if (this._config.identity)
170
+ this.sendPresence(CLIENT_CHANNEL, this._config.identity);
171
+ this.emit('connected', this, true);
172
+ this.syncState();
173
+ resolve(this);
174
+ })
175
+ .catch(e => {
176
+ console.error(e);
177
+ reject(e);
178
+ });
179
+ };
180
+ this._ws.onmessage = (ev) => {
181
+ if (ev.data instanceof ArrayBuffer) {
182
+ this.handleBinaryFrame(new Uint8Array(ev.data));
183
+ }
184
+ else if (typeof ev.data === 'string') {
185
+ this.handleTextFrame(ev.data);
186
+ }
187
+ };
188
+ this._ws.onerror = (ev) => {
189
+ this.syncState();
190
+ this.emit('conn_error', this, ev);
191
+ if (!this._connected) {
192
+ reject(ev);
193
+ }
194
+ };
195
+ this._ws.onclose = (ev) => {
196
+ const wasConnected = this._connected;
197
+ this._connected = false;
198
+ // Codes 1000 (normal) and 1005 (no status) indicate deliberate closure
199
+ const deliberate = ev.code === 1000 || ev.code === 1005;
200
+ if (!deliberate && wasConnected) {
201
+ this.emit('conn_error', this, ev.reason || `WebSocket closed with code ${ev.code}`);
202
+ }
203
+ // Graphic that arrived before the close is added, as it was before frames were batched
204
+ this.flushGraphic();
205
+ // Reject all pending requests
206
+ for (const [, pending] of this._pending) {
207
+ pending.reject(new Error('WebSocket closed'));
208
+ }
209
+ this._pending.clear();
210
+ // Presence is meaningless once disconnected.
211
+ if (this._peers.size > 0) {
212
+ this._peers.clear();
213
+ this.emit('peers_changed', this, this.peers);
214
+ }
215
+ this.clearIdentities();
216
+ this.syncState();
217
+ };
218
+ }
219
+ catch (error) {
220
+ reject(error);
221
+ }
222
+ });
223
+ }
224
+ /** Closes the WebSocket; the server ends the session if this connection made it. No `conn_error` is emitted. */
225
+ disconnect() {
226
+ return new Promise((resolve, reject) => {
227
+ try {
228
+ if (this._ws) {
229
+ this._ws.onclose = null;
230
+ this._ws.close();
231
+ this._ws = undefined;
232
+ }
233
+ this._connected = false;
234
+ this._pending.clear();
235
+ this.flushGraphic();
236
+ this.syncState();
237
+ resolve(this);
238
+ }
239
+ catch (error) {
240
+ reject(error);
241
+ }
242
+ });
243
+ }
244
+ /**
245
+ * Sends `command` to the server and resolves to its reply, once the server's `Result` frame arrives. Structure,
246
+ * graphic and messages that come before it go into the drawing on the way. Rejects with the reply when it carries
247
+ * an error, and when the socket closes first.
248
+ *
249
+ * @param _name - Not used by this client.
250
+ * @param command - The request.
251
+ */
252
+ requestByName(_name, command) {
253
+ return new Promise((resolve, reject) => {
254
+ const transactionID = uuidv4();
255
+ try {
256
+ this._pending.set(transactionID, { resolve, reject, messages: [], maxLevel: undefined });
257
+ // Send the command as raw JSON — the Drogon server routes via CommandFactory
258
+ // based on the `command` field. commandVersion: 'v1' selects CommandProcessorJsonV1.
259
+ // Emission flags are NOT attached: the server keeps them per connection
260
+ // (set on connect and via setEmissionConfig); a `config` field only travels with
261
+ // the SetEmissionConfig command itself.
262
+ this.sendCommand(Object.assign(Object.assign({}, command), { commandVersion: 'v1', transactionID }));
263
+ }
264
+ catch (error) {
265
+ this._pending.delete(transactionID);
266
+ reject(error);
267
+ }
268
+ });
269
+ }
270
+ request(command) {
271
+ return this.requestByName('send', command);
272
+ }
273
+ /**
274
+ * Mints an invite token for this connection's session (multi-client invite
275
+ * model). The returned token can be handed to other clients, which join via
276
+ * `new WSClient(url, id, { invite })`. Server-side this is a controller-level
277
+ * meta command; it is rejected when this connection itself joined via invite.
278
+ *
279
+ * `name` is optional and purely for display (e.g. "workgroup"); it has no
280
+ * effect on behavior. Multiple tokens can be minted (e.g. a named group token
281
+ * plus an unnamed one-off token). The examples of {@link WSClient} show the host and a guest.
282
+ *
283
+ * @param role - What guests with the invite may do: `'edit'` (default) or `'view'`.
284
+ * @param name - A name to show for the invite.
285
+ */
286
+ createInvite(role = 'edit', name = '') {
287
+ return this.requestByName('createInvite', { command: 'CreateInvite', role, name }).then(sr => {
288
+ const r = sr.result;
289
+ const invite = { invite: r.invite, role: r.role, name: r.name, kind: 'invite' };
290
+ this.trackInvite(invite);
291
+ return invite;
292
+ });
293
+ }
294
+ /**
295
+ * Revokes a previously minted invite token. Any guests currently connected
296
+ * with that token are immediately disconnected, and the token can no longer
297
+ * be used to join. Owner-only; rejected on connections that joined via invite.
298
+ *
299
+ * @param invite - The invite token.
300
+ * @returns The token, whether it was revoked, and how many guests were cut off.
301
+ */
302
+ revokeInvite(invite) {
303
+ return this.requestByName('revokeInvite', { command: 'RevokeInvite', invite }).then(sr => {
304
+ this.untrackInvite(invite);
305
+ return sr.result;
306
+ });
307
+ }
308
+ /**
309
+ * Fire-and-forget ephemeral presence broadcast to the session's siblings
310
+ * (e.g. this client's camera viewpoint on the 'view' channel). Handled by a
311
+ * server fast-path that bypasses the command queue entirely; the server
312
+ * stamps the sender's peerId and fans the frame out. Siblings receive it via
313
+ * the `presence` event; late joiners get the last frame per channel as a
314
+ * snapshot. NOTE: the server matches on the exact serialized prefix
315
+ * `{"command":"Presence"`, so `command` must stay the first key here.
316
+ *
317
+ * The guest example of {@link WSClient} shares the camera this way.
318
+ *
319
+ * @param channel - The channel, e.g. `'view'` for a camera viewpoint.
320
+ * @param data - The payload, sent as it is. The server drops a frame larger than 8 KB.
321
+ */
322
+ sendPresence(channel, data) {
323
+ this.sendCommand({ command: 'Presence', channel, data });
324
+ }
325
+ /**
326
+ * Goes back to the state before the current one of the session's undo history, or to
327
+ * `options.state`. The server records a state after every command sent with
328
+ * `options.undoable` (api-js marks the modelling calls) and answers with the frames of the
329
+ * change and an UndoStack frame, which updates `cad.states` of every client in the session.
330
+ * The result is the history afterwards: `{ stack, current }`.
331
+ */
332
+ undo(options) {
333
+ return this.requestByName('undo', Object.assign({ command: 'Undo' }, ((options === null || options === void 0 ? void 0 : options.state) ? { state: options.state } : {})));
334
+ }
335
+ /** Goes forward to the state after the current one, or to `options.state` (see undo). */
336
+ redo(options) {
337
+ return this.requestByName('redo', Object.assign({ command: 'Redo' }, ((options === null || options === void 0 ? void 0 : options.state) ? { state: options.state } : {})));
338
+ }
339
+ // ---------------------------------------------------------------------------
340
+ // URL construction
341
+ // ---------------------------------------------------------------------------
342
+ buildUrl() {
343
+ var _a;
344
+ const path = (_a = this._config.path) !== null && _a !== void 0 ? _a : '/';
345
+ // A URL without a scheme ('/session') is on the server the page came from:
346
+ // an app served by the engine's host needs no address built into it.
347
+ const absolute = this._url.startsWith('/') && typeof window !== 'undefined'
348
+ ? `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}${this._url}`
349
+ : this._url;
350
+ const base = absolute.replace(/\/+$/, '');
351
+ const normalizedPath = path.startsWith('/') ? path : `/${path}`;
352
+ let url = `${base}${normalizedPath}`;
353
+ // Query params are the only channel available to browser WebSocket
354
+ // clients (no custom headers on the upgrade). Without an invite the
355
+ // server creates a fresh main session for this connection.
356
+ if (this._config.invite) {
357
+ const separator = url.includes('?') ? '&' : '?';
358
+ url += `${separator}invite=${encodeURIComponent(this._config.invite)}`;
359
+ }
360
+ return url;
361
+ }
362
+ // ---------------------------------------------------------------------------
363
+ // Outgoing
364
+ // ---------------------------------------------------------------------------
365
+ sendCommand(msg) {
366
+ if (this._ws && this._ws.readyState === WebSocket.OPEN) {
367
+ this._ws.send(JSON.stringify(msg));
368
+ }
369
+ }
370
+ // ---------------------------------------------------------------------------
371
+ // Incoming — binary frames
372
+ //
373
+ // With sendGraphic_ImmediatelyBinary the Drogon server raw-deflates the whole
374
+ // text envelope (`{command: "Graphic", _from_, _transactionID_, graphic, …}`)
375
+ // into one binary frame. Inflate, parse, then run it through the same handler
376
+ // the text path uses — which knows how to deal with compressed inner fields.
377
+ // ---------------------------------------------------------------------------
378
+ handleBinaryFrame(data) {
379
+ try {
380
+ const inflated = inflate(data, { raw: true, to: 'string' });
381
+ const frame = JSON.parse(inflated);
382
+ if (Array.isArray(frame)) {
383
+ for (const f of frame)
384
+ this.handleFrame(f);
385
+ }
386
+ else {
387
+ this.handleFrame(frame);
388
+ }
389
+ }
390
+ catch (e) {
391
+ console.warn('[WSClient] failed to decode binary frame', e);
392
+ }
393
+ }
394
+ // ---------------------------------------------------------------------------
395
+ // Incoming — text frames
396
+ //
397
+ // The Drogon server (CommandProcessorJsonV1) sends responses as JSON text
398
+ // frames. With *_Immediately flags, a single request may produce multiple
399
+ // frames before the final `command: "Result"` frame:
400
+ //
401
+ // { command: "Message", _from_, _transactionID_, messages, maxLevel }
402
+ // { command: "Structure", _from_, _transactionID_, structure }
403
+ // { command: "Patch", _from_, _transactionID_, structurePatch }
404
+ // { command: "Graphic", _from_, _transactionID_, graphic }
405
+ // { command: "Result", _from_, _transactionID_, result, ... } ← final
406
+ //
407
+ // All frames share the same `_transactionID_`.
408
+ // ---------------------------------------------------------------------------
409
+ handleTextFrame(raw) {
410
+ let data;
411
+ try {
412
+ data = JSON.parse(raw);
413
+ }
414
+ catch (_a) {
415
+ return;
416
+ }
417
+ if (Array.isArray(data)) {
418
+ for (const item of data) {
419
+ this.handleFrame(item);
420
+ }
421
+ }
422
+ else {
423
+ this.handleFrame(data);
424
+ }
425
+ }
426
+ /**
427
+ * When the server is configured with `sendStructure_Compressed` /
428
+ * `sendGraphic_Compressed`, the corresponding payload field arrives as a
429
+ * base64 string of raw-deflated JSON instead of an inline object. Decode it
430
+ * back to the structured form before handing it to the drawing APIs.
431
+ */
432
+ decodeMaybeCompressed(value) {
433
+ if (value === undefined || value === null)
434
+ return undefined;
435
+ if (typeof value !== 'string')
436
+ return value;
437
+ try {
438
+ const bytes = new Uint8Array(decode(value));
439
+ const inflated = inflate(bytes, { raw: true, to: 'string' });
440
+ return JSON.parse(inflated);
441
+ }
442
+ catch (e) {
443
+ console.warn('[WSClient] failed to inflate compressed payload', e);
444
+ return undefined;
445
+ }
446
+ }
447
+ /** Adds the queued graphic packages to the drawing in one call. */
448
+ flushGraphic() {
449
+ var _a;
450
+ if (this._graphicFlushTimer !== undefined) {
451
+ clearTimeout(this._graphicFlushTimer);
452
+ this._graphicFlushTimer = undefined;
453
+ }
454
+ if (this._graphicQueue.length === 0)
455
+ return;
456
+ const packages = this._graphicQueue;
457
+ this._graphicQueue = [];
458
+ (_a = getDrawing(this._drawingId)) === null || _a === void 0 ? void 0 : _a.api.graphic.addPackages(packages);
459
+ }
460
+ handleFrame(data) {
461
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
462
+ // Sent by the server as the first frame after a successful invite join.
463
+ // Carries the role attached to the invite; the sessionId is never revealed.
464
+ if (data.command === 'SessionJoined') {
465
+ this.role = data.role === 'view' ? 'view' : 'edit';
466
+ this.inviteName = (_a = data.inviteName) !== null && _a !== void 0 ? _a : '';
467
+ this.emit('session_joined', this, this.role, this.inviteName);
468
+ return;
469
+ }
470
+ // Ephemeral presence from a session sibling (camera viewpoints etc.), or
471
+ // the 'leave' channel when a peer disconnects. Apps subscribe via
472
+ // client.on('presence', (client, msg: PresenceMessage) => ...).
473
+ if (data.command === 'Presence') {
474
+ const msg = { channel: (_b = data.channel) !== null && _b !== void 0 ? _b : '', peerId: (_c = data.peerId) !== null && _c !== void 0 ? _c : '', data: (_d = data.data) !== null && _d !== void 0 ? _d : {} };
475
+ this.noteIdentity(msg);
476
+ this.emit('presence', this, msg);
477
+ return;
478
+ }
479
+ // Presence events, delivered only to the main (owner) connection: a guest
480
+ // joined or left the shared session. A GUI can use these to show who is
481
+ // connected (e.g. dots per invite token).
482
+ if (data.command === 'PeerJoined') {
483
+ const peer = {
484
+ peerId: (_e = data.peerId) !== null && _e !== void 0 ? _e : '',
485
+ invite: (_f = data.invite) !== null && _f !== void 0 ? _f : '',
486
+ inviteName: (_g = data.inviteName) !== null && _g !== void 0 ? _g : '',
487
+ role: data.role === 'view' ? 'view' : 'edit',
488
+ };
489
+ this._peers.set(peer.peerId, peer);
490
+ this.emit('peer_joined', this, peer);
491
+ this.emit('peers_changed', this, this.peers);
492
+ return;
493
+ }
494
+ // The session's undo history changed (an undoable command, an undo / redo, by this client or
495
+ // a sibling), or this guest just joined: take it over into cad.states.
496
+ if (data.command === 'UndoStack') {
497
+ this.applyUndoStack(data);
498
+ return;
499
+ }
500
+ if (data.command === 'PeerLeft') {
501
+ const peerId = (_h = data.peerId) !== null && _h !== void 0 ? _h : '';
502
+ const peer = this._peers.get(peerId);
503
+ this._peers.delete(peerId);
504
+ this.emit('peer_left', this, peer !== null && peer !== void 0 ? peer : { peerId, invite: (_j = data.invite) !== null && _j !== void 0 ? _j : '', inviteName: (_k = data.inviteName) !== null && _k !== void 0 ? _k : '', role: 'edit' });
505
+ this.emit('peers_changed', this, this.peers);
506
+ return;
507
+ }
508
+ const transactionID = data._transactionID_;
509
+ const pending = transactionID ? this._pending.get(transactionID) : undefined;
510
+ const drawing = getDrawing(this._drawingId);
511
+ // Queued graphic goes into the drawing before a structure change or a settled request, so both keep the
512
+ // order in which the server sent them.
513
+ if (data.structure || data.structurePatch || data.command === 'Result') {
514
+ this.flushGraphic();
515
+ }
516
+ // --- Apply side-effects immediately regardless of frame type ---
517
+ // Full structure snapshot (object inline, or base64 raw-deflate JSON when sendStructure_Compressed)
518
+ if (data.structure) {
519
+ const structure = this.decodeMaybeCompressed(data.structure);
520
+ if (structure)
521
+ drawing.api.structure.set(structure);
522
+ }
523
+ // Structure patches: array of JSON Patch ops, or base64 raw-deflate JSON when sendStructure_Compressed
524
+ if (data.structurePatch) {
525
+ const patches = this.decodeMaybeCompressed(data.structurePatch);
526
+ if (patches && !drawing.api.structure.applyPatches(patches)) {
527
+ // Patches are relative to a shared per-session baseline; a failed
528
+ // block means this client's tree has diverged and would stay wrong
529
+ // forever. Recover by re-fetching the full tree once.
530
+ this.resyncStructure();
531
+ }
532
+ }
533
+ // Graphic package: object inline, or base64 raw-deflate JSON when sendGraphic_Compressed. Collected and
534
+ // added in batches; a Result frame adds everything at once, so the request settles with its graphic.
535
+ if (data.graphic) {
536
+ const pkg = this.decodeMaybeCompressed(data.graphic);
537
+ if (pkg) {
538
+ this._graphicQueue.push(pkg);
539
+ if (data.command === 'Result') {
540
+ this.flushGraphic();
541
+ }
542
+ else if (this._graphicFlushTimer === undefined) {
543
+ this._graphicFlushTimer = setTimeout(() => this.flushGraphic(), GRAPHIC_BATCH_MS);
544
+ }
545
+ }
546
+ }
547
+ // Accumulate messages from intermediate Message frames
548
+ if (pending && data.messages) {
549
+ for (const msg of data.messages) {
550
+ pending.messages.push(msg);
551
+ if (pending.maxLevel === undefined || msg.level > pending.maxLevel) {
552
+ pending.maxLevel = msg.level;
553
+ }
554
+ }
555
+ }
556
+ // Inflate stream data if present (base64-encoded deflate-raw)
557
+ let streamData;
558
+ if (data.streamData) {
559
+ streamData = {};
560
+ for (const [key, value] of Object.entries(data.streamData)) {
561
+ try {
562
+ const decoded = decode(value);
563
+ streamData[key] = inflate(new Uint8Array(decoded), { raw: true });
564
+ }
565
+ catch (_o) {
566
+ streamData[key] = value;
567
+ }
568
+ }
569
+ }
570
+ // --- Settle the pending request on the final Result frame ---
571
+ if (data.command === 'Result' && pending && transactionID) {
572
+ this._pending.delete(transactionID);
573
+ let jobResult = data.result;
574
+ if (typeof ((_l = data.result) === null || _l === void 0 ? void 0 : _l.result) !== 'undefined') {
575
+ jobResult = data.result.result;
576
+ }
577
+ // Merge any messages from the Result frame with previously accumulated ones
578
+ const resultMessages = (_m = data.messages) !== null && _m !== void 0 ? _m : [];
579
+ const allMessages = [...pending.messages];
580
+ for (const msg of resultMessages) {
581
+ // Avoid duplicates if messages were already sent via intermediate frames
582
+ if (!allMessages.some(m => m.message === msg.message && m.level === msg.level)) {
583
+ allMessages.push(msg);
584
+ }
585
+ }
586
+ // The Drogon server sends INFO-level trace messages (COMMANDCALL, RETURN)
587
+ // for every command. These are not present in SocketIO/WASM server responses
588
+ // and must be excluded so that consumer code checking messages.length === 0
589
+ // for successful commands works consistently across all transports.
590
+ const messages = allMessages.filter(m => m.level > MessageLevel.info);
591
+ let maxLevel;
592
+ for (const msg of messages) {
593
+ if (maxLevel === undefined || msg.level > maxLevel) {
594
+ maxLevel = msg.level;
595
+ }
596
+ }
597
+ const sr = {
598
+ result: jobResult,
599
+ maxLevel,
600
+ messages,
601
+ streamData,
602
+ };
603
+ const hadError = typeof sr.maxLevel !== 'undefined' && sr.maxLevel >= MessageLevel.error;
604
+ if (hadError) {
605
+ pending.reject(sr);
606
+ }
607
+ else {
608
+ pending.resolve(sr);
609
+ }
610
+ }
611
+ }
612
+ /**
613
+ * Recovers from a structure patch that failed to apply: fetches the full
614
+ * tree from the server. The GetTree result carries the complete structure
615
+ * and graphic, so the drawing heals entirely — and since the server
616
+ * broadcasts result frames to all session siblings, any sibling that
617
+ * diverged the same way heals along with it. Guarded so a burst of failing
618
+ * patches triggers only one round trip.
619
+ */
620
+ resyncStructure() {
621
+ if (this._resyncing)
622
+ return;
623
+ this._resyncing = true;
624
+ console.warn('[WSClient] structure patch failed to apply — resyncing the full tree');
625
+ BuerliCadFacade.utils
626
+ .fetchTree(this._drawingId)
627
+ .catch(e => console.error('[WSClient] structure resync failed', e))
628
+ .finally(() => {
629
+ this._resyncing = false;
630
+ });
631
+ }
632
+ // ---------------------------------------------------------------------------
633
+ // State
634
+ // ---------------------------------------------------------------------------
635
+ syncState() {
636
+ var _a, _b, _c, _d, _e;
637
+ const dr = getDrawing(this._drawingId);
638
+ const isOpen = ((_a = this._ws) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN;
639
+ (_c = (_b = dr === null || dr === void 0 ? void 0 : dr.api) === null || _b === void 0 ? void 0 : _b.cad) === null || _c === void 0 ? void 0 : _c.setActive(isOpen);
640
+ (_e = (_d = dr === null || dr === void 0 ? void 0 : dr.api) === null || _d === void 0 ? void 0 : _d.cad) === null || _e === void 0 ? void 0 : _e.setConnected(isOpen);
641
+ }
642
+ }