@monterosa/sdk-identify-kit 2.0.0-rc.1 → 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,1502 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var sdkCore = require('@monterosa/sdk-core');
6
- var sdkUtil = require('@monterosa/sdk-util');
7
- var sdkLauncherKit = require('@monterosa/sdk-launcher-kit');
8
- var sdkConnectKit = require('@monterosa/sdk-connect-kit');
9
- var sdkInteractInterop = require('@monterosa/sdk-interact-interop');
10
-
11
- /******************************************************************************
12
- Copyright (c) Microsoft Corporation.
13
-
14
- Permission to use, copy, modify, and/or distribute this software for any
15
- purpose with or without fee is hereby granted.
16
-
17
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
- PERFORMANCE OF THIS SOFTWARE.
24
- ***************************************************************************** */
25
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
26
-
27
- var extendStatics = function(d, b) {
28
- extendStatics = Object.setPrototypeOf ||
29
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
31
- return extendStatics(d, b);
32
- };
33
-
34
- function __extends(d, b) {
35
- if (typeof b !== "function" && b !== null)
36
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
37
- extendStatics(d, b);
38
- function __() { this.constructor = d; }
39
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40
- }
41
-
42
- var __assign = function() {
43
- __assign = Object.assign || function __assign(t) {
44
- for (var s, i = 1, n = arguments.length; i < n; i++) {
45
- s = arguments[i];
46
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
47
- }
48
- return t;
49
- };
50
- return __assign.apply(this, arguments);
51
- };
52
-
53
- function __awaiter(thisArg, _arguments, P, generator) {
54
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
55
- return new (P || (P = Promise))(function (resolve, reject) {
56
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
57
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
58
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
59
- step((generator = generator.apply(thisArg, _arguments || [])).next());
60
- });
61
- }
62
-
63
- function __generator(thisArg, body) {
64
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
65
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
66
- function verb(n) { return function (v) { return step([n, v]); }; }
67
- function step(op) {
68
- if (f) throw new TypeError("Generator is already executing.");
69
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
70
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
71
- if (y = 0, t) op = [op[0] & 2, t.value];
72
- switch (op[0]) {
73
- case 0: case 1: t = op; break;
74
- case 4: _.label++; return { value: op[1], done: false };
75
- case 5: _.label++; y = op[1]; op = [0]; continue;
76
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
77
- default:
78
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
79
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
80
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
81
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
82
- if (t[2]) _.ops.pop();
83
- _.trys.pop(); continue;
84
- }
85
- op = body.call(thisArg, _);
86
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
87
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
88
- }
89
- }
90
-
91
- function __spreadArray(to, from, pack) {
92
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
93
- if (ar || !(i in from)) {
94
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
95
- ar[i] = from[i];
96
- }
97
- }
98
- return to.concat(ar || Array.prototype.slice.call(from));
99
- }
100
-
101
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
102
- var e = new Error(message);
103
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
104
- };
105
-
106
- /**
107
- * @license
108
- * @monterosa/sdk-identify-kit
109
- *
110
- * Copyright © 2023-2026 Monterosa Productions Limited. All rights reserved.
111
- *
112
- * More details on the license can be found at https://www.monterosa.co/sdk/license
113
- */
114
- var _a;
115
- /**
116
- * @internal
117
- */
118
- var IdentifyEvent;
119
- (function (IdentifyEvent) {
120
- IdentifyEvent["StateUpdated"] = "state_updated";
121
- IdentifyEvent["LoginRequested"] = "login_requested";
122
- IdentifyEvent["LogoutRequested"] = "logout_requested";
123
- IdentifyEvent["SignatureUpdated"] = "signature_updated";
124
- IdentifyEvent["UserdataUpdated"] = "userdata_updated";
125
- IdentifyEvent["CredentialsUpdated"] = "credentials_updated";
126
- IdentifyEvent["EnmasseLogin"] = "enmasse_login";
127
- })(IdentifyEvent || (IdentifyEvent = {}));
128
- /**
129
- * Defines a set of error codes that may be encountered when using the
130
- * Identify kit of the Monterosa SDK.
131
- *
132
- * @example
133
- * ```javascript
134
- * try {
135
- * // some code that uses the IdentifyKit
136
- * } catch (err) {
137
- * if (err.code === IdentifyError.NoCredentials) {
138
- * // handle missing credentials error
139
- * } else if (err.code === IdentifyError.NotInitialised) {
140
- * // handle initialization error
141
- * } else {
142
- * // handle other error types
143
- * }
144
- * }
145
- * ```
146
- *
147
- * @remarks
148
- * - The `IdentifyError` enum provides a convenient way to handle errors
149
- * encountered when using the `IdentifyKit` module. By checking the code
150
- * property of the caught error against the values of the enum, the error
151
- * type can be determined and appropriate action taken.
152
- *
153
- * - The `IdentifyError` enum is not intended to be instantiated or extended.
154
- */
155
- exports.IdentifyError = void 0;
156
- (function (IdentifyError) {
157
- /**
158
- * Indicates an error occurred during the call to the extension API.
159
- */
160
- IdentifyError["ExtensionApiError"] = "extension_api_error";
161
- /**
162
- * Indicates the extension required by the IdentifyKit is not set up properly.
163
- */
164
- IdentifyError["ExtensionNotSetup"] = "extension_not_setup";
165
- /**
166
- * Indicates the user's authentication credentials are not available
167
- * or have expired.
168
- */
169
- IdentifyError["NoCredentials"] = "no_credentials";
170
- /**
171
- * Indicates the IdentifyKit has not been initialized properly.
172
- */
173
- IdentifyError["NotInitialised"] = "not_initialised";
174
- /**
175
- * Indicates an error occurred in the parent app.
176
- */
177
- IdentifyError["ParentAppError"] = "parent_app_error";
178
- /**
179
- * Indicates an unexpected or invalid login state was encountered.
180
- */
181
- IdentifyError["UnexpectedState"] = "unexpected_state";
182
- /**
183
- * Indicates there is no parent application to delegate to.
184
- */
185
- IdentifyError["NoParentApplication"] = "no_parent_application";
186
- /**
187
- * Indicates a timeout occurred when communicating with the parent app.
188
- */
189
- IdentifyError["ParentTimeoutError"] = "parent_timeout_error";
190
- })(exports.IdentifyError || (exports.IdentifyError = {}));
191
- /**
192
- * @internal
193
- */
194
- var IdentifyErrorMessages = (_a = {},
195
- _a[exports.IdentifyError.ExtensionApiError] = function (error) {
196
- return "Identify extension API returned an error: ".concat(error);
197
- },
198
- _a[exports.IdentifyError.ExtensionNotSetup] = function () {
199
- return 'Identify extension is not set up for this project';
200
- },
201
- _a[exports.IdentifyError.NoCredentials] = function () { return 'Identify credentials are not set'; },
202
- _a[exports.IdentifyError.NotInitialised] = function () { return 'Identify instance is not initialised'; },
203
- _a[exports.IdentifyError.ParentAppError] = function (error) {
204
- return "Parent application error: ".concat(error);
205
- },
206
- _a[exports.IdentifyError.UnexpectedState] = function (state) {
207
- return "Unexpected LoginState: ".concat(state);
208
- },
209
- _a[exports.IdentifyError.NoParentApplication] = function () {
210
- return 'No parent application available for delegation';
211
- },
212
- _a[exports.IdentifyError.ParentTimeoutError] = function (error) {
213
- return "Parent application timeout: ".concat(error, ". Please check if the identify-kit is imported on the parent page.");
214
- },
215
- _a);
216
- var IdentifyAction;
217
- (function (IdentifyAction) {
218
- IdentifyAction["Login"] = "identifyLogin";
219
- IdentifyAction["Logout"] = "identifyLogout";
220
- IdentifyAction["RequestLogin"] = "identifyRequestLogin";
221
- IdentifyAction["RequestLogout"] = "identifyRequestLogout";
222
- IdentifyAction["GetUserData"] = "identifyGetUserData";
223
- IdentifyAction["GetSessionSignature"] = "identifyGetSessionSignature";
224
- IdentifyAction["SetCredentials"] = "identifySetCredentials";
225
- IdentifyAction["ClearCredentials"] = "identifyClearCredentials";
226
- IdentifyAction["OnStateUpdated"] = "identifyOnStateUpdated";
227
- IdentifyAction["OnCredentialsUpdated"] = "identifyOnCredentialsUpdated";
228
- IdentifyAction["OnUserDataUpdated"] = "identifyOnUserDataUpdated";
229
- IdentifyAction["OnSessionSignatureUpdated"] = "identifyOnSessionSignatureUpdated";
230
- })(IdentifyAction || (IdentifyAction = {}));
231
-
232
- /**
233
- * @license
234
- * @monterosa/sdk-identify-kit
235
- *
236
- * Copyright © 2023 Monterosa Productions Limited. All rights reserved.
237
- *
238
- * More details on the license can be found at https://www.monterosa.co/sdk/license
239
- */
240
- var EXTENSION_ID = 'lvis-id-custom-tab';
241
- var SIGNATURE_TTL = 10000;
242
-
243
- /**
244
- * @license
245
- * @monterosa/sdk-identify-kit
246
- *
247
- * Copyright © 2023 Monterosa Productions Limited. All rights reserved.
248
- *
249
- * More details on the license can be found at https://www.monterosa.co/sdk/license
250
- */
251
- var Identify = /** @class */ (function (_super) {
252
- __extends(Identify, _super);
253
- function Identify(sdk, options) {
254
- if (options === void 0) { options = {}; }
255
- var _this = _super.call(this) || this;
256
- _this.sdk = sdk;
257
- _this.wasLoggedIn = false;
258
- _this._credentials = null;
259
- _this._signature = null;
260
- _this._userData = null;
261
- _this._state = {
262
- state: 'logged_out',
263
- };
264
- _this._options = __assign({ strategy: 'email', deviceId: sdkCore.getDeviceId(), version: 1, loginPolicy: 'disabled' }, options);
265
- return _this;
266
- }
267
- Identify.fetchIdentifyHost = function (host, projectId) {
268
- var _a, _b;
269
- return __awaiter(this, void 0, void 0, function () {
270
- var listings, extensionAssets, endpointAsset;
271
- return __generator(this, function (_c) {
272
- switch (_c.label) {
273
- case 0: return [4 /*yield*/, sdkInteractInterop.fetchListings(host, projectId)];
274
- case 1:
275
- listings = _c.sent();
276
- extensionAssets = (_b = (_a = listings.assets) === null || _a === void 0 ? void 0 : _a[EXTENSION_ID]) !== null && _b !== void 0 ? _b : [];
277
- endpointAsset = extensionAssets.find(function (_a) {
278
- var name = _a.name;
279
- return name === 'endpoint';
280
- });
281
- if (!endpointAsset) {
282
- throw sdkUtil.createError(exports.IdentifyError.ExtensionNotSetup, IdentifyErrorMessages);
283
- }
284
- return [2 /*return*/, endpointAsset.data];
285
- }
286
- });
287
- });
288
- };
289
- Object.defineProperty(Identify.prototype, "state", {
290
- get: function () {
291
- return this._state;
292
- },
293
- set: function (state) {
294
- if (this._state.state === state.state) {
295
- return;
296
- }
297
- switch (state.state) {
298
- case 'logged_in':
299
- this.wasLoggedIn = true;
300
- break;
301
- case 'logged_out':
302
- case 'error':
303
- this.wasLoggedIn = false;
304
- break;
305
- case 'pending':
306
- // preserve wasLoggedIn value during transitional state
307
- break;
308
- default: {
309
- // Exhaustiveness check: TypeScript errors if a new state is added
310
- // but not handled. This is a compile-time error.
311
- //
312
- // See: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#exhaustiveness-checking
313
- var exhaustiveCheck = state.state;
314
- throw sdkUtil.createError(exports.IdentifyError.UnexpectedState, IdentifyErrorMessages, String(exhaustiveCheck));
315
- }
316
- }
317
- this._state = state;
318
- this.emit(IdentifyEvent.StateUpdated, state);
319
- },
320
- enumerable: false,
321
- configurable: true
322
- });
323
- Object.defineProperty(Identify.prototype, "options", {
324
- get: function () {
325
- return this._options;
326
- },
327
- enumerable: false,
328
- configurable: true
329
- });
330
- Object.defineProperty(Identify.prototype, "signature", {
331
- get: function () {
332
- return this._signature;
333
- },
334
- set: function (signature) {
335
- var _this = this;
336
- if (this._signature === signature) {
337
- return;
338
- }
339
- this._signature = signature;
340
- clearTimeout(this.signatureExpireTimeout);
341
- if (signature !== null) {
342
- this.signatureExpireTimeout = setTimeout(function () {
343
- _this.signature = null;
344
- }, SIGNATURE_TTL);
345
- }
346
- this.emit(IdentifyEvent.SignatureUpdated, this.signature);
347
- },
348
- enumerable: false,
349
- configurable: true
350
- });
351
- Object.defineProperty(Identify.prototype, "credentials", {
352
- get: function () {
353
- return this._credentials;
354
- },
355
- set: function (credentials) {
356
- if (this._credentials === credentials) {
357
- return;
358
- }
359
- this._credentials = credentials;
360
- this.emit(IdentifyEvent.CredentialsUpdated, credentials);
361
- },
362
- enumerable: false,
363
- configurable: true
364
- });
365
- Object.defineProperty(Identify.prototype, "userData", {
366
- get: function () {
367
- return this._userData;
368
- },
369
- set: function (data) {
370
- if (this._userData === data) {
371
- return;
372
- }
373
- this._userData = data;
374
- clearTimeout(this.userDataExpireTimeout);
375
- this.emit(IdentifyEvent.UserdataUpdated, data);
376
- },
377
- enumerable: false,
378
- configurable: true
379
- });
380
- Object.defineProperty(Identify.prototype, "shouldLoginOnReconnect", {
381
- get: function () {
382
- return (this.wasLoggedIn &&
383
- this.options.loginPolicy === 'auto' &&
384
- this.credentials !== null);
385
- },
386
- enumerable: false,
387
- configurable: true
388
- });
389
- Identify.prototype.reset = function () {
390
- this.credentials = null;
391
- this.userData = null;
392
- this.signature = null;
393
- this.wasLoggedIn = false;
394
- };
395
- Identify.prototype.getUrl = function (path) {
396
- if (path === void 0) { path = ''; }
397
- return __awaiter(this, void 0, void 0, function () {
398
- var _a, host, projectId, _b, url, _c, version, deviceId, strategy, provider;
399
- return __generator(this, function (_d) {
400
- switch (_d.label) {
401
- case 0:
402
- _a = this.sdk.options, host = _a.host, projectId = _a.projectId;
403
- if (!(this.host === undefined)) return [3 /*break*/, 2];
404
- _b = this;
405
- return [4 /*yield*/, Identify.fetchIdentifyHost(host, projectId)];
406
- case 1:
407
- _b.host = _d.sent();
408
- _d.label = 2;
409
- case 2:
410
- url = new URL(this.host);
411
- _c = this._options, version = _c.version, deviceId = _c.deviceId, strategy = _c.strategy, provider = _c.provider;
412
- url.pathname = "/v".concat(version).concat(path);
413
- url.searchParams.set('projectId', projectId);
414
- url.searchParams.set('deviceId', deviceId);
415
- url.searchParams.set('strategy', strategy);
416
- if (provider !== undefined) {
417
- url.searchParams.set('provider', provider);
418
- }
419
- return [2 /*return*/, url.toString()];
420
- }
421
- });
422
- });
423
- };
424
- return Identify;
425
- }(sdkUtil.Emitter));
426
-
427
- /**
428
- * @license
429
- * @monterosa/sdk-identify-kit
430
- *
431
- * Copyright © 2025-2026 Monterosa Productions Limited. All rights reserved.
432
- *
433
- * More details on the license can be found at https://www.monterosa.co/sdk/license
434
- */
435
- var entries = new Map();
436
- function getExperiences() {
437
- return Array.from(entries.values()).map(function (entry) { return entry.experience; });
438
- }
439
- function addExperience(experience, unsubs) {
440
- if (unsubs === void 0) { unsubs = []; }
441
- entries.set(experience.id, {
442
- experience: experience,
443
- unsubs: new Set(unsubs),
444
- });
445
- }
446
- function deleteExperience(experience) {
447
- var entry = entries.get(experience.id);
448
- if (entry) {
449
- entry.unsubs.forEach(function (unsub) { return unsub(); });
450
- entries.delete(experience.id);
451
- }
452
- }
453
-
454
- /**
455
- * @license
456
- * identify-kit
457
- *
458
- * Copyright © 2023-2026 Monterosa Productions Limited. All rights reserved.
459
- *
460
- * More details on the license can be found at https://www.monterosa.co/sdk/license
461
- */
462
- var identifyKits = new Map();
463
- var identifyHooks = [];
464
- /**
465
- * @internal
466
- */
467
- var taskQueue = new sdkUtil.TaskQueue();
468
- function isSdk(value) {
469
- return value instanceof sdkCore.Sdk;
470
- }
471
- function api(url, token, method) {
472
- if (method === void 0) { method = 'GET'; }
473
- return __awaiter(this, void 0, void 0, function () {
474
- var headers, credentials, response, data;
475
- return __generator(this, function (_a) {
476
- switch (_a.label) {
477
- case 0:
478
- headers = {
479
- accept: 'application/json',
480
- };
481
- // Only include Authorization header for bearer token authentication
482
- // When token is 'cookie', use credentials: 'include' to ensure HttpOnly
483
- // cookies are sent
484
- if (token === 'cookie') {
485
- // Use credentials: 'include' to ensure HttpOnly cookies are sent
486
- credentials = 'include';
487
- }
488
- else {
489
- headers.Authorization = "Bearer ".concat(token);
490
- }
491
- return [4 /*yield*/, fetch(url, {
492
- method: method,
493
- headers: headers,
494
- credentials: credentials,
495
- })];
496
- case 1:
497
- response = _a.sent();
498
- return [4 /*yield*/, response.json()];
499
- case 2:
500
- data = (_a.sent());
501
- if (data.result < 0) {
502
- throw sdkUtil.createError(exports.IdentifyError.ExtensionApiError, IdentifyErrorMessages, data.message);
503
- }
504
- return [2 /*return*/, data];
505
- }
506
- });
507
- });
508
- }
509
- /**
510
- * @internal
511
- */
512
- function parentAppRequest(identify, action, payload) {
513
- var _a;
514
- return __awaiter(this, void 0, void 0, function () {
515
- var parentApp, _b, host, projectId, origin, response, _c, error, data, err_1, errorMessage;
516
- return __generator(this, function (_d) {
517
- switch (_d.label) {
518
- case 0:
519
- parentApp = sdkLauncherKit.getParentApplication();
520
- if (parentApp === null) {
521
- throw sdkUtil.createError(exports.IdentifyError.NoParentApplication, IdentifyErrorMessages);
522
- }
523
- _b = identify.sdk.options, host = _b.host, projectId = _b.projectId;
524
- origin = (_a = payload === null || payload === void 0 ? void 0 : payload.origin) !== null && _a !== void 0 ? _a : { host: host, projectId: projectId };
525
- _d.label = 1;
526
- case 1:
527
- _d.trys.push([1, 3, , 4]);
528
- return [4 /*yield*/, sdkLauncherKit.sendSdkRequest(parentApp, action, __assign(__assign({}, payload), { origin: origin }))];
529
- case 2:
530
- response = _d.sent();
531
- _c = response.payload, error = _c.error, data = _c.data;
532
- if (error !== undefined) {
533
- throw sdkUtil.createError(exports.IdentifyError.ParentAppError, IdentifyErrorMessages, error);
534
- }
535
- return [2 /*return*/, data];
536
- case 3:
537
- err_1 = _d.sent();
538
- if (err_1 instanceof sdkUtil.MonterosaError &&
539
- err_1.code === sdkLauncherKit.BridgeError.RequestTimeoutError) {
540
- errorMessage = sdkUtil.getErrorMessage(err_1);
541
- throw sdkUtil.createError(exports.IdentifyError.ParentTimeoutError, IdentifyErrorMessages, errorMessage);
542
- }
543
- throw err_1;
544
- case 4: return [2 /*return*/];
545
- }
546
- });
547
- });
548
- }
549
- /**
550
- * @internal
551
- */
552
- function registerIdentifyHook(hook) {
553
- identifyHooks.push(hook);
554
- }
555
- /**
556
- * @internal
557
- */
558
- function login(identify, credentials) {
559
- return __awaiter(this, void 0, void 0, function () {
560
- var signature, conn;
561
- return __generator(this, function (_a) {
562
- switch (_a.label) {
563
- case 0: return [4 /*yield*/, getSessionSignatureMemoized(identify, credentials)];
564
- case 1:
565
- signature = _a.sent();
566
- return [4 /*yield*/, sdkConnectKit.getConnect(identify.sdk.options.host)];
567
- case 2:
568
- conn = _a.sent();
569
- return [4 /*yield*/, sdkConnectKit.connect(conn)];
570
- case 3:
571
- _a.sent();
572
- return [4 /*yield*/, sdkConnectKit.login.apply(void 0, __spreadArray([conn], signature, false))];
573
- case 4:
574
- _a.sent();
575
- return [2 /*return*/];
576
- }
577
- });
578
- });
579
- }
580
- var loginWithRetry = sdkUtil.withRetryAsync(login);
581
- /**
582
- * @internal
583
- */
584
- function logout(identify) {
585
- return __awaiter(this, void 0, void 0, function () {
586
- var conn;
587
- return __generator(this, function (_a) {
588
- switch (_a.label) {
589
- case 0: return [4 /*yield*/, sdkConnectKit.getConnect(identify.sdk.options.host)];
590
- case 1:
591
- conn = _a.sent();
592
- return [4 /*yield*/, sdkConnectKit.connect(conn)];
593
- case 2:
594
- _a.sent();
595
- return [4 /*yield*/, sdkConnectKit.logout(conn)];
596
- case 3:
597
- _a.sent();
598
- return [2 /*return*/];
599
- }
600
- });
601
- });
602
- }
603
- var logoutWithRetry = sdkUtil.withRetryAsync(logout);
604
- /**
605
- * @internal
606
- */
607
- function loginTask(identify, credentials) {
608
- return __awaiter(this, void 0, void 0, function () {
609
- var err_2;
610
- return __generator(this, function (_a) {
611
- switch (_a.label) {
612
- case 0:
613
- _a.trys.push([0, 2, , 3]);
614
- identify.state = {
615
- state: 'pending',
616
- };
617
- return [4 /*yield*/, loginWithRetry(identify, credentials)];
618
- case 1:
619
- _a.sent();
620
- // Update state only if there are no pending tasks in the queue
621
- if (taskQueue.isEmpty()) {
622
- identify.state = {
623
- state: 'logged_in',
624
- };
625
- }
626
- return [3 /*break*/, 3];
627
- case 2:
628
- err_2 = _a.sent();
629
- taskQueue.clear();
630
- identify.state = {
631
- state: 'error',
632
- error: err_2 instanceof Error ? err_2.message : 'Unknown error',
633
- errorType: 'login',
634
- };
635
- return [3 /*break*/, 3];
636
- case 3: return [2 /*return*/];
637
- }
638
- });
639
- });
640
- }
641
- /**
642
- * @internal
643
- */
644
- function logoutTask(identify) {
645
- return __awaiter(this, void 0, void 0, function () {
646
- var err_3;
647
- return __generator(this, function (_a) {
648
- switch (_a.label) {
649
- case 0:
650
- _a.trys.push([0, 2, , 3]);
651
- identify.state = {
652
- state: 'pending',
653
- };
654
- return [4 /*yield*/, logoutWithRetry(identify)];
655
- case 1:
656
- _a.sent();
657
- // Update state only if there are no pending tasks in the queue
658
- if (taskQueue.isEmpty()) {
659
- identify.state = {
660
- state: 'logged_out',
661
- };
662
- }
663
- return [3 /*break*/, 3];
664
- case 2:
665
- err_3 = _a.sent();
666
- taskQueue.clear();
667
- identify.state = {
668
- state: 'error',
669
- error: err_3 instanceof Error ? err_3.message : 'Unknown error',
670
- errorType: 'logout',
671
- };
672
- return [3 /*break*/, 3];
673
- case 3: return [2 /*return*/];
674
- }
675
- });
676
- });
677
- }
678
- /**
679
- * @internal
680
- */
681
- function enqueueLogin(identify, credentials, prioritise) {
682
- if (prioritise === void 0) { prioritise = false; }
683
- if (identify.options.loginPolicy === 'auto') {
684
- if (prioritise) {
685
- taskQueue.enqueueFront(function () { return loginTask(identify, credentials); });
686
- }
687
- else {
688
- taskQueue.enqueue(function () { return loginTask(identify, credentials); });
689
- }
690
- }
691
- for (var _i = 0, _a = getExperiences(); _i < _a.length; _i++) {
692
- var experience = _a[_i];
693
- sdkLauncherKit.sendSdkMessage(experience, IdentifyAction.Login, credentials);
694
- }
695
- }
696
- /**
697
- * @internal
698
- */
699
- function enqueueLogout(identify) {
700
- if (identify.options.loginPolicy === 'auto') {
701
- taskQueue.enqueue(function () { return logoutTask(identify); });
702
- }
703
- for (var _i = 0, _a = getExperiences(); _i < _a.length; _i++) {
704
- var experience = _a[_i];
705
- sdkLauncherKit.sendSdkMessage(experience, IdentifyAction.Logout);
706
- }
707
- }
708
- function getIdentify(sdkOrOptions, options) {
709
- var sdk;
710
- var identifyOptions;
711
- if (isSdk(sdkOrOptions)) {
712
- /**
713
- * Interface: getIdentify(sdk, options?)
714
- */
715
- sdk = sdkOrOptions;
716
- if (options !== undefined) {
717
- identifyOptions = options;
718
- }
719
- else {
720
- identifyOptions = {};
721
- }
722
- }
723
- else if (sdkOrOptions !== undefined) {
724
- /**
725
- * Interface: getIdentify(options)
726
- */
727
- sdk = sdkCore.getSdk();
728
- identifyOptions = sdkOrOptions;
729
- }
730
- else {
731
- /**
732
- * Interface: getIdentify()
733
- */
734
- sdk = sdkCore.getSdk();
735
- identifyOptions = {};
736
- }
737
- var projectId = sdk.options.projectId;
738
- if (identifyKits.has(projectId)) {
739
- return identifyKits.get(projectId);
740
- }
741
- var identify = new Identify(sdk, identifyOptions);
742
- for (var _i = 0, identifyHooks_1 = identifyHooks; _i < identifyHooks_1.length; _i++) {
743
- var hook = identifyHooks_1[_i];
744
- hook(identify);
745
- }
746
- watchConnectionStatus(identify);
747
- identifyKits.set(projectId, identify);
748
- return identify;
749
- }
750
- /**
751
- * A function that requests a user login via the `IdentifyKit` of the Monterosa SDK.
752
- *
753
- * @example
754
- * ```javascript
755
- * import { configure } from '@monterosa/sdk-core';
756
- * import { getIdentify, requestLogin } from '@monterosa/sdk-identify-kit';
757
- *
758
- * configure({ host: '...', projectId: '...' });
759
- *
760
- * try {
761
- * const identify = getIdentify();
762
- *
763
- * await requestLogin(identify);
764
- *
765
- * console.log('Login request successful');
766
- * } catch (err) {
767
- * console.error('Error requesting login:', error.message)
768
- * }
769
- * ```
770
- *
771
- * @remarks
772
- * - If the app is running within a third-party application that uses
773
- * the Monterosa SDK, the function delegates to the parent app
774
- * to handle the login process.
775
- *
776
- * @param identify - An instance of the `IdentifyKit` class used for user
777
- * identification.
778
- * @returns A Promise that resolves with `void` when the login request
779
- * is completed.
780
- */
781
- function requestLogin(identify) {
782
- return __awaiter(this, void 0, void 0, function () {
783
- var parentApp;
784
- return __generator(this, function (_a) {
785
- switch (_a.label) {
786
- case 0:
787
- parentApp = sdkLauncherKit.getParentApplication();
788
- if (!(parentApp !== null)) return [3 /*break*/, 2];
789
- return [4 /*yield*/, parentAppRequest(identify, IdentifyAction.RequestLogin)];
790
- case 1:
791
- _a.sent();
792
- return [2 /*return*/];
793
- case 2:
794
- identify.emit(IdentifyEvent.LoginRequested);
795
- return [2 /*return*/];
796
- }
797
- });
798
- });
799
- }
800
- /**
801
- * A function that requests a user login via the `IdentifyKit` of the Space.
802
- *
803
- * @example
804
- * ```javascript
805
- * import { getSpace } from '@monterosa/sdk-core';
806
- * import { getIdentify, requestLogout } from '@monterosa/sdk-identify-kit';
807
- *
808
- * const space = getSpace('host', 'space-id');
809
- * const identify = getIdentify(space);
810
- *
811
- * try {
812
- * await requestLogout(identify);
813
- *
814
- * console.log('Logout request successful');
815
- * } catch (err) {
816
- * console.error('Error requesting logout:', error.message)
817
- * }
818
- * ```
819
- *
820
- * @remarks
821
- * - If the app is running within a third-party application that uses
822
- * the Space, the function delegates to the parent app
823
- * to handle the logout process.
824
- *
825
- * @param identify - An instance of the `IdentifyKit` class used for user
826
- * identification.
827
- * @returns A Promise that resolves with `void` when the logout request
828
- * is completed.
829
- */
830
- function requestLogout(identify) {
831
- return __awaiter(this, void 0, void 0, function () {
832
- var parentApp;
833
- return __generator(this, function (_a) {
834
- switch (_a.label) {
835
- case 0:
836
- parentApp = sdkLauncherKit.getParentApplication();
837
- if (!(parentApp !== null)) return [3 /*break*/, 2];
838
- return [4 /*yield*/, parentAppRequest(identify, IdentifyAction.RequestLogout)];
839
- case 1:
840
- _a.sent();
841
- return [2 /*return*/];
842
- case 2:
843
- identify.emit(IdentifyEvent.LogoutRequested);
844
- return [2 /*return*/];
845
- }
846
- });
847
- });
848
- }
849
- /**
850
- * @internal
851
- *
852
- * Internal function to get a fresh session signature.
853
- * This function does not handle errors — callers are responsible
854
- * for catching and handling failures.
855
- *
856
- * @param identify - An instance of the `IdentifyKit` class used for user
857
- * identification.
858
- * @param credentials - The credentials of the user.
859
- *
860
- * @returns A Promise that resolves to a `Signature` object.
861
- */
862
- function getSessionSignature(identify, credentials) {
863
- return __awaiter(this, void 0, void 0, function () {
864
- var parentApp, signature_1, url, data, signature;
865
- return __generator(this, function (_a) {
866
- switch (_a.label) {
867
- case 0:
868
- parentApp = sdkLauncherKit.getParentApplication();
869
- if (!(parentApp !== null)) return [3 /*break*/, 2];
870
- return [4 /*yield*/, parentAppRequest(identify, IdentifyAction.GetSessionSignature, credentials)];
871
- case 1:
872
- signature_1 = _a.sent();
873
- return [2 /*return*/, signature_1];
874
- case 2:
875
- if (identify.signature !== null) {
876
- return [2 /*return*/, identify.signature];
877
- }
878
- return [4 /*yield*/, identify.getUrl('/user/check')];
879
- case 3:
880
- url = _a.sent();
881
- return [4 /*yield*/, api(url, credentials.token)];
882
- case 4:
883
- data = (_a.sent()).data;
884
- signature = [data.userId, data.timeStamp, data.signature];
885
- identify.signature = signature;
886
- return [2 /*return*/, signature];
887
- }
888
- });
889
- });
890
- }
891
- /**
892
- * A memoized version of the `getSessionSignature` function.
893
- */
894
- var getSessionSignatureMemoized = sdkUtil.memoizePromise(getSessionSignature, function (identify, credentials) { return credentials.token; }, {
895
- clearOnResolve: true,
896
- clearOnReject: true,
897
- });
898
- /**
899
- * The function that takes an instance of `IdentifyKit` as its argument and
900
- * returns a Promise that resolves to a key-value object representing user data.
901
- *
902
- * @example
903
- * ```javascript
904
- * import { configure } from '@monterosa/sdk-core';
905
- * import { getIdentify, getUserData } from '@monterosa/sdk-identify-kit';
906
- *
907
- * configure({ host: '...', projectId: '...' });
908
- *
909
- * const identify = getIdentify();
910
- * const userData = await getUserData(identify);
911
- *
912
- * console.log('User data:', userData);
913
- * ```
914
- *
915
- * @remarks
916
- * - If the app is running within a third-party application that uses
917
- * the Monterosa SDK, the function delegates to the parent app
918
- * to get user data.
919
- *
920
- * - If the request is successful, the function resolves with a key-value object
921
- * representing user data. If not, a `MonterosaError` is thrown.
922
- *
923
- * @param identify - An instance of `IdentifyKit` that provides the user
924
- * identification functionality.
925
- * @returns A Promise that resolves to a key-value object representing user data.
926
- * The structure and content of the user data object depend on the identify
927
- * service provider and may vary. It typically contains information about the user,
928
- * but the specific fields are determined by the Identify service provider.
929
- */
930
- function getUserData(identify) {
931
- return __awaiter(this, void 0, void 0, function () {
932
- var parentApp, userData, url, data;
933
- return __generator(this, function (_a) {
934
- switch (_a.label) {
935
- case 0:
936
- parentApp = sdkLauncherKit.getParentApplication();
937
- if (!(parentApp !== null)) return [3 /*break*/, 2];
938
- return [4 /*yield*/, parentAppRequest(identify, IdentifyAction.GetUserData)];
939
- case 1:
940
- userData = _a.sent();
941
- return [2 /*return*/, userData];
942
- case 2:
943
- // Return cached user data if available
944
- if (identify.userData !== null) {
945
- return [2 /*return*/, identify.userData];
946
- }
947
- if (identify.credentials === null) {
948
- throw sdkUtil.createError(exports.IdentifyError.NoCredentials, IdentifyErrorMessages);
949
- }
950
- return [4 /*yield*/, identify.getUrl('/user')];
951
- case 3:
952
- url = _a.sent();
953
- return [4 /*yield*/, api(url, identify.credentials.token)];
954
- case 4:
955
- data = (_a.sent()).data;
956
- identify.userData = data;
957
- return [2 /*return*/, data];
958
- }
959
- });
960
- });
961
- }
962
- /**
963
- * Sets the user's authentication credentials.
964
- *
965
- * @example
966
- * ```javascript
967
- * import { configure } from '@monterosa/sdk-core';
968
- * import { getIdentify, setCredentials } from '@monterosa/sdk-identify-kit';
969
- *
970
- * configure({ host: '...', projectId: '...' });
971
- *
972
- * const credentials = { token: 'abc123' };
973
- * const identify = getIdentify();
974
- *
975
- * await setCredentials(identify, credentials)
976
- * ```
977
- *
978
- * @remarks
979
- * - If the app is running within a third-party application that uses
980
- * the Monterosa SDK, the function delegates to the parent app
981
- * to set user credentials.
982
- *
983
- * - If the request is successful, the function resolves to `void`.
984
- * If not, a `MonterosaError` is thrown.
985
- *
986
- * @param identify - An instance of `IdentifyKit` that provides the user
987
- * identification functionality.
988
- * @param credentials - An object representing the user's authentication
989
- * credentials.
990
- * @returns A Promise that resolves to `void`.
991
- */
992
- function setCredentials(identify, credentials) {
993
- return __awaiter(this, void 0, void 0, function () {
994
- var parentApp, shouldLogin;
995
- return __generator(this, function (_a) {
996
- switch (_a.label) {
997
- case 0:
998
- parentApp = sdkLauncherKit.getParentApplication();
999
- if (!(parentApp !== null)) return [3 /*break*/, 2];
1000
- return [4 /*yield*/, parentAppRequest(identify, IdentifyAction.SetCredentials, credentials)];
1001
- case 1:
1002
- _a.sent();
1003
- return [2 /*return*/];
1004
- case 2:
1005
- shouldLogin = identify.credentials === null;
1006
- identify.credentials = credentials;
1007
- if (shouldLogin) {
1008
- enqueueLogin(identify, credentials);
1009
- }
1010
- return [2 /*return*/];
1011
- }
1012
- });
1013
- });
1014
- }
1015
- /**
1016
- * Clears the user's authentication credentials.
1017
- *
1018
- * @example
1019
- * ```javascript
1020
- * import { configure } from '@monterosa/sdk-core';
1021
- * import { getIdentify, clearCredentials } from '@monterosa/sdk-identify-kit';
1022
- *
1023
- * configure({ host: '...', projectId: '...' });
1024
- *
1025
- * const identify = getIdentify();
1026
- *
1027
- * await clearCredentials(identify);
1028
- * ```
1029
- *
1030
- * @remarks
1031
- * - If the app is running within a third-party application that uses
1032
- * the Monterosa SDK, the function delegates to the parent app
1033
- * to clear user credentials.
1034
- *
1035
- * - If the request is successful, the function resolves to `void`.
1036
- * If not, a `MonterosaError` is thrown.
1037
- *
1038
- * @param identify - An instance of `IdentifyKit` that provides the user
1039
- * identification functionality.
1040
- * @returns A Promise that resolves to `void`.
1041
- */
1042
- function clearCredentials(identify) {
1043
- return __awaiter(this, void 0, void 0, function () {
1044
- var parentApp, shouldLogout;
1045
- return __generator(this, function (_a) {
1046
- switch (_a.label) {
1047
- case 0:
1048
- parentApp = sdkLauncherKit.getParentApplication();
1049
- if (!(parentApp !== null)) return [3 /*break*/, 2];
1050
- return [4 /*yield*/, parentAppRequest(identify, IdentifyAction.ClearCredentials)];
1051
- case 1:
1052
- _a.sent();
1053
- return [2 /*return*/];
1054
- case 2:
1055
- shouldLogout = identify.credentials !== null;
1056
- identify.credentials = null;
1057
- identify.userData = null;
1058
- identify.signature = null;
1059
- if (shouldLogout) {
1060
- enqueueLogout(identify);
1061
- }
1062
- return [2 /*return*/];
1063
- }
1064
- });
1065
- });
1066
- }
1067
- /**
1068
- * Registers a callback function that will be called whenever the `LoginState`
1069
- * object associated with the `IdentifyKit` instance is updated.
1070
- *
1071
- * @example
1072
- * ```javascript
1073
- * import { configure } from '@monterosa/sdk-core';
1074
- * import { getIdentify, onStateUpdated } from '@monterosa/sdk-identify-kit';
1075
- *
1076
- * configure({ host: '...', projectId: '...' });
1077
- *
1078
- * const identify = getIdentify();
1079
- *
1080
- * const unsubscribe = onStateUpdated(identify, (state) => {
1081
- * console.log("State updated:", state);
1082
- * });
1083
- *
1084
- * // Call unsubscribe() to unregister the callback function
1085
- * // unsubscribe();
1086
- * ```
1087
- *
1088
- * @param identify - An instance of `IdentifyKit` that provides the user
1089
- * identification functionality.
1090
- * @param callback - The callback function to register. This function will be
1091
- * called with the updated `LoginState` object as its only argument.
1092
- * @returns An `Unsubscribe` function that can be called to unregister
1093
- * the callback function.
1094
- */
1095
- function onStateUpdated(identify, callback) {
1096
- return sdkUtil.subscribe(identify, IdentifyEvent.StateUpdated, callback);
1097
- }
1098
- /**
1099
- * Registers a callback function that will be called whenever the `Credentials`
1100
- * object associated with the `IdentifyKit` instance is updated.
1101
- *
1102
- * @example
1103
- * ```javascript
1104
- * import { configure } from '@monterosa/sdk-core';
1105
- * import { getIdentify, onCredentialsUpdated } from '@monterosa/sdk-identify-kit';
1106
- *
1107
- * configure({ host: '...', projectId: '...' });
1108
- *
1109
- * const identify = getIdentify();
1110
- *
1111
- * const unsubscribe = onCredentialsUpdated(identify, (credentials) => {
1112
- * if (credentials !== null) {
1113
- * console.log("Credentials updated:", credentials);
1114
- * } else {
1115
- * console.log("Credentials cleared.");
1116
- * }
1117
- * });
1118
- *
1119
- * // Call unsubscribe() to unregister the callback function
1120
- * // unsubscribe();
1121
- * ```
1122
- *
1123
- * @param identify - An instance of `IdentifyKit` that provides the user
1124
- * identification functionality.
1125
- * @param callback - The callback function to register. This function will be
1126
- * called with the updated `Credentials` object as its only argument.
1127
- * If the value `null` is received, it indicates that the signature has
1128
- * been cleared
1129
- * @returns An `Unsubscribe` function that can be called to unregister
1130
- * the callback function.
1131
- */
1132
- function onCredentialsUpdated(identify, callback) {
1133
- return sdkUtil.subscribe(identify, IdentifyEvent.CredentialsUpdated, callback);
1134
- }
1135
- /**
1136
- * Registers a callback function that will be called whenever the `Signature`
1137
- * object associated with the `IdentifyKit` instance is updated.
1138
- *
1139
- * @example
1140
- * ```javascript
1141
- * import { configure } from '@monterosa/sdk-core';
1142
- * import { getIdentify, onSignatureUpdated } from '@monterosa/sdk-identify-kit';
1143
- *
1144
- * configure({ host: '...', projectId: '...' });
1145
- *
1146
- * const identify = getIdentify();
1147
- *
1148
- * const unsubscribe = onSignatureUpdated(identify, (signature) => {
1149
- * if (signature !== null) {
1150
- * console.log("Signature updated:", signature);
1151
- * } else {
1152
- * console.log("Signature cleared.");
1153
- * }
1154
- * });
1155
- *
1156
- * // Call unsubscribe() to unregister the callback function
1157
- * // unsubscribe();
1158
- * ```
1159
- *
1160
- * @param identify - An instance of `IdentifyKit` that provides the user
1161
- * identification functionality.
1162
- * @param callback - The callback function to register. This function will be
1163
- * called with the updated `Signature` object as its only argument.
1164
- * If the value `null` is received, it indicates that the signature has
1165
- * been cleared
1166
- * @returns An `Unsubscribe` function that can be called to unregister
1167
- * the callback function.
1168
- */
1169
- function onSignatureUpdated(identify, callback) {
1170
- return sdkUtil.subscribe(identify, IdentifyEvent.SignatureUpdated, callback);
1171
- }
1172
- /**
1173
- * Registers a callback function that will be called whenever the `UserData`
1174
- * object associated with the `IdentifyKit` instance is updated.
1175
- *
1176
- * @example
1177
- * ```javascript
1178
- * import { configure } from '@monterosa/sdk-core';
1179
- * import { getIdentify, onUserDataUpdated } from '@monterosa/sdk-identify-kit';
1180
- *
1181
- * configure({ host: '...', projectId: '...' });
1182
- *
1183
- * const identify = getIdentify();
1184
- *
1185
- * const unsubscribe = onUserDataUpdated(identify, (userData) => {
1186
- * if (userData !== null) {
1187
- * console.log("User's data updated:", userData);
1188
- * } else {
1189
- * console.log("User's data cleared.");
1190
- * }
1191
- * });
1192
- *
1193
- * // Call unsubscribe() to unregister the callback function
1194
- * // unsubscribe();
1195
- * ```
1196
- *
1197
- * @param identify - An instance of `IdentifyKit` that provides the user
1198
- * identification functionality.
1199
- * @param callback - The callback function to register. This function will be
1200
- * called with the updated `UserData` object as its only argument.
1201
- * If the value `null` is received, it indicates that the user's data has
1202
- * been cleared
1203
- * @returns An `Unsubscribe` function that can be called to unregister
1204
- * the callback function.
1205
- */
1206
- function onUserDataUpdated(identify, callback) {
1207
- return sdkUtil.subscribe(identify, IdentifyEvent.UserdataUpdated, callback);
1208
- }
1209
- /**
1210
- * Registers a callback function that will be called when a login is requested
1211
- * by an Experience.
1212
- *
1213
- * @example
1214
- * ```javascript
1215
- * import { configure } from '@monterosa/sdk-core';
1216
- * import { getIdentify, onLoginRequestedByExperience } from '@monterosa/sdk-identify-kit';
1217
- *
1218
- * configure({ host: '...', projectId: '...' });
1219
- *
1220
- * const identify = getIdentify();
1221
- *
1222
- * const unsubscribe = onLoginRequestedByExperience(identify, () => {
1223
- * showLoginForm();
1224
- * });
1225
- *
1226
- * // Call unsubscribe() to unregister the callback function
1227
- * // unsubscribe();
1228
- * ```
1229
- *
1230
- * @param identify - An instance of `IdentifyKit` that provides the user
1231
- * identification functionality.
1232
- * @param callback - The callback function to register. This function will
1233
- * be called when a login is requested by an experience.
1234
- * @returns An `Unsubscribe` function that can be called to unregister
1235
- * the callback function.
1236
- */
1237
- function onLoginRequestedByExperience(identify, callback) {
1238
- return sdkUtil.subscribe(identify, IdentifyEvent.LoginRequested, callback);
1239
- }
1240
- /**
1241
- * Registers a callback function that will be called when a logout is requested
1242
- * by an Experience.
1243
- *
1244
- * @example
1245
- * ```javascript
1246
- * import { getSpace } from '@monterosa/sdk-core';
1247
- * import { getIdentify, onLogoutRequestedByExperience } from '@monterosa/sdk-identify-kit';
1248
- *
1249
- * const space = getSpace('host', 'space-id');
1250
- * const identify = getIdentify(space);
1251
- *
1252
- * const unsubscribe = onLogoutRequestedByExperience(identify, () => {
1253
- * // logout requested by experience
1254
- * // perform logout from Auth service
1255
- * });
1256
- *
1257
- * // Call unsubscribe() to unregister the callback function
1258
- * // unsubscribe();
1259
- * ```
1260
- *
1261
- * @param identify - An instance of `IdentifyKit` that provides the user
1262
- * identification functionality.
1263
- * @param callback - The callback function to register. This function will
1264
- * be called when a logout is requested by an experience.
1265
- * @returns An `Unsubscribe` function that can be called to unregister
1266
- * the callback function.
1267
- */
1268
- function onLogoutRequestedByExperience(identify, callback) {
1269
- return sdkUtil.subscribe(identify, IdentifyEvent.LogoutRequested, callback);
1270
- }
1271
- /**
1272
- *
1273
- * @internal
1274
- */
1275
- function watchConnectionStatus(identify) {
1276
- return __awaiter(this, void 0, void 0, function () {
1277
- var conn;
1278
- return __generator(this, function (_a) {
1279
- switch (_a.label) {
1280
- case 0: return [4 /*yield*/, sdkConnectKit.getConnect(identify.sdk.options.host)];
1281
- case 1:
1282
- conn = _a.sent();
1283
- sdkConnectKit.onConnected(conn, function () {
1284
- if (identify.shouldLoginOnReconnect) {
1285
- enqueueLogin(identify, identify.credentials, true);
1286
- }
1287
- taskQueue.resume();
1288
- });
1289
- sdkConnectKit.onConnecting(conn, function () {
1290
- taskQueue.pause();
1291
- // If the user was logged in before the connection loss, set the state
1292
- // to pending to notify that the user is no longer logged in and a login
1293
- // attempt will be made when the connection is restored.
1294
- if (identify.state.state === 'logged_in') {
1295
- identify.state = {
1296
- state: 'pending',
1297
- };
1298
- }
1299
- });
1300
- sdkConnectKit.onDisconnected(conn, function () {
1301
- taskQueue.pause();
1302
- taskQueue.clear();
1303
- // If the user was logged in before the connection loss, set the state
1304
- // to logged_out to notify that the user is no longer logged in.
1305
- if (identify.state.state === 'logged_in') {
1306
- identify.state = {
1307
- state: 'logged_out',
1308
- };
1309
- }
1310
- });
1311
- return [2 /*return*/];
1312
- }
1313
- });
1314
- });
1315
- }
1316
-
1317
- /**
1318
- * @license
1319
- * @monterosa/sdk-identify-kit
1320
- *
1321
- * Copyright © 2023-2026 Monterosa Productions Limited. All rights reserved.
1322
- *
1323
- * More details on the license can be found at https://www.monterosa.co/sdk/license
1324
- */
1325
- /**
1326
- * @internal
1327
- */
1328
- function parentMessagesHook(identify) {
1329
- var _this = this;
1330
- var parentApp = sdkLauncherKit.getParentApplication();
1331
- if (parentApp === null) {
1332
- return function () { };
1333
- }
1334
- return sdkLauncherKit.onSdkMessage(parentApp, function (message) { return __awaiter(_this, void 0, void 0, function () {
1335
- return __generator(this, function (_a) {
1336
- switch (message.action) {
1337
- case IdentifyAction.OnCredentialsUpdated: {
1338
- identify.credentials = message.payload.data;
1339
- break;
1340
- }
1341
- case IdentifyAction.OnSessionSignatureUpdated: {
1342
- identify.signature = message.payload.data;
1343
- break;
1344
- }
1345
- case IdentifyAction.OnUserDataUpdated: {
1346
- identify.userData = message.payload.data;
1347
- break;
1348
- }
1349
- case IdentifyAction.Login: {
1350
- enqueueLogin(identify, message.payload);
1351
- break;
1352
- }
1353
- case IdentifyAction.Logout: {
1354
- enqueueLogout(identify);
1355
- break;
1356
- }
1357
- }
1358
- return [2 /*return*/];
1359
- });
1360
- }); });
1361
- }
1362
- /**
1363
- * Finds an existing SDK with matching projectId, or creates a new one.
1364
- */
1365
- function getOrConfigureSdk(host, projectId) {
1366
- var existingSdk = sdkCore.getSdks().find(function (sdk) { return sdk.options.projectId === projectId; });
1367
- return existingSdk !== null && existingSdk !== void 0 ? existingSdk : sdkCore.configure({ host: host, projectId: projectId }, projectId);
1368
- }
1369
- /**
1370
- * @internal
1371
- */
1372
- function handleExperienceEmbedded(experience) {
1373
- var _this = this;
1374
- var identify = getIdentify(experience.sdk);
1375
- // Send login action with current credentials to the new experience if available.
1376
- // The bridge queues this message until the experience is initialised.
1377
- if (identify.credentials) {
1378
- sdkLauncherKit.sendSdkMessage(experience, IdentifyAction.Login, identify.credentials);
1379
- }
1380
- var credentialsUpdatedUnsub = onCredentialsUpdated(identify, function (data) {
1381
- sdkLauncherKit.sendSdkMessage(experience, IdentifyAction.OnCredentialsUpdated, {
1382
- data: data,
1383
- });
1384
- });
1385
- var signatureUpdatedUnsub = onSignatureUpdated(identify, function (data) {
1386
- sdkLauncherKit.sendSdkMessage(experience, IdentifyAction.OnSessionSignatureUpdated, {
1387
- data: data,
1388
- });
1389
- });
1390
- var userDataUpdatedUnsub = onUserDataUpdated(identify, function (data) {
1391
- sdkLauncherKit.sendSdkMessage(experience, IdentifyAction.OnUserDataUpdated, {
1392
- data: data,
1393
- });
1394
- });
1395
- var sdkMessageUnsub = sdkLauncherKit.onSdkMessage(experience, function (message) { return __awaiter(_this, void 0, void 0, function () {
1396
- var origin, originSdk, originIdentify, respond, _a, data, signature, err_1;
1397
- return __generator(this, function (_b) {
1398
- switch (_b.label) {
1399
- case 0:
1400
- if (!Object.values(IdentifyAction).includes(message.action)) {
1401
- return [2 /*return*/];
1402
- }
1403
- origin = message.payload.origin;
1404
- originSdk = origin
1405
- ? getOrConfigureSdk(origin.host, origin.projectId)
1406
- : experience.sdk;
1407
- originIdentify = getIdentify(originSdk);
1408
- respond = function (payload) {
1409
- return sdkLauncherKit.respondToSdkMessage(experience, message, payload);
1410
- };
1411
- _b.label = 1;
1412
- case 1:
1413
- _b.trys.push([1, 15, , 16]);
1414
- _a = message.action;
1415
- switch (_a) {
1416
- case IdentifyAction.RequestLogin: return [3 /*break*/, 2];
1417
- case IdentifyAction.RequestLogout: return [3 /*break*/, 4];
1418
- case IdentifyAction.GetUserData: return [3 /*break*/, 6];
1419
- case IdentifyAction.GetSessionSignature: return [3 /*break*/, 8];
1420
- case IdentifyAction.SetCredentials: return [3 /*break*/, 10];
1421
- case IdentifyAction.ClearCredentials: return [3 /*break*/, 12];
1422
- }
1423
- return [3 /*break*/, 14];
1424
- case 2: return [4 /*yield*/, requestLogin(originIdentify)];
1425
- case 3:
1426
- _b.sent();
1427
- respond();
1428
- return [3 /*break*/, 14];
1429
- case 4: return [4 /*yield*/, requestLogout(identify)];
1430
- case 5:
1431
- _b.sent();
1432
- respond();
1433
- return [3 /*break*/, 14];
1434
- case 6: return [4 /*yield*/, getUserData(identify)];
1435
- case 7:
1436
- data = _b.sent();
1437
- respond({ data: data });
1438
- return [3 /*break*/, 14];
1439
- case 8: return [4 /*yield*/, getSessionSignatureMemoized(identify, message.payload)];
1440
- case 9:
1441
- signature = _b.sent();
1442
- respond({ data: signature });
1443
- return [3 /*break*/, 14];
1444
- case 10: return [4 /*yield*/, setCredentials(originIdentify, {
1445
- token: message.payload.token,
1446
- })];
1447
- case 11:
1448
- _b.sent();
1449
- respond();
1450
- return [3 /*break*/, 14];
1451
- case 12: return [4 /*yield*/, clearCredentials(identify)];
1452
- case 13:
1453
- _b.sent();
1454
- respond();
1455
- return [3 /*break*/, 14];
1456
- case 14: return [3 /*break*/, 16];
1457
- case 15:
1458
- err_1 = _b.sent();
1459
- respond({
1460
- error: sdkUtil.getErrorMessage(err_1),
1461
- });
1462
- return [3 /*break*/, 16];
1463
- case 16: return [2 /*return*/];
1464
- }
1465
- });
1466
- }); });
1467
- addExperience(experience, [
1468
- credentialsUpdatedUnsub,
1469
- signatureUpdatedUnsub,
1470
- userDataUpdatedUnsub,
1471
- sdkMessageUnsub,
1472
- ]);
1473
- }
1474
- /**
1475
- * @internal
1476
- */
1477
- function handleExperienceUnmounted(experience) {
1478
- deleteExperience(experience);
1479
- }
1480
- sdkLauncherKit.onStateChanged(function (experience, state) {
1481
- if (state === 'mounted') {
1482
- handleExperienceEmbedded(experience);
1483
- }
1484
- else if (state === 'unmounted') {
1485
- handleExperienceUnmounted(experience);
1486
- }
1487
- });
1488
- registerIdentifyHook(parentMessagesHook);
1489
-
1490
- exports.clearCredentials = clearCredentials;
1491
- exports.getIdentify = getIdentify;
1492
- exports.getUserData = getUserData;
1493
- exports.onCredentialsUpdated = onCredentialsUpdated;
1494
- exports.onLoginRequestedByExperience = onLoginRequestedByExperience;
1495
- exports.onLogoutRequestedByExperience = onLogoutRequestedByExperience;
1496
- exports.onSignatureUpdated = onSignatureUpdated;
1497
- exports.onStateUpdated = onStateUpdated;
1498
- exports.onUserDataUpdated = onUserDataUpdated;
1499
- exports.requestLogin = requestLogin;
1500
- exports.requestLogout = requestLogout;
1501
- exports.setCredentials = setCredentials;
1502
- //# sourceMappingURL=index.cjs.js.map