@monterosa/sdk-interact-kit 2.0.0-rc.1 → 2.0.0-rc.3

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/dist/index.cjs.js DELETED
@@ -1,2961 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var sdkConnectKit = require('@monterosa/sdk-connect-kit');
6
- var sdkUtil = require('@monterosa/sdk-util');
7
- var sdkCore = require('@monterosa/sdk-core');
8
- var sdkInteractInterop = require('@monterosa/sdk-interact-interop');
9
- var sdkStorageKit = require('@monterosa/sdk-storage-kit');
10
-
11
- /******************************************************************************
12
- Copyright (c) Microsoft Corporation.
13
-
14
- Permission to use, copy, modify, and/or distribute this software for any
15
- purpose with or without fee is hereby granted.
16
-
17
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
- PERFORMANCE OF THIS SOFTWARE.
24
- ***************************************************************************** */
25
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
26
-
27
- var extendStatics = function(d, b) {
28
- extendStatics = Object.setPrototypeOf ||
29
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
31
- return extendStatics(d, b);
32
- };
33
-
34
- function __extends(d, b) {
35
- if (typeof b !== "function" && b !== null)
36
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
37
- extendStatics(d, b);
38
- function __() { this.constructor = d; }
39
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40
- }
41
-
42
- var __assign = function() {
43
- __assign = Object.assign || function __assign(t) {
44
- for (var s, i = 1, n = arguments.length; i < n; i++) {
45
- s = arguments[i];
46
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
47
- }
48
- return t;
49
- };
50
- return __assign.apply(this, arguments);
51
- };
52
-
53
- function __awaiter(thisArg, _arguments, P, generator) {
54
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
55
- return new (P || (P = Promise))(function (resolve, reject) {
56
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
57
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
58
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
59
- step((generator = generator.apply(thisArg, _arguments || [])).next());
60
- });
61
- }
62
-
63
- function __generator(thisArg, body) {
64
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
65
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
66
- function verb(n) { return function (v) { return step([n, v]); }; }
67
- function step(op) {
68
- if (f) throw new TypeError("Generator is already executing.");
69
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
70
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
71
- if (y = 0, t) op = [op[0] & 2, t.value];
72
- switch (op[0]) {
73
- case 0: case 1: t = op; break;
74
- case 4: _.label++; return { value: op[1], done: false };
75
- case 5: _.label++; y = op[1]; op = [0]; continue;
76
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
77
- default:
78
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
79
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
80
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
81
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
82
- if (t[2]) _.ops.pop();
83
- _.trys.pop(); continue;
84
- }
85
- op = body.call(thisArg, _);
86
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
87
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
88
- }
89
- }
90
-
91
- function __values(o) {
92
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
93
- if (m) return m.call(o);
94
- if (o && typeof o.length === "number") return {
95
- next: function () {
96
- if (o && i >= o.length) o = void 0;
97
- return { value: o && o[i++], done: !o };
98
- }
99
- };
100
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
101
- }
102
-
103
- function __spreadArray(to, from, pack) {
104
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
105
- if (ar || !(i in from)) {
106
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
107
- ar[i] = from[i];
108
- }
109
- }
110
- return to.concat(ar || Array.prototype.slice.call(from));
111
- }
112
-
113
- function __asyncValues(o) {
114
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
115
- var m = o[Symbol.asyncIterator], i;
116
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
117
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
118
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
119
- }
120
-
121
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
122
- var e = new Error(message);
123
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
124
- };
125
-
126
- /**
127
- * @license
128
- * @monterosa/sdk-interact-kit
129
- *
130
- * Copyright © 2023-2024 Monterosa Productions Limited. All rights reserved.
131
- *
132
- * More details on the license can be found at https://www.monterosa.co/sdk/license
133
- */
134
- /**
135
- * Sign in the user to submit data that requires a verified user.
136
- *
137
- * @example
138
- * ```javascript
139
- * try {
140
- * const sdk = getSdk();
141
- * const userId = "b236e331-ee62-4238-90d0-47588c7facdc";
142
- * const timestamp = 1684934960;
143
- * const signature = "9ABC4892838DC13986A63B736E95A7D99DF95C72";
144
- *
145
- * await login(sdk, userId, timestamp, signature);
146
- *
147
- * console.log('logged in successfully!');
148
- * } catch (err) {
149
- * console.log(err)
150
- * }
151
- * ```
152
- *
153
- * @param sdk - Monterosa SDK instance
154
- * @param userId - The unique user UUID
155
- * @param timestamp - The timecode when the signature was generated
156
- * @param signature - A unique identifier that serves as proof of the user's authenticity.
157
- * The signature must only contain the following characters: 0-9, a-z, A-Z, and must be uppercased
158
- * @returns A Promise that resolves with `void` when the login is successful, otherwise it rejects.
159
- */
160
- function login(sdk, userId, timestamp, signature) {
161
- return __awaiter(this, void 0, void 0, function () {
162
- var connect;
163
- return __generator(this, function (_a) {
164
- switch (_a.label) {
165
- case 0: return [4 /*yield*/, sdkConnectKit.getConnect(sdk.options.host)];
166
- case 1:
167
- connect = _a.sent();
168
- return [2 /*return*/, sdkConnectKit.login(connect, userId, timestamp, signature)];
169
- }
170
- });
171
- });
172
- }
173
-
174
- /**
175
- * @license
176
- * @monterosa/sdk-interact-kit
177
- *
178
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
179
- *
180
- * More details on the license can be found at https://www.monterosa.co/sdk/license
181
- */
182
- /**
183
- * @internal
184
- */
185
- exports.State = void 0;
186
- (function (State) {
187
- State["Ok"] = "ok";
188
- State["Error"] = "error";
189
- })(exports.State || (exports.State = {}));
190
- /**
191
- * @internal
192
- */
193
- exports.Klass = void 0;
194
- (function (Klass) {
195
- Klass["Listings"] = "listings";
196
- Klass["History"] = "history";
197
- Klass["Create"] = "create";
198
- Klass["Revoke"] = "revoke";
199
- Klass["Stop"] = "stop";
200
- Klass["Reveal"] = "reveal";
201
- Klass["Poll"] = "p";
202
- Klass["Feedback"] = "fb";
203
- Klass["Eoc"] = "eoc";
204
- Klass["Vote"] = "v";
205
- Klass["SubsCounter"] = "subscounter";
206
- })(exports.Klass || (exports.Klass = {}));
207
- /**
208
- * @internal
209
- */
210
- exports.Channel = void 0;
211
- (function (Channel) {
212
- Channel["Poll"] = "p";
213
- Channel["Live"] = "l";
214
- })(exports.Channel || (exports.Channel = {}));
215
-
216
- /**
217
- * @license
218
- * @monterosa/sdk-interact-kit
219
- *
220
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
221
- *
222
- * More details on the license can be found at https://www.monterosa.co/sdk/license
223
- */
224
- var ConnectImpl = /** @class */ (function (_super) {
225
- __extends(ConnectImpl, _super);
226
- function ConnectImpl(host) {
227
- var _this = _super.call(this) || this;
228
- _this.host = host;
229
- _this._state = exports.State.Ok;
230
- _this._enmasse = null;
231
- return _this;
232
- }
233
- Object.defineProperty(ConnectImpl.prototype, "state", {
234
- get: function () {
235
- return this._state;
236
- },
237
- set: function (state) {
238
- if (state === this._state) {
239
- return;
240
- }
241
- this._state = state;
242
- this.emit('state', this._state);
243
- },
244
- enumerable: false,
245
- configurable: true
246
- });
247
- Object.defineProperty(ConnectImpl.prototype, "enmasse", {
248
- get: function () {
249
- if (this._enmasse === null) {
250
- throw new Error('Connect is not initialised, init() method should be called first.');
251
- }
252
- return this._enmasse;
253
- },
254
- set: function (enmasse) {
255
- this._enmasse = enmasse;
256
- },
257
- enumerable: false,
258
- configurable: true
259
- });
260
- ConnectImpl.prototype.init = function () {
261
- return __awaiter(this, void 0, void 0, function () {
262
- var _a;
263
- return __generator(this, function (_b) {
264
- switch (_b.label) {
265
- case 0:
266
- _a = this;
267
- return [4 /*yield*/, sdkConnectKit.getConnect(this.host)];
268
- case 1:
269
- _a.enmasse = _b.sent();
270
- this.enmasse.on('message', this.handleMessage.bind(this));
271
- this.enmasse.on('state', this.handleState.bind(this));
272
- return [2 /*return*/];
273
- }
274
- });
275
- });
276
- };
277
- ConnectImpl.prototype.connect = function () {
278
- return __awaiter(this, void 0, void 0, function () {
279
- return __generator(this, function (_a) {
280
- switch (_a.label) {
281
- case 0: return [4 /*yield*/, sdkConnectKit.connect(this.enmasse)];
282
- case 1:
283
- _a.sent();
284
- return [2 /*return*/];
285
- }
286
- });
287
- });
288
- };
289
- ConnectImpl.prototype.disconnect = function () {
290
- sdkConnectKit.disconnect(this.enmasse);
291
- };
292
- ConnectImpl.prototype.subscribeProject = function (id) {
293
- return __awaiter(this, void 0, void 0, function () {
294
- return __generator(this, function (_a) {
295
- switch (_a.label) {
296
- case 0: return [4 /*yield*/, sdkConnectKit.subscribe(this.enmasse, "".concat(exports.Channel.Live, "-").concat(id))];
297
- case 1:
298
- _a.sent();
299
- return [2 /*return*/];
300
- }
301
- });
302
- });
303
- };
304
- ConnectImpl.prototype.unsubscribeProject = function (id) {
305
- sdkConnectKit.unsubscribe(this.enmasse, "".concat(exports.Channel.Live, "-").concat(id));
306
- };
307
- ConnectImpl.prototype.subscribeEvent = function (id) {
308
- return __awaiter(this, void 0, void 0, function () {
309
- return __generator(this, function (_a) {
310
- switch (_a.label) {
311
- case 0: return [4 /*yield*/, Promise.all([
312
- sdkConnectKit.subscribe(this.enmasse, "".concat(exports.Channel.Live, "-").concat(id)),
313
- sdkConnectKit.subscribe(this.enmasse, "".concat(exports.Channel.Poll, "-").concat(id)),
314
- ])];
315
- case 1:
316
- _a.sent();
317
- return [2 /*return*/];
318
- }
319
- });
320
- });
321
- };
322
- ConnectImpl.prototype.unsubscribeEvent = function (id) {
323
- sdkConnectKit.unsubscribe(this.enmasse, "".concat(exports.Channel.Live, "-").concat(id));
324
- sdkConnectKit.unsubscribe(this.enmasse, "".concat(exports.Channel.Poll, "-").concat(id));
325
- };
326
- ConnectImpl.prototype.sendVote = function (eventId, pollId, answer) {
327
- sdkConnectKit.send(this.enmasse, "".concat(exports.Channel.Poll, "-").concat(eventId), exports.Klass.Vote, [
328
- pollId,
329
- answer,
330
- '',
331
- ]);
332
- };
333
- ConnectImpl.prototype.handleMessage = function (message) {
334
- var klass = message.klass, data = message.body, channel = message.channel;
335
- var id = channel.substring(channel.indexOf('-') + 1);
336
- this.emit('message', {
337
- id: id,
338
- klass: klass,
339
- data: data,
340
- });
341
- };
342
- ConnectImpl.prototype.handleState = function (state) {
343
- var args = [];
344
- for (var _i = 1; _i < arguments.length; _i++) {
345
- args[_i - 1] = arguments[_i];
346
- }
347
- switch (state) {
348
- case sdkConnectKit.ConnState.Disconnected:
349
- this.state = exports.State.Error;
350
- break;
351
- case sdkConnectKit.ConnState.Connecting: {
352
- var attempt = args[0];
353
- if (attempt > 1) {
354
- this.state = exports.State.Error;
355
- }
356
- break;
357
- }
358
- case sdkConnectKit.ConnState.Connected:
359
- this.state = exports.State.Ok;
360
- break;
361
- }
362
- };
363
- return ConnectImpl;
364
- }(sdkUtil.Emitter));
365
-
366
- /**
367
- * @license
368
- * @monterosa/sdk-interact-kit
369
- *
370
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
371
- *
372
- * More details on the license can be found at https://www.monterosa.co/sdk/license
373
- */
374
- var getConnectMemoized = sdkUtil.memoizePromise(function (host) { return __awaiter(void 0, void 0, void 0, function () {
375
- var connect;
376
- return __generator(this, function (_a) {
377
- switch (_a.label) {
378
- case 0:
379
- connect = new ConnectImpl(host);
380
- return [4 /*yield*/, connect.init()];
381
- case 1:
382
- _a.sent();
383
- return [4 /*yield*/, connect.connect()];
384
- case 2:
385
- _a.sent();
386
- return [2 /*return*/, connect];
387
- }
388
- });
389
- }); }, function (host) { return host; });
390
- /**
391
- * @internal
392
- */
393
- function getConnect(host) {
394
- return getConnectMemoized(host);
395
- }
396
-
397
- /**
398
- * @license
399
- * @monterosa/sdk-interact-kit
400
- *
401
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
402
- *
403
- * More details on the license can be found at https://www.monterosa.co/sdk/license
404
- */
405
- /**
406
- * Provides states of the connection health
407
- */
408
- exports.ConnectionHealthState = void 0;
409
- (function (ConnectionHealthState) {
410
- /**
411
- * The client is connected and the connection is healthy
412
- */
413
- ConnectionHealthState["Ok"] = "ok";
414
- /**
415
- * The client is either trying to establish a connection but failing, or
416
- * the client has been explicetily {@link @monterosa/sdk-connect-kit#disconnect() | disconnected}
417
- */
418
- ConnectionHealthState["Error"] = "error";
419
- })(exports.ConnectionHealthState || (exports.ConnectionHealthState = {}));
420
-
421
- /**
422
- * @license
423
- * @monterosa/sdk-interact-kit
424
- *
425
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
426
- *
427
- * More details on the license can be found at https://www.monterosa.co/sdk/license
428
- */
429
- var ConnectionHealthImpl = /** @class */ (function (_super) {
430
- __extends(ConnectionHealthImpl, _super);
431
- function ConnectionHealthImpl(connect) {
432
- var _this = _super.call(this) || this;
433
- _this.connect = connect;
434
- _this._state = exports.ConnectionHealthState.Ok;
435
- _this.connect.on('state', _this.handleState.bind(_this));
436
- return _this;
437
- }
438
- Object.defineProperty(ConnectionHealthImpl.prototype, "state", {
439
- get: function () {
440
- return this._state;
441
- },
442
- set: function (state) {
443
- this._state = state;
444
- this.emit('state', state);
445
- },
446
- enumerable: false,
447
- configurable: true
448
- });
449
- ConnectionHealthImpl.prototype.handleState = function () {
450
- switch (this.connect.state) {
451
- default:
452
- case exports.State.Ok:
453
- this.state = exports.ConnectionHealthState.Ok;
454
- break;
455
- case exports.State.Error:
456
- this.state = exports.ConnectionHealthState.Error;
457
- break;
458
- }
459
- };
460
- return ConnectionHealthImpl;
461
- }(sdkUtil.Emitter));
462
-
463
- /**
464
- * @license
465
- * @monterosa/sdk-interact-kit
466
- *
467
- * Copyright © 2022-2024 Monterosa Productions Limited. All rights reserved.
468
- *
469
- * More details on the license can be found at https://www.monterosa.co/sdk/license
470
- */
471
- var getConnectionHealthMemoized = sdkUtil.memoizePromise(function (sdk) { return __awaiter(void 0, void 0, void 0, function () {
472
- var connect, connectionHealth;
473
- return __generator(this, function (_a) {
474
- switch (_a.label) {
475
- case 0: return [4 /*yield*/, getConnect(sdk.options.host)];
476
- case 1:
477
- connect = _a.sent();
478
- connectionHealth = new ConnectionHealthImpl(connect);
479
- return [2 /*return*/, connectionHealth];
480
- }
481
- });
482
- }); }, function (sdk) { return sdk.options.host; });
483
- /**
484
- * Returns {@link ConnectionHealth | connection health} instance
485
- */
486
- function getConnectionHealth(sdk) {
487
- if (sdk === void 0) { sdk = sdkCore.getSdk(); }
488
- return getConnectionHealthMemoized(sdk);
489
- }
490
- /**
491
- * Adds an observer for when
492
- * {@link ConnectionHealth.state | connection health state} changed
493
- */
494
- function onConnectionHealthState(connectionHealth, callback) {
495
- return sdkUtil.subscribe(connectionHealth, 'state', callback);
496
- }
497
-
498
- /**
499
- * @license
500
- * @monterosa/sdk-interact-kit
501
- *
502
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
503
- *
504
- * More details on the license can be found at https://www.monterosa.co/sdk/license
505
- */
506
- var DEFAULT_IGNORE_TIME = 30;
507
-
508
- /**
509
- * @license
510
- * @monterosa/sdk-interact-kit
511
- *
512
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
513
- *
514
- * More details on the license can be found at https://www.monterosa.co/sdk/license
515
- */
516
- /**
517
- * Converts tag for identifying languages (rfc5646) into ISO language code
518
- */
519
- function tagToLanguage(tag) {
520
- // The tag is split not only by `-` as its stated in the rfc
521
- // but also by `_` as it is returned by Studio for some locales
522
- var chunks = tag.split(/[-_]/);
523
- return chunks[0];
524
- }
525
- /**
526
- * Returns either:
527
- * * a locale from the list of provided locales that correspond OS locale preferences
528
- * * or default locale if OS locale doesn't correspond to any from the provided list
529
- *
530
- * * @internal
531
- */
532
- function getLocale(locales) {
533
- // The list of user's preferred language tags,
534
- var languageTags = __spreadArray([
535
- // where the first item is the user's default language
536
- navigator.language
537
- ], navigator.languages, true);
538
- // firstly, trying to check if one of languages tag
539
- // has a full match with passed locales
540
- for (var _i = 0, languageTags_1 = languageTags; _i < languageTags_1.length; _i++) {
541
- var tag = languageTags_1[_i];
542
- if (locales.includes(tag)) {
543
- // if language tag has a match return it right away
544
- return tag;
545
- }
546
- }
547
- // secondly, checking if user's language (ISO string)
548
- // has occurrences in the list of locales
549
- for (var _a = 0, languageTags_2 = languageTags; _a < languageTags_2.length; _a++) {
550
- var tag = languageTags_2[_a];
551
- var userLang = tagToLanguage(tag);
552
- for (var _b = 0, locales_1 = locales; _b < locales_1.length; _b++) {
553
- var locale = locales_1[_b];
554
- var studioLang = tagToLanguage(locale);
555
- if (studioLang === userLang) {
556
- // return the first locale that has the same
557
- // language ISO string as the user language tag
558
- return locale;
559
- }
560
- }
561
- }
562
- // if none locales matches users preferred languages tags
563
- // return default locale
564
- return locales[0];
565
- }
566
- function localise(value, locale) {
567
- if (Object.prototype.hasOwnProperty.call(value, locale)) {
568
- return value[locale];
569
- }
570
- return value.all;
571
- }
572
-
573
- /**
574
- * @license
575
- * @monterosa/sdk-interact-kit
576
- *
577
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
578
- *
579
- * More details on the license can be found at https://www.monterosa.co/sdk/license
580
- */
581
- /**
582
- * @internal
583
- */
584
- var ProjectImpl = /** @class */ (function (_super) {
585
- __extends(ProjectImpl, _super);
586
- function ProjectImpl(options, context) {
587
- var _this = _super.call(this) || this;
588
- _this.eventsChecksum = null;
589
- _this.id = options.id;
590
- _this.host = options.host;
591
- _this._context = context;
592
- return _this;
593
- }
594
- Object.defineProperty(ProjectImpl.prototype, "context", {
595
- get: function () {
596
- return this._context;
597
- },
598
- enumerable: false,
599
- configurable: true
600
- });
601
- Object.defineProperty(ProjectImpl.prototype, "embedUrl", {
602
- get: function () {
603
- var _a;
604
- return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.embed;
605
- },
606
- enumerable: false,
607
- configurable: true
608
- });
609
- Object.defineProperty(ProjectImpl.prototype, "uuid", {
610
- get: function () {
611
- var _a;
612
- return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.uuid;
613
- },
614
- enumerable: false,
615
- configurable: true
616
- });
617
- Object.defineProperty(ProjectImpl.prototype, "events", {
618
- get: function () {
619
- var _a;
620
- return ((_a = this._listings) === null || _a === void 0 ? void 0 : _a.events) || [];
621
- },
622
- enumerable: false,
623
- configurable: true
624
- });
625
- Object.defineProperty(ProjectImpl.prototype, "listings", {
626
- get: function () {
627
- return this._listings;
628
- },
629
- set: function (newListings) {
630
- var createdEvents = this._calculateCreatedEvents(newListings);
631
- var updatedEvents = this._calculateUpdatedEvents(newListings);
632
- var deletedEvents = this._calculateDeletedEvents(newListings);
633
- this._listings = __assign({}, newListings);
634
- this._updateLocales(newListings);
635
- this._updateEventsChecksum(newListings);
636
- this._emitListingsEvents(createdEvents, updatedEvents, deletedEvents);
637
- },
638
- enumerable: false,
639
- configurable: true
640
- });
641
- /**
642
- * Calculates events that were created (present in new listings but not in old)
643
- */
644
- ProjectImpl.prototype._calculateCreatedEvents = function (newListings) {
645
- var _this = this;
646
- if (!this._listings) {
647
- return [];
648
- }
649
- return newListings.events.filter(function (_a) {
650
- var id = _a.id;
651
- return !_this._listings.events.some(function (event) { return id === event.id; });
652
- });
653
- };
654
- /**
655
- * Calculates events that were updated (present in old listings and new,
656
- * but with different digest)
657
- */
658
- ProjectImpl.prototype._calculateUpdatedEvents = function (newListings) {
659
- var _this = this;
660
- if (!this._listings) {
661
- return [];
662
- }
663
- return newListings.events.filter(function (event) {
664
- // find event data in new listings
665
- var existingEvent = _this._listings.events.find(function (_a) {
666
- var id = _a.id;
667
- return event.id === id;
668
- });
669
- // return true if event data is found and digest is different
670
- return existingEvent && event.digest !== existingEvent.digest;
671
- });
672
- };
673
- /**
674
- * Calculates events that were deleted (present in old listings but not in new)
675
- */
676
- ProjectImpl.prototype._calculateDeletedEvents = function (newListings) {
677
- if (!this._listings) {
678
- return [];
679
- }
680
- return this._listings.events.filter(function (_a) {
681
- var id = _a.id;
682
- return !newListings.events.some(function (event) { return id === event.id; });
683
- });
684
- };
685
- /**
686
- * Processes and updates locales from project listings
687
- */
688
- ProjectImpl.prototype._updateLocales = function (newListings) {
689
- this._locales = newListings.project.locales
690
- // clone the array first
691
- .map(function (locale) { return (__assign({}, locale)); })
692
- // sort an array so that the default locale is the first
693
- .sort(function (locale) { return (locale.default ? -1 : 0); })
694
- // return only keys of the locales
695
- .map(function (locale) { return locale.key; });
696
- this._locale = getLocale(this._locales);
697
- };
698
- /**
699
- * Updates the events checksum based on new listings
700
- */
701
- ProjectImpl.prototype._updateEventsChecksum = function (newListings) {
702
- this.eventsChecksum = sdkUtil.checksum(newListings.events.map(function (event) { return event.digest; }).join(''));
703
- };
704
- /**
705
- * Emits events based on created and deleted events
706
- */
707
- ProjectImpl.prototype._emitListingsEvents = function (createdEvents, updatedEvents, deletedEvents) {
708
- var hasCreatedEvents = createdEvents.length > 0;
709
- var hasDeletedEvents = deletedEvents.length > 0;
710
- var hasUpdatedEvents = updatedEvents.length > 0;
711
- var hasChanges = hasCreatedEvents || hasDeletedEvents || hasUpdatedEvents;
712
- if (hasCreatedEvents) {
713
- this.emit('listings_events_created', createdEvents);
714
- }
715
- if (hasDeletedEvents) {
716
- this.emit('listings_events_deleted', deletedEvents);
717
- }
718
- if (hasUpdatedEvents) {
719
- this.emit('listings_events_updated', updatedEvents);
720
- }
721
- if (hasChanges) {
722
- this.emit('listings');
723
- }
724
- };
725
- Object.defineProperty(ProjectImpl.prototype, "isLocalisationSupported", {
726
- get: function () {
727
- var _a;
728
- return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.is_localisation_supported;
729
- },
730
- enumerable: false,
731
- configurable: true
732
- });
733
- Object.defineProperty(ProjectImpl.prototype, "locale", {
734
- get: function () {
735
- return this._locale;
736
- },
737
- set: function (locale) {
738
- if (!this.locales.includes(locale)) {
739
- throw new Error("Unknown locale name \"".concat(locale, "\""));
740
- }
741
- this._locale = locale;
742
- },
743
- enumerable: false,
744
- configurable: true
745
- });
746
- Object.defineProperty(ProjectImpl.prototype, "locales", {
747
- get: function () {
748
- return this._locales;
749
- },
750
- enumerable: false,
751
- configurable: true
752
- });
753
- Object.defineProperty(ProjectImpl.prototype, "fields", {
754
- get: function () {
755
- if (this._fields !== undefined) {
756
- return localise(this._fields, this.locale);
757
- }
758
- return {};
759
- },
760
- /**
761
- * Sets custom fields
762
- *
763
- * It accepts both Localised<Record<string, unknown>> and Record<string, unknown> to
764
- * avoid mistyping between setter and getter
765
- *
766
- * @internal
767
- */
768
- set: function (value) {
769
- var isUpdate = typeof this._fields !== 'undefined';
770
- this._fields = __assign({}, value);
771
- if (isUpdate) {
772
- this.emit('updated');
773
- }
774
- },
775
- enumerable: false,
776
- configurable: true
777
- });
778
- Object.defineProperty(ProjectImpl.prototype, "extensions", {
779
- get: function () {
780
- var _a;
781
- return (_a = this._listings) === null || _a === void 0 ? void 0 : _a.assets;
782
- },
783
- enumerable: false,
784
- configurable: true
785
- });
786
- Object.defineProperty(ProjectImpl.prototype, "historyIgnore", {
787
- get: function () {
788
- var _a;
789
- var value = (_a = this._listings) === null || _a === void 0 ? void 0 : _a.project.history_ignore;
790
- if (value && value > 0) {
791
- return value;
792
- }
793
- return DEFAULT_IGNORE_TIME;
794
- },
795
- enumerable: false,
796
- configurable: true
797
- });
798
- // TODO: must be implemented
799
- // eslint-disable-next-line
800
- ProjectImpl.prototype.delete = function () { };
801
- return ProjectImpl;
802
- }(sdkUtil.Emitter));
803
-
804
- /**
805
- * @license
806
- * @monterosa/sdk-interact-kit
807
- *
808
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
809
- *
810
- * More details on the license can be found at https://www.monterosa.co/sdk/license
811
- */
812
- var projects = new Map();
813
- var connects = new Map();
814
- function buildProject(options, context) {
815
- return __awaiter(this, void 0, void 0, function () {
816
- var id, host, project, setup, _a, err_1, connect;
817
- return __generator(this, function (_b) {
818
- switch (_b.label) {
819
- case 0:
820
- id = options.id, host = options.host;
821
- if (projects.has(id)) {
822
- return [2 /*return*/, projects.get(id)];
823
- }
824
- project = new ProjectImpl(options, context);
825
- /**
826
- * Add it to the cache of projects, so that we could find it to populate it
827
- * with the data when /listings/ message is coming from the EnMasse.
828
- */
829
- projects.set(id, project);
830
- _b.label = 1;
831
- case 1:
832
- _b.trys.push([1, 5, , 6]);
833
- return [4 /*yield*/, setupConnect(host)];
834
- case 2:
835
- setup = _b.sent();
836
- return [4 /*yield*/, setup.subscribeProject(id)];
837
- case 3:
838
- _b.sent();
839
- /**
840
- * By the time goLive successfully resolved listings must be present
841
- * in project. If they are not, then there is no /listings/ in the channel's cache.
842
- * This might be due to either studio is malfunctioning or project id is incorrect.
843
- */
844
- if (!project.listings) {
845
- throw new Error("Unable to fetch project ".concat(id, " listings. Possibly wrong project id."));
846
- }
847
- _a = project;
848
- return [4 /*yield*/, sdkInteractInterop.fetchSettings(project.host, project.id)];
849
- case 4:
850
- _a.fields = _b.sent();
851
- return [2 /*return*/, project];
852
- case 5:
853
- err_1 = _b.sent();
854
- /**
855
- * If anything goes wrong we need to unsubscribe from the EnMasse project's
856
- * channel by switching it to the offline mode.
857
- */
858
- if (connects.has(id)) {
859
- connect = connects.get(id);
860
- connect.unsubscribeProject(id);
861
- }
862
- /**
863
- * And project should be removed from the list of cached projects so that
864
- * it won't be automatically returned upon consequent buildProject call
865
- */
866
- projects.delete(id);
867
- throw err_1;
868
- case 6: return [2 /*return*/];
869
- }
870
- });
871
- });
872
- }
873
- function setupConnect(host) {
874
- return __awaiter(this, void 0, void 0, function () {
875
- var connect;
876
- return __generator(this, function (_a) {
877
- switch (_a.label) {
878
- case 0:
879
- if (connects.has(host)) {
880
- return [2 /*return*/, connects.get(host)];
881
- }
882
- return [4 /*yield*/, getConnect(host)];
883
- case 1:
884
- connect = _a.sent();
885
- connect.on('message', handleConnectMessage$1);
886
- return [2 /*return*/, connect];
887
- }
888
- });
889
- });
890
- }
891
- function handleConnectMessage$1(message) {
892
- return __awaiter(this, void 0, void 0, function () {
893
- var id, klass, data, project, _a;
894
- return __generator(this, function (_b) {
895
- switch (_b.label) {
896
- case 0:
897
- id = message.id, klass = message.klass, data = message.data;
898
- project = projects.get(id);
899
- if (!project) {
900
- return [2 /*return*/];
901
- }
902
- _a = klass;
903
- switch (_a) {
904
- case exports.Klass.Listings: return [3 /*break*/, 1];
905
- }
906
- return [3 /*break*/, 3];
907
- case 1: return [4 /*yield*/, handleListings(project, data[0])];
908
- case 2:
909
- _b.sent();
910
- return [3 /*break*/, 3];
911
- case 3: return [2 /*return*/];
912
- }
913
- });
914
- });
915
- }
916
- function handleListings(project, data) {
917
- var _a;
918
- return __awaiter(this, void 0, void 0, function () {
919
- var listings, newDigest, oldDigest, _b;
920
- return __generator(this, function (_d) {
921
- switch (_d.label) {
922
- case 0:
923
- listings = JSON.parse(data);
924
- newDigest = listings.project.app_settings_digest;
925
- oldDigest = (_a = project.listings) === null || _a === void 0 ? void 0 : _a.project.app_settings_digest;
926
- project.listings = listings;
927
- _d.label = 1;
928
- case 1:
929
- _d.trys.push([1, 4, , 5]);
930
- if (!(oldDigest !== undefined && newDigest !== oldDigest)) return [3 /*break*/, 3];
931
- _b = project;
932
- return [4 /*yield*/, sdkInteractInterop.fetchSettings(project.host, project.id)];
933
- case 2:
934
- _b.fields = _d.sent();
935
- _d.label = 3;
936
- case 3: return [3 /*break*/, 5];
937
- case 4:
938
- _d.sent();
939
- console.warn("Unable to fetch project ".concat(project.id, " settings"));
940
- return [3 /*break*/, 5];
941
- case 5: return [2 /*return*/];
942
- }
943
- });
944
- });
945
- }
946
-
947
- /**
948
- * @license
949
- * @monterosa/sdk-interact-kit
950
- *
951
- * Copyright © 2022-2024 Monterosa Productions Limited. All rights reserved.
952
- *
953
- * More details on the license can be found at https://www.monterosa.co/sdk/license
954
- */
955
- /**
956
- * @internal
957
- */
958
- var getProjectMemoized = sdkUtil.memoizePromise(function (sdk) { return __awaiter(void 0, void 0, void 0, function () {
959
- var project;
960
- return __generator(this, function (_a) {
961
- switch (_a.label) {
962
- case 0: return [4 /*yield*/, buildProject({
963
- id: sdk.options.projectId,
964
- host: sdk.options.host,
965
- }, {
966
- sdk: sdk,
967
- })];
968
- case 1:
969
- project = _a.sent();
970
- return [2 /*return*/, project];
971
- }
972
- });
973
- }); }, function (sdk) { return sdk.options.projectId; });
974
- /**
975
- * Returns {@link InteractProject | project instance} associated
976
- * with the {@link @monterosa/sdk-core#MonterosaSdk | configured sdk}
977
- */
978
- function getProject(sdk) {
979
- if (sdk === void 0) { sdk = sdkCore.getSdk(); }
980
- return getProjectMemoized(sdk);
981
- }
982
- /**
983
- * Adds an observer for when {@link InteractProject.fields | project fields}
984
- * are updated
985
- */
986
- function onProjectFieldsUpdated(project, callback) {
987
- return sdkUtil.subscribe(project, 'updated', callback);
988
- }
989
- /**
990
- * Adds an observer that is called when the project listings are updated.
991
- *
992
- * @deprecated Use {@link onEventAdded()}, {@link onEventUpdated()} and
993
- * {@link onEventRemoved()} instead
994
- */
995
- function onProjectListingsUpdated(project, callback) {
996
- console.warn('onProjectListingsUpdated() is deprecated. Please use onEventAdded(), onEventUpdated() and onEventRemoved() instead');
997
- return sdkUtil.subscribe(project, 'listings', callback);
998
- }
999
-
1000
- /**
1001
- * @license
1002
- * @monterosa/sdk-interact-kit
1003
- *
1004
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1005
- *
1006
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1007
- */
1008
- function fetchHistory(host, id) {
1009
- return __awaiter(this, void 0, void 0, function () {
1010
- var response, data;
1011
- return __generator(this, function (_a) {
1012
- switch (_a.label) {
1013
- case 0: return [4 /*yield*/, fetch("https://".concat(host, "/events/").concat(id.substring(0, 2), "/").concat(id, "/history.json"))];
1014
- case 1:
1015
- response = _a.sent();
1016
- if (!response.ok) {
1017
- throw new Error("Failed to fetch event ".concat(id, " history"));
1018
- }
1019
- return [4 /*yield*/, response.json()];
1020
- case 2:
1021
- data = _a.sent();
1022
- return [2 /*return*/, data];
1023
- }
1024
- });
1025
- });
1026
- }
1027
-
1028
- /**
1029
- * @license
1030
- * @monterosa/sdk-interact-kit
1031
- *
1032
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1033
- *
1034
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1035
- */
1036
- /**
1037
- * Describes the event state.
1038
- */
1039
- exports.EventState = void 0;
1040
- (function (EventState) {
1041
- /**
1042
- * The event is in the `upcoming` state when its {@link InteractEvent.startAt | start time}
1043
- * less than the {@link now | current time}.
1044
- */
1045
- EventState["Upcoming"] = "upcoming";
1046
- /**
1047
- * The event is in the `active` state when its {@link InteractEvent.startAt | start time}
1048
- * equal or more than the {@link now | current time} and less than the
1049
- * {@link InteractEvent.endAt | end time}.
1050
- */
1051
- EventState["Active"] = "active";
1052
- /**
1053
- * @internal
1054
- */
1055
- EventState["Prolonged"] = "prolonged";
1056
- /**
1057
- * The event is in the `finished` state when its {@link InteractEvent.endAt | end time}
1058
- * equal or more than the {@link now | current time}.
1059
- */
1060
- EventState["Finished"] = "finished";
1061
- })(exports.EventState || (exports.EventState = {}));
1062
- var InitState;
1063
- (function (InitState) {
1064
- InitState["Uninitialised"] = "uninitialised";
1065
- InitState["Initialising"] = "initialising";
1066
- InitState["Initialised"] = "initialised";
1067
- })(InitState || (InitState = {}));
1068
-
1069
- /**
1070
- * @license
1071
- * @monterosa/sdk-interact-kit
1072
- *
1073
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1074
- *
1075
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1076
- */
1077
- /**
1078
- * @internal
1079
- */
1080
- var EventImpl = /** @class */ (function (_super) {
1081
- __extends(EventImpl, _super);
1082
- function EventImpl(data, context) {
1083
- var _this = _super.call(this) || this;
1084
- _this._initState = InitState.Uninitialised;
1085
- _this._history = null;
1086
- _this._data = data;
1087
- _this._context = context;
1088
- _this._state = _this.calculateState();
1089
- _this._internalState = _this.calculateInternalState();
1090
- _this.boundHandleState = _this.handleState.bind(_this);
1091
- _this.boundHandleInternalState = _this.handleInternalState.bind(_this);
1092
- _this.boundHandleEventsUpdated = _this.handleEventsUpdated.bind(_this);
1093
- _this.unsubscribeStateHandler = sdkUtil.onTick(_this.boundHandleState);
1094
- _this.unsubscribeInternalStateHandler = sdkUtil.onTick(_this.boundHandleInternalState);
1095
- _this.unsubscribeListingsHandler = sdkUtil.subscribe(_this.context.project, 'listings_events_updated', _this.boundHandleEventsUpdated);
1096
- return _this;
1097
- }
1098
- EventImpl.prototype.calculateState = function () {
1099
- if (!this._data.started || sdkUtil.now() < this.startAt) {
1100
- return exports.EventState.Upcoming;
1101
- }
1102
- if (sdkUtil.now() < this.endAt) {
1103
- return exports.EventState.Active;
1104
- }
1105
- return exports.EventState.Finished;
1106
- };
1107
- EventImpl.prototype.calculateInternalState = function () {
1108
- if (!this._data.started || sdkUtil.now() < this.startAt) {
1109
- return exports.EventState.Upcoming;
1110
- }
1111
- if (sdkUtil.now() < this.endAt) {
1112
- return exports.EventState.Active;
1113
- }
1114
- if (sdkUtil.now() < this.endAt + this._data.extra_time) {
1115
- return exports.EventState.Prolonged;
1116
- }
1117
- return exports.EventState.Finished;
1118
- };
1119
- EventImpl.prototype.handleState = function () {
1120
- var state = this.calculateState();
1121
- if (state === exports.EventState.Finished) {
1122
- this.unsubscribeStateHandler();
1123
- }
1124
- if (state !== this._state) {
1125
- this._state = state;
1126
- this.emit('state', state);
1127
- }
1128
- };
1129
- EventImpl.prototype.handleInternalState = function () {
1130
- var internalState = this.calculateInternalState();
1131
- if (internalState === exports.EventState.Finished) {
1132
- this.unsubscribeInternalStateHandler();
1133
- }
1134
- if (internalState !== this._internalState) {
1135
- this._internalState = internalState;
1136
- this.emit('internal_state', internalState);
1137
- }
1138
- };
1139
- EventImpl.prototype.handleEventsUpdated = function (events) {
1140
- var _this = this;
1141
- var data = events.find(function (_a) {
1142
- var id = _a.id;
1143
- return id === _this.id;
1144
- });
1145
- if (data && this._data.digest !== data.digest) {
1146
- this._data = data;
1147
- // Forcing state recalculation to ensure the event is in the correct state
1148
- this.handleState();
1149
- this.handleInternalState();
1150
- this.emit('updated');
1151
- }
1152
- };
1153
- /** @internal */
1154
- EventImpl.prototype.destroy = function () {
1155
- this.unsubscribeStateHandler();
1156
- this.unsubscribeInternalStateHandler();
1157
- this.unsubscribeListingsHandler();
1158
- };
1159
- Object.defineProperty(EventImpl.prototype, "context", {
1160
- get: function () {
1161
- return this._context;
1162
- },
1163
- enumerable: false,
1164
- configurable: true
1165
- });
1166
- Object.defineProperty(EventImpl.prototype, "id", {
1167
- get: function () {
1168
- return this._data.id;
1169
- },
1170
- enumerable: false,
1171
- configurable: true
1172
- });
1173
- Object.defineProperty(EventImpl.prototype, "name", {
1174
- get: function () {
1175
- return this._data.name;
1176
- },
1177
- enumerable: false,
1178
- configurable: true
1179
- });
1180
- Object.defineProperty(EventImpl.prototype, "startAt", {
1181
- get: function () {
1182
- return this._data.start_at;
1183
- },
1184
- enumerable: false,
1185
- configurable: true
1186
- });
1187
- Object.defineProperty(EventImpl.prototype, "startAtIso", {
1188
- get: function () {
1189
- return this._data.start_at_iso;
1190
- },
1191
- enumerable: false,
1192
- configurable: true
1193
- });
1194
- Object.defineProperty(EventImpl.prototype, "endAt", {
1195
- get: function () {
1196
- return this._data.end_at;
1197
- },
1198
- enumerable: false,
1199
- configurable: true
1200
- });
1201
- Object.defineProperty(EventImpl.prototype, "endAtIso", {
1202
- get: function () {
1203
- return this._data.end_at_iso;
1204
- },
1205
- enumerable: false,
1206
- configurable: true
1207
- });
1208
- Object.defineProperty(EventImpl.prototype, "duration", {
1209
- get: function () {
1210
- return this._data.duration;
1211
- },
1212
- enumerable: false,
1213
- configurable: true
1214
- });
1215
- Object.defineProperty(EventImpl.prototype, "fields", {
1216
- get: function () {
1217
- var locale = this.context.project.locale;
1218
- return localise(this._data.custom_fields, locale);
1219
- },
1220
- enumerable: false,
1221
- configurable: true
1222
- });
1223
- Object.defineProperty(EventImpl.prototype, "state", {
1224
- get: function () {
1225
- return this._state;
1226
- },
1227
- enumerable: false,
1228
- configurable: true
1229
- });
1230
- Object.defineProperty(EventImpl.prototype, "internalState", {
1231
- get: function () {
1232
- return this._internalState;
1233
- },
1234
- enumerable: false,
1235
- configurable: true
1236
- });
1237
- Object.defineProperty(EventImpl.prototype, "initState", {
1238
- get: function () {
1239
- return this._initState;
1240
- },
1241
- set: function (state) {
1242
- this._initState = state;
1243
- },
1244
- enumerable: false,
1245
- configurable: true
1246
- });
1247
- Object.defineProperty(EventImpl.prototype, "history", {
1248
- get: function () {
1249
- return this._history;
1250
- },
1251
- set: function (value) {
1252
- this._history = value;
1253
- this.emit('history', value);
1254
- },
1255
- enumerable: false,
1256
- configurable: true
1257
- });
1258
- Object.defineProperty(EventImpl.prototype, "canSubscribe", {
1259
- get: function () {
1260
- return (this._internalState === exports.EventState.Active ||
1261
- this._internalState === exports.EventState.Prolonged);
1262
- },
1263
- enumerable: false,
1264
- configurable: true
1265
- });
1266
- Object.defineProperty(EventImpl.prototype, "canLoadHistory", {
1267
- get: function () {
1268
- return sdkUtil.now() >= this.startAt + this.context.project.historyIgnore;
1269
- },
1270
- enumerable: false,
1271
- configurable: true
1272
- });
1273
- return EventImpl;
1274
- }(sdkUtil.Emitter));
1275
-
1276
- /**
1277
- * @license
1278
- * @monterosa/sdk-interact-kit
1279
- *
1280
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1281
- *
1282
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1283
- */
1284
- var events = new Map();
1285
- var healthListeners = new Map();
1286
- function buildEvent(options, context) {
1287
- if (events.has(options.id)) {
1288
- return events.get(options.id);
1289
- }
1290
- var event = new EventImpl(options, context);
1291
- event.on('internal_state', handleEventInternalState.bind(event));
1292
- events.set(options.id, event);
1293
- return event;
1294
- }
1295
- function init(event) {
1296
- return __awaiter(this, void 0, void 0, function () {
1297
- var history_1;
1298
- return __generator(this, function (_a) {
1299
- switch (_a.label) {
1300
- case 0:
1301
- if (event.initState === InitState.Initialising) {
1302
- return [2 /*return*/, Promise.reject(new Error("can't initialise event, event is already being initialised"))];
1303
- }
1304
- if (event.initState === InitState.Initialised) {
1305
- return [2 /*return*/, Promise.reject(new Error("can't initialise event, event is already initialised"))];
1306
- }
1307
- event.initState = InitState.Initialising;
1308
- if (!(event.canLoadHistory && event.history === null)) return [3 /*break*/, 2];
1309
- return [4 /*yield*/, fetchHistory(event.context.project.host, event.id)];
1310
- case 1:
1311
- history_1 = _a.sent();
1312
- event.history = history_1;
1313
- _a.label = 2;
1314
- case 2:
1315
- if (!event.canSubscribe) return [3 /*break*/, 4];
1316
- return [4 /*yield*/, subscribe(event)];
1317
- case 3:
1318
- _a.sent();
1319
- _a.label = 4;
1320
- case 4: return [4 /*yield*/, listenConnHealth(event)];
1321
- case 5:
1322
- _a.sent();
1323
- event.initState = InitState.Initialised;
1324
- return [2 /*return*/, Promise.resolve()];
1325
- }
1326
- });
1327
- });
1328
- }
1329
- function subscribe(event) {
1330
- return __awaiter(this, void 0, void 0, function () {
1331
- var connect;
1332
- return __generator(this, function (_a) {
1333
- switch (_a.label) {
1334
- case 0:
1335
- if (!event.canSubscribe) {
1336
- return [2 /*return*/, Promise.reject(new Error("Event can't be subscribed"))];
1337
- }
1338
- return [4 /*yield*/, getConnect(event.context.project.host)];
1339
- case 1:
1340
- connect = _a.sent();
1341
- return [4 /*yield*/, connect.subscribeEvent(event.id)];
1342
- case 2:
1343
- _a.sent();
1344
- return [2 /*return*/, Promise.resolve()];
1345
- }
1346
- });
1347
- });
1348
- }
1349
- function unsubscribe(event) {
1350
- return __awaiter(this, void 0, void 0, function () {
1351
- var connect;
1352
- return __generator(this, function (_a) {
1353
- switch (_a.label) {
1354
- case 0: return [4 /*yield*/, getConnect(event.context.project.host)];
1355
- case 1:
1356
- connect = _a.sent();
1357
- return [4 /*yield*/, connect.unsubscribeEvent(event.id)];
1358
- case 2:
1359
- _a.sent();
1360
- return [2 /*return*/, Promise.resolve()];
1361
- }
1362
- });
1363
- });
1364
- }
1365
- function listenConnHealth(event) {
1366
- return __awaiter(this, void 0, void 0, function () {
1367
- var project, connect, unsub;
1368
- return __generator(this, function (_a) {
1369
- switch (_a.label) {
1370
- case 0:
1371
- project = event.context.project;
1372
- if (healthListeners.has(project.id)) {
1373
- return [2 /*return*/];
1374
- }
1375
- return [4 /*yield*/, getConnect(project.host)];
1376
- case 1:
1377
- connect = _a.sent();
1378
- if (connect.enmasse !== null) {
1379
- unsub = sdkConnectKit.onConnected(connect.enmasse, handleEnmasseConnected);
1380
- healthListeners.set(project.id, unsub);
1381
- }
1382
- return [2 /*return*/];
1383
- }
1384
- });
1385
- });
1386
- }
1387
- function handleEventInternalState(state) {
1388
- return __awaiter(this, void 0, void 0, function () {
1389
- return __generator(this, function (_a) {
1390
- switch (_a.label) {
1391
- case 0:
1392
- if (!(state === exports.EventState.Finished)) return [3 /*break*/, 2];
1393
- return [4 /*yield*/, unsubscribe(this)];
1394
- case 1:
1395
- _a.sent();
1396
- _a.label = 2;
1397
- case 2: return [2 /*return*/];
1398
- }
1399
- });
1400
- });
1401
- }
1402
- function handleEnmasseConnected() {
1403
- var _a, e_1, _b, _c;
1404
- return __awaiter(this, void 0, void 0, function () {
1405
- var _d, _e, _f, event_1, history_2, e_1_1;
1406
- return __generator(this, function (_g) {
1407
- switch (_g.label) {
1408
- case 0:
1409
- _g.trys.push([0, 9, 10, 15]);
1410
- _d = true, _e = __asyncValues(Array.from(events.values()));
1411
- _g.label = 1;
1412
- case 1: return [4 /*yield*/, _e.next()];
1413
- case 2:
1414
- if (!(_f = _g.sent(), _a = _f.done, !_a)) return [3 /*break*/, 8];
1415
- _c = _f.value;
1416
- _d = false;
1417
- _g.label = 3;
1418
- case 3:
1419
- _g.trys.push([3, , 6, 7]);
1420
- event_1 = _c;
1421
- if (!(event_1.initState === InitState.Initialised)) return [3 /*break*/, 5];
1422
- return [4 /*yield*/, fetchHistory(event_1.context.project.host, event_1.id)];
1423
- case 4:
1424
- history_2 = _g.sent();
1425
- event_1.history = history_2;
1426
- _g.label = 5;
1427
- case 5: return [3 /*break*/, 7];
1428
- case 6:
1429
- _d = true;
1430
- return [7 /*endfinally*/];
1431
- case 7: return [3 /*break*/, 1];
1432
- case 8: return [3 /*break*/, 15];
1433
- case 9:
1434
- e_1_1 = _g.sent();
1435
- e_1 = { error: e_1_1 };
1436
- return [3 /*break*/, 15];
1437
- case 10:
1438
- _g.trys.push([10, , 13, 14]);
1439
- if (!(!_d && !_a && (_b = _e.return))) return [3 /*break*/, 12];
1440
- return [4 /*yield*/, _b.call(_e)];
1441
- case 11:
1442
- _g.sent();
1443
- _g.label = 12;
1444
- case 12: return [3 /*break*/, 14];
1445
- case 13:
1446
- if (e_1) throw e_1.error;
1447
- return [7 /*endfinally*/];
1448
- case 14: return [7 /*endfinally*/];
1449
- case 15: return [2 /*return*/];
1450
- }
1451
- });
1452
- });
1453
- }
1454
-
1455
- /**
1456
- * @internal
1457
- */
1458
- var getEventsMemoized = sdkUtil.memoizePromise(function (project) { return __awaiter(void 0, void 0, void 0, function () {
1459
- var context;
1460
- return __generator(this, function (_a) {
1461
- switch (_a.label) {
1462
- case 0:
1463
- if (!(project === undefined)) return [3 /*break*/, 2];
1464
- return [4 /*yield*/, getProject()];
1465
- case 1:
1466
- project = _a.sent();
1467
- _a.label = 2;
1468
- case 2:
1469
- context = __assign(__assign({}, project.context), { project: project });
1470
- return [2 /*return*/, (project.events
1471
- // Calling builder function that creates an event instance.
1472
- // Existing event will be returned if it already exists in the cache
1473
- .map(function (data) { return buildEvent(data, context); })
1474
- // Sort events so the most recent event is first, and the oldest is last
1475
- .sort(function (a, b) { return a.startAt - b.startAt; }))];
1476
- }
1477
- });
1478
- }); },
1479
- /**
1480
- * Resolver function that determines the cache key for memoization.
1481
- *
1482
- * The cache key is used to determine whether a cached result can be reused.
1483
- * It prioritizes `eventsChecksum` over `id` to ensure cache invalidation when
1484
- * the events list changes, even if the project ID remains the same.
1485
- *
1486
- * @param project - Optional project instance. If not provided, attempts to
1487
- * resolve using the default project from the SDK.
1488
- * @returns A cache key string derived from the project's checksum/id or SDK projectId
1489
- */
1490
- function (project) {
1491
- var _a, _b;
1492
- // If project is provided, use its checksum (if available) or id as cache key
1493
- if (project !== undefined) {
1494
- return (_a = project.eventsChecksum) !== null && _a !== void 0 ? _a : project.id;
1495
- }
1496
- // If no project provided, try to get default project from SDK
1497
- var sdk = sdkCore.getSdk();
1498
- var defaultProject = projects.get(sdk.options.projectId);
1499
- // Use default project's checksum/id if available
1500
- if (defaultProject) {
1501
- return (_b = defaultProject.eventsChecksum) !== null && _b !== void 0 ? _b : defaultProject.id;
1502
- }
1503
- // Fallback to SDK's projectId option
1504
- return sdk.options.projectId;
1505
- });
1506
- /**
1507
- * Returns all events in a project, including all active events and
1508
- * past/upcoming events, according to Listings settings in Project Setup
1509
- * in Studio.
1510
- *
1511
- * @param project - A project instance. If not provided,
1512
- * the one from the default sdk will be fetched.
1513
- */
1514
- function getEvents(project) {
1515
- return getEventsMemoized(project);
1516
- }
1517
- /**
1518
- * @internal
1519
- */
1520
- var getEventMemoized = sdkUtil.memoizePromise(function (id, project) { return __awaiter(void 0, void 0, void 0, function () {
1521
- var context, data, event_1, history_1, history_2, event_2;
1522
- return __generator(this, function (_a) {
1523
- switch (_a.label) {
1524
- case 0:
1525
- if (events.has(id)) {
1526
- return [2 /*return*/, events.get(id)];
1527
- }
1528
- if (!(project === undefined)) return [3 /*break*/, 2];
1529
- return [4 /*yield*/, getProject()];
1530
- case 1:
1531
- project = _a.sent();
1532
- _a.label = 2;
1533
- case 2:
1534
- context = __assign(__assign({}, project.context), { project: project });
1535
- data = project.events.find(function (eventData) { return eventData.id === id; });
1536
- if (!(data !== undefined)) return [3 /*break*/, 5];
1537
- event_1 = buildEvent(data, context);
1538
- if (!event_1.canLoadHistory) return [3 /*break*/, 4];
1539
- return [4 /*yield*/, fetchHistory(project.host, id)];
1540
- case 3:
1541
- history_1 = _a.sent();
1542
- event_1.history = history_1;
1543
- _a.label = 4;
1544
- case 4: return [2 /*return*/, event_1];
1545
- case 5:
1546
- _a.trys.push([5, 7, , 8]);
1547
- return [4 /*yield*/, fetchHistory(project.host, id)];
1548
- case 6:
1549
- history_2 = _a.sent();
1550
- event_2 = buildEvent(history_2.config, context);
1551
- event_2.history = history_2;
1552
- return [2 /*return*/, event_2];
1553
- case 7:
1554
- _a.sent();
1555
- return [2 /*return*/, null];
1556
- case 8: return [2 /*return*/];
1557
- }
1558
- });
1559
- }); }, function (id) { return id; });
1560
- /**
1561
- * Returns an event by its id
1562
- *
1563
- * @param id - Id of the event
1564
- * @param project - A project instance. If not provided,
1565
- * the one from the default sdk will be fetched.
1566
- *
1567
- * @returns A an event associated with the provided id and project or null if no such
1568
- * event exists in the project.
1569
- */
1570
- function getEvent(id, project) {
1571
- return getEventMemoized(id, project);
1572
- }
1573
- /**
1574
- * Adds an observer for when {@link InteractEvent.state | event state} changed
1575
- */
1576
- function onEventState(event, callback) {
1577
- return sdkUtil.subscribe(event, 'state', callback);
1578
- }
1579
- /**
1580
- * Adds an observer for when event's data changed
1581
- */
1582
- function onEventUpdated(event, callback) {
1583
- return sdkUtil.subscribe(event, 'updated', callback);
1584
- }
1585
- /**
1586
- * Adds an observer that is called when an event is added to listings.
1587
- *
1588
- * @remarks
1589
- * The following actions will result in adding an event to listings:
1590
- *
1591
- * - The start of the event in Studio
1592
- *
1593
- * - The scheduling of a future event in Studio, when listings are configured
1594
- * to include future events in Project Settings.
1595
- *
1596
- * - When a future event starts, a new future event may be added to the list,
1597
- * depending on the project configuration, to ensure a minimum number of
1598
- * upcoming events are always available.
1599
- */
1600
- function onEventAdded(project, callback) {
1601
- var _this = this;
1602
- return sdkUtil.subscribe(project, 'listings_events_created', function (data) { var _a, data_1, data_1_1; return __awaiter(_this, void 0, void 0, function () {
1603
- var options, event_3, e_1_1;
1604
- var _b, e_1, _c, _d;
1605
- return __generator(this, function (_e) {
1606
- switch (_e.label) {
1607
- case 0:
1608
- _e.trys.push([0, 8, 9, 14]);
1609
- _a = true, data_1 = __asyncValues(data);
1610
- _e.label = 1;
1611
- case 1: return [4 /*yield*/, data_1.next()];
1612
- case 2:
1613
- if (!(data_1_1 = _e.sent(), _b = data_1_1.done, !_b)) return [3 /*break*/, 7];
1614
- _d = data_1_1.value;
1615
- _a = false;
1616
- _e.label = 3;
1617
- case 3:
1618
- _e.trys.push([3, , 5, 6]);
1619
- options = _d;
1620
- return [4 /*yield*/, getEvent(options.id, project)];
1621
- case 4:
1622
- event_3 = _e.sent();
1623
- if (event_3 !== null) {
1624
- callback(event_3);
1625
- }
1626
- return [3 /*break*/, 6];
1627
- case 5:
1628
- _a = true;
1629
- return [7 /*endfinally*/];
1630
- case 6: return [3 /*break*/, 1];
1631
- case 7: return [3 /*break*/, 14];
1632
- case 8:
1633
- e_1_1 = _e.sent();
1634
- e_1 = { error: e_1_1 };
1635
- return [3 /*break*/, 14];
1636
- case 9:
1637
- _e.trys.push([9, , 12, 13]);
1638
- if (!(!_a && !_b && (_c = data_1.return))) return [3 /*break*/, 11];
1639
- return [4 /*yield*/, _c.call(data_1)];
1640
- case 10:
1641
- _e.sent();
1642
- _e.label = 11;
1643
- case 11: return [3 /*break*/, 13];
1644
- case 12:
1645
- if (e_1) throw e_1.error;
1646
- return [7 /*endfinally*/];
1647
- case 13: return [7 /*endfinally*/];
1648
- case 14: return [2 /*return*/];
1649
- }
1650
- });
1651
- }); });
1652
- }
1653
- /**
1654
- * {@link onEventAdded} alias.
1655
- *
1656
- * @deprecated Use the new {@link onEventAdded} function instead.
1657
- */
1658
- function onEventPublished(project, callback) {
1659
- console.warn('onEventPublished() is deprecated. Please use onEventAdded() instead');
1660
- return onEventAdded(project, callback);
1661
- }
1662
- /**
1663
- * Adds an observer that is called when an event is removed from listings.
1664
- *
1665
- * @remarks
1666
- * The following actions will result in removing an event from listings:
1667
- *
1668
- * - The deletion of the event from Studio
1669
- *
1670
- * - The change of listings confuguration in Project Settings to exclude future
1671
- * or past events.
1672
- *
1673
- * - The event is removed after a period of time since its completion. This period
1674
- * is calculated as 45 seconds plus the Maximum allowed delay (configured in
1675
- * Project Settings in Studio).
1676
- */
1677
- function onEventRemoved(project, callback) {
1678
- var _this = this;
1679
- return sdkUtil.subscribe(project, 'listings_events_deleted', function (data) { var _a, data_2, data_2_1; return __awaiter(_this, void 0, void 0, function () {
1680
- var options, event_4, e_2_1;
1681
- var _b, e_2, _c, _d;
1682
- return __generator(this, function (_e) {
1683
- switch (_e.label) {
1684
- case 0:
1685
- _e.trys.push([0, 8, 9, 14]);
1686
- _a = true, data_2 = __asyncValues(data);
1687
- _e.label = 1;
1688
- case 1: return [4 /*yield*/, data_2.next()];
1689
- case 2:
1690
- if (!(data_2_1 = _e.sent(), _b = data_2_1.done, !_b)) return [3 /*break*/, 7];
1691
- _d = data_2_1.value;
1692
- _a = false;
1693
- _e.label = 3;
1694
- case 3:
1695
- _e.trys.push([3, , 5, 6]);
1696
- options = _d;
1697
- return [4 /*yield*/, getEvent(options.id, project)];
1698
- case 4:
1699
- event_4 = _e.sent();
1700
- if (event_4 !== null) {
1701
- callback(event_4);
1702
- }
1703
- return [3 /*break*/, 6];
1704
- case 5:
1705
- _a = true;
1706
- return [7 /*endfinally*/];
1707
- case 6: return [3 /*break*/, 1];
1708
- case 7: return [3 /*break*/, 14];
1709
- case 8:
1710
- e_2_1 = _e.sent();
1711
- e_2 = { error: e_2_1 };
1712
- return [3 /*break*/, 14];
1713
- case 9:
1714
- _e.trys.push([9, , 12, 13]);
1715
- if (!(!_a && !_b && (_c = data_2.return))) return [3 /*break*/, 11];
1716
- return [4 /*yield*/, _c.call(data_2)];
1717
- case 10:
1718
- _e.sent();
1719
- _e.label = 11;
1720
- case 11: return [3 /*break*/, 13];
1721
- case 12:
1722
- if (e_2) throw e_2.error;
1723
- return [7 /*endfinally*/];
1724
- case 13: return [7 /*endfinally*/];
1725
- case 14: return [2 /*return*/];
1726
- }
1727
- });
1728
- }); });
1729
- }
1730
-
1731
- /**
1732
- * @license
1733
- * @monterosa/sdk-interact-kit
1734
- *
1735
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1736
- *
1737
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1738
- */
1739
- var _a;
1740
- /**
1741
- * A map of potential error codes to compare with errors thrown by
1742
- * vote() or validateAnswer() functions.
1743
- */
1744
- exports.AnswerError = void 0;
1745
- (function (AnswerError) {
1746
- AnswerError["OptionIndexOutOfRange"] = "out_of_range";
1747
- AnswerError["BelowMinVoteOptions"] = "below_min_vote_options";
1748
- AnswerError["AboveMaxVoteOptions"] = "above_max_vote_options";
1749
- AnswerError["AboveMaxVotesPerUser"] = "above_max_per_user";
1750
- AnswerError["AboveMaxVotesPerOption"] = "above_max_per_option";
1751
- AnswerError["VotedOnNonInteractiveElement"] = "non_interactive_element";
1752
- AnswerError["VotedOnClosedElement"] = "closed_element";
1753
- AnswerError["EmptyVote"] = "empty_vote";
1754
- })(exports.AnswerError || (exports.AnswerError = {}));
1755
- var AnswerErrorMessages = (_a = {},
1756
- _a[exports.AnswerError.OptionIndexOutOfRange] = function (max, idx) {
1757
- return "Options index ".concat(idx, " is out of range [0..").concat(max, "]");
1758
- },
1759
- _a[exports.AnswerError.BelowMinVoteOptions] = function (min, total) {
1760
- return "Below min (".concat(min, ") vote options: ").concat(total);
1761
- },
1762
- _a[exports.AnswerError.AboveMaxVoteOptions] = function (max, total) {
1763
- return "Above max (".concat(max, ") vote options: ").concat(total);
1764
- },
1765
- _a[exports.AnswerError.AboveMaxVotesPerUser] = function (max, total) {
1766
- return "Above max (".concat(max, ") votes per user: ").concat(total);
1767
- },
1768
- _a[exports.AnswerError.AboveMaxVotesPerOption] = function (max, total) {
1769
- return "Above max (".concat(max, ") votes per option: ").concat(total);
1770
- },
1771
- _a[exports.AnswerError.VotedOnNonInteractiveElement] = function (id) {
1772
- return "Non interact element ".concat(id);
1773
- },
1774
- _a[exports.AnswerError.VotedOnClosedElement] = function (id) { return "Element ".concat(id, " is closed"); },
1775
- _a[exports.AnswerError.EmptyVote] = function (indices) {
1776
- return "Empty value for options indices: ".concat(indices);
1777
- },
1778
- _a);
1779
- /**
1780
- * The ElementState represents the potential states an element is in.
1781
- */
1782
- exports.ElementState = void 0;
1783
- (function (ElementState) {
1784
- /**
1785
- * Element is opened and active. The user can vote if
1786
- * element is `interactive`
1787
- */
1788
- ElementState["Opened"] = "opened";
1789
- /**
1790
- * Element is closed and the user can no longer vote for
1791
- * `interactive` elements
1792
- */
1793
- ElementState["Closed"] = "closed";
1794
- })(exports.ElementState || (exports.ElementState = {}));
1795
-
1796
- /**
1797
- * @license
1798
- * @monterosa/sdk-interact-kit
1799
- *
1800
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1801
- *
1802
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1803
- */
1804
- /**
1805
- * An `Answer` contains data of the user answer. Can be used to manage number of
1806
- * votes that the user placed for a specific option.
1807
- */
1808
- var Answer = /** @class */ (function () {
1809
- function Answer(answers) {
1810
- if (answers === void 0) { answers = []; }
1811
- this._answers = new Map();
1812
- for (var _i = 0, answers_1 = answers; _i < answers_1.length; _i++) {
1813
- var _a = answers_1[_i], option = _a.option, value = _a.value;
1814
- this._answers.set(option, value);
1815
- }
1816
- }
1817
- Object.defineProperty(Answer.prototype, "answers", {
1818
- /**
1819
- * The array of user answers
1820
- */
1821
- get: function () {
1822
- return Array.from(this._answers.entries()).map(function (_a) {
1823
- var option = _a[0], value = _a[1];
1824
- return ({
1825
- option: option,
1826
- value: value,
1827
- });
1828
- });
1829
- },
1830
- enumerable: false,
1831
- configurable: true
1832
- });
1833
- /**
1834
- * Instantiate Answer class with the provided options indices. Number
1835
- * of votes will be set to 1 for all options
1836
- *
1837
- * @example
1838
- * ```javascript
1839
- * // user votes for the first and fourth options
1840
- * const answer = Answer.fromIndices([0, 3]);
1841
- * ```
1842
- *
1843
- * @param indices - The array of option indices
1844
- */
1845
- Answer.fromIndices = function (indices) {
1846
- return new Answer(indices.map(function (option) { return ({
1847
- option: option,
1848
- value: 1,
1849
- }); }));
1850
- };
1851
- /**
1852
- * Adds a vote for the provided option index
1853
- *
1854
- * @param option - The index of the option, starting with 0
1855
- * @param value - The number of votes that will be placed against the option
1856
- */
1857
- Answer.prototype.set = function (option, value) {
1858
- this._answers.set(option, value);
1859
- return this;
1860
- };
1861
- /**
1862
- * Removes the vote for the provided option index
1863
- *
1864
- * @param option - The index of the option, starting with 0
1865
- */
1866
- Answer.prototype.remove = function (option) {
1867
- this._answers.delete(option);
1868
- return this;
1869
- };
1870
- /** @internal */
1871
- Answer.prototype.toJSON = function () {
1872
- return this.answers;
1873
- };
1874
- /** @internal */
1875
- Answer.fromJSON = function (value) {
1876
- return new Answer(JSON.parse(value));
1877
- };
1878
- return Answer;
1879
- }());
1880
-
1881
- /**
1882
- * @license
1883
- * @monterosa/sdk-interact-kit
1884
- *
1885
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1886
- *
1887
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1888
- */
1889
- /**
1890
- * Describes element types
1891
- */
1892
- exports.ElementType = void 0;
1893
- (function (ElementType) {
1894
- /**
1895
- * Data element
1896
- */
1897
- ElementType["Data"] = "data";
1898
- /**
1899
- * Poll element
1900
- */
1901
- ElementType["Poll"] = "poll";
1902
- /**
1903
- * Regular poll element
1904
- */
1905
- ElementType["RegularPoll"] = "rpoll";
1906
- /**
1907
- * Diametric poll element
1908
- */
1909
- ElementType["DiametricPoll"] = "dpoll";
1910
- /**
1911
- * Emoting poll
1912
- */
1913
- ElementType["EmotingPoll"] = "emo";
1914
- /**
1915
- * Powerbar element
1916
- */
1917
- ElementType["Powerbar"] = "powerbar";
1918
- /**
1919
- * Prediction element
1920
- */
1921
- ElementType["Prediction"] = "prediction";
1922
- /**
1923
- * Trivia element
1924
- */
1925
- ElementType["Trivia"] = "trivia";
1926
- })(exports.ElementType || (exports.ElementType = {}));
1927
- var ShowResultsMode;
1928
- (function (ShowResultsMode) {
1929
- ShowResultsMode["OnVote"] = "vote";
1930
- ShowResultsMode["OnClose"] = "close";
1931
- ShowResultsMode["OnEventEnd"] = "event_end";
1932
- ShowResultsMode["Manual"] = "manual";
1933
- ShowResultsMode["Never"] = "never";
1934
- ShowResultsMode["Always"] = "always";
1935
- })(ShowResultsMode || (ShowResultsMode = {}));
1936
-
1937
- /**
1938
- * @license
1939
- * @monterosa/sdk-interact-kit
1940
- *
1941
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
1942
- *
1943
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1944
- */
1945
- /**
1946
- * @internal
1947
- */
1948
- var ElementImpl = /** @class */ (function (_super) {
1949
- __extends(ElementImpl, _super);
1950
- function ElementImpl(data, context) {
1951
- var _this = this;
1952
- var _a, _b;
1953
- _this = _super.call(this) || this;
1954
- _this._results = null;
1955
- _this._userAnswer = null;
1956
- _this._correctOption = null;
1957
- _this._data = data;
1958
- _this._context = context;
1959
- _this._results = ((_a = data.data) === null || _a === void 0 ? void 0 : _a.results) || null;
1960
- _this._correctOption = ((_b = data.data) === null || _b === void 0 ? void 0 : _b.correct_option)
1961
- ? data.data.correct_option - 1
1962
- : null;
1963
- _this._state = _this.calculateState();
1964
- _this.unsubscribeStateHandler = sdkUtil.onTick(function () { return _this.handleState(); });
1965
- return _this;
1966
- }
1967
- ElementImpl.prototype.calculateState = function () {
1968
- if (sdkUtil.now() < this.publishedAt + this.duration) {
1969
- return exports.ElementState.Opened;
1970
- }
1971
- return exports.ElementState.Closed;
1972
- };
1973
- ElementImpl.prototype.handleState = function () {
1974
- var state = this.calculateState();
1975
- if (state === exports.ElementState.Closed) {
1976
- this.unsubscribeStateHandler();
1977
- }
1978
- if (state !== this._state) {
1979
- this._state = state;
1980
- this.emit('state', state);
1981
- }
1982
- };
1983
- ElementImpl.prototype.update = function (data) {
1984
- this._data = data;
1985
- this.handleState();
1986
- };
1987
- ElementImpl.prototype.destroy = function () {
1988
- this.unsubscribeStateHandler();
1989
- };
1990
- Object.defineProperty(ElementImpl.prototype, "context", {
1991
- get: function () {
1992
- return this._context;
1993
- },
1994
- enumerable: false,
1995
- configurable: true
1996
- });
1997
- Object.defineProperty(ElementImpl.prototype, "id", {
1998
- get: function () {
1999
- return this._data.id;
2000
- },
2001
- enumerable: false,
2002
- configurable: true
2003
- });
2004
- Object.defineProperty(ElementImpl.prototype, "eventId", {
2005
- get: function () {
2006
- return this.context.event.id;
2007
- },
2008
- enumerable: false,
2009
- configurable: true
2010
- });
2011
- Object.defineProperty(ElementImpl.prototype, "state", {
2012
- get: function () {
2013
- return this._state;
2014
- },
2015
- enumerable: false,
2016
- configurable: true
2017
- });
2018
- Object.defineProperty(ElementImpl.prototype, "type", {
2019
- get: function () {
2020
- return this._data.type;
2021
- },
2022
- enumerable: false,
2023
- configurable: true
2024
- });
2025
- Object.defineProperty(ElementImpl.prototype, "contentType", {
2026
- get: function () {
2027
- return this._data.content_type;
2028
- },
2029
- enumerable: false,
2030
- configurable: true
2031
- });
2032
- Object.defineProperty(ElementImpl.prototype, "publishedAt", {
2033
- get: function () {
2034
- return this._data.published_at;
2035
- },
2036
- enumerable: false,
2037
- configurable: true
2038
- });
2039
- Object.defineProperty(ElementImpl.prototype, "publishedAtIso", {
2040
- get: function () {
2041
- return this._data.published_at_iso;
2042
- },
2043
- enumerable: false,
2044
- configurable: true
2045
- });
2046
- Object.defineProperty(ElementImpl.prototype, "updatedAt", {
2047
- get: function () {
2048
- return this._data.updated_at;
2049
- },
2050
- enumerable: false,
2051
- configurable: true
2052
- });
2053
- Object.defineProperty(ElementImpl.prototype, "updatedAtIso", {
2054
- get: function () {
2055
- return this._data.updated_at_iso;
2056
- },
2057
- enumerable: false,
2058
- configurable: true
2059
- });
2060
- Object.defineProperty(ElementImpl.prototype, "duration", {
2061
- get: function () {
2062
- return this._data.duration;
2063
- },
2064
- enumerable: false,
2065
- configurable: true
2066
- });
2067
- Object.defineProperty(ElementImpl.prototype, "fields", {
2068
- get: function () {
2069
- var locale = this.context.project.locale;
2070
- return localise(this._data.custom_fields, locale);
2071
- },
2072
- enumerable: false,
2073
- configurable: true
2074
- });
2075
- Object.defineProperty(ElementImpl.prototype, "interactive", {
2076
- get: function () {
2077
- return this.type !== exports.ElementType.Data;
2078
- },
2079
- enumerable: false,
2080
- configurable: true
2081
- });
2082
- Object.defineProperty(ElementImpl.prototype, "pollId", {
2083
- get: function () {
2084
- return this._data.data.id || null;
2085
- },
2086
- enumerable: false,
2087
- configurable: true
2088
- });
2089
- Object.defineProperty(ElementImpl.prototype, "question", {
2090
- get: function () {
2091
- var locale = this.context.project.locale;
2092
- if (this._data.data.question === undefined) {
2093
- return null;
2094
- }
2095
- return localise(this._data.data.question, locale);
2096
- },
2097
- enumerable: false,
2098
- configurable: true
2099
- });
2100
- Object.defineProperty(ElementImpl.prototype, "answerOptions", {
2101
- get: function () {
2102
- var locale = this.context.project.locale;
2103
- if (this._data.data.options === undefined) {
2104
- return null;
2105
- }
2106
- return localise(this._data.data.options, locale);
2107
- },
2108
- enumerable: false,
2109
- configurable: true
2110
- });
2111
- Object.defineProperty(ElementImpl.prototype, "minOptionsPerVote", {
2112
- get: function () {
2113
- return this._data.data.min_options_per_vote || 1;
2114
- },
2115
- enumerable: false,
2116
- configurable: true
2117
- });
2118
- Object.defineProperty(ElementImpl.prototype, "maxOptionsPerVote", {
2119
- get: function () {
2120
- return this._data.data.max_options_per_vote || 1;
2121
- },
2122
- enumerable: false,
2123
- configurable: true
2124
- });
2125
- Object.defineProperty(ElementImpl.prototype, "maxVotesPerOption", {
2126
- get: function () {
2127
- return this._data.data.max_votes_per_option || 1;
2128
- },
2129
- enumerable: false,
2130
- configurable: true
2131
- });
2132
- Object.defineProperty(ElementImpl.prototype, "maxVotesPerUser", {
2133
- get: function () {
2134
- return this._data.data.max_votes_per_user || null;
2135
- },
2136
- enumerable: false,
2137
- configurable: true
2138
- });
2139
- Object.defineProperty(ElementImpl.prototype, "userAnswer", {
2140
- get: function () {
2141
- return this._userAnswer;
2142
- },
2143
- set: function (value) {
2144
- this._userAnswer = value;
2145
- },
2146
- enumerable: false,
2147
- configurable: true
2148
- });
2149
- Object.defineProperty(ElementImpl.prototype, "hasBeenAnswered", {
2150
- get: function () {
2151
- return this._userAnswer !== null;
2152
- },
2153
- enumerable: false,
2154
- configurable: true
2155
- });
2156
- Object.defineProperty(ElementImpl.prototype, "showResultsMode", {
2157
- get: function () {
2158
- return this._data.data.reveal_results_mode || null;
2159
- },
2160
- enumerable: false,
2161
- configurable: true
2162
- });
2163
- Object.defineProperty(ElementImpl.prototype, "canShowResults", {
2164
- get: function () {
2165
- switch (this.showResultsMode) {
2166
- case ShowResultsMode.OnVote:
2167
- return this.hasBeenAnswered || this.state === exports.ElementState.Closed;
2168
- case ShowResultsMode.OnClose:
2169
- return this.state === exports.ElementState.Closed;
2170
- case ShowResultsMode.Manual:
2171
- return this._results !== null;
2172
- case ShowResultsMode.OnEventEnd:
2173
- return this.context.event.state === exports.EventState.Finished;
2174
- case ShowResultsMode.Never:
2175
- return false;
2176
- case ShowResultsMode.Always:
2177
- default:
2178
- return true;
2179
- }
2180
- },
2181
- enumerable: false,
2182
- configurable: true
2183
- });
2184
- Object.defineProperty(ElementImpl.prototype, "results", {
2185
- get: function () {
2186
- if (!this.canShowResults) {
2187
- return null;
2188
- }
2189
- return this._results;
2190
- },
2191
- set: function (results) {
2192
- // skip setting results if they weren't changed
2193
- if (JSON.stringify(results) === JSON.stringify(this.results)) {
2194
- return;
2195
- }
2196
- this._results = results;
2197
- if (this.canShowResults) {
2198
- this.emit('results');
2199
- }
2200
- },
2201
- enumerable: false,
2202
- configurable: true
2203
- });
2204
- Object.defineProperty(ElementImpl.prototype, "correctOption", {
2205
- get: function () {
2206
- return this._correctOption;
2207
- },
2208
- set: function (value) {
2209
- this._correctOption = value;
2210
- },
2211
- enumerable: false,
2212
- configurable: true
2213
- });
2214
- Object.defineProperty(ElementImpl.prototype, "isCorrectOptionRevealed", {
2215
- get: function () {
2216
- return this._correctOption !== null;
2217
- },
2218
- enumerable: false,
2219
- configurable: true
2220
- });
2221
- return ElementImpl;
2222
- }(sdkUtil.Emitter));
2223
-
2224
- /**
2225
- * @license
2226
- * @monterosa/sdk-interact-kit
2227
- *
2228
- * Copyright © 2022-2024 Monterosa Productions Limited. All rights reserved.
2229
- *
2230
- * More details on the license can be found at https://www.monterosa.co/sdk/license
2231
- */
2232
- var elements = new Map();
2233
- function buildElement(options, context) {
2234
- return __awaiter(this, void 0, void 0, function () {
2235
- var element;
2236
- return __generator(this, function (_a) {
2237
- switch (_a.label) {
2238
- case 0:
2239
- if (elements.has(options.id)) {
2240
- return [2 /*return*/, elements.get(options.id)];
2241
- }
2242
- element = new ElementImpl(options, context);
2243
- return [4 /*yield*/, restoreAnswer(element)];
2244
- case 1:
2245
- _a.sent();
2246
- elements.set(element.id, element);
2247
- return [2 /*return*/, element];
2248
- }
2249
- });
2250
- });
2251
- }
2252
- function getElementByPolld(pollId) {
2253
- return Array.from(elements.values()).find(function (element) { return element.pollId === pollId; });
2254
- }
2255
- var configureEventMemoized = sdkUtil.memoizePromise(function (event) { return __awaiter(void 0, void 0, void 0, function () {
2256
- return __generator(this, function (_a) {
2257
- switch (_a.label) {
2258
- case 0:
2259
- event.on('history', handleEventHistory);
2260
- if (event.history !== null) {
2261
- handleEventHistory(event.history);
2262
- }
2263
- return [4 /*yield*/, configureConnect(event.context.sdk.options.host)];
2264
- case 1:
2265
- _a.sent();
2266
- return [4 /*yield*/, init(event)];
2267
- case 2:
2268
- _a.sent();
2269
- return [2 /*return*/];
2270
- }
2271
- });
2272
- }); }, function (event) { return event.id; });
2273
- function configureEvent(event) {
2274
- return __awaiter(this, void 0, void 0, function () {
2275
- return __generator(this, function (_a) {
2276
- return [2 /*return*/, configureEventMemoized(event)];
2277
- });
2278
- });
2279
- }
2280
- var configureConnectMemoized = sdkUtil.memoizePromise(function (host) { return __awaiter(void 0, void 0, void 0, function () {
2281
- var connect;
2282
- return __generator(this, function (_a) {
2283
- switch (_a.label) {
2284
- case 0: return [4 /*yield*/, getConnect(host)];
2285
- case 1:
2286
- connect = _a.sent();
2287
- connect.on('message', handleConnectMessage);
2288
- return [2 /*return*/];
2289
- }
2290
- });
2291
- }); }, function (host) { return host; });
2292
- function configureConnect(host) {
2293
- return __awaiter(this, void 0, void 0, function () {
2294
- return __generator(this, function (_a) {
2295
- return [2 /*return*/, configureConnectMemoized(host)];
2296
- });
2297
- });
2298
- }
2299
- function handleConnectMessage(message) {
2300
- return __awaiter(this, void 0, void 0, function () {
2301
- var klass, _a;
2302
- return __generator(this, function (_b) {
2303
- switch (_b.label) {
2304
- case 0:
2305
- klass = message.klass;
2306
- _a = klass;
2307
- switch (_a) {
2308
- case exports.Klass.Create: return [3 /*break*/, 1];
2309
- case exports.Klass.Revoke: return [3 /*break*/, 3];
2310
- case exports.Klass.Feedback: return [3 /*break*/, 5];
2311
- case exports.Klass.Reveal: return [3 /*break*/, 7];
2312
- }
2313
- return [3 /*break*/, 9];
2314
- case 1: return [4 /*yield*/, handleCreateMessage(message)];
2315
- case 2:
2316
- _b.sent();
2317
- return [3 /*break*/, 9];
2318
- case 3: return [4 /*yield*/, handleRevokeMessage(message)];
2319
- case 4:
2320
- _b.sent();
2321
- return [3 /*break*/, 9];
2322
- case 5: return [4 /*yield*/, handleFeedbackMessage(message)];
2323
- case 6:
2324
- _b.sent();
2325
- return [3 /*break*/, 9];
2326
- case 7: return [4 /*yield*/, handleRevealMessage(message)];
2327
- case 8:
2328
- _b.sent();
2329
- return [3 /*break*/, 9];
2330
- case 9: return [2 /*return*/];
2331
- }
2332
- });
2333
- });
2334
- }
2335
- function handleCreateMessage(message) {
2336
- return __awaiter(this, void 0, void 0, function () {
2337
- var id, data, options, event, element, context, element;
2338
- return __generator(this, function (_a) {
2339
- switch (_a.label) {
2340
- case 0:
2341
- id = message.id, data = message.data;
2342
- options = JSON.parse(data[0]);
2343
- return [4 /*yield*/, getEvent(id)];
2344
- case 1:
2345
- event = _a.sent();
2346
- if (event === null) {
2347
- return [2 /*return*/];
2348
- }
2349
- if (!elements.has(options.id)) return [3 /*break*/, 2];
2350
- element = elements.get(options.id);
2351
- if (options.updated_at > element.updatedAt ||
2352
- // This is a workaround to handle a Studio issue when two /create/ messages
2353
- // are sent upon correct option reveal. The first /create/ message contains
2354
- // the same duration but a different updated_at timestamp. The second /create/
2355
- // message contains the same updated_at timestamp but a different duration.
2356
- // Therefore, we need to check if the duration is different to ensure that
2357
- // the element is updated correctly.
2358
- options.duration !== element.duration) {
2359
- element.update(options);
2360
- event.emit('update', element);
2361
- }
2362
- return [3 /*break*/, 4];
2363
- case 2:
2364
- context = __assign(__assign({}, event.context), { event: event });
2365
- return [4 /*yield*/, buildElement(options, context)];
2366
- case 3:
2367
- element = _a.sent();
2368
- event.emit('publish', element);
2369
- _a.label = 4;
2370
- case 4: return [2 /*return*/];
2371
- }
2372
- });
2373
- });
2374
- }
2375
- function handleRevokeMessage(message) {
2376
- var data = message.data;
2377
- var id = JSON.parse(data[0]).id;
2378
- if (!elements.has(id)) {
2379
- return;
2380
- }
2381
- var element = elements.get(id);
2382
- elements.delete(id);
2383
- element.destroy();
2384
- element.context.event.emit('revoke', element);
2385
- }
2386
- function handleFeedbackMessage(message) {
2387
- return __awaiter(this, void 0, void 0, function () {
2388
- var data, pollId, counters, element, votes, percentages, results;
2389
- return __generator(this, function (_a) {
2390
- data = message.data;
2391
- pollId = +data[0];
2392
- counters = data[3];
2393
- element = getElementByPolld(pollId);
2394
- if (!element) {
2395
- return [2 /*return*/];
2396
- }
2397
- votes = counters.split(':').map(function (value) { return +value; });
2398
- percentages = sdkUtil.calculatePercentage(votes);
2399
- results = votes.map(function (item, idx) { return ({
2400
- percentage: percentages[idx],
2401
- votes: item,
2402
- }); });
2403
- element.results = results;
2404
- return [2 /*return*/];
2405
- });
2406
- });
2407
- }
2408
- function handleRevealMessage(message) {
2409
- var data = message.data;
2410
- // Reveal message format:
2411
- //
2412
- // [pollId, index (1-based), timestamp]
2413
- var pollId = +data[0];
2414
- var correctOption = +data[1] - 1;
2415
- var element = getElementByPolld(pollId);
2416
- if (!element) {
2417
- return;
2418
- }
2419
- if (element.correctOption !== correctOption) {
2420
- element.correctOption = correctOption;
2421
- element.context.event.emit('update', element);
2422
- }
2423
- }
2424
- function handleEventHistory(history) {
2425
- var _a, e_1, _b, _c;
2426
- return __awaiter(this, void 0, void 0, function () {
2427
- var event, context, _d, _e, _f, snapshot, e_1_1;
2428
- return __generator(this, function (_g) {
2429
- switch (_g.label) {
2430
- case 0:
2431
- if (history.timeline.length === 0) {
2432
- return [2 /*return*/];
2433
- }
2434
- return [4 /*yield*/, getEvent(history.config.id)];
2435
- case 1:
2436
- event = _g.sent();
2437
- if (event === null) {
2438
- return [2 /*return*/];
2439
- }
2440
- context = __assign(__assign({}, event.context), { event: event });
2441
- _g.label = 2;
2442
- case 2:
2443
- _g.trys.push([2, 11, 12, 17]);
2444
- _d = true, _e = __asyncValues(history.timeline);
2445
- _g.label = 3;
2446
- case 3: return [4 /*yield*/, _e.next()];
2447
- case 4:
2448
- if (!(_f = _g.sent(), _a = _f.done, !_a)) return [3 /*break*/, 10];
2449
- _c = _f.value;
2450
- _d = false;
2451
- _g.label = 5;
2452
- case 5:
2453
- _g.trys.push([5, , 8, 9]);
2454
- snapshot = _c;
2455
- if (!!elements.has(snapshot.id)) return [3 /*break*/, 7];
2456
- return [4 /*yield*/, buildElement(snapshot, context)];
2457
- case 6:
2458
- _g.sent();
2459
- _g.label = 7;
2460
- case 7: return [3 /*break*/, 9];
2461
- case 8:
2462
- _d = true;
2463
- return [7 /*endfinally*/];
2464
- case 9: return [3 /*break*/, 3];
2465
- case 10: return [3 /*break*/, 17];
2466
- case 11:
2467
- e_1_1 = _g.sent();
2468
- e_1 = { error: e_1_1 };
2469
- return [3 /*break*/, 17];
2470
- case 12:
2471
- _g.trys.push([12, , 15, 16]);
2472
- if (!(!_d && !_a && (_b = _e.return))) return [3 /*break*/, 14];
2473
- return [4 /*yield*/, _b.call(_e)];
2474
- case 13:
2475
- _g.sent();
2476
- _g.label = 14;
2477
- case 14: return [3 /*break*/, 16];
2478
- case 15:
2479
- if (e_1) throw e_1.error;
2480
- return [7 /*endfinally*/];
2481
- case 16: return [7 /*endfinally*/];
2482
- case 17: return [2 /*return*/];
2483
- }
2484
- });
2485
- });
2486
- }
2487
- function sendAnswer(element, userAnswer) {
2488
- return __awaiter(this, void 0, void 0, function () {
2489
- var _a, project, event, connect, answer;
2490
- return __generator(this, function (_b) {
2491
- switch (_b.label) {
2492
- case 0:
2493
- _a = element.context, project = _a.project, event = _a.event;
2494
- return [4 /*yield*/, getConnect(project.host)];
2495
- case 1:
2496
- connect = _b.sent();
2497
- answer = userAnswer.answers
2498
- .map(function (_a) {
2499
- var option = _a.option, value = _a.value;
2500
- return [option + 1, value];
2501
- })
2502
- .flat()
2503
- .join(':');
2504
- connect.sendVote(event.id, element.pollId, answer);
2505
- return [2 /*return*/];
2506
- }
2507
- });
2508
- });
2509
- }
2510
- function storeAnswer(element, userAnswer) {
2511
- return __awaiter(this, void 0, void 0, function () {
2512
- var err_1;
2513
- return __generator(this, function (_a) {
2514
- switch (_a.label) {
2515
- case 0:
2516
- _a.trys.push([0, 2, , 3]);
2517
- element.userAnswer = userAnswer;
2518
- return [4 /*yield*/, sdkStorageKit.storageWrite("element_".concat(element.id, "_vote"), JSON.stringify(userAnswer))];
2519
- case 1:
2520
- _a.sent();
2521
- return [3 /*break*/, 3];
2522
- case 2:
2523
- err_1 = _a.sent();
2524
- console.warn("Failed to store user answer: ".concat(sdkUtil.getErrorMessage(err_1)));
2525
- return [3 /*break*/, 3];
2526
- case 3: return [2 /*return*/];
2527
- }
2528
- });
2529
- });
2530
- }
2531
- function restoreAnswer(element) {
2532
- return __awaiter(this, void 0, void 0, function () {
2533
- var userAnswer;
2534
- return __generator(this, function (_a) {
2535
- switch (_a.label) {
2536
- case 0: return [4 /*yield*/, sdkStorageKit.storageRead("element_".concat(element.id, "_vote"))];
2537
- case 1:
2538
- userAnswer = _a.sent();
2539
- if (userAnswer !== null) {
2540
- element.userAnswer = Answer.fromJSON(userAnswer);
2541
- }
2542
- return [2 /*return*/];
2543
- }
2544
- });
2545
- });
2546
- }
2547
-
2548
- /**
2549
- * @license
2550
- * @monterosa/sdk-interact-kit
2551
- *
2552
- * Copyright © 2022 Monterosa Productions Limited. All rights reserved.
2553
- *
2554
- * More details on the license can be found at https://www.monterosa.co/sdk/license
2555
- */
2556
- /**
2557
- * @internal
2558
- */
2559
- var getElementMemoized = sdkUtil.memoizePromise(function (event, id) { return __awaiter(void 0, void 0, void 0, function () {
2560
- var element;
2561
- return __generator(this, function (_a) {
2562
- switch (_a.label) {
2563
- case 0: return [4 /*yield*/, configureEvent(event)];
2564
- case 1:
2565
- _a.sent();
2566
- element = Array.from(elements.values()).find(function (el) { return el.id === id; });
2567
- return [2 /*return*/, element || null];
2568
- }
2569
- });
2570
- }); }, function (event, id) { return id; });
2571
- /**
2572
- * Returns an element of a specific event by its id
2573
- */
2574
- function getElement(event, id) {
2575
- return getElementMemoized(event, id);
2576
- }
2577
- /**
2578
- * @internal
2579
- */
2580
- var getElementsMemoized = sdkUtil.memoizePromise(function (event) { return __awaiter(void 0, void 0, void 0, function () {
2581
- return __generator(this, function (_a) {
2582
- switch (_a.label) {
2583
- case 0: return [4 /*yield*/, configureEvent(event)];
2584
- case 1:
2585
- _a.sent();
2586
- return [2 /*return*/, (Array.from(elements.values())
2587
- // Get elements which belong only to the provided event
2588
- .filter(function (element) { return element.eventId === event.id; })
2589
- // Sort elements so the most recent event is first, and the oldest is last
2590
- .sort(function (a, b) { return a.publishedAt - b.publishedAt; }))];
2591
- }
2592
- });
2593
- }); }, function (event) { return event.id; }, {
2594
- clearOnResolve: true,
2595
- });
2596
- /**
2597
- * Returns the list of elements published in a specific event
2598
- */
2599
- function getElements(event) {
2600
- return getElementsMemoized(event);
2601
- }
2602
- function answer(element) {
2603
- var value = [];
2604
- for (var _i = 1; _i < arguments.length; _i++) {
2605
- value[_i - 1] = arguments[_i];
2606
- }
2607
- var answerObj = answerParametersToAnswer.apply(void 0, value);
2608
- validateAnswer.apply(void 0, __spreadArray([element], value, false));
2609
- sendAnswer(element, answerObj);
2610
- storeAnswer(element, answerObj);
2611
- }
2612
- function validateAnswer(element) {
2613
- var value = [];
2614
- for (var _i = 1; _i < arguments.length; _i++) {
2615
- value[_i - 1] = arguments[_i];
2616
- }
2617
- var answerObj = answerParametersToAnswer.apply(void 0, value);
2618
- var answers = answerObj.answers;
2619
- var indices = answers.map(function (_a) {
2620
- var option = _a.option;
2621
- return option;
2622
- });
2623
- var values = answers.map(function (_a) {
2624
- var v = _a.value;
2625
- return v;
2626
- });
2627
- var maxIndex = Math.max.apply(Math, indices);
2628
- var maxValue = Math.max.apply(Math, values);
2629
- var sumValues = values.reduce(function (memo, val) { return memo + val; }, 0);
2630
- var emptyIndices = values.reduce(function (memo, val, idx) {
2631
- if (val === 0) {
2632
- memo.push(indices[idx]);
2633
- }
2634
- return memo;
2635
- }, []);
2636
- if (!element.interactive) {
2637
- throw sdkUtil.createError(exports.AnswerError.VotedOnNonInteractiveElement, AnswerErrorMessages, element.id);
2638
- }
2639
- if (element.state === exports.ElementState.Closed) {
2640
- throw sdkUtil.createError(exports.AnswerError.VotedOnClosedElement, AnswerErrorMessages, element.id);
2641
- }
2642
- if (maxIndex > element.answerOptions.length - 1) {
2643
- throw sdkUtil.createError(exports.AnswerError.OptionIndexOutOfRange, AnswerErrorMessages, element.answerOptions.length - 1, maxIndex);
2644
- }
2645
- if (element.minOptionsPerVote !== null &&
2646
- indices.length < element.minOptionsPerVote) {
2647
- throw sdkUtil.createError(exports.AnswerError.BelowMinVoteOptions, AnswerErrorMessages, element.minOptionsPerVote, indices.length);
2648
- }
2649
- if (element.maxOptionsPerVote !== null &&
2650
- indices.length > element.maxOptionsPerVote) {
2651
- throw sdkUtil.createError(exports.AnswerError.AboveMaxVoteOptions, AnswerErrorMessages, element.maxOptionsPerVote, indices.length);
2652
- }
2653
- if (sumValues > element.maxVotesPerUser) {
2654
- throw sdkUtil.createError(exports.AnswerError.AboveMaxVotesPerUser, AnswerErrorMessages, element.maxVotesPerUser, sumValues);
2655
- }
2656
- if (maxValue > element.maxVotesPerOption) {
2657
- throw sdkUtil.createError(exports.AnswerError.AboveMaxVotesPerOption, AnswerErrorMessages, element.maxVotesPerOption, maxValue);
2658
- }
2659
- if (emptyIndices.length > 0) {
2660
- throw sdkUtil.createError(exports.AnswerError.EmptyVote, AnswerErrorMessages, emptyIndices.join(', '));
2661
- }
2662
- }
2663
- function answerParametersToAnswer() {
2664
- var value = [];
2665
- for (var _i = 0; _i < arguments.length; _i++) {
2666
- value[_i] = arguments[_i];
2667
- }
2668
- var answerValues = value.flat();
2669
- if (isAnswer(answerValues[0])) {
2670
- return answerValues[0];
2671
- }
2672
- if (isNumbers(answerValues)) {
2673
- return Answer.fromIndices(answerValues);
2674
- }
2675
- if (isAnswerValues(answerValues)) {
2676
- return new Answer(answerValues);
2677
- }
2678
- return new Answer();
2679
- }
2680
- function isAnswer(value) {
2681
- return value instanceof Answer;
2682
- }
2683
- function isAnswerValues(value) {
2684
- return value.every(function (v) {
2685
- return Object.prototype.hasOwnProperty.call(v, 'option') &&
2686
- Object.prototype.hasOwnProperty.call(v, 'value');
2687
- });
2688
- }
2689
- function isNumbers(value) {
2690
- return value.every(function (v) { return typeof v === 'number'; });
2691
- }
2692
- /**
2693
- * Adds an observer for when {@link InteractElement.results | element results}
2694
- * are updated
2695
- */
2696
- function onElementResults(element, callback) {
2697
- return sdkUtil.subscribe(element, 'results', callback);
2698
- }
2699
- /**
2700
- * Adds an observer for when {@link InteractElement.state | element state}
2701
- * changed
2702
- */
2703
- function onElementStateChanged(element, callback) {
2704
- return sdkUtil.subscribe(element, 'state', callback);
2705
- }
2706
- /**
2707
- * Adds an observer for when {@link InteractElement.fields | element's data}
2708
- * is updated
2709
- */
2710
- function onElementUpdated(event, callback) {
2711
- configureEvent(event);
2712
- return sdkUtil.subscribe(event, 'update', callback);
2713
- }
2714
- /**
2715
- * Adds an observer for when a new element is published
2716
- */
2717
- function onElementPublished(event, callback) {
2718
- configureEvent(event);
2719
- return sdkUtil.subscribe(event, 'publish', function (element) {
2720
- if (event.initState === InitState.Initialised) {
2721
- callback(element);
2722
- }
2723
- });
2724
- }
2725
- /**
2726
- * Adds an observer for when an element is revoked
2727
- */
2728
- function onElementRevoked(event, callback) {
2729
- configureEvent(event);
2730
- return sdkUtil.subscribe(event, 'revoke', callback);
2731
- }
2732
-
2733
- /**
2734
- * @license
2735
- * @monterosa/sdk-interact-kit
2736
- *
2737
- * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
2738
- *
2739
- * More details on the license can be found at https://www.monterosa.co/sdk/license
2740
- */
2741
- exports.PresenceCounterState = void 0;
2742
- (function (PresenceCounterState) {
2743
- PresenceCounterState["Opened"] = "opened";
2744
- PresenceCounterState["Closed"] = "closed";
2745
- })(exports.PresenceCounterState || (exports.PresenceCounterState = {}));
2746
-
2747
- /**
2748
- * @license
2749
- * @monterosa/sdk-interact-kit
2750
- *
2751
- * Copyright © 2023 Monterosa Productions Limited. All rights reserved.
2752
- *
2753
- * More details on the license can be found at https://www.monterosa.co/sdk/license
2754
- */
2755
- var logger = new sdkCore.Logger('@monterosa/sdk-interact-kit');
2756
-
2757
- /**
2758
- * @license
2759
- * @monterosa/sdk-interact-kit
2760
- *
2761
- * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
2762
- *
2763
- * More details on the license can be found at https://www.monterosa.co/sdk/license
2764
- */
2765
- var PresenceCounterImpl = /** @class */ (function (_super) {
2766
- __extends(PresenceCounterImpl, _super);
2767
- function PresenceCounterImpl(host, id) {
2768
- var _this = _super.call(this) || this;
2769
- _this.host = host;
2770
- _this.id = id;
2771
- _this.state = exports.PresenceCounterState.Closed;
2772
- _this.lastCount = 0;
2773
- _this.connect = null;
2774
- _this.boundHandleMessage = _this.handleMessage.bind(_this);
2775
- _this.boundHandleTimeout = _this.handleTimeout.bind(_this);
2776
- return _this;
2777
- }
2778
- PresenceCounterImpl.prototype.init = function () {
2779
- return __awaiter(this, void 0, void 0, function () {
2780
- var _a;
2781
- return __generator(this, function (_b) {
2782
- switch (_b.label) {
2783
- case 0:
2784
- _a = this;
2785
- return [4 /*yield*/, getConnect(this.host)];
2786
- case 1:
2787
- _a.connect = _b.sent();
2788
- this.connect.on('message', this.boundHandleMessage);
2789
- return [2 /*return*/];
2790
- }
2791
- });
2792
- });
2793
- };
2794
- Object.defineProperty(PresenceCounterImpl.prototype, "isOpened", {
2795
- get: function () {
2796
- return this.state === exports.PresenceCounterState.Opened;
2797
- },
2798
- enumerable: false,
2799
- configurable: true
2800
- });
2801
- PresenceCounterImpl.prototype.handleMessage = function (message) {
2802
- return __awaiter(this, void 0, void 0, function () {
2803
- var id, klass, data, subsData;
2804
- return __generator(this, function (_a) {
2805
- id = message.id, klass = message.klass, data = message.data;
2806
- if (id !== this.id || klass !== exports.Klass.SubsCounter) {
2807
- return [2 /*return*/];
2808
- }
2809
- try {
2810
- subsData = JSON.parse(data[0]);
2811
- this.handleCounterUpdate(subsData.counter);
2812
- this.resetTimeout(subsData.next_update_at);
2813
- }
2814
- catch (e) {
2815
- logger.warn("Couldn't parse subscounter message.");
2816
- }
2817
- return [2 /*return*/];
2818
- });
2819
- });
2820
- };
2821
- PresenceCounterImpl.prototype.handleCounterUpdate = function (count) {
2822
- if (count < 0) {
2823
- return;
2824
- }
2825
- var shouldEmitUpdated = false;
2826
- var shouldEmitState = false;
2827
- if (this.lastCount !== count) {
2828
- shouldEmitUpdated = true;
2829
- this.lastCount = count;
2830
- }
2831
- if (this.state === exports.PresenceCounterState.Closed) {
2832
- shouldEmitState = true;
2833
- this.state = exports.PresenceCounterState.Opened;
2834
- }
2835
- if (shouldEmitUpdated) {
2836
- this.emit('updated', this.lastCount);
2837
- }
2838
- if (shouldEmitState) {
2839
- this.emit('state', exports.PresenceCounterState.Opened);
2840
- }
2841
- };
2842
- PresenceCounterImpl.prototype.handleTimeout = function () {
2843
- this.state = exports.PresenceCounterState.Closed;
2844
- this.emit('state', exports.PresenceCounterState.Closed);
2845
- };
2846
- PresenceCounterImpl.prototype.resetTimeout = function (nextUpdateAt) {
2847
- clearTimeout(this.closeTimeout);
2848
- this.closeTimeout = setTimeout(this.boundHandleTimeout,
2849
- // because of the time difference between the server and the client,
2850
- // we need to add 3 seconds to the timeout
2851
- (nextUpdateAt - sdkUtil.now() + 3) * 1000);
2852
- };
2853
- PresenceCounterImpl.prototype.destroy = function () {
2854
- if (this.connect !== null) {
2855
- this.connect.off('message', this.boundHandleMessage);
2856
- }
2857
- };
2858
- return PresenceCounterImpl;
2859
- }(sdkUtil.Emitter));
2860
-
2861
- /**
2862
- * @license
2863
- * @monterosa/sdk-interact-kit
2864
- *
2865
- * Copyright © 2025 Monterosa Productions Limited. All rights reserved.
2866
- *
2867
- * More details on the license can be found at https://www.monterosa.co/sdk/license
2868
- */
2869
- var presenceCounters = new Map();
2870
- var getPresenceCounterMemoized = sdkUtil.memoizePromise(function (host, id) { return __awaiter(void 0, void 0, void 0, function () {
2871
- var presenceCounter;
2872
- return __generator(this, function (_a) {
2873
- switch (_a.label) {
2874
- case 0:
2875
- if (presenceCounters.has(id)) {
2876
- return [2 /*return*/, presenceCounters.get(id)];
2877
- }
2878
- presenceCounter = new PresenceCounterImpl(host, id);
2879
- return [4 /*yield*/, presenceCounter.init()];
2880
- case 1:
2881
- _a.sent();
2882
- presenceCounters.set(id, presenceCounter);
2883
- return [2 /*return*/, presenceCounter];
2884
- }
2885
- });
2886
- }); }, function (_, id) { return id; });
2887
- function getPresenceCounter(project) {
2888
- return __awaiter(this, void 0, void 0, function () {
2889
- return __generator(this, function (_a) {
2890
- switch (_a.label) {
2891
- case 0:
2892
- if (!(project === undefined)) return [3 /*break*/, 2];
2893
- return [4 /*yield*/, getProject()];
2894
- case 1:
2895
- project = _a.sent();
2896
- _a.label = 2;
2897
- case 2: return [2 /*return*/, getPresenceCounterMemoized(project.context.sdk.options.host, project.id)];
2898
- }
2899
- });
2900
- });
2901
- }
2902
- function onPresenceCounterUpdate(presenceCounter, callback) {
2903
- presenceCounter.on('updated', callback);
2904
- return function () { return presenceCounter.off('updated', callback); };
2905
- }
2906
- function onPresenceCounterOpen(presenceCounter, callback) {
2907
- var handler = function (state) {
2908
- if (state === exports.PresenceCounterState.Opened) {
2909
- callback();
2910
- }
2911
- };
2912
- presenceCounter.on('state', handler);
2913
- return function () { return presenceCounter.off('state', handler); };
2914
- }
2915
- function onPresenceCounterClose(presenceCounter, callback) {
2916
- var handler = function (state) {
2917
- if (state === exports.PresenceCounterState.Closed) {
2918
- callback();
2919
- }
2920
- };
2921
- presenceCounter.on('state', handler);
2922
- return function () { return presenceCounter.off('state', handler); };
2923
- }
2924
-
2925
- exports.Answer = Answer;
2926
- exports.ElementImpl = ElementImpl;
2927
- exports.EventImpl = EventImpl;
2928
- exports.ProjectImpl = ProjectImpl;
2929
- exports.answer = answer;
2930
- exports.getConnect = getConnect;
2931
- exports.getConnectionHealth = getConnectionHealth;
2932
- exports.getElement = getElement;
2933
- exports.getElementMemoized = getElementMemoized;
2934
- exports.getElements = getElements;
2935
- exports.getElementsMemoized = getElementsMemoized;
2936
- exports.getEvent = getEvent;
2937
- exports.getEventMemoized = getEventMemoized;
2938
- exports.getEvents = getEvents;
2939
- exports.getEventsMemoized = getEventsMemoized;
2940
- exports.getPresenceCounter = getPresenceCounter;
2941
- exports.getProject = getProject;
2942
- exports.getProjectMemoized = getProjectMemoized;
2943
- exports.login = login;
2944
- exports.onConnectionHealthState = onConnectionHealthState;
2945
- exports.onElementPublished = onElementPublished;
2946
- exports.onElementResults = onElementResults;
2947
- exports.onElementRevoked = onElementRevoked;
2948
- exports.onElementStateChanged = onElementStateChanged;
2949
- exports.onElementUpdated = onElementUpdated;
2950
- exports.onEventAdded = onEventAdded;
2951
- exports.onEventPublished = onEventPublished;
2952
- exports.onEventRemoved = onEventRemoved;
2953
- exports.onEventState = onEventState;
2954
- exports.onEventUpdated = onEventUpdated;
2955
- exports.onPresenceCounterClose = onPresenceCounterClose;
2956
- exports.onPresenceCounterOpen = onPresenceCounterOpen;
2957
- exports.onPresenceCounterUpdate = onPresenceCounterUpdate;
2958
- exports.onProjectFieldsUpdated = onProjectFieldsUpdated;
2959
- exports.onProjectListingsUpdated = onProjectListingsUpdated;
2960
- exports.validateAnswer = validateAnswer;
2961
- //# sourceMappingURL=index.cjs.js.map