@monterosa/sdk-interact-kit 0.19.0-rc.6 → 2.0.0-rc.2

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