@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,339 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SocketIOClient = exports.SocketIOEvent = void 0;
7
+ const sdkjs_1 = require("@classcad/sdkjs");
8
+ const socket_io_client_1 = __importDefault(require("socket.io-client"));
9
+ const BuerliCadFacade_1 = require("../BuerliCadFacade");
10
+ const re_export_1 = require("../re-export");
11
+ const AwvNodeClient_1 = require("./AwvNodeClient");
12
+ const Transaction_1 = require("./Transaction");
13
+ const noop = () => { };
14
+ /**
15
+ * The Socket.IO events of the ClassCAD server's protocol.
16
+ *
17
+ * @internal
18
+ */
19
+ var SocketIOEvent;
20
+ (function (SocketIOEvent) {
21
+ SocketIOEvent["CONNECT"] = "connect";
22
+ SocketIOEvent["INIT"] = "init";
23
+ SocketIOEvent["PERMISSION"] = "permission";
24
+ SocketIOEvent["CONNECT_ERROR"] = "connect_error";
25
+ SocketIOEvent["CONNECT_TIMEOUT"] = "connect_timeout";
26
+ SocketIOEvent["SEND"] = "send";
27
+ SocketIOEvent["BINARY"] = "binary";
28
+ SocketIOEvent["JSON"] = "json";
29
+ SocketIOEvent["UNDO"] = "undo";
30
+ SocketIOEvent["REDO"] = "redo";
31
+ })(SocketIOEvent || (exports.SocketIOEvent = SocketIOEvent = {}));
32
+ /**
33
+ * Connects the SDK to a ClassCAD server (`classcad-socketio`) over Socket.IO.
34
+ *
35
+ * The server runs the engine and keeps the drawing's undo history, so `undo`, `redo` and `undoable` requests work
36
+ * with this client. It cannot share its session (`shareKind` is null). When the connection drops and comes back, the
37
+ * client reconnects the drawing, recalculates it and emits `reconnect`.
38
+ *
39
+ * Its events (`connected`, `conn_error`, …) and the members all clients share are on {@link AwvNodeClient}.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * import { init, SocketIOClient } from '@classcad/client'
44
+ *
45
+ * // The ClassCAD server (classcad-socketio); a connection that drops is picked up again
46
+ * init(drawingId => {
47
+ * const client = new SocketIOClient('ws://localhost:9091', drawingId)
48
+ * client.on('conn_error', () => notify('The connection to ClassCAD is lost'))
49
+ * client.on('reconnect', () => notify('Connected again; the model was recalculated'))
50
+ * return client
51
+ * })
52
+ * ```
53
+ * @category Clients
54
+ */
55
+ class SocketIOClient extends AwvNodeClient_1.AwvNodeClient {
56
+ /**
57
+ * @param url - The server's address, e.g. `ws://localhost:9091`.
58
+ * @param drawingId - The drawing the client serves (the factory given to {@link init} is called with it).
59
+ */
60
+ constructor(url, drawingId) {
61
+ super();
62
+ this.url = url;
63
+ this._transactions = new Map();
64
+ this.setDrawingId(drawingId);
65
+ }
66
+ /**
67
+ * Opens the connection, registers the drawing with the server and loads its structure tree. Rejects on a
68
+ * connection error or timeout.
69
+ */
70
+ connect() {
71
+ return new Promise(async (resolve, reject) => {
72
+ try {
73
+ this._socket = (0, socket_io_client_1.default)(this.url, { transports: ['websocket', 'polling'] });
74
+ this._socket.once(SocketIOEvent.CONNECT, () => {
75
+ var _a;
76
+ (_a = this._socket) === null || _a === void 0 ? void 0 : _a.emit(SocketIOEvent.INIT, { id: this._drawingId });
77
+ });
78
+ this._socket.once(SocketIOEvent.PERMISSION, (data) => {
79
+ this._version = data.version;
80
+ // Connection is not valid until fetchTree is executed
81
+ // fetchTree has to be called right after the connection has been established
82
+ BuerliCadFacade_1.BuerliCadFacade.utils
83
+ .fetchTree(this._drawingId)
84
+ .then(() => {
85
+ this.emit('connected', this, true);
86
+ this.syncState();
87
+ resolve(this);
88
+ })
89
+ .catch(e => console.error(e));
90
+ });
91
+ this._socket.on('disconnect', (reason) => {
92
+ // https://socket.io/docs/v4/client-api/#event-disconnect
93
+ // This should prevent deliberate disconnects from triggering the reconnect logic
94
+ if (
95
+ // The server did not send a PING within the pingInterval + pingTimeout range
96
+ reason === 'ping timeout' ||
97
+ // The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
98
+ reason === 'transport close' ||
99
+ // The connection has encountered an error (example: the server was killed during a HTTP long-polling cycle)
100
+ reason === 'transport error') {
101
+ this.emit('conn_error', this, reason);
102
+ }
103
+ this.syncState();
104
+ });
105
+ this._socket.io.on('reconnect', async () => {
106
+ // https://socket.io/docs/v4/client-socket-instance/#events
107
+ await BuerliCadFacade_1.BuerliCadFacade.utils.reconnect(this._drawingId);
108
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.cad.clearPending();
109
+ this.emit('reconnect', this);
110
+ });
111
+ this._socket.io.on('error', (reason) => {
112
+ // Baseline websocket errors
113
+ this.syncState();
114
+ this.emit('conn_error', this, reason);
115
+ reject(reason);
116
+ });
117
+ this._socket.on(SocketIOEvent.CONNECT_ERROR, (reason) => {
118
+ this.syncState();
119
+ this.emit('conn_error', this, reason);
120
+ reject(reason);
121
+ });
122
+ this._socket.on(SocketIOEvent.CONNECT_TIMEOUT, (reason) => {
123
+ this.syncState();
124
+ this.emit('conn_timeout', this, reason);
125
+ reject(reason);
126
+ });
127
+ let current;
128
+ this._socket.on(SocketIOEvent.BINARY, (data, fn) => {
129
+ if (!this._version) {
130
+ this.ack();
131
+ } // Backward compatible ack
132
+ if (current) {
133
+ current.handleData(new Uint8Array(data));
134
+ }
135
+ if (fn) {
136
+ fn('ack');
137
+ } // Newer awv3-node 8.x.x ack
138
+ });
139
+ this._socket.on(SocketIOEvent.JSON, (data, fn) => {
140
+ if (!this._version) {
141
+ this.ack();
142
+ } // Backward compatible ack
143
+ if (data.from === 'BeginFrame') {
144
+ current = this._transactions.get(data.transactionID);
145
+ }
146
+ if (current) {
147
+ current.handleData(data);
148
+ }
149
+ if (current && data.from === 'EndFrame' && data.transactionID === current.transactionID) {
150
+ this._transactions.delete(current.transactionID);
151
+ current = undefined;
152
+ }
153
+ if (fn) {
154
+ fn('ack');
155
+ } // Newer awv3-node 8.x.x ack
156
+ });
157
+ this._socket.on(SocketIOEvent.UNDO, (args) => {
158
+ // TODO: Remove conditional branch if (args.stack !== undefined), if we're sure no old
159
+ // classcad-node packages are used anymore. This conditional branch is only used to avoid
160
+ // that captionMap will be overfilled and never deleted. If args.stack === undefined we know, that an
161
+ // old classcad-node package is used.
162
+ if (args.stack !== undefined) {
163
+ const captionMap = (0, sdkjs_1.getDrawing)(this._drawingId).cad.states.captionMap;
164
+ const tempCaptionMap = {};
165
+ if (args.id) {
166
+ // Add current state to caption map with key = args.id
167
+ // If it was an instance change and the state was stored automatically, no caption is available then,
168
+ // we will use 'Instance changed' for caption value
169
+ const caption = args.id.includes('instanceChange')
170
+ ? 'Instance changed'
171
+ : captionMap[args.id].caption;
172
+ tempCaptionMap[args.id] = { caption: caption, stateName: args.current, undoable: args.undoable };
173
+ // Iterate over all others and add existing ones also to the map
174
+ for (const key in captionMap) {
175
+ if (key !== args.id) {
176
+ if (args.stack.includes(captionMap[key].stateName) || captionMap[key].stateName === '') {
177
+ tempCaptionMap[key] = captionMap[key];
178
+ }
179
+ }
180
+ }
181
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.cad.setStates(Number.parseInt(args.current), args.stack, tempCaptionMap);
182
+ }
183
+ else {
184
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.cad.setStates(Number.parseInt(args.current), args.stack, captionMap);
185
+ }
186
+ }
187
+ else {
188
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.cad.setStates(0, args.stack, {});
189
+ }
190
+ });
191
+ }
192
+ catch (error) {
193
+ reject(error);
194
+ }
195
+ });
196
+ }
197
+ /** Closes the connection to the server. */
198
+ disconnect() {
199
+ return new Promise(async (resolve, reject) => {
200
+ try {
201
+ this._socket && this._socket.close();
202
+ resolve(this);
203
+ }
204
+ catch (error) {
205
+ reject(error);
206
+ }
207
+ });
208
+ }
209
+ /**
210
+ * Sends `command` to the server as the event `name` and resolves to the reply once all its frames have arrived.
211
+ * Structure patches and graphic go into the drawing on the way. Rejects with the reply when it carries an error.
212
+ *
213
+ * @param name - The server's event: `send` for requests, `undo`, `redo`.
214
+ * @param command - The request.
215
+ */
216
+ requestByName(name, command) {
217
+ // TODO: handle request by request, and wait with next request until current finished.
218
+ return new Promise((resolve, reject) => {
219
+ var _a;
220
+ const tr = new Transaction_1.Transaction();
221
+ try {
222
+ tr.on('result', value => {
223
+ if (value.command === 'Result' && value.from === 'GetTree') {
224
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.structure.set(value.result);
225
+ }
226
+ })
227
+ .on('patches', patches => {
228
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.structure.applyPatches(patches);
229
+ })
230
+ .on('blob', blob => {
231
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.graphic.addPackages([blob.data]);
232
+ })
233
+ .on('error', error => {
234
+ // Nothing to do
235
+ })
236
+ .on('finished', (data) => {
237
+ var _a, _b, _c, _d, _e, _f;
238
+ // Transform the "old" ClassCAD response to the new ClassCAD response format introduced by api.v1.
239
+ // There is always only one result expected per command!
240
+ const result = (_a = data.results[0]) === null || _a === void 0 ? void 0 : _a.result;
241
+ let jobResult = result;
242
+ if (typeof ((_c = (_b = data.results[0]) === null || _b === void 0 ? void 0 : _b.result) === null || _c === void 0 ? void 0 : _c.result) !== 'undefined') {
243
+ jobResult = (_e = (_d = data.results[0]) === null || _d === void 0 ? void 0 : _d.result) === null || _e === void 0 ? void 0 : _e.result;
244
+ }
245
+ const streamData = (result === null || result === void 0 ? void 0 : result.streamData) || ((_f = data.results[0]) === null || _f === void 0 ? void 0 : _f.streamData);
246
+ const messages = (result === null || result === void 0 ? void 0 : result.messages) || data.messages || [];
247
+ const oldErrors = (result === null || result === void 0 ? void 0 : result.errors) || data.errors;
248
+ if (oldErrors) {
249
+ for (const oldError of oldErrors) {
250
+ let level = re_export_1.MessageLevel.info;
251
+ // errorState --> 0:eCCNoError, 1:eCCErrorWarning, 2:eCCErrorGoOn, 3:eCCErrorStop
252
+ switch (oldError.errorState) {
253
+ case 1:
254
+ level = re_export_1.MessageLevel.warning;
255
+ break;
256
+ case 2:
257
+ case 3:
258
+ case 4:
259
+ level = re_export_1.MessageLevel.error;
260
+ break;
261
+ default:
262
+ break;
263
+ }
264
+ messages.push({ code: oldError.errorCode, message: oldError.errorMessage, level, api: '' }); // TODO: remove api from
265
+ }
266
+ }
267
+ let maxLevel = undefined;
268
+ for (const message of messages) {
269
+ if (!maxLevel || message.level > maxLevel) {
270
+ maxLevel = message.level;
271
+ }
272
+ }
273
+ const sr = { result: jobResult, maxLevel, messages, streamData };
274
+ const hadError = typeof sr.maxLevel !== 'undefined' && sr.maxLevel >= re_export_1.MessageLevel.error;
275
+ if (hadError) {
276
+ reject(sr);
277
+ }
278
+ else {
279
+ resolve(sr);
280
+ }
281
+ });
282
+ this._transactions.set(tr.transactionID, tr);
283
+ // this.emit("requestStarted", this);
284
+ // If undoable flag is set, save current command with transactionId to the caption map
285
+ // After response from classcad-node state name will also be added to caption map
286
+ if ((_a = command === null || command === void 0 ? void 0 : command.options) === null || _a === void 0 ? void 0 : _a.undoable) {
287
+ if (command === null || command === void 0 ? void 0 : command.task) {
288
+ const tempCaptionMap = {};
289
+ const captionMap = (0, sdkjs_1.getDrawing)(this._drawingId).cad.states.captionMap;
290
+ // Add new caption with empty state name to the temp map, correct state name will be added later
291
+ tempCaptionMap[tr.transactionID] = { stateName: '', caption: Object.keys(command === null || command === void 0 ? void 0 : command.task[0])[0] };
292
+ // Add existing elements of caption map to the temporary map
293
+ for (const key in captionMap) {
294
+ tempCaptionMap[key] = captionMap[key];
295
+ }
296
+ (0, sdkjs_1.getDrawing)(this._drawingId).api.cad.setCaptionMap(tempCaptionMap);
297
+ }
298
+ }
299
+ this._socket && this._socket.emit(name, tr.transactionID, command);
300
+ }
301
+ catch (error) {
302
+ reject(error);
303
+ }
304
+ });
305
+ }
306
+ request(command) {
307
+ return this.requestByName(SocketIOEvent.SEND, command);
308
+ }
309
+ /**
310
+ * Steps back in the drawing's undo history on the server: to `options.state` when given.
311
+ *
312
+ * @param options - The state to go back to, and options for the server.
313
+ */
314
+ undo(options) {
315
+ // Using command object in redo actually not necessary, but we can use
316
+ // RequestOptions for undo options and have a clean structure, like common requests
317
+ return this.requestByName(SocketIOEvent.UNDO, { command: '', options });
318
+ }
319
+ /**
320
+ * Steps forward in the drawing's undo history on the server: to `options.state` when given.
321
+ *
322
+ * @param options - The state to go forward to, and options for the server.
323
+ */
324
+ redo(options) {
325
+ // Using command object in redo actually not necessary, but we can use
326
+ // RequestOptions for redo options and have a clean structure, like common requests
327
+ return this.requestByName(SocketIOEvent.REDO, { command: '', options });
328
+ }
329
+ ack() {
330
+ this._socket ? this._socket.emit('received') : noop();
331
+ }
332
+ syncState() {
333
+ var _a, _b, _c, _d, _e, _f;
334
+ const dr = (0, sdkjs_1.getDrawing)(this._drawingId);
335
+ (_b = (_a = dr === null || dr === void 0 ? void 0 : dr.api) === null || _a === void 0 ? void 0 : _a.cad) === null || _b === void 0 ? void 0 : _b.setActive(Boolean((_c = this._socket) === null || _c === void 0 ? void 0 : _c.active));
336
+ (_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(Boolean((_f = this._socket) === null || _f === void 0 ? void 0 : _f.connected));
337
+ }
338
+ }
339
+ exports.SocketIOClient = SocketIOClient;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transaction = void 0;
4
+ const base64_arraybuffer_1 = require("base64-arraybuffer");
5
+ const events_1 = require("events");
6
+ const pako_1 = require("pako");
7
+ const uuid_1 = require("uuid");
8
+ class Transaction extends events_1.EventEmitter {
9
+ constructor(transactionID = (0, uuid_1.v4)()) {
10
+ super();
11
+ this.transactionID = transactionID;
12
+ // Bytes processed (compressed)
13
+ this.bytes = 0;
14
+ // Bytes processed (uncompressed)
15
+ this.bytesUncompressed = 0;
16
+ // Parsing time
17
+ this.time = 0;
18
+ // The results
19
+ this.results = [];
20
+ // The patches
21
+ this.patches = [];
22
+ // The blobs
23
+ this.blobs = [];
24
+ // The errors
25
+ this.errors = [];
26
+ // The messages
27
+ this.messages = [];
28
+ }
29
+ handleData(data) {
30
+ // TODO: Why double negation --> Ask Paul
31
+ if (data.type === 'Buffer' && !!data.data) {
32
+ // Node Buffer
33
+ data = Uint8Array.from(data.data);
34
+ }
35
+ if (data instanceof Uint8Array) {
36
+ // Wrap binary data into json Blob
37
+ data = {
38
+ command: 'Blob',
39
+ type: 'Binary',
40
+ data,
41
+ };
42
+ }
43
+ if (typeof data === 'string' || data instanceof String) {
44
+ // Plain text package
45
+ const length = data.length;
46
+ data = JSON.parse(data);
47
+ this.bytes += length;
48
+ if (data.command !== 'Blob') {
49
+ this.bytesUncompressed += length;
50
+ }
51
+ }
52
+ if (Array.isArray(data)) {
53
+ // TODO: Why array, possible? Ask Paul.
54
+ // Collection of commands
55
+ data.forEach(item => this.handleItem(item));
56
+ }
57
+ else {
58
+ this.handleItem(data);
59
+ }
60
+ }
61
+ handleItem(object) {
62
+ if (object.from === 'EndFrame' && object.transactionID === this.transactionID) {
63
+ this.emit('finished', {
64
+ results: this.results,
65
+ patches: this.patches,
66
+ blobs: this.blobs,
67
+ errors: this.errors,
68
+ messages: this.messages,
69
+ });
70
+ }
71
+ else if (object.command === 'Endpoint') {
72
+ // TODO: What is an EndPoint? Ask Paul.
73
+ // Scaled endpoints
74
+ const res = Object.assign(Object.assign({}, object), { command: 'Result', from: 'ip' }); // TODO: ???
75
+ this.results.push(res);
76
+ this.emit('result', res);
77
+ }
78
+ else if (object.command === 'Blob') {
79
+ let stream = object.data;
80
+ // TimeMeasMap.get().startTimeMeas(`unpack-${this.transactionID}`);
81
+ if (!(stream instanceof Uint8Array)) {
82
+ stream = (0, base64_arraybuffer_1.decode)(stream);
83
+ }
84
+ const blob = {
85
+ command: 'Blob',
86
+ type: 'Binary',
87
+ data: JSON.parse((0, pako_1.inflate)(stream, { raw: true, to: 'string' })),
88
+ size: stream.length,
89
+ };
90
+ // TimeMeasMap.get().stopTimeMeas(`unpack-${this.transactionID}`);
91
+ this.blobs.push(blob);
92
+ this.emit('blob', blob);
93
+ }
94
+ else if (object.command === 'Result' && object.from !== 'BeginFrame' && object.from !== 'EndFrame') {
95
+ try {
96
+ if (typeof object.result === 'string') {
97
+ const json = JSON.parse(object.result);
98
+ object.result = json;
99
+ }
100
+ }
101
+ catch (e) { }
102
+ let inflatedStreams;
103
+ const inputStreams = object.streamData;
104
+ if (inputStreams) {
105
+ inflatedStreams = {};
106
+ Object.getOwnPropertyNames(inputStreams).forEach(key => {
107
+ let stream = inputStreams[key];
108
+ if (!(stream instanceof Uint8Array)) {
109
+ stream = (0, base64_arraybuffer_1.decode)(stream);
110
+ }
111
+ inflatedStreams[key] = (0, pako_1.inflate)(stream, { raw: true });
112
+ });
113
+ }
114
+ const res = Object.assign(Object.assign({}, object), { command: 'Result', streamData: inflatedStreams });
115
+ this.results.push(res);
116
+ this.emit('result', res);
117
+ }
118
+ else if (object.command === 'Patch') {
119
+ this.patches = [...this.patches, ...object.ops];
120
+ this.emit('patches', object.ops);
121
+ }
122
+ else if (object.command === 'ErrorMessage') {
123
+ // ClassCAD error messages
124
+ this.errors.push(object.attributes);
125
+ this.emit('error', object.attributes);
126
+ }
127
+ else if (object.command === 'InfoMessage') {
128
+ // ClassCAD info messages
129
+ this.messages.push(object.attributes);
130
+ this.emit('message', object.attributes);
131
+ }
132
+ }
133
+ }
134
+ exports.Transaction = Transaction;