@mocanetwork/airkit 1.3.0-beta.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/airkit.cjs.js +1849 -1642
  2. package/dist/airkit.esm.js +1848 -1643
  3. package/dist/airkit.umd.js +1849 -1642
  4. package/dist/types/airService.d.ts +8 -25
  5. package/dist/types/airWalletProvider.d.ts +4 -10
  6. package/dist/types/authMessageService.d.ts +18 -0
  7. package/dist/types/common/air/error/codes.d.ts +16 -1
  8. package/dist/types/common/{realm → air}/messaging/auth.d.ts +42 -43
  9. package/dist/types/common/air/messaging/messageServiceBase.d.ts +35 -0
  10. package/dist/types/common/{realm → air}/messaging/provider.d.ts +2 -2
  11. package/dist/types/common/air/messaging/types.d.ts +16 -0
  12. package/dist/types/common/air/messaging/wallet.d.ts +101 -0
  13. package/dist/types/common/logging.d.ts +3 -0
  14. package/dist/types/common/provider/types.d.ts +105 -4
  15. package/dist/types/common/realm/partner/config.d.ts +3 -1
  16. package/dist/types/common/realm/smart-session/rule.d.ts +1 -1
  17. package/dist/types/common/realm/smart-session/types.d.ts +1 -1
  18. package/dist/types/common/realm/user/types.d.ts +10 -1
  19. package/dist/types/common/realm/wallet/index.d.ts +5 -0
  20. package/dist/types/common/types.d.ts +2 -0
  21. package/dist/types/common/utils.d.ts +10 -2
  22. package/dist/types/{windowController.d.ts → common/window/windowController.d.ts} +8 -3
  23. package/dist/types/error.d.ts +7 -1
  24. package/dist/types/interfaces.d.ts +0 -2
  25. package/dist/types/providerMessageService.d.ts +8 -0
  26. package/dist/types/utils.d.ts +2 -2
  27. package/dist/types/walletMessageService.d.ts +20 -0
  28. package/dist/types/windowService.d.ts +8 -3
  29. package/package.json +1 -1
  30. package/dist/types/common/realm/messaging/types.d.ts +0 -144
  31. package/dist/types/common/realm/smart-session/hex.d.ts +0 -1
  32. package/dist/types/loglevel.d.ts +0 -3
  33. package/dist/types/messageService.d.ts +0 -67
@@ -39,7 +39,7 @@ function __values(o) {
39
39
  if (m) return m.call(o);
40
40
  if (o && typeof o.length === "number") return {
41
41
  next: function () {
42
- if (o && i >= o.length) o = undefined;
42
+ if (o && i >= o.length) o = void 0;
43
43
  return {
44
44
  value: o && o[i++],
45
45
  done: !o
@@ -118,14 +118,16 @@ const AirAuthMessageTypes = {
118
118
  SIGN_SIWE_MESSAGE_RESPONSE: "air_auth_sign_siwe_message_response",
119
119
  CROSS_PARTNER_TOKEN_REQUEST: "air_auth_cross_partner_token_request",
120
120
  CROSS_PARTNER_TOKEN_RESPONSE: "air_auth_cross_partner_token_response",
121
- GET_PARTNER_ACCESS_TOKEN_REQUEST: "air_auth_get_partner_access_token_request",
122
- GET_PARTNER_ACCESS_TOKEN_RESPONSE: "air_auth_get_partner_access_token_response",
121
+ PARTNER_ACCESS_TOKEN_REQUEST: "air_auth_partner_access_token_request",
122
+ PARTNER_ACCESS_TOKEN_RESPONSE: "air_auth_partner_access_token_response",
123
+ CREDENTIAL_SALT_REQUEST: "air_auth_credential_salt_request",
124
+ CREDENTIAL_SALT_RESPONSE: "air_auth_credential_salt_response",
123
125
  LOGOUT_REQUEST: "air_auth_logout_request",
124
126
  LOGOUT_RESPONSE: "air_auth_logout_response",
125
127
  RESET_WALLET_COMMUNICATION: "air_auth_reset_wallet_communication"
126
128
  };
127
129
 
128
- const AirMessageTypes = {
130
+ const AirWalletMessageTypes = {
129
131
  SERVICE_STARTED: "air_service_started",
130
132
  INITIALIZATION_REQUEST: "air_initialization_request",
131
133
  INITIALIZATION_RESPONSE: "air_initialization_response",
@@ -133,23 +135,17 @@ const AirMessageTypes = {
133
135
  WALLET_INITIALIZED: "air_wallet_initialized",
134
136
  WALLET_LOGIN_REQUEST: "air_wallet_login_request",
135
137
  WALLET_LOGIN_RESPONSE: "air_wallet_login_response",
136
- SETUP_MFA_REQUEST: "air_setup_mfa_request",
137
- SETUP_MFA_RESPONSE: "air_setup_mfa_response",
138
+ SETUP_OR_UPDATE_MFA_REQUEST: "air_setup_mfa_request",
139
+ SETUP_OR_UPDATE_MFA_RESPONSE: "air_setup_mfa_response",
138
140
  CLAIM_ID_REQUEST: "air_claim_id_request",
139
141
  CLAIM_ID_RESPONSE: "air_claim_id_response",
140
142
  DEPLOY_SMART_ACCOUNT_REQUEST: "air_deploy_smart_account_request",
141
143
  DEPLOY_SMART_ACCOUNT_RESPONSE: "air_deploy_smart_account_response",
142
- GRANT_PERMISSIONS_REQUEST: "air_grant_permissions_request",
143
- GRANT_PERMISSIONS_RESPONSE: "air_grant_permissions_response",
144
- EXECUTE_ACTION_REQUEST: "air_execute_action_request",
145
- EXECUTE_ACTION_RESPONSE: "air_execute_action_response",
146
- REVOKE_PERMISSIONS_REQUEST: "air_revoke_permissions_request",
147
- REVOKE_PERMISSIONS_RESPONSE: "air_revoke_permissions_response",
148
- LIST_ALL_SESSION_KEY_SCOPES_REQUEST: "air_list_all_session_key_scopes_request",
149
- LIST_ALL_SESSION_KEY_SCOPES_RESPONSE: "air_list_all_session_key_scopes_response",
150
144
  WALLET_IFRAME_VISIBILITY_REQUEST: "air_wallet_iframe_visibility_request",
151
145
  OPEN_WINDOW_REQUEST: "air_open_window_request",
152
146
  OPEN_WINDOW_RESPONSE: "air_open_window_response",
147
+ OPEN_WINDOW_RETRY_REQUEST: "air_open_window_retry_request",
148
+ OPEN_WINDOW_RETRY_RESPONSE: "air_open_window_retry_response",
153
149
  WINDOW_CLOSED: "air_window_closed",
154
150
  IS_SMART_ACCOUNT_DEPLOYED_REQUEST: "air_is_smart_account_deployed_request",
155
151
  IS_SMART_ACCOUNT_DEPLOYED_RESPONSE: "air_is_smart_account_deployed_response",
@@ -189,6 +185,50 @@ function ensureError(value) {
189
185
  return new Error(`This value was not thrown as type Error: ${stringified}`);
190
186
  }
191
187
 
188
+ const BUILD_ENV = {
189
+ PRODUCTION: "production",
190
+ UAT: "uat",
191
+ STAGING: "staging",
192
+ DEVELOPMENT: "development",
193
+ };
194
+
195
+ const AIR_URLS = {
196
+ [BUILD_ENV.DEVELOPMENT]: {
197
+ authUrl: "http://localhost:8200/auth/",
198
+ walletUrl: "http://localhost:8200/wallet/",
199
+ },
200
+ [BUILD_ENV.UAT]: {
201
+ authUrl: "https://account.uat.air3.com/auth/",
202
+ walletUrl: "https://account.uat.air3.com/wallet/",
203
+ },
204
+ [BUILD_ENV.STAGING]: {
205
+ authUrl: "https://account.staging.air3.com/auth/",
206
+ walletUrl: "https://account.staging.air3.com/wallet/",
207
+ },
208
+ [BUILD_ENV.PRODUCTION]: {
209
+ authUrl: "https://account.air3.com/auth/",
210
+ walletUrl: "https://account.air3.com/wallet/",
211
+ },
212
+ };
213
+ const isElement = (element) => element instanceof Element || element instanceof Document;
214
+ const randomId = () => Math.random().toString(36).slice(2);
215
+ const extractErrorHash = (message) => {
216
+ if (!message)
217
+ return "";
218
+ // Format: "reason: 0x..."
219
+ if (message.includes("reason:")) {
220
+ return message.split("reason:")[1].trim();
221
+ }
222
+ // Format: "UserOperation reverted during simulation with reason: 0x..."
223
+ if (message.includes("with reason:")) {
224
+ const match = message.match(/with reason: (0x[a-fA-F0-9]+)/);
225
+ return match ? match[1].trim() : "";
226
+ }
227
+ // Look for any 0x pattern that could be a hash
228
+ const hexMatch = message.match(/(0x[a-fA-F0-9]{8,})/);
229
+ return hexMatch ? hexMatch[1].trim() : "";
230
+ };
231
+
192
232
  class AirServiceError extends BaseError {
193
233
  static from(error) {
194
234
  if (error instanceof AirServiceError) {
@@ -206,6 +246,7 @@ class AirServiceError extends BaseError {
206
246
  class ProviderRpcError extends Error {
207
247
  constructor(message) {
208
248
  super(message);
249
+ this.metaMessages = [];
209
250
  }
210
251
  }
211
252
  class UserRejectedRequestError extends ProviderRpcError {
@@ -250,6 +291,17 @@ class SwitchChainError extends ProviderRpcError {
250
291
  this.name = "SwitchChainError";
251
292
  }
252
293
  }
294
+ class TransactionRejectedRpcError extends ProviderRpcError {
295
+ constructor(message) {
296
+ // Remove the "Version: viem@x.x.x" suffix if present
297
+ const cleanMessage = message.replace(/\nVersion:.*$/, '');
298
+ super(cleanMessage);
299
+ this.code = -32003;
300
+ this.name = "TransactionRejectedRpcError";
301
+ // Parse the error hash from the message
302
+ this.metaMessages.push(extractErrorHash(cleanMessage));
303
+ }
304
+ }
253
305
  class InvalidRequestRpcError extends ProviderRpcError {
254
306
  constructor() {
255
307
  super(...arguments);
@@ -300,6 +352,8 @@ function ensureProviderRpcError(value) {
300
352
  return new ChainDisconnectedError(value.errorMessage);
301
353
  case 4902:
302
354
  return new SwitchChainError(value.errorMessage);
355
+ case -32003:
356
+ return new TransactionRejectedRpcError(value.errorMessage);
303
357
  }
304
358
  }
305
359
  }
@@ -313,1485 +367,1384 @@ function ensureProviderRpcError(value) {
313
367
  return new InternalRpcError(`Invalid value for ProviderRpcError: ${stringified}`);
314
368
  }
315
369
 
316
- function isFunction(value) {
317
- return typeof value === 'function';
370
+ function getDefaultExportFromCjs (x) {
371
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
318
372
  }
319
373
 
320
- function createErrorClass(createImpl) {
321
- var _super = function (instance) {
322
- Error.call(instance);
323
- instance.stack = new Error().stack;
324
- };
325
- var ctorFunc = createImpl(_super);
326
- ctorFunc.prototype = Object.create(Error.prototype);
327
- ctorFunc.prototype.constructor = ctorFunc;
328
- return ctorFunc;
329
- }
374
+ var loglevel$1 = {exports: {}};
330
375
 
331
- var UnsubscriptionError = createErrorClass(function (_super) {
332
- return function UnsubscriptionErrorImpl(errors) {
333
- _super(this);
334
- this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) {
335
- return i + 1 + ") " + err.toString();
336
- }).join('\n ') : '';
337
- this.name = 'UnsubscriptionError';
338
- this.errors = errors;
339
- };
340
- });
376
+ /*
377
+ * loglevel - https://github.com/pimterry/loglevel
378
+ *
379
+ * Copyright (c) 2013 Tim Perry
380
+ * Licensed under the MIT license.
381
+ */
382
+ var loglevel = loglevel$1.exports;
383
+ var hasRequiredLoglevel;
384
+ function requireLoglevel() {
385
+ if (hasRequiredLoglevel) return loglevel$1.exports;
386
+ hasRequiredLoglevel = 1;
387
+ (function (module) {
388
+ (function (root, definition) {
341
389
 
342
- function arrRemove(arr, item) {
343
- if (arr) {
344
- var index = arr.indexOf(item);
345
- 0 <= index && arr.splice(index, 1);
346
- }
347
- }
390
+ if (module.exports) {
391
+ module.exports = definition();
392
+ } else {
393
+ root.log = definition();
394
+ }
395
+ })(loglevel, function () {
348
396
 
349
- var Subscription = function () {
350
- function Subscription(initialTeardown) {
351
- this.initialTeardown = initialTeardown;
352
- this.closed = false;
353
- this._parentage = null;
354
- this._finalizers = null;
355
- }
356
- Subscription.prototype.unsubscribe = function () {
357
- var e_1, _a, e_2, _b;
358
- var errors;
359
- if (!this.closed) {
360
- this.closed = true;
361
- var _parentage = this._parentage;
362
- if (_parentage) {
363
- this._parentage = null;
364
- if (Array.isArray(_parentage)) {
397
+ // Slightly dubious tricks to cut down minimized file size
398
+ var noop = function () {};
399
+ var undefinedType = "undefined";
400
+ var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
401
+ var logMethods = ["trace", "debug", "info", "warn", "error"];
402
+ var _loggersByName = {};
403
+ var defaultLogger = null;
404
+
405
+ // Cross-browser bind equivalent that works at least back to IE6
406
+ function bindMethod(obj, methodName) {
407
+ var method = obj[methodName];
408
+ if (typeof method.bind === 'function') {
409
+ return method.bind(obj);
410
+ } else {
365
411
  try {
366
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
367
- var parent_1 = _parentage_1_1.value;
368
- parent_1.remove(this);
369
- }
370
- } catch (e_1_1) {
371
- e_1 = {
372
- error: e_1_1
412
+ return Function.prototype.bind.call(method, obj);
413
+ } catch (e) {
414
+ // Missing bind shim or IE8 + Modernizr, fallback to wrapping
415
+ return function () {
416
+ return Function.prototype.apply.apply(method, [obj, arguments]);
373
417
  };
374
- } finally {
375
- try {
376
- if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
377
- } finally {
378
- if (e_1) throw e_1.error;
379
- }
380
418
  }
381
- } else {
382
- _parentage.remove(this);
383
- }
384
- }
385
- var initialFinalizer = this.initialTeardown;
386
- if (isFunction(initialFinalizer)) {
387
- try {
388
- initialFinalizer();
389
- } catch (e) {
390
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
391
419
  }
392
420
  }
393
- var _finalizers = this._finalizers;
394
- if (_finalizers) {
395
- this._finalizers = null;
396
- try {
397
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
398
- var finalizer = _finalizers_1_1.value;
399
- try {
400
- execFinalizer(finalizer);
401
- } catch (err) {
402
- errors = errors !== null && errors !== void 0 ? errors : [];
403
- if (err instanceof UnsubscriptionError) {
404
- errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
405
- } else {
406
- errors.push(err);
407
- }
408
- }
409
- }
410
- } catch (e_2_1) {
411
- e_2 = {
412
- error: e_2_1
413
- };
414
- } finally {
415
- try {
416
- if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
417
- } finally {
418
- if (e_2) throw e_2.error;
421
+
422
+ // Trace() doesn't print the message in IE, so for that case we need to wrap it
423
+ function traceForIE() {
424
+ if (console.log) {
425
+ if (console.log.apply) {
426
+ console.log.apply(console, arguments);
427
+ } else {
428
+ // In old IE, native console methods themselves don't have apply().
429
+ Function.prototype.apply.apply(console.log, [console, arguments]);
419
430
  }
420
431
  }
432
+ if (console.trace) console.trace();
421
433
  }
422
- if (errors) {
423
- throw new UnsubscriptionError(errors);
424
- }
425
- }
426
- };
427
- Subscription.prototype.add = function (teardown) {
428
- var _a;
429
- if (teardown && teardown !== this) {
430
- if (this.closed) {
431
- execFinalizer(teardown);
432
- } else {
433
- if (teardown instanceof Subscription) {
434
- if (teardown.closed || teardown._hasParent(this)) {
435
- return;
436
- }
437
- teardown._addParent(this);
434
+
435
+ // Build the best logging method possible for this env
436
+ // Wherever possible we want to bind, not wrap, to preserve stack traces
437
+ function realMethod(methodName) {
438
+ if (methodName === 'debug') {
439
+ methodName = 'log';
440
+ }
441
+ if (typeof console === undefinedType) {
442
+ return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
443
+ } else if (methodName === 'trace' && isIE) {
444
+ return traceForIE;
445
+ } else if (console[methodName] !== undefined) {
446
+ return bindMethod(console, methodName);
447
+ } else if (console.log !== undefined) {
448
+ return bindMethod(console, 'log');
449
+ } else {
450
+ return noop;
438
451
  }
439
- (this._finalizers = (_a = this._finalizers) !== null && _a !== undefined ? _a : []).push(teardown);
440
452
  }
441
- }
442
- };
443
- Subscription.prototype._hasParent = function (parent) {
444
- var _parentage = this._parentage;
445
- return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
446
- };
447
- Subscription.prototype._addParent = function (parent) {
448
- var _parentage = this._parentage;
449
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
450
- };
451
- Subscription.prototype._removeParent = function (parent) {
452
- var _parentage = this._parentage;
453
- if (_parentage === parent) {
454
- this._parentage = null;
455
- } else if (Array.isArray(_parentage)) {
456
- arrRemove(_parentage, parent);
457
- }
458
- };
459
- Subscription.prototype.remove = function (teardown) {
460
- var _finalizers = this._finalizers;
461
- _finalizers && arrRemove(_finalizers, teardown);
462
- if (teardown instanceof Subscription) {
463
- teardown._removeParent(this);
464
- }
465
- };
466
- Subscription.EMPTY = function () {
467
- var empty = new Subscription();
468
- empty.closed = true;
469
- return empty;
470
- }();
471
- return Subscription;
472
- }();
473
- var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
474
- function isSubscription(value) {
475
- return value instanceof Subscription || value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
476
- }
477
- function execFinalizer(finalizer) {
478
- if (isFunction(finalizer)) {
479
- finalizer();
480
- } else {
481
- finalizer.unsubscribe();
482
- }
483
- }
484
453
 
485
- var config = {
486
- onUnhandledError: null,
487
- onStoppedNotification: null,
488
- Promise: undefined,
489
- useDeprecatedSynchronousErrorHandling: false,
490
- useDeprecatedNextContext: false
491
- };
454
+ // These private functions always need `this` to be set properly
492
455
 
493
- var timeoutProvider = {
494
- setTimeout: function (handler, timeout) {
495
- var args = [];
496
- for (var _i = 2; _i < arguments.length; _i++) {
497
- args[_i - 2] = arguments[_i];
498
- }
499
- return setTimeout.apply(undefined, __spreadArray([handler, timeout], __read(args)));
500
- },
501
- clearTimeout: function (handle) {
502
- return (clearTimeout)(handle);
503
- },
504
- delegate: undefined
505
- };
506
-
507
- function reportUnhandledError(err) {
508
- timeoutProvider.setTimeout(function () {
509
- {
510
- throw err;
511
- }
512
- });
513
- }
456
+ function replaceLoggingMethods() {
457
+ /*jshint validthis:true */
458
+ var level = this.getLevel();
514
459
 
515
- function noop() {}
460
+ // Replace the actual methods.
461
+ for (var i = 0; i < logMethods.length; i++) {
462
+ var methodName = logMethods[i];
463
+ this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name);
464
+ }
516
465
 
517
- function errorContext(cb) {
518
- {
519
- cb();
520
- }
521
- }
466
+ // Define log.log as an alias for log.debug
467
+ this.log = this.debug;
522
468
 
523
- var Subscriber = function (_super) {
524
- __extends(Subscriber, _super);
525
- function Subscriber(destination) {
526
- var _this = _super.call(this) || this;
527
- _this.isStopped = false;
528
- if (destination) {
529
- _this.destination = destination;
530
- if (isSubscription(destination)) {
531
- destination.add(_this);
532
- }
533
- } else {
534
- _this.destination = EMPTY_OBSERVER;
535
- }
536
- return _this;
537
- }
538
- Subscriber.create = function (next, error, complete) {
539
- return new SafeSubscriber(next, error, complete);
540
- };
541
- Subscriber.prototype.next = function (value) {
542
- if (this.isStopped) ; else {
543
- this._next(value);
544
- }
545
- };
546
- Subscriber.prototype.error = function (err) {
547
- if (this.isStopped) ; else {
548
- this.isStopped = true;
549
- this._error(err);
550
- }
551
- };
552
- Subscriber.prototype.complete = function () {
553
- if (this.isStopped) ; else {
554
- this.isStopped = true;
555
- this._complete();
556
- }
557
- };
558
- Subscriber.prototype.unsubscribe = function () {
559
- if (!this.closed) {
560
- this.isStopped = true;
561
- _super.prototype.unsubscribe.call(this);
562
- this.destination = null;
563
- }
564
- };
565
- Subscriber.prototype._next = function (value) {
566
- this.destination.next(value);
567
- };
568
- Subscriber.prototype._error = function (err) {
569
- try {
570
- this.destination.error(err);
571
- } finally {
572
- this.unsubscribe();
573
- }
574
- };
575
- Subscriber.prototype._complete = function () {
576
- try {
577
- this.destination.complete();
578
- } finally {
579
- this.unsubscribe();
580
- }
581
- };
582
- return Subscriber;
583
- }(Subscription);
584
- var ConsumerObserver = function () {
585
- function ConsumerObserver(partialObserver) {
586
- this.partialObserver = partialObserver;
587
- }
588
- ConsumerObserver.prototype.next = function (value) {
589
- var partialObserver = this.partialObserver;
590
- if (partialObserver.next) {
591
- try {
592
- partialObserver.next(value);
593
- } catch (error) {
594
- handleUnhandledError(error);
595
- }
596
- }
597
- };
598
- ConsumerObserver.prototype.error = function (err) {
599
- var partialObserver = this.partialObserver;
600
- if (partialObserver.error) {
601
- try {
602
- partialObserver.error(err);
603
- } catch (error) {
604
- handleUnhandledError(error);
469
+ // Return any important warnings.
470
+ if (typeof console === undefinedType && level < this.levels.SILENT) {
471
+ return "No console available for logging";
472
+ }
605
473
  }
606
- } else {
607
- handleUnhandledError(err);
608
- }
609
- };
610
- ConsumerObserver.prototype.complete = function () {
611
- var partialObserver = this.partialObserver;
612
- if (partialObserver.complete) {
613
- try {
614
- partialObserver.complete();
615
- } catch (error) {
616
- handleUnhandledError(error);
474
+
475
+ // In old IE versions, the console isn't present until you first open it.
476
+ // We build realMethod() replacements here that regenerate logging methods
477
+ function enableLoggingWhenConsoleArrives(methodName) {
478
+ return function () {
479
+ if (typeof console !== undefinedType) {
480
+ replaceLoggingMethods.call(this);
481
+ this[methodName].apply(this, arguments);
482
+ }
483
+ };
617
484
  }
618
- }
619
- };
620
- return ConsumerObserver;
621
- }();
622
- var SafeSubscriber = function (_super) {
623
- __extends(SafeSubscriber, _super);
624
- function SafeSubscriber(observerOrNext, error, complete) {
625
- var _this = _super.call(this) || this;
626
- var partialObserver;
627
- if (isFunction(observerOrNext) || !observerOrNext) {
628
- partialObserver = {
629
- next: observerOrNext !== null && observerOrNext !== undefined ? observerOrNext : undefined,
630
- error: error !== null && error !== undefined ? error : undefined,
631
- complete: complete !== null && complete !== undefined ? complete : undefined
632
- };
633
- } else {
634
- {
635
- partialObserver = observerOrNext;
485
+
486
+ // By default, we use closely bound real methods wherever possible, and
487
+ // otherwise we wait for a console to appear, and then try again.
488
+ function defaultMethodFactory(methodName, _level, _loggerName) {
489
+ /*jshint validthis:true */
490
+ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
636
491
  }
637
- }
638
- _this.destination = new ConsumerObserver(partialObserver);
639
- return _this;
640
- }
641
- return SafeSubscriber;
642
- }(Subscriber);
643
- function handleUnhandledError(error) {
644
- {
645
- reportUnhandledError(error);
646
- }
647
- }
648
- function defaultErrorHandler(err) {
649
- throw err;
650
- }
651
- var EMPTY_OBSERVER = {
652
- closed: true,
653
- next: noop,
654
- error: defaultErrorHandler,
655
- complete: noop
656
- };
492
+ function Logger(name, factory) {
493
+ // Private instance variables.
494
+ var self = this;
495
+ /**
496
+ * The level inherited from a parent logger (or a global default). We
497
+ * cache this here rather than delegating to the parent so that it stays
498
+ * in sync with the actual logging methods that we have installed (the
499
+ * parent could change levels but we might not have rebuilt the loggers
500
+ * in this child yet).
501
+ * @type {number}
502
+ */
503
+ var inheritedLevel;
504
+ /**
505
+ * The default level for this logger, if any. If set, this overrides
506
+ * `inheritedLevel`.
507
+ * @type {number|null}
508
+ */
509
+ var defaultLevel;
510
+ /**
511
+ * A user-specific level for this logger. If set, this overrides
512
+ * `defaultLevel`.
513
+ * @type {number|null}
514
+ */
515
+ var userLevel;
516
+ var storageKey = "loglevel";
517
+ if (typeof name === "string") {
518
+ storageKey += ":" + name;
519
+ } else if (typeof name === "symbol") {
520
+ storageKey = undefined;
521
+ }
522
+ function persistLevelIfPossible(levelNum) {
523
+ var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
524
+ if (typeof window === undefinedType || !storageKey) return;
657
525
 
658
- var observable = function () {
659
- return typeof Symbol === 'function' && Symbol.observable || '@@observable';
660
- }();
526
+ // Use localStorage if available
527
+ try {
528
+ window.localStorage[storageKey] = levelName;
529
+ return;
530
+ } catch (ignore) {}
661
531
 
662
- function identity(x) {
663
- return x;
664
- }
532
+ // Use session cookie as fallback
533
+ try {
534
+ window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
535
+ } catch (ignore) {}
536
+ }
537
+ function getPersistedLevel() {
538
+ var storedLevel;
539
+ if (typeof window === undefinedType || !storageKey) return;
540
+ try {
541
+ storedLevel = window.localStorage[storageKey];
542
+ } catch (ignore) {}
665
543
 
666
- function pipeFromArray(fns) {
667
- if (fns.length === 0) {
668
- return identity;
669
- }
670
- if (fns.length === 1) {
671
- return fns[0];
672
- }
673
- return function piped(input) {
674
- return fns.reduce(function (prev, fn) {
675
- return fn(prev);
676
- }, input);
677
- };
678
- }
544
+ // Fallback to cookies if local storage gives us nothing
545
+ if (typeof storedLevel === undefinedType) {
546
+ try {
547
+ var cookie = window.document.cookie;
548
+ var cookieName = encodeURIComponent(storageKey);
549
+ var location = cookie.indexOf(cookieName + "=");
550
+ if (location !== -1) {
551
+ storedLevel = /^([^;]+)/.exec(cookie.slice(location + cookieName.length + 1))[1];
552
+ }
553
+ } catch (ignore) {}
554
+ }
679
555
 
680
- var Observable = function () {
681
- function Observable(subscribe) {
682
- if (subscribe) {
683
- this._subscribe = subscribe;
684
- }
685
- }
686
- Observable.prototype.lift = function (operator) {
687
- var observable = new Observable();
688
- observable.source = this;
689
- observable.operator = operator;
690
- return observable;
691
- };
692
- Observable.prototype.subscribe = function (observerOrNext, error, complete) {
693
- var _this = this;
694
- var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
695
- errorContext(function () {
696
- var _a = _this,
697
- operator = _a.operator,
698
- source = _a.source;
699
- subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
556
+ // If the stored level is not valid, treat it as if nothing was stored.
557
+ if (self.levels[storedLevel] === undefined) {
558
+ storedLevel = undefined;
559
+ }
560
+ return storedLevel;
561
+ }
562
+ function clearPersistedLevel() {
563
+ if (typeof window === undefinedType || !storageKey) return;
564
+
565
+ // Use localStorage if available
566
+ try {
567
+ window.localStorage.removeItem(storageKey);
568
+ } catch (ignore) {}
569
+
570
+ // Use session cookie as fallback
571
+ try {
572
+ window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
573
+ } catch (ignore) {}
574
+ }
575
+ function normalizeLevel(input) {
576
+ var level = input;
577
+ if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
578
+ level = self.levels[level.toUpperCase()];
579
+ }
580
+ if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
581
+ return level;
582
+ } else {
583
+ throw new TypeError("log.setLevel() called with invalid level: " + input);
584
+ }
585
+ }
586
+
587
+ /*
588
+ *
589
+ * Public logger API - see https://github.com/pimterry/loglevel for details
590
+ *
591
+ */
592
+
593
+ self.name = name;
594
+ self.levels = {
595
+ "TRACE": 0,
596
+ "DEBUG": 1,
597
+ "INFO": 2,
598
+ "WARN": 3,
599
+ "ERROR": 4,
600
+ "SILENT": 5
601
+ };
602
+ self.methodFactory = factory || defaultMethodFactory;
603
+ self.getLevel = function () {
604
+ if (userLevel != null) {
605
+ return userLevel;
606
+ } else if (defaultLevel != null) {
607
+ return defaultLevel;
608
+ } else {
609
+ return inheritedLevel;
610
+ }
611
+ };
612
+ self.setLevel = function (level, persist) {
613
+ userLevel = normalizeLevel(level);
614
+ if (persist !== false) {
615
+ // defaults to true
616
+ persistLevelIfPossible(userLevel);
617
+ }
618
+
619
+ // NOTE: in v2, this should call rebuild(), which updates children.
620
+ return replaceLoggingMethods.call(self);
621
+ };
622
+ self.setDefaultLevel = function (level) {
623
+ defaultLevel = normalizeLevel(level);
624
+ if (!getPersistedLevel()) {
625
+ self.setLevel(level, false);
626
+ }
627
+ };
628
+ self.resetLevel = function () {
629
+ userLevel = null;
630
+ clearPersistedLevel();
631
+ replaceLoggingMethods.call(self);
632
+ };
633
+ self.enableAll = function (persist) {
634
+ self.setLevel(self.levels.TRACE, persist);
635
+ };
636
+ self.disableAll = function (persist) {
637
+ self.setLevel(self.levels.SILENT, persist);
638
+ };
639
+ self.rebuild = function () {
640
+ if (defaultLogger !== self) {
641
+ inheritedLevel = normalizeLevel(defaultLogger.getLevel());
642
+ }
643
+ replaceLoggingMethods.call(self);
644
+ if (defaultLogger === self) {
645
+ for (var childName in _loggersByName) {
646
+ _loggersByName[childName].rebuild();
647
+ }
648
+ }
649
+ };
650
+
651
+ // Initialize all the internal levels.
652
+ inheritedLevel = normalizeLevel(defaultLogger ? defaultLogger.getLevel() : "WARN");
653
+ var initialLevel = getPersistedLevel();
654
+ if (initialLevel != null) {
655
+ userLevel = normalizeLevel(initialLevel);
656
+ }
657
+ replaceLoggingMethods.call(self);
658
+ }
659
+
660
+ /*
661
+ *
662
+ * Top-level API
663
+ *
664
+ */
665
+
666
+ defaultLogger = new Logger();
667
+ defaultLogger.getLogger = function getLogger(name) {
668
+ if (typeof name !== "symbol" && typeof name !== "string" || name === "") {
669
+ throw new TypeError("You must supply a name when creating a logger.");
670
+ }
671
+ var logger = _loggersByName[name];
672
+ if (!logger) {
673
+ logger = _loggersByName[name] = new Logger(name, defaultLogger.methodFactory);
674
+ }
675
+ return logger;
676
+ };
677
+
678
+ // Grab the current global log variable in case of overwrite
679
+ var _log = typeof window !== undefinedType ? window.log : undefined;
680
+ defaultLogger.noConflict = function () {
681
+ if (typeof window !== undefinedType && window.log === defaultLogger) {
682
+ window.log = _log;
683
+ }
684
+ return defaultLogger;
685
+ };
686
+ defaultLogger.getLoggers = function getLoggers() {
687
+ return _loggersByName;
688
+ };
689
+
690
+ // ES6 default export, for compatibility
691
+ defaultLogger['default'] = defaultLogger;
692
+ return defaultLogger;
700
693
  });
701
- return subscriber;
694
+ })(loglevel$1);
695
+ return loglevel$1.exports;
696
+ }
697
+
698
+ var loglevelExports = requireLoglevel();
699
+ var log = /*@__PURE__*/getDefaultExportFromCjs(loglevelExports);
700
+
701
+ function isFunction(value) {
702
+ return typeof value === 'function';
703
+ }
704
+
705
+ function createErrorClass(createImpl) {
706
+ var _super = function (instance) {
707
+ Error.call(instance);
708
+ instance.stack = new Error().stack;
702
709
  };
703
- Observable.prototype._trySubscribe = function (sink) {
704
- try {
705
- return this._subscribe(sink);
706
- } catch (err) {
707
- sink.error(err);
708
- }
710
+ var ctorFunc = createImpl(_super);
711
+ ctorFunc.prototype = Object.create(Error.prototype);
712
+ ctorFunc.prototype.constructor = ctorFunc;
713
+ return ctorFunc;
714
+ }
715
+
716
+ var UnsubscriptionError = createErrorClass(function (_super) {
717
+ return function UnsubscriptionErrorImpl(errors) {
718
+ _super(this);
719
+ this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) {
720
+ return i + 1 + ") " + err.toString();
721
+ }).join('\n ') : '';
722
+ this.name = 'UnsubscriptionError';
723
+ this.errors = errors;
709
724
  };
710
- Observable.prototype.forEach = function (next, promiseCtor) {
711
- var _this = this;
712
- promiseCtor = getPromiseCtor(promiseCtor);
713
- return new promiseCtor(function (resolve, reject) {
714
- var subscriber = new SafeSubscriber({
715
- next: function (value) {
725
+ });
726
+
727
+ function arrRemove(arr, item) {
728
+ if (arr) {
729
+ var index = arr.indexOf(item);
730
+ 0 <= index && arr.splice(index, 1);
731
+ }
732
+ }
733
+
734
+ var Subscription = function () {
735
+ function Subscription(initialTeardown) {
736
+ this.initialTeardown = initialTeardown;
737
+ this.closed = false;
738
+ this._parentage = null;
739
+ this._finalizers = null;
740
+ }
741
+ Subscription.prototype.unsubscribe = function () {
742
+ var e_1, _a, e_2, _b;
743
+ var errors;
744
+ if (!this.closed) {
745
+ this.closed = true;
746
+ var _parentage = this._parentage;
747
+ if (_parentage) {
748
+ this._parentage = null;
749
+ if (Array.isArray(_parentage)) {
750
+ try {
751
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
752
+ var parent_1 = _parentage_1_1.value;
753
+ parent_1.remove(this);
754
+ }
755
+ } catch (e_1_1) {
756
+ e_1 = {
757
+ error: e_1_1
758
+ };
759
+ } finally {
760
+ try {
761
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
762
+ } finally {
763
+ if (e_1) throw e_1.error;
764
+ }
765
+ }
766
+ } else {
767
+ _parentage.remove(this);
768
+ }
769
+ }
770
+ var initialFinalizer = this.initialTeardown;
771
+ if (isFunction(initialFinalizer)) {
772
+ try {
773
+ initialFinalizer();
774
+ } catch (e) {
775
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
776
+ }
777
+ }
778
+ var _finalizers = this._finalizers;
779
+ if (_finalizers) {
780
+ this._finalizers = null;
781
+ try {
782
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
783
+ var finalizer = _finalizers_1_1.value;
784
+ try {
785
+ execFinalizer(finalizer);
786
+ } catch (err) {
787
+ errors = errors !== null && errors !== void 0 ? errors : [];
788
+ if (err instanceof UnsubscriptionError) {
789
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
790
+ } else {
791
+ errors.push(err);
792
+ }
793
+ }
794
+ }
795
+ } catch (e_2_1) {
796
+ e_2 = {
797
+ error: e_2_1
798
+ };
799
+ } finally {
716
800
  try {
717
- next(value);
718
- } catch (err) {
719
- reject(err);
720
- subscriber.unsubscribe();
801
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
802
+ } finally {
803
+ if (e_2) throw e_2.error;
721
804
  }
722
- },
723
- error: reject,
724
- complete: resolve
725
- });
726
- _this.subscribe(subscriber);
727
- });
805
+ }
806
+ }
807
+ if (errors) {
808
+ throw new UnsubscriptionError(errors);
809
+ }
810
+ }
728
811
  };
729
- Observable.prototype._subscribe = function (subscriber) {
812
+ Subscription.prototype.add = function (teardown) {
730
813
  var _a;
731
- return (_a = this.source) === null || _a === undefined ? undefined : _a.subscribe(subscriber);
814
+ if (teardown && teardown !== this) {
815
+ if (this.closed) {
816
+ execFinalizer(teardown);
817
+ } else {
818
+ if (teardown instanceof Subscription) {
819
+ if (teardown.closed || teardown._hasParent(this)) {
820
+ return;
821
+ }
822
+ teardown._addParent(this);
823
+ }
824
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
825
+ }
826
+ }
732
827
  };
733
- Observable.prototype[observable] = function () {
734
- return this;
828
+ Subscription.prototype._hasParent = function (parent) {
829
+ var _parentage = this._parentage;
830
+ return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
735
831
  };
736
- Observable.prototype.pipe = function () {
737
- var operations = [];
738
- for (var _i = 0; _i < arguments.length; _i++) {
739
- operations[_i] = arguments[_i];
740
- }
741
- return pipeFromArray(operations)(this);
832
+ Subscription.prototype._addParent = function (parent) {
833
+ var _parentage = this._parentage;
834
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
742
835
  };
743
- Observable.prototype.toPromise = function (promiseCtor) {
744
- var _this = this;
745
- promiseCtor = getPromiseCtor(promiseCtor);
746
- return new promiseCtor(function (resolve, reject) {
747
- var value;
748
- _this.subscribe(function (x) {
749
- return value = x;
750
- }, function (err) {
751
- return reject(err);
752
- }, function () {
753
- return resolve(value);
754
- });
755
- });
836
+ Subscription.prototype._removeParent = function (parent) {
837
+ var _parentage = this._parentage;
838
+ if (_parentage === parent) {
839
+ this._parentage = null;
840
+ } else if (Array.isArray(_parentage)) {
841
+ arrRemove(_parentage, parent);
842
+ }
756
843
  };
757
- Observable.create = function (subscribe) {
758
- return new Observable(subscribe);
844
+ Subscription.prototype.remove = function (teardown) {
845
+ var _finalizers = this._finalizers;
846
+ _finalizers && arrRemove(_finalizers, teardown);
847
+ if (teardown instanceof Subscription) {
848
+ teardown._removeParent(this);
849
+ }
759
850
  };
760
- return Observable;
851
+ Subscription.EMPTY = function () {
852
+ var empty = new Subscription();
853
+ empty.closed = true;
854
+ return empty;
855
+ }();
856
+ return Subscription;
761
857
  }();
762
- function getPromiseCtor(promiseCtor) {
763
- var _a;
764
- return (_a = promiseCtor !== null && promiseCtor !== undefined ? promiseCtor : config.Promise) !== null && _a !== undefined ? _a : Promise;
765
- }
766
- function isObserver(value) {
767
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
858
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
859
+ function isSubscription(value) {
860
+ return value instanceof Subscription || value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
768
861
  }
769
- function isSubscriber(value) {
770
- return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
862
+ function execFinalizer(finalizer) {
863
+ if (isFunction(finalizer)) {
864
+ finalizer();
865
+ } else {
866
+ finalizer.unsubscribe();
867
+ }
771
868
  }
772
869
 
773
- function hasLift(source) {
774
- return isFunction(source === null || source === undefined ? undefined : source.lift);
775
- }
776
- function operate(init) {
777
- return function (source) {
778
- if (hasLift(source)) {
779
- return source.lift(function (liftedSource) {
780
- try {
781
- return init(liftedSource, this);
782
- } catch (err) {
783
- this.error(err);
784
- }
785
- });
870
+ var config = {
871
+ Promise: undefined};
872
+
873
+ var timeoutProvider = {
874
+ setTimeout: function (handler, timeout) {
875
+ var args = [];
876
+ for (var _i = 2; _i < arguments.length; _i++) {
877
+ args[_i - 2] = arguments[_i];
786
878
  }
787
- throw new TypeError('Unable to lift unknown Observable type');
788
- };
879
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
880
+ },
881
+ clearTimeout: function (handle) {
882
+ return (clearTimeout)(handle);
883
+ },
884
+ delegate: undefined
885
+ };
886
+
887
+ function reportUnhandledError(err) {
888
+ timeoutProvider.setTimeout(function () {
889
+ {
890
+ throw err;
891
+ }
892
+ });
789
893
  }
790
894
 
791
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
792
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
895
+ function noop() {}
896
+
897
+ function errorContext(cb) {
898
+ {
899
+ cb();
900
+ }
793
901
  }
794
- var OperatorSubscriber = function (_super) {
795
- __extends(OperatorSubscriber, _super);
796
- function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
797
- var _this = _super.call(this, destination) || this;
798
- _this.onFinalize = onFinalize;
799
- _this.shouldUnsubscribe = shouldUnsubscribe;
800
- _this._next = onNext ? function (value) {
801
- try {
802
- onNext(value);
803
- } catch (err) {
804
- destination.error(err);
805
- }
806
- } : _super.prototype._next;
807
- _this._error = onError ? function (err) {
808
- try {
809
- onError(err);
810
- } catch (err) {
811
- destination.error(err);
812
- } finally {
813
- this.unsubscribe();
814
- }
815
- } : _super.prototype._error;
816
- _this._complete = onComplete ? function () {
817
- try {
818
- onComplete();
819
- } catch (err) {
820
- destination.error(err);
821
- } finally {
822
- this.unsubscribe();
902
+
903
+ var Subscriber = function (_super) {
904
+ __extends(Subscriber, _super);
905
+ function Subscriber(destination) {
906
+ var _this = _super.call(this) || this;
907
+ _this.isStopped = false;
908
+ if (destination) {
909
+ _this.destination = destination;
910
+ if (isSubscription(destination)) {
911
+ destination.add(_this);
823
912
  }
824
- } : _super.prototype._complete;
913
+ } else {
914
+ _this.destination = EMPTY_OBSERVER;
915
+ }
825
916
  return _this;
826
917
  }
827
- OperatorSubscriber.prototype.unsubscribe = function () {
828
- var _a;
829
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
830
- var closed_1 = this.closed;
918
+ Subscriber.create = function (next, error, complete) {
919
+ return new SafeSubscriber(next, error, complete);
920
+ };
921
+ Subscriber.prototype.next = function (value) {
922
+ if (this.isStopped) ; else {
923
+ this._next(value);
924
+ }
925
+ };
926
+ Subscriber.prototype.error = function (err) {
927
+ if (this.isStopped) ; else {
928
+ this.isStopped = true;
929
+ this._error(err);
930
+ }
931
+ };
932
+ Subscriber.prototype.complete = function () {
933
+ if (this.isStopped) ; else {
934
+ this.isStopped = true;
935
+ this._complete();
936
+ }
937
+ };
938
+ Subscriber.prototype.unsubscribe = function () {
939
+ if (!this.closed) {
940
+ this.isStopped = true;
831
941
  _super.prototype.unsubscribe.call(this);
832
- !closed_1 && ((_a = this.onFinalize) === null || _a === undefined ? undefined : _a.call(this));
942
+ this.destination = null;
833
943
  }
834
944
  };
835
- return OperatorSubscriber;
836
- }(Subscriber);
837
-
838
- var ObjectUnsubscribedError = createErrorClass(function (_super) {
839
- return function ObjectUnsubscribedErrorImpl() {
840
- _super(this);
841
- this.name = 'ObjectUnsubscribedError';
842
- this.message = 'object unsubscribed';
945
+ Subscriber.prototype._next = function (value) {
946
+ this.destination.next(value);
843
947
  };
844
- });
845
-
846
- var Subject = function (_super) {
847
- __extends(Subject, _super);
848
- function Subject() {
849
- var _this = _super.call(this) || this;
850
- _this.closed = false;
851
- _this.currentObservers = null;
852
- _this.observers = [];
853
- _this.isStopped = false;
854
- _this.hasError = false;
855
- _this.thrownError = null;
856
- return _this;
857
- }
858
- Subject.prototype.lift = function (operator) {
859
- var subject = new AnonymousSubject(this, this);
860
- subject.operator = operator;
861
- return subject;
948
+ Subscriber.prototype._error = function (err) {
949
+ try {
950
+ this.destination.error(err);
951
+ } finally {
952
+ this.unsubscribe();
953
+ }
862
954
  };
863
- Subject.prototype._throwIfClosed = function () {
864
- if (this.closed) {
865
- throw new ObjectUnsubscribedError();
955
+ Subscriber.prototype._complete = function () {
956
+ try {
957
+ this.destination.complete();
958
+ } finally {
959
+ this.unsubscribe();
866
960
  }
867
961
  };
868
- Subject.prototype.next = function (value) {
869
- var _this = this;
870
- errorContext(function () {
871
- var e_1, _a;
872
- _this._throwIfClosed();
873
- if (!_this.isStopped) {
874
- if (!_this.currentObservers) {
875
- _this.currentObservers = Array.from(_this.observers);
876
- }
877
- try {
878
- for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
879
- var observer = _c.value;
880
- observer.next(value);
881
- }
882
- } catch (e_1_1) {
883
- e_1 = {
884
- error: e_1_1
885
- };
886
- } finally {
887
- try {
888
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
889
- } finally {
890
- if (e_1) throw e_1.error;
891
- }
892
- }
962
+ return Subscriber;
963
+ }(Subscription);
964
+ var ConsumerObserver = function () {
965
+ function ConsumerObserver(partialObserver) {
966
+ this.partialObserver = partialObserver;
967
+ }
968
+ ConsumerObserver.prototype.next = function (value) {
969
+ var partialObserver = this.partialObserver;
970
+ if (partialObserver.next) {
971
+ try {
972
+ partialObserver.next(value);
973
+ } catch (error) {
974
+ handleUnhandledError(error);
893
975
  }
894
- });
976
+ }
895
977
  };
896
- Subject.prototype.error = function (err) {
897
- var _this = this;
898
- errorContext(function () {
899
- _this._throwIfClosed();
900
- if (!_this.isStopped) {
901
- _this.hasError = _this.isStopped = true;
902
- _this.thrownError = err;
903
- var observers = _this.observers;
904
- while (observers.length) {
905
- observers.shift().error(err);
906
- }
978
+ ConsumerObserver.prototype.error = function (err) {
979
+ var partialObserver = this.partialObserver;
980
+ if (partialObserver.error) {
981
+ try {
982
+ partialObserver.error(err);
983
+ } catch (error) {
984
+ handleUnhandledError(error);
907
985
  }
908
- });
986
+ } else {
987
+ handleUnhandledError(err);
988
+ }
909
989
  };
910
- Subject.prototype.complete = function () {
911
- var _this = this;
912
- errorContext(function () {
913
- _this._throwIfClosed();
914
- if (!_this.isStopped) {
915
- _this.isStopped = true;
916
- var observers = _this.observers;
917
- while (observers.length) {
918
- observers.shift().complete();
919
- }
990
+ ConsumerObserver.prototype.complete = function () {
991
+ var partialObserver = this.partialObserver;
992
+ if (partialObserver.complete) {
993
+ try {
994
+ partialObserver.complete();
995
+ } catch (error) {
996
+ handleUnhandledError(error);
920
997
  }
921
- });
922
- };
923
- Subject.prototype.unsubscribe = function () {
924
- this.isStopped = this.closed = true;
925
- this.observers = this.currentObservers = null;
926
- };
927
- Object.defineProperty(Subject.prototype, "observed", {
928
- get: function () {
929
- var _a;
930
- return ((_a = this.observers) === null || _a === undefined ? undefined : _a.length) > 0;
931
- },
932
- enumerable: false,
933
- configurable: true
934
- });
935
- Subject.prototype._trySubscribe = function (subscriber) {
936
- this._throwIfClosed();
937
- return _super.prototype._trySubscribe.call(this, subscriber);
938
- };
939
- Subject.prototype._subscribe = function (subscriber) {
940
- this._throwIfClosed();
941
- this._checkFinalizedStatuses(subscriber);
942
- return this._innerSubscribe(subscriber);
943
- };
944
- Subject.prototype._innerSubscribe = function (subscriber) {
945
- var _this = this;
946
- var _a = this,
947
- hasError = _a.hasError,
948
- isStopped = _a.isStopped,
949
- observers = _a.observers;
950
- if (hasError || isStopped) {
951
- return EMPTY_SUBSCRIPTION;
952
998
  }
953
- this.currentObservers = null;
954
- observers.push(subscriber);
955
- return new Subscription(function () {
956
- _this.currentObservers = null;
957
- arrRemove(observers, subscriber);
958
- });
959
999
  };
960
- Subject.prototype._checkFinalizedStatuses = function (subscriber) {
961
- var _a = this,
962
- hasError = _a.hasError,
963
- thrownError = _a.thrownError,
964
- isStopped = _a.isStopped;
965
- if (hasError) {
966
- subscriber.error(thrownError);
967
- } else if (isStopped) {
968
- subscriber.complete();
1000
+ return ConsumerObserver;
1001
+ }();
1002
+ var SafeSubscriber = function (_super) {
1003
+ __extends(SafeSubscriber, _super);
1004
+ function SafeSubscriber(observerOrNext, error, complete) {
1005
+ var _this = _super.call(this) || this;
1006
+ var partialObserver;
1007
+ if (isFunction(observerOrNext) || !observerOrNext) {
1008
+ partialObserver = {
1009
+ next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
1010
+ error: error !== null && error !== void 0 ? error : undefined,
1011
+ complete: complete !== null && complete !== void 0 ? complete : undefined
1012
+ };
1013
+ } else {
1014
+ {
1015
+ partialObserver = observerOrNext;
1016
+ }
969
1017
  }
1018
+ _this.destination = new ConsumerObserver(partialObserver);
1019
+ return _this;
1020
+ }
1021
+ return SafeSubscriber;
1022
+ }(Subscriber);
1023
+ function handleUnhandledError(error) {
1024
+ {
1025
+ reportUnhandledError(error);
1026
+ }
1027
+ }
1028
+ function defaultErrorHandler(err) {
1029
+ throw err;
1030
+ }
1031
+ var EMPTY_OBSERVER = {
1032
+ closed: true,
1033
+ next: noop,
1034
+ error: defaultErrorHandler,
1035
+ complete: noop
1036
+ };
1037
+
1038
+ var observable = function () {
1039
+ return typeof Symbol === 'function' && Symbol.observable || '@@observable';
1040
+ }();
1041
+
1042
+ function identity(x) {
1043
+ return x;
1044
+ }
1045
+
1046
+ function pipeFromArray(fns) {
1047
+ if (fns.length === 0) {
1048
+ return identity;
1049
+ }
1050
+ if (fns.length === 1) {
1051
+ return fns[0];
1052
+ }
1053
+ return function piped(input) {
1054
+ return fns.reduce(function (prev, fn) {
1055
+ return fn(prev);
1056
+ }, input);
970
1057
  };
971
- Subject.prototype.asObservable = function () {
1058
+ }
1059
+
1060
+ var Observable = function () {
1061
+ function Observable(subscribe) {
1062
+ if (subscribe) {
1063
+ this._subscribe = subscribe;
1064
+ }
1065
+ }
1066
+ Observable.prototype.lift = function (operator) {
972
1067
  var observable = new Observable();
973
1068
  observable.source = this;
1069
+ observable.operator = operator;
974
1070
  return observable;
975
1071
  };
976
- Subject.create = function (destination, source) {
977
- return new AnonymousSubject(destination, source);
1072
+ Observable.prototype.subscribe = function (observerOrNext, error, complete) {
1073
+ var _this = this;
1074
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
1075
+ errorContext(function () {
1076
+ var _a = _this,
1077
+ operator = _a.operator,
1078
+ source = _a.source;
1079
+ subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
1080
+ });
1081
+ return subscriber;
978
1082
  };
979
- return Subject;
980
- }(Observable);
981
- var AnonymousSubject = function (_super) {
982
- __extends(AnonymousSubject, _super);
983
- function AnonymousSubject(destination, source) {
984
- var _this = _super.call(this) || this;
985
- _this.destination = destination;
986
- _this.source = source;
987
- return _this;
988
- }
989
- AnonymousSubject.prototype.next = function (value) {
990
- var _a, _b;
991
- (_b = (_a = this.destination) === null || _a === undefined ? undefined : _a.next) === null || _b === undefined ? undefined : _b.call(_a, value);
1083
+ Observable.prototype._trySubscribe = function (sink) {
1084
+ try {
1085
+ return this._subscribe(sink);
1086
+ } catch (err) {
1087
+ sink.error(err);
1088
+ }
992
1089
  };
993
- AnonymousSubject.prototype.error = function (err) {
994
- var _a, _b;
995
- (_b = (_a = this.destination) === null || _a === undefined ? undefined : _a.error) === null || _b === undefined ? undefined : _b.call(_a, err);
1090
+ Observable.prototype.forEach = function (next, promiseCtor) {
1091
+ var _this = this;
1092
+ promiseCtor = getPromiseCtor(promiseCtor);
1093
+ return new promiseCtor(function (resolve, reject) {
1094
+ var subscriber = new SafeSubscriber({
1095
+ next: function (value) {
1096
+ try {
1097
+ next(value);
1098
+ } catch (err) {
1099
+ reject(err);
1100
+ subscriber.unsubscribe();
1101
+ }
1102
+ },
1103
+ error: reject,
1104
+ complete: resolve
1105
+ });
1106
+ _this.subscribe(subscriber);
1107
+ });
996
1108
  };
997
- AnonymousSubject.prototype.complete = function () {
998
- var _a, _b;
999
- (_b = (_a = this.destination) === null || _a === undefined ? undefined : _a.complete) === null || _b === undefined ? undefined : _b.call(_a);
1109
+ Observable.prototype._subscribe = function (subscriber) {
1110
+ var _a;
1111
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1000
1112
  };
1001
- AnonymousSubject.prototype._subscribe = function (subscriber) {
1002
- var _a, _b;
1003
- return (_b = (_a = this.source) === null || _a === undefined ? undefined : _a.subscribe(subscriber)) !== null && _b !== undefined ? _b : EMPTY_SUBSCRIPTION;
1113
+ Observable.prototype[observable] = function () {
1114
+ return this;
1004
1115
  };
1005
- return AnonymousSubject;
1006
- }(Subject);
1007
-
1008
- var EmptyError = createErrorClass(function (_super) {
1009
- return function EmptyErrorImpl() {
1010
- _super(this);
1011
- this.name = 'EmptyError';
1012
- this.message = 'no elements in sequence';
1116
+ Observable.prototype.pipe = function () {
1117
+ var operations = [];
1118
+ for (var _i = 0; _i < arguments.length; _i++) {
1119
+ operations[_i] = arguments[_i];
1120
+ }
1121
+ return pipeFromArray(operations)(this);
1013
1122
  };
1014
- });
1015
-
1016
- function firstValueFrom(source, config) {
1017
- return new Promise(function (resolve, reject) {
1018
- var subscriber = new SafeSubscriber({
1019
- next: function (value) {
1020
- resolve(value);
1021
- subscriber.unsubscribe();
1022
- },
1023
- error: reject,
1024
- complete: function () {
1025
- {
1026
- reject(new EmptyError());
1027
- }
1028
- }
1123
+ Observable.prototype.toPromise = function (promiseCtor) {
1124
+ var _this = this;
1125
+ promiseCtor = getPromiseCtor(promiseCtor);
1126
+ return new promiseCtor(function (resolve, reject) {
1127
+ var value;
1128
+ _this.subscribe(function (x) {
1129
+ return value = x;
1130
+ }, function (err) {
1131
+ return reject(err);
1132
+ }, function () {
1133
+ return resolve(value);
1134
+ });
1029
1135
  });
1030
- source.subscribe(subscriber);
1031
- });
1136
+ };
1137
+ Observable.create = function (subscribe) {
1138
+ return new Observable(subscribe);
1139
+ };
1140
+ return Observable;
1141
+ }();
1142
+ function getPromiseCtor(promiseCtor) {
1143
+ var _a;
1144
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
1032
1145
  }
1033
-
1034
- function filter(predicate, thisArg) {
1035
- return operate(function (source, subscriber) {
1036
- var index = 0;
1037
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1038
- return predicate.call(thisArg, value, index++) && subscriber.next(value);
1039
- }));
1040
- });
1146
+ function isObserver(value) {
1147
+ return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1041
1148
  }
1042
-
1043
- function getDefaultExportFromCjs (x) {
1044
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1149
+ function isSubscriber(value) {
1150
+ return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
1045
1151
  }
1046
1152
 
1047
- var loglevel$1 = {exports: {}};
1048
-
1049
- /*
1050
- * loglevel - https://github.com/pimterry/loglevel
1051
- *
1052
- * Copyright (c) 2013 Tim Perry
1053
- * Licensed under the MIT license.
1054
- */
1055
- var loglevel = loglevel$1.exports;
1056
- var hasRequiredLoglevel;
1057
- function requireLoglevel() {
1058
- if (hasRequiredLoglevel) return loglevel$1.exports;
1059
- hasRequiredLoglevel = 1;
1060
- (function (module) {
1061
- (function (root, definition) {
1062
-
1063
- if (module.exports) {
1064
- module.exports = definition();
1065
- } else {
1066
- root.log = definition();
1067
- }
1068
- })(loglevel, function () {
1069
-
1070
- // Slightly dubious tricks to cut down minimized file size
1071
- var noop = function () {};
1072
- var undefinedType = "undefined";
1073
- var isIE = typeof window !== undefinedType && typeof window.navigator !== undefinedType && /Trident\/|MSIE /.test(window.navigator.userAgent);
1074
- var logMethods = ["trace", "debug", "info", "warn", "error"];
1075
- var _loggersByName = {};
1076
- var defaultLogger = null;
1077
-
1078
- // Cross-browser bind equivalent that works at least back to IE6
1079
- function bindMethod(obj, methodName) {
1080
- var method = obj[methodName];
1081
- if (typeof method.bind === 'function') {
1082
- return method.bind(obj);
1083
- } else {
1084
- try {
1085
- return Function.prototype.bind.call(method, obj);
1086
- } catch (e) {
1087
- // Missing bind shim or IE8 + Modernizr, fallback to wrapping
1088
- return function () {
1089
- return Function.prototype.apply.apply(method, [obj, arguments]);
1090
- };
1091
- }
1092
- }
1093
- }
1094
-
1095
- // Trace() doesn't print the message in IE, so for that case we need to wrap it
1096
- function traceForIE() {
1097
- if (console.log) {
1098
- if (console.log.apply) {
1099
- console.log.apply(console, arguments);
1100
- } else {
1101
- // In old IE, native console methods themselves don't have apply().
1102
- Function.prototype.apply.apply(console.log, [console, arguments]);
1103
- }
1104
- }
1105
- if (console.trace) console.trace();
1106
- }
1107
-
1108
- // Build the best logging method possible for this env
1109
- // Wherever possible we want to bind, not wrap, to preserve stack traces
1110
- function realMethod(methodName) {
1111
- if (methodName === 'debug') {
1112
- methodName = 'log';
1113
- }
1114
- if (typeof console === undefinedType) {
1115
- return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
1116
- } else if (methodName === 'trace' && isIE) {
1117
- return traceForIE;
1118
- } else if (console[methodName] !== undefined) {
1119
- return bindMethod(console, methodName);
1120
- } else if (console.log !== undefined) {
1121
- return bindMethod(console, 'log');
1122
- } else {
1123
- return noop;
1124
- }
1125
- }
1126
-
1127
- // These private functions always need `this` to be set properly
1128
-
1129
- function replaceLoggingMethods() {
1130
- /*jshint validthis:true */
1131
- var level = this.getLevel();
1132
-
1133
- // Replace the actual methods.
1134
- for (var i = 0; i < logMethods.length; i++) {
1135
- var methodName = logMethods[i];
1136
- this[methodName] = i < level ? noop : this.methodFactory(methodName, level, this.name);
1153
+ function hasLift(source) {
1154
+ return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1155
+ }
1156
+ function operate(init) {
1157
+ return function (source) {
1158
+ if (hasLift(source)) {
1159
+ return source.lift(function (liftedSource) {
1160
+ try {
1161
+ return init(liftedSource, this);
1162
+ } catch (err) {
1163
+ this.error(err);
1137
1164
  }
1165
+ });
1166
+ }
1167
+ throw new TypeError('Unable to lift unknown Observable type');
1168
+ };
1169
+ }
1138
1170
 
1139
- // Define log.log as an alias for log.debug
1140
- this.log = this.debug;
1141
-
1142
- // Return any important warnings.
1143
- if (typeof console === undefinedType && level < this.levels.SILENT) {
1144
- return "No console available for logging";
1145
- }
1171
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1172
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1173
+ }
1174
+ var OperatorSubscriber = function (_super) {
1175
+ __extends(OperatorSubscriber, _super);
1176
+ function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1177
+ var _this = _super.call(this, destination) || this;
1178
+ _this.onFinalize = onFinalize;
1179
+ _this.shouldUnsubscribe = shouldUnsubscribe;
1180
+ _this._next = onNext ? function (value) {
1181
+ try {
1182
+ onNext(value);
1183
+ } catch (err) {
1184
+ destination.error(err);
1146
1185
  }
1147
-
1148
- // In old IE versions, the console isn't present until you first open it.
1149
- // We build realMethod() replacements here that regenerate logging methods
1150
- function enableLoggingWhenConsoleArrives(methodName) {
1151
- return function () {
1152
- if (typeof console !== undefinedType) {
1153
- replaceLoggingMethods.call(this);
1154
- this[methodName].apply(this, arguments);
1155
- }
1156
- };
1186
+ } : _super.prototype._next;
1187
+ _this._error = onError ? function (err) {
1188
+ try {
1189
+ onError(err);
1190
+ } catch (err) {
1191
+ destination.error(err);
1192
+ } finally {
1193
+ this.unsubscribe();
1157
1194
  }
1158
-
1159
- // By default, we use closely bound real methods wherever possible, and
1160
- // otherwise we wait for a console to appear, and then try again.
1161
- function defaultMethodFactory(methodName, _level, _loggerName) {
1162
- /*jshint validthis:true */
1163
- return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments);
1195
+ } : _super.prototype._error;
1196
+ _this._complete = onComplete ? function () {
1197
+ try {
1198
+ onComplete();
1199
+ } catch (err) {
1200
+ destination.error(err);
1201
+ } finally {
1202
+ this.unsubscribe();
1164
1203
  }
1165
- function Logger(name, factory) {
1166
- // Private instance variables.
1167
- var self = this;
1168
- /**
1169
- * The level inherited from a parent logger (or a global default). We
1170
- * cache this here rather than delegating to the parent so that it stays
1171
- * in sync with the actual logging methods that we have installed (the
1172
- * parent could change levels but we might not have rebuilt the loggers
1173
- * in this child yet).
1174
- * @type {number}
1175
- */
1176
- var inheritedLevel;
1177
- /**
1178
- * The default level for this logger, if any. If set, this overrides
1179
- * `inheritedLevel`.
1180
- * @type {number|null}
1181
- */
1182
- var defaultLevel;
1183
- /**
1184
- * A user-specific level for this logger. If set, this overrides
1185
- * `defaultLevel`.
1186
- * @type {number|null}
1187
- */
1188
- var userLevel;
1189
- var storageKey = "loglevel";
1190
- if (typeof name === "string") {
1191
- storageKey += ":" + name;
1192
- } else if (typeof name === "symbol") {
1193
- storageKey = undefined;
1194
- }
1195
- function persistLevelIfPossible(levelNum) {
1196
- var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
1197
- if (typeof window === undefinedType || !storageKey) return;
1204
+ } : _super.prototype._complete;
1205
+ return _this;
1206
+ }
1207
+ OperatorSubscriber.prototype.unsubscribe = function () {
1208
+ var _a;
1209
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1210
+ var closed_1 = this.closed;
1211
+ _super.prototype.unsubscribe.call(this);
1212
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1213
+ }
1214
+ };
1215
+ return OperatorSubscriber;
1216
+ }(Subscriber);
1198
1217
 
1199
- // Use localStorage if available
1200
- try {
1201
- window.localStorage[storageKey] = levelName;
1202
- return;
1203
- } catch (ignore) {}
1218
+ var ObjectUnsubscribedError = createErrorClass(function (_super) {
1219
+ return function ObjectUnsubscribedErrorImpl() {
1220
+ _super(this);
1221
+ this.name = 'ObjectUnsubscribedError';
1222
+ this.message = 'object unsubscribed';
1223
+ };
1224
+ });
1204
1225
 
1205
- // Use session cookie as fallback
1206
- try {
1207
- window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";";
1208
- } catch (ignore) {}
1226
+ var Subject = function (_super) {
1227
+ __extends(Subject, _super);
1228
+ function Subject() {
1229
+ var _this = _super.call(this) || this;
1230
+ _this.closed = false;
1231
+ _this.currentObservers = null;
1232
+ _this.observers = [];
1233
+ _this.isStopped = false;
1234
+ _this.hasError = false;
1235
+ _this.thrownError = null;
1236
+ return _this;
1237
+ }
1238
+ Subject.prototype.lift = function (operator) {
1239
+ var subject = new AnonymousSubject(this, this);
1240
+ subject.operator = operator;
1241
+ return subject;
1242
+ };
1243
+ Subject.prototype._throwIfClosed = function () {
1244
+ if (this.closed) {
1245
+ throw new ObjectUnsubscribedError();
1246
+ }
1247
+ };
1248
+ Subject.prototype.next = function (value) {
1249
+ var _this = this;
1250
+ errorContext(function () {
1251
+ var e_1, _a;
1252
+ _this._throwIfClosed();
1253
+ if (!_this.isStopped) {
1254
+ if (!_this.currentObservers) {
1255
+ _this.currentObservers = Array.from(_this.observers);
1209
1256
  }
1210
- function getPersistedLevel() {
1211
- var storedLevel;
1212
- if (typeof window === undefinedType || !storageKey) return;
1213
- try {
1214
- storedLevel = window.localStorage[storageKey];
1215
- } catch (ignore) {}
1216
-
1217
- // Fallback to cookies if local storage gives us nothing
1218
- if (typeof storedLevel === undefinedType) {
1219
- try {
1220
- var cookie = window.document.cookie;
1221
- var cookieName = encodeURIComponent(storageKey);
1222
- var location = cookie.indexOf(cookieName + "=");
1223
- if (location !== -1) {
1224
- storedLevel = /^([^;]+)/.exec(cookie.slice(location + cookieName.length + 1))[1];
1225
- }
1226
- } catch (ignore) {}
1227
- }
1228
-
1229
- // If the stored level is not valid, treat it as if nothing was stored.
1230
- if (self.levels[storedLevel] === undefined) {
1231
- storedLevel = undefined;
1257
+ try {
1258
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1259
+ var observer = _c.value;
1260
+ observer.next(value);
1232
1261
  }
1233
- return storedLevel;
1234
- }
1235
- function clearPersistedLevel() {
1236
- if (typeof window === undefinedType || !storageKey) return;
1237
-
1238
- // Use localStorage if available
1239
- try {
1240
- window.localStorage.removeItem(storageKey);
1241
- } catch (ignore) {}
1242
-
1243
- // Use session cookie as fallback
1262
+ } catch (e_1_1) {
1263
+ e_1 = {
1264
+ error: e_1_1
1265
+ };
1266
+ } finally {
1244
1267
  try {
1245
- window.document.cookie = encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
1246
- } catch (ignore) {}
1247
- }
1248
- function normalizeLevel(input) {
1249
- var level = input;
1250
- if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
1251
- level = self.levels[level.toUpperCase()];
1252
- }
1253
- if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
1254
- return level;
1255
- } else {
1256
- throw new TypeError("log.setLevel() called with invalid level: " + input);
1268
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1269
+ } finally {
1270
+ if (e_1) throw e_1.error;
1257
1271
  }
1258
1272
  }
1259
-
1260
- /*
1261
- *
1262
- * Public logger API - see https://github.com/pimterry/loglevel for details
1263
- *
1264
- */
1265
-
1266
- self.name = name;
1267
- self.levels = {
1268
- "TRACE": 0,
1269
- "DEBUG": 1,
1270
- "INFO": 2,
1271
- "WARN": 3,
1272
- "ERROR": 4,
1273
- "SILENT": 5
1274
- };
1275
- self.methodFactory = factory || defaultMethodFactory;
1276
- self.getLevel = function () {
1277
- if (userLevel != null) {
1278
- return userLevel;
1279
- } else if (defaultLevel != null) {
1280
- return defaultLevel;
1281
- } else {
1282
- return inheritedLevel;
1283
- }
1284
- };
1285
- self.setLevel = function (level, persist) {
1286
- userLevel = normalizeLevel(level);
1287
- if (persist !== false) {
1288
- // defaults to true
1289
- persistLevelIfPossible(userLevel);
1290
- }
1291
-
1292
- // NOTE: in v2, this should call rebuild(), which updates children.
1293
- return replaceLoggingMethods.call(self);
1294
- };
1295
- self.setDefaultLevel = function (level) {
1296
- defaultLevel = normalizeLevel(level);
1297
- if (!getPersistedLevel()) {
1298
- self.setLevel(level, false);
1299
- }
1300
- };
1301
- self.resetLevel = function () {
1302
- userLevel = null;
1303
- clearPersistedLevel();
1304
- replaceLoggingMethods.call(self);
1305
- };
1306
- self.enableAll = function (persist) {
1307
- self.setLevel(self.levels.TRACE, persist);
1308
- };
1309
- self.disableAll = function (persist) {
1310
- self.setLevel(self.levels.SILENT, persist);
1311
- };
1312
- self.rebuild = function () {
1313
- if (defaultLogger !== self) {
1314
- inheritedLevel = normalizeLevel(defaultLogger.getLevel());
1315
- }
1316
- replaceLoggingMethods.call(self);
1317
- if (defaultLogger === self) {
1318
- for (var childName in _loggersByName) {
1319
- _loggersByName[childName].rebuild();
1320
- }
1321
- }
1322
- };
1323
-
1324
- // Initialize all the internal levels.
1325
- inheritedLevel = normalizeLevel(defaultLogger ? defaultLogger.getLevel() : "WARN");
1326
- var initialLevel = getPersistedLevel();
1327
- if (initialLevel != null) {
1328
- userLevel = normalizeLevel(initialLevel);
1273
+ }
1274
+ });
1275
+ };
1276
+ Subject.prototype.error = function (err) {
1277
+ var _this = this;
1278
+ errorContext(function () {
1279
+ _this._throwIfClosed();
1280
+ if (!_this.isStopped) {
1281
+ _this.hasError = _this.isStopped = true;
1282
+ _this.thrownError = err;
1283
+ var observers = _this.observers;
1284
+ while (observers.length) {
1285
+ observers.shift().error(err);
1329
1286
  }
1330
- replaceLoggingMethods.call(self);
1331
1287
  }
1288
+ });
1289
+ };
1290
+ Subject.prototype.complete = function () {
1291
+ var _this = this;
1292
+ errorContext(function () {
1293
+ _this._throwIfClosed();
1294
+ if (!_this.isStopped) {
1295
+ _this.isStopped = true;
1296
+ var observers = _this.observers;
1297
+ while (observers.length) {
1298
+ observers.shift().complete();
1299
+ }
1300
+ }
1301
+ });
1302
+ };
1303
+ Subject.prototype.unsubscribe = function () {
1304
+ this.isStopped = this.closed = true;
1305
+ this.observers = this.currentObservers = null;
1306
+ };
1307
+ Object.defineProperty(Subject.prototype, "observed", {
1308
+ get: function () {
1309
+ var _a;
1310
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1311
+ },
1312
+ enumerable: false,
1313
+ configurable: true
1314
+ });
1315
+ Subject.prototype._trySubscribe = function (subscriber) {
1316
+ this._throwIfClosed();
1317
+ return _super.prototype._trySubscribe.call(this, subscriber);
1318
+ };
1319
+ Subject.prototype._subscribe = function (subscriber) {
1320
+ this._throwIfClosed();
1321
+ this._checkFinalizedStatuses(subscriber);
1322
+ return this._innerSubscribe(subscriber);
1323
+ };
1324
+ Subject.prototype._innerSubscribe = function (subscriber) {
1325
+ var _this = this;
1326
+ var _a = this,
1327
+ hasError = _a.hasError,
1328
+ isStopped = _a.isStopped,
1329
+ observers = _a.observers;
1330
+ if (hasError || isStopped) {
1331
+ return EMPTY_SUBSCRIPTION;
1332
+ }
1333
+ this.currentObservers = null;
1334
+ observers.push(subscriber);
1335
+ return new Subscription(function () {
1336
+ _this.currentObservers = null;
1337
+ arrRemove(observers, subscriber);
1338
+ });
1339
+ };
1340
+ Subject.prototype._checkFinalizedStatuses = function (subscriber) {
1341
+ var _a = this,
1342
+ hasError = _a.hasError,
1343
+ thrownError = _a.thrownError,
1344
+ isStopped = _a.isStopped;
1345
+ if (hasError) {
1346
+ subscriber.error(thrownError);
1347
+ } else if (isStopped) {
1348
+ subscriber.complete();
1349
+ }
1350
+ };
1351
+ Subject.prototype.asObservable = function () {
1352
+ var observable = new Observable();
1353
+ observable.source = this;
1354
+ return observable;
1355
+ };
1356
+ Subject.create = function (destination, source) {
1357
+ return new AnonymousSubject(destination, source);
1358
+ };
1359
+ return Subject;
1360
+ }(Observable);
1361
+ var AnonymousSubject = function (_super) {
1362
+ __extends(AnonymousSubject, _super);
1363
+ function AnonymousSubject(destination, source) {
1364
+ var _this = _super.call(this) || this;
1365
+ _this.destination = destination;
1366
+ _this.source = source;
1367
+ return _this;
1368
+ }
1369
+ AnonymousSubject.prototype.next = function (value) {
1370
+ var _a, _b;
1371
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1372
+ };
1373
+ AnonymousSubject.prototype.error = function (err) {
1374
+ var _a, _b;
1375
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1376
+ };
1377
+ AnonymousSubject.prototype.complete = function () {
1378
+ var _a, _b;
1379
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1380
+ };
1381
+ AnonymousSubject.prototype._subscribe = function (subscriber) {
1382
+ var _a, _b;
1383
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1384
+ };
1385
+ return AnonymousSubject;
1386
+ }(Subject);
1332
1387
 
1333
- /*
1334
- *
1335
- * Top-level API
1336
- *
1337
- */
1388
+ var EmptyError = createErrorClass(function (_super) {
1389
+ return function EmptyErrorImpl() {
1390
+ _super(this);
1391
+ this.name = 'EmptyError';
1392
+ this.message = 'no elements in sequence';
1393
+ };
1394
+ });
1338
1395
 
1339
- defaultLogger = new Logger();
1340
- defaultLogger.getLogger = function getLogger(name) {
1341
- if (typeof name !== "symbol" && typeof name !== "string" || name === "") {
1342
- throw new TypeError("You must supply a name when creating a logger.");
1343
- }
1344
- var logger = _loggersByName[name];
1345
- if (!logger) {
1346
- logger = _loggersByName[name] = new Logger(name, defaultLogger.methodFactory);
1396
+ function firstValueFrom(source, config) {
1397
+ return new Promise(function (resolve, reject) {
1398
+ var subscriber = new SafeSubscriber({
1399
+ next: function (value) {
1400
+ resolve(value);
1401
+ subscriber.unsubscribe();
1402
+ },
1403
+ error: reject,
1404
+ complete: function () {
1405
+ {
1406
+ reject(new EmptyError());
1347
1407
  }
1348
- return logger;
1349
- };
1408
+ }
1409
+ });
1410
+ source.subscribe(subscriber);
1411
+ });
1412
+ }
1350
1413
 
1351
- // Grab the current global log variable in case of overwrite
1352
- var _log = typeof window !== undefinedType ? window.log : undefined;
1353
- defaultLogger.noConflict = function () {
1354
- if (typeof window !== undefinedType && window.log === defaultLogger) {
1355
- window.log = _log;
1356
- }
1357
- return defaultLogger;
1358
- };
1359
- defaultLogger.getLoggers = function getLoggers() {
1360
- return _loggersByName;
1361
- };
1414
+ function map(project, thisArg) {
1415
+ return operate(function (source, subscriber) {
1416
+ var index = 0;
1417
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1418
+ subscriber.next(project.call(thisArg, value, index++));
1419
+ }));
1420
+ });
1421
+ }
1362
1422
 
1363
- // ES6 default export, for compatibility
1364
- defaultLogger['default'] = defaultLogger;
1365
- return defaultLogger;
1366
- });
1367
- })(loglevel$1);
1368
- return loglevel$1.exports;
1423
+ function filter(predicate, thisArg) {
1424
+ return operate(function (source, subscriber) {
1425
+ var index = 0;
1426
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1427
+ return predicate.call(thisArg, value, index++) && subscriber.next(value);
1428
+ }));
1429
+ });
1369
1430
  }
1370
1431
 
1371
- var loglevelExports = requireLoglevel();
1372
- var log$1 = /*@__PURE__*/getDefaultExportFromCjs(loglevelExports);
1432
+ const bigIntReplacer = (_key, value) => {
1433
+ return typeof value === "bigint" ? value.toString() : value;
1434
+ };
1435
+ /**
1436
+ * Creates a window features string for `window.open`, based on the current screen size.
1437
+ * It tries to center the window and limits the size to the given max width and height.
1438
+ * Slightly reduces the size to avoid browser auto-resizing.
1439
+ */
1440
+ const getWindowFeatures = (maxWidth, maxHeight) => {
1441
+ const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
1442
+ const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
1443
+ const w = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : window.screen.width;
1444
+ const h = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : window.screen.height;
1445
+ // 95% adjustment for mobile devices, some browser might resize the window
1446
+ const finalWidth = Math.min(w, maxWidth) * 0.95;
1447
+ const finalHeight = Math.min(h, maxHeight) * 0.95;
1448
+ const systemZoom = 1; // No reliable estimate
1449
+ const left = Math.abs((w - finalWidth) / 2 / systemZoom + dualScreenLeft);
1450
+ const top = Math.abs((h - finalHeight) / 2 / systemZoom + dualScreenTop);
1451
+ return `titlebar=0,toolbar=0,status=0,location=0,menubar=0,height=${finalHeight / systemZoom},width=${finalWidth / systemZoom},top=${top},left=${left}`;
1452
+ };
1373
1453
 
1374
- var log = log$1.getLogger("airkit");
1454
+ // refer to realm-network-api/src/common/enums/error-codes.enum.ts
1455
+ /*** Authentication Errors ***/
1456
+ var AuthErrorName;
1457
+ (function (AuthErrorName) {
1458
+ AuthErrorName["UNAUTHORIZED"] = "UNAUTHORIZED";
1459
+ AuthErrorName["INVALID_TOKEN"] = "INVALID_TOKEN";
1460
+ AuthErrorName["TOKEN_EXPIRED"] = "TOKEN_EXPIRED";
1461
+ AuthErrorName["INVALID_CREDENTIALS"] = "INVALID_CREDENTIALS";
1462
+ })(AuthErrorName || (AuthErrorName = {}));
1463
+ /*** Partner Access Token Errors ***/
1464
+ var PartnerAccessTokenErrorName;
1465
+ (function (PartnerAccessTokenErrorName) {
1466
+ PartnerAccessTokenErrorName["PARTNER_ACCESS_TOKEN_INVALID"] = "PARTNER_ACCESS_TOKEN_INVALID";
1467
+ PartnerAccessTokenErrorName["USER_MISMATCH"] = "USER_MISMATCH";
1468
+ })(PartnerAccessTokenErrorName || (PartnerAccessTokenErrorName = {}));
1469
+ /*** Realm ID Errors ***/
1470
+ var RealmIDErrorName;
1471
+ (function (RealmIDErrorName) {
1472
+ RealmIDErrorName["REALM_ID_NOT_FOUND"] = "REALM_ID_NOT_FOUND";
1473
+ RealmIDErrorName["REALM_ID_INVALID_NAME"] = "REALM_ID_INVALID_NAME";
1474
+ RealmIDErrorName["REALM_ID_ALREADY_EXISTS"] = "REALM_ID_ALREADY_EXISTS";
1475
+ RealmIDErrorName["REALM_ID_DUPLICATE_PARTNER_USER"] = "REALM_ID_DUPLICATE_PARTNER_USER";
1476
+ })(RealmIDErrorName || (RealmIDErrorName = {}));
1477
+ /*** Parameter Errors ***/
1478
+ var ParameterErrorName;
1479
+ (function (ParameterErrorName) {
1480
+ ParameterErrorName["INVALID_PARAMETER"] = "INVALID_PARAMETER";
1481
+ })(ParameterErrorName || (ParameterErrorName = {}));
1482
+ /*** Server Errors ***/
1483
+ var ServerErrorName;
1484
+ (function (ServerErrorName) {
1485
+ ServerErrorName["INTERNAL_SERVER_ERROR"] = "INTERNAL_SERVER_ERROR";
1486
+ })(ServerErrorName || (ServerErrorName = {}));
1487
+ /*** Passkey Errors ***/
1488
+ var PasskeyErrorName;
1489
+ (function (PasskeyErrorName) {
1490
+ PasskeyErrorName["PASSKEY_REGISTRATION_FAILED"] = "PASSKEY_REGISTRATION_FAILED";
1491
+ PasskeyErrorName["PASSKEY_AUTHENTICATION_FAILED"] = "PASSKEY_AUTHENTICATION_FAILED";
1492
+ PasskeyErrorName["PASSKEY_LIMIT_EXCEEDED"] = "PASSKEY_LIMIT_EXCEEDED";
1493
+ PasskeyErrorName["PASSKEY_NOT_FOUND"] = "PASSKEY_NOT_FOUND";
1494
+ PasskeyErrorName["PASSKEY_UNAUTHORIZED"] = "PASSKEY_UNAUTHORIZED";
1495
+ PasskeyErrorName["PASSKEY_CHALLENGE_INVALID"] = "PASSKEY_CHALLENGE_INVALID";
1496
+ })(PasskeyErrorName || (PasskeyErrorName = {}));
1497
+ /*** Passwordless Authentication Errors ***/
1498
+ var PasswordlessErrorName;
1499
+ (function (PasswordlessErrorName) {
1500
+ PasswordlessErrorName["PASSWORDLESS_CODE_EXPIRED"] = "PASSWORDLESS_CODE_EXPIRED";
1501
+ PasswordlessErrorName["PASSWORDLESS_INVALID_CODE"] = "PASSWORDLESS_INVALID_CODE";
1502
+ PasswordlessErrorName["PASSWORDLESS_MAX_ATTEMPTS"] = "PASSWORDLESS_MAX_ATTEMPTS";
1503
+ PasswordlessErrorName["PASSWORDLESS_HOURLY_LIMIT"] = "PASSWORDLESS_HOURLY_LIMIT";
1504
+ PasswordlessErrorName["PASSWORDLESS_LOCK_EXCEEDED"] = "PASSWORDLESS_LOCK_EXCEEDED";
1505
+ PasswordlessErrorName["CAPTCHA_TOKEN_VERIFICATION_FAILED"] = "CAPTCHA_TOKEN_VERIFICATION_FAILED";
1506
+ PasswordlessErrorName["CAPTCHA_TOKEN_INVALID"] = "CAPTCHA_TOKEN_INVALID";
1507
+ PasswordlessErrorName["CAPTCHA_SECRET_MISSING"] = "CAPTCHA_SECRET_MISSING";
1508
+ PasswordlessErrorName["CAPTCHA_TOKEN_MISSING"] = "CAPTCHA_TOKEN_MISSING";
1509
+ })(PasswordlessErrorName || (PasswordlessErrorName = {}));
1510
+ /*** Authentication Wallet Errors ***/
1511
+ var AuthWalletErrorName;
1512
+ (function (AuthWalletErrorName) {
1513
+ AuthWalletErrorName["AUTH_WALLET_LOCK_EXCEEDED"] = "AUTH_WALLET_LOCK_EXCEEDED";
1514
+ AuthWalletErrorName["AUTH_WALLET_NONCE_EXPIRED_OR_INVALID"] = "AUTH_WALLET_NONCE_EXPIRED_OR_INVALID";
1515
+ AuthWalletErrorName["AUTH_WALLET_ADDRESS_MISMATCH"] = "AUTH_WALLET_ADDRESS_MISMATCH";
1516
+ AuthWalletErrorName["AUTH_WALLET_SIGNATURE_VERIFICATION_FAILED"] = "AUTH_WALLET_SIGNATURE_VERIFICATION_FAILED";
1517
+ })(AuthWalletErrorName || (AuthWalletErrorName = {}));
1518
+ /*** Wallet Linking Errors ***/
1519
+ var WalletLinkErrorName;
1520
+ (function (WalletLinkErrorName) {
1521
+ WalletLinkErrorName["LINK_WALLET_ALREADY_LINKED"] = "LINK_WALLET_ALREADY_LINKED";
1522
+ WalletLinkErrorName["LINK_WALLET_LINKED_OTHER_ACCOUNT"] = "LINK_WALLET_LINKED_OTHER_ACCOUNT";
1523
+ WalletLinkErrorName["LINK_EMAIL_LINKED_OTHER_ACCOUNT"] = "LINK_EMAIL_LINKED_OTHER_ACCOUNT";
1524
+ })(WalletLinkErrorName || (WalletLinkErrorName = {}));
1525
+ /*** Intent Errors ***/
1526
+ var IntentErrorName;
1527
+ (function (IntentErrorName) {
1528
+ IntentErrorName["INTENT_INVALID"] = "INTENT_INVALID";
1529
+ IntentErrorName["INTENT_LOCK_EXCEEDED"] = "INTENT_LOCK_EXCEEDED";
1530
+ IntentErrorName["INTENT_REQUIRED"] = "INTENT_REQUIRED";
1531
+ IntentErrorName["INTENT_UNSUPPORTED_TYPE"] = "INTENT_UNSUPPORTED_TYPE";
1532
+ })(IntentErrorName || (IntentErrorName = {}));
1533
+ /*** Privy Errors ***/
1534
+ var PrivyErrorName;
1535
+ (function (PrivyErrorName) {
1536
+ PrivyErrorName["WALLET_PROVIDER_ERROR"] = "WALLET_PROVIDER_ERROR";
1537
+ })(PrivyErrorName || (PrivyErrorName = {}));
1538
+ /*** Air ID Errors ***/
1539
+ var AirIDErrorName;
1540
+ (function (AirIDErrorName) {
1541
+ AirIDErrorName["AIR_ID_MINT_TRANSACTION_NOT_FOUND"] = "AIR_ID_MINT_TRANSACTION_NOT_FOUND";
1542
+ AirIDErrorName["AIR_ID_ON_CHAIN_TRANSACTION_NOT_FOUND"] = "AIR_ID_ON_CHAIN_TRANSACTION_NOT_FOUND";
1543
+ AirIDErrorName["AIR_ID_NOT_FOUND"] = "AIR_ID_NOT_FOUND";
1544
+ AirIDErrorName["AIR_ID_INVALID_OR_DISABLED_CONFIGURATION"] = "AIR_ID_INVALID_OR_DISABLED_CONFIGURATION";
1545
+ AirIDErrorName["AIR_ID_RPC_URL_NOT_CONFIGURED"] = "AIR_ID_RPC_URL_NOT_CONFIGURED";
1546
+ AirIDErrorName["AIR_ID_INVALID_STATUS"] = "AIR_ID_INVALID_STATUS";
1547
+ AirIDErrorName["AIR_ID_PARTNER_ELIGIBILITY_CHECK_FAILED"] = "AIR_ID_PARTNER_ELIGIBILITY_CHECK_FAILED";
1548
+ AirIDErrorName["AIR_ID_PARTNER_ELIGIBILITY_CHECK_TIMEOUT"] = "AIR_ID_PARTNER_ELIGIBILITY_CHECK_TIMEOUT";
1549
+ AirIDErrorName["AIR_ID_MULTIPLE_AIR_IDS_FOUND"] = "AIR_ID_MULTIPLE_AIR_IDS_FOUND";
1550
+ AirIDErrorName["AIR_ID_NAME_RESERVED"] = "AIR_ID_NAME_RESERVED";
1551
+ AirIDErrorName["AIR_ID_NAME_PROFANITY"] = "AIR_ID_NAME_PROFANITY";
1552
+ AirIDErrorName["AIR_ID_USER_ALREADY_HAS_AIR_ID"] = "AIR_ID_USER_ALREADY_HAS_AIR_ID";
1553
+ AirIDErrorName["AIR_ID_NAME_ALREADY_EXISTS"] = "AIR_ID_NAME_ALREADY_EXISTS";
1554
+ AirIDErrorName["AIR_ID_INVALID_MINT_NAME"] = "AIR_ID_INVALID_MINT_NAME";
1555
+ AirIDErrorName["AIR_ID_MINT_TRANSACTION_HASH_MISMATCH"] = "AIR_ID_MINT_TRANSACTION_HASH_MISMATCH";
1556
+ })(AirIDErrorName || (AirIDErrorName = {}));
1557
+ /*** Window Errors ***/
1558
+ var WindowErrorName;
1559
+ (function (WindowErrorName) {
1560
+ WindowErrorName["WINDOW_BLOCKED"] = "WINDOW_BLOCKED";
1561
+ WindowErrorName["WINDOW_CLOSED"] = "WINDOW_CLOSED";
1562
+ })(WindowErrorName || (WindowErrorName = {}));
1563
+ const Codes = {
1564
+ ...AuthErrorName,
1565
+ ...PartnerAccessTokenErrorName,
1566
+ ...RealmIDErrorName,
1567
+ ...ParameterErrorName,
1568
+ ...ServerErrorName,
1569
+ ...PasskeyErrorName,
1570
+ ...PasswordlessErrorName,
1571
+ ...AuthWalletErrorName,
1572
+ ...WalletLinkErrorName,
1573
+ ...IntentErrorName,
1574
+ ...PrivyErrorName,
1575
+ ...AirIDErrorName,
1576
+ ...WindowErrorName
1577
+ };
1375
1578
 
1376
- var AirWalletProviderMessageTypes;
1377
- (function (AirWalletProviderMessageTypes) {
1378
- AirWalletProviderMessageTypes["REQUEST"] = "JRPC_REQUEST";
1379
- AirWalletProviderMessageTypes["RESPONSE"] = "JRPC_RESPONSE";
1380
- AirWalletProviderMessageTypes["EVENT"] = "JRPC_EVENT";
1381
- })(AirWalletProviderMessageTypes || (AirWalletProviderMessageTypes = {}));
1579
+ const AirClientUserErrors = ["USER_CANCELLED", "CONFIG_ERROR", "CLIENT_ERROR", "UNKNOWN_ERROR", "PERMISSION_NOT_ENABLED", "SMART_ACCOUNT_NOT_DEPLOYED"];
1382
1580
 
1383
- const ACCOUNT_MESSAGES = [
1384
- AirMessageTypes.INITIALIZATION_RESPONSE,
1385
- AirMessageTypes.WALLET_INITIALIZED,
1386
- AirMessageTypes.WALLET_LOGIN_RESPONSE,
1387
- AirMessageTypes.SETUP_MFA_RESPONSE,
1388
- AirMessageTypes.CLAIM_ID_RESPONSE,
1389
- AirMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_RESPONSE,
1390
- AirMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE,
1391
- AirMessageTypes.EXECUTE_ACTION_RESPONSE,
1392
- AirMessageTypes.REVOKE_PERMISSIONS_RESPONSE,
1393
- AirMessageTypes.GRANT_PERMISSIONS_RESPONSE,
1394
- AirMessageTypes.LIST_ALL_SESSION_KEY_SCOPES_RESPONSE,
1395
- AirMessageTypes.WALLET_INITIALIZED,
1396
- AirMessageTypes.WALLET_IFRAME_VISIBILITY_REQUEST,
1397
- AirMessageTypes.LOGOUT_RESPONSE,
1398
- AirMessageTypes.OPEN_WINDOW_REQUEST,
1399
- ];
1400
- const AUTH_MESSAGES = [
1401
- AirAuthMessageTypes.INITIALIZATION_RESPONSE,
1402
- AirAuthMessageTypes.LOGIN_RESPONSE,
1403
- AirAuthMessageTypes.REFRESH_TOKEN_RESPONSE,
1404
- AirAuthMessageTypes.SETUP_WALLET_REQUEST,
1405
- AirAuthMessageTypes.LOGOUT_RESPONSE,
1406
- AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE,
1407
- AirAuthMessageTypes.CROSS_PARTNER_TOKEN_RESPONSE,
1408
- AirAuthMessageTypes.GET_PARTNER_ACCESS_TOKEN_RESPONSE,
1409
- AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST,
1410
- ];
1411
- class AirMessageService {
1412
- constructor() {
1413
- this.closeAuthMessageListeners = null;
1414
- this.closeRealmMessageListeners = null;
1415
- this.closeWalletMessageListeners = null;
1416
- }
1417
- static get instance() {
1418
- if (!AirMessageService._instance) {
1419
- AirMessageService._instance = new AirMessageService();
1420
- }
1421
- return AirMessageService._instance;
1422
- }
1423
- get messages$() {
1424
- return this.airMessages$.asObservable();
1425
- }
1426
- get authMessage$() {
1427
- return this._authMessage$.asObservable();
1428
- }
1429
- get providerMessage$() {
1430
- return this._providerMessage$.asObservable();
1431
- }
1432
- get providerEvent$() {
1433
- return this._providerEvent$.asObservable();
1434
- }
1435
- async openAuthObservables({ authIframeOrigin }) {
1436
- this.closeAuthObservables();
1437
- this.setupAuthObservables();
1438
- const handleAuthMessage = async (ev) => {
1439
- if (ev.origin !== authIframeOrigin || !ev.data || !(ev.data instanceof Object))
1440
- return;
1441
- log.debug("Embed auth message received from auth", ev.data);
1442
- if (AUTH_MESSAGES.includes(ev.data.type)) {
1443
- this._authMessage$.next(ev.data);
1444
- }
1445
- };
1446
- window.addEventListener("message", handleAuthMessage);
1447
- this.closeAuthMessageListeners = () => {
1448
- window.removeEventListener("message", handleAuthMessage);
1449
- };
1450
- }
1451
- async openWalletObservables({ walletIframeOrigin }) {
1452
- this.closeAirObservables();
1453
- this.setupAirObservables();
1454
- const handleMessage = async (ev) => {
1455
- if (ev.origin !== walletIframeOrigin || !ev.data || !(ev.data instanceof Object))
1456
- return;
1457
- log.debug("Account messages received from wallet frontend", ev.data);
1458
- if (ACCOUNT_MESSAGES.includes(ev.data.type)) {
1459
- this.airMessages$.next(ev.data);
1460
- }
1461
- };
1462
- window.addEventListener("message", handleMessage);
1463
- this.closeRealmMessageListeners = () => {
1464
- window.removeEventListener("message", handleMessage);
1465
- };
1466
- this.closeWalletObservables();
1467
- this.setupWalletObservables();
1468
- const handleWalletMessage = async (ev) => {
1469
- if (ev.origin !== walletIframeOrigin || !ev.data || !(ev.data instanceof Object))
1470
- return;
1471
- log.debug("Wallet provider messages received from wallet frontend", ev.data);
1472
- if (ev.data.type === AirWalletProviderMessageTypes.RESPONSE) {
1473
- this._providerMessage$.next(ev.data);
1474
- }
1475
- if (ev.data.type === AirWalletProviderMessageTypes.EVENT) {
1476
- this._providerEvent$.next(ev.data);
1477
- }
1478
- };
1479
- window.addEventListener("message", handleWalletMessage);
1480
- this.closeWalletMessageListeners = () => {
1481
- window.removeEventListener("message", handleWalletMessage);
1482
- };
1483
- }
1484
- setupIframeCommunication(authIframe, walletIframe, skipWalletLogin) {
1485
- const channel = new MessageChannel();
1486
- const authOrigin = new URL(authIframe.src).origin;
1487
- authIframe.contentWindow.postMessage({
1488
- type: AirAuthMessageTypes.INIT_WALLET_COMMUNICATION,
1489
- }, authOrigin, [channel.port1]);
1490
- const walletOrigin = new URL(walletIframe.src).origin;
1491
- walletIframe.contentWindow.postMessage({
1492
- type: AirMessageTypes.INIT_AUTH_COMMUNICATION,
1493
- payload: {
1494
- skipWalletLogin,
1495
- },
1496
- }, walletOrigin, [channel.port2]);
1497
- }
1498
- async sendGrantPermissionRequest(walletIframe, policies) {
1499
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.GRANT_PERMISSIONS_RESPONSE)));
1500
- const { origin } = new URL(walletIframe.src);
1501
- walletIframe.contentWindow.postMessage({
1502
- type: AirMessageTypes.GRANT_PERMISSIONS_REQUEST,
1503
- payload: {
1504
- policies,
1505
- },
1506
- }, origin);
1507
- const result = await response;
1508
- if (result.payload.success === false) {
1509
- throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
1510
- }
1511
- return result.payload.sessionData;
1512
- }
1513
- async sendExecuteActionRequest(walletIframe, params) {
1514
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.EXECUTE_ACTION_RESPONSE)));
1515
- const { origin } = new URL(walletIframe.src);
1516
- walletIframe.contentWindow.postMessage({
1517
- type: AirMessageTypes.EXECUTE_ACTION_REQUEST,
1518
- payload: {
1519
- sessionData: params.sessionData,
1520
- call: {
1521
- to: params.call.to,
1522
- value: params.call.value,
1523
- data: params.call.data,
1524
- },
1525
- sessionOwnerPrivateKey: params.sessionOwnerPrivateKey,
1526
- },
1527
- }, origin);
1528
- const result = await response;
1529
- if (result.payload.success === false) {
1530
- throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
1531
- }
1532
- return result.payload.txHash;
1533
- }
1534
- async sendRevokePermissionsRequest(walletIframe, permissionId) {
1535
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.REVOKE_PERMISSIONS_RESPONSE)));
1536
- const { origin } = new URL(walletIframe.src);
1537
- walletIframe.contentWindow.postMessage({
1538
- type: AirMessageTypes.REVOKE_PERMISSIONS_REQUEST,
1539
- payload: {
1540
- permissionId,
1541
- },
1542
- }, origin);
1543
- const result = await response;
1544
- if (result.payload.success === false) {
1545
- throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
1546
- }
1547
- return result.payload.txHash;
1548
- }
1549
- sendDeploySmartAccountRequest(walletIframe) {
1550
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE)));
1551
- const { origin } = new URL(walletIframe.src);
1552
- walletIframe.contentWindow.postMessage({
1553
- type: AirMessageTypes.DEPLOY_SMART_ACCOUNT_REQUEST,
1554
- }, origin);
1555
- return response;
1556
- }
1557
- async sendIsSmartAccountDeployedRequest(walletIframe) {
1558
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_RESPONSE)));
1559
- const { origin } = new URL(walletIframe.src);
1560
- walletIframe.contentWindow.postMessage({
1561
- type: AirMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_REQUEST,
1562
- }, origin);
1563
- return response;
1564
- }
1565
- async sendPartnerUserInfoRequest(authIframe) {
1566
- const response = firstValueFrom(this.authMessage$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE)));
1567
- const { origin } = new URL(authIframe.src);
1568
- authIframe.contentWindow.postMessage({ type: AirAuthMessageTypes.PARTNER_USER_INFO_REQUEST }, origin);
1569
- return response;
1570
- }
1571
- async sendAuthLoginRequest(authIframe, payload) {
1572
- const response = firstValueFrom(this.authMessage$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.LOGIN_RESPONSE)));
1573
- const { origin } = new URL(authIframe.src);
1574
- authIframe.contentWindow.postMessage({ type: AirAuthMessageTypes.LOGIN_REQUEST, payload }, origin);
1575
- return response;
1576
- }
1577
- async logoutAuth(authIframe) {
1578
- const response = firstValueFrom(this.authMessage$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.LOGOUT_RESPONSE)));
1579
- const { origin } = new URL(authIframe.src);
1580
- authIframe.contentWindow.postMessage({ type: AirAuthMessageTypes.LOGOUT_REQUEST }, origin);
1581
- return response;
1582
- }
1583
- async logoutWallet(walletIframe) {
1584
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.LOGOUT_RESPONSE)));
1585
- const { origin } = new URL(walletIframe.src);
1586
- walletIframe.contentWindow.postMessage({ type: AirMessageTypes.LOGOUT_REQUEST }, origin);
1587
- return response;
1588
- }
1589
- sendResetAuthServiceWalletCommunication(authIframe) {
1590
- const { origin: authOrigin } = new URL(authIframe.src);
1591
- authIframe.contentWindow.postMessage({ type: AirAuthMessageTypes.RESET_WALLET_COMMUNICATION }, authOrigin);
1592
- }
1593
- async sendAuthInitializationRequest(authIframe, payload) {
1594
- const response = firstValueFrom(this._authMessage$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.INITIALIZATION_RESPONSE)));
1595
- const { origin } = new URL(authIframe.src);
1596
- authIframe.contentWindow.postMessage({ type: AirAuthMessageTypes.INITIALIZATION_REQUEST, payload }, origin);
1597
- return response;
1598
- }
1599
- async sendWalletInitializationRequest(walletIframe, payload) {
1600
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.INITIALIZATION_RESPONSE)));
1601
- const { origin } = new URL(walletIframe.src);
1602
- walletIframe.contentWindow.postMessage({ type: AirMessageTypes.INITIALIZATION_REQUEST, payload }, origin);
1603
- return response;
1604
- }
1605
- async sendCrossPartnerTokenRequest(authIframe, targetPartnerUrl) {
1606
- const response = firstValueFrom(this.authMessage$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.CROSS_PARTNER_TOKEN_RESPONSE)));
1607
- const { origin } = new URL(authIframe.src);
1608
- authIframe.contentWindow.postMessage({
1609
- type: AirAuthMessageTypes.CROSS_PARTNER_TOKEN_REQUEST,
1610
- payload: {
1611
- targetPartnerUrl,
1612
- },
1613
- }, origin);
1614
- return response;
1615
- }
1616
- async sendGrantPermissionsRequest(walletIframe, payload) {
1617
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.GRANT_PERMISSIONS_RESPONSE)));
1618
- const { origin } = new URL(walletIframe.src);
1619
- walletIframe.contentWindow.postMessage({ type: AirMessageTypes.GRANT_PERMISSIONS_REQUEST, payload }, origin);
1620
- return response;
1621
- }
1622
- async sendListAllSessionKeyScopesRequest(walletIframe) {
1623
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.LIST_ALL_SESSION_KEY_SCOPES_RESPONSE)));
1624
- const { origin } = new URL(walletIframe.src);
1625
- walletIframe.contentWindow.postMessage({ type: AirMessageTypes.LIST_ALL_SESSION_KEY_SCOPES_REQUEST }, origin);
1626
- return response;
1627
- }
1628
- onWalletInitialized() {
1629
- return firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.WALLET_INITIALIZED)));
1630
- }
1631
- sendWalletLoginRequest(walletIframe) {
1632
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.WALLET_LOGIN_RESPONSE)));
1633
- const { origin } = new URL(walletIframe.src);
1634
- walletIframe.contentWindow.postMessage({ type: AirMessageTypes.WALLET_LOGIN_REQUEST }, origin);
1635
- return response;
1636
- }
1637
- async sendSetupMfaRequest(walletIframe) {
1638
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.SETUP_MFA_RESPONSE)));
1639
- const { origin } = new URL(walletIframe.src);
1640
- walletIframe.contentWindow.postMessage({ type: AirMessageTypes.SETUP_MFA_REQUEST }, origin);
1641
- return response;
1642
- }
1643
- sendOpenWindowSuccessResponse(walletIframe, windowId, port) {
1644
- const { origin: walletOrigin } = new URL(walletIframe.src);
1645
- walletIframe.contentWindow.postMessage({
1646
- type: AirMessageTypes.OPEN_WINDOW_RESPONSE,
1647
- payload: {
1648
- success: true,
1649
- windowId,
1650
- },
1651
- }, walletOrigin, [port]);
1652
- }
1653
- sendOpenWindowErrorResponse(walletIframe, windowId, error) {
1654
- const { origin: walletOrigin } = new URL(walletIframe.src);
1655
- walletIframe.contentWindow.postMessage({
1656
- type: AirMessageTypes.OPEN_WINDOW_RESPONSE,
1657
- payload: {
1658
- success: false,
1659
- windowId,
1660
- errorName: "UNKNOWN_ERROR",
1661
- errorMessage: error.message,
1662
- },
1663
- }, walletOrigin);
1581
+ class AirError extends BaseError {}
1582
+ new Set(AirClientUserErrors);
1583
+ new Set(Object.values(Codes));
1584
+
1585
+ class MessageServiceBase {
1586
+ get events$() {
1587
+ return this._events$;
1588
+ }
1589
+ get messages$() {
1590
+ return this._messages$;
1591
+ }
1592
+ get isOpen() {
1593
+ return !!this.closeListener;
1594
+ }
1595
+ constructor(name, allowedMessageTypes) {
1596
+ this.name = name;
1597
+ this.allowedMessageTypes = allowedMessageTypes;
1598
+ this.closeListener = null;
1599
+ }
1600
+ async _open(target) {
1601
+ await this.close();
1602
+ this.eventSubject = new Subject();
1603
+ this._events$ = this.eventSubject.asObservable();
1604
+ this._messages$ = this.eventSubject.pipe(map(ev => ev.data));
1605
+ this._events$.subscribe(event => {
1606
+ const sentOrReceived = event.origin === window.origin ? "sent" : "received";
1607
+ log.debug(`[${this.name}] Message ${sentOrReceived}:`, event.data);
1608
+ });
1609
+ const handleMessage = async ev => {
1610
+ if (this.targetOrigin && ev.origin !== this.targetOrigin || !ev.data || !(ev.data instanceof Object)) return;
1611
+ if (this.isMessageAllowed(ev.data)) {
1612
+ await this.onBeforeEvent(ev);
1613
+ this.eventSubject.next(ev);
1614
+ }
1615
+ };
1616
+ if (target instanceof MessagePort) {
1617
+ this.messagePort = target;
1618
+ target.onmessage = handleMessage;
1619
+ this.closeListener = async () => {
1620
+ this.messagePort?.close();
1621
+ this.messagePort = undefined;
1622
+ };
1623
+ } else if (target instanceof BroadcastChannel) {
1624
+ this.messageChannel = target;
1625
+ target.onmessage = handleMessage;
1626
+ this.closeListener = async () => {
1627
+ this.messageChannel?.close();
1628
+ this.messageChannel = undefined;
1629
+ };
1630
+ } else {
1631
+ this.targetWindow = target.window;
1632
+ this.targetOrigin = target.origin;
1633
+ window.addEventListener("message", handleMessage);
1634
+ this.closeListener = async () => {
1635
+ window.removeEventListener("message", handleMessage);
1636
+ };
1664
1637
  }
1665
- sendWindowClosed(walletIframe, windowId) {
1666
- const { origin: walletOrigin } = new URL(walletIframe.src);
1667
- walletIframe.contentWindow.postMessage({
1668
- type: AirMessageTypes.WINDOW_CLOSED,
1669
- payload: {
1670
- windowId,
1671
- },
1672
- }, walletOrigin);
1638
+ }
1639
+ isMessageAllowed(message) {
1640
+ return this.allowedMessageTypes.includes(message.type);
1641
+ }
1642
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1643
+ async onBeforeEvent(_event) {
1644
+ // by default not used
1645
+ }
1646
+ async close() {
1647
+ if (this.closeListener) {
1648
+ await this.closeListener();
1649
+ this.closeListener = null;
1673
1650
  }
1674
- async sendClaimIdRequest(walletIframe, payload) {
1675
- const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirMessageTypes.CLAIM_ID_RESPONSE)));
1676
- const { origin } = new URL(walletIframe.src);
1677
- walletIframe.contentWindow.postMessage({ type: AirMessageTypes.CLAIM_ID_REQUEST, payload }, origin);
1678
- return response;
1651
+ if (this.eventSubject && !this.eventSubject.closed) {
1652
+ this.eventSubject.complete();
1679
1653
  }
1680
- async sendWalletProviderRequest(walletIframe, payload) {
1681
- const response = firstValueFrom(this.providerMessage$.pipe(filter((msg) => msg.type === AirWalletProviderMessageTypes.RESPONSE &&
1682
- msg.payload.requestId === payload.requestId)));
1683
- const { origin } = new URL(walletIframe.src);
1684
- walletIframe.contentWindow.postMessage({
1685
- type: AirWalletProviderMessageTypes.REQUEST,
1686
- payload,
1687
- }, origin);
1688
- return response;
1654
+ }
1655
+ createErrorResponseMessage(type, error) {
1656
+ return {
1657
+ type,
1658
+ payload: {
1659
+ success: false,
1660
+ errorName: error instanceof AirError ? error.name : "UNKNOWN_ERROR",
1661
+ errorMessage: error.message
1662
+ }
1663
+ };
1664
+ }
1665
+ async sendMessage(message, transfer) {
1666
+ // To prevent any non-cloneable objects causing errors in postMessage
1667
+ const clonedMessage = this.deepClone(message);
1668
+ if (this.messagePort) {
1669
+ this.messagePort.postMessage(clonedMessage);
1670
+ } else if (this.messageChannel) {
1671
+ this.messageChannel.postMessage(clonedMessage);
1672
+ } else if (this.targetWindow && this.targetOrigin) {
1673
+ this.targetWindow.postMessage(clonedMessage, this.targetOrigin, transfer);
1674
+ } else {
1675
+ log.debug(`[${this.name}] Not opened yet`);
1676
+ return;
1689
1677
  }
1690
- closeAuthObservables() {
1691
- if (this._authMessage$ && !this._authMessage$.closed)
1692
- this._authMessage$.complete();
1693
- if (this.closeAuthMessageListeners)
1694
- this.closeAuthMessageListeners();
1695
- }
1696
- closeAirObservables() {
1697
- if (this.airMessages$ && !this.airMessages$.closed)
1698
- this.airMessages$.complete();
1699
- if (this.closeRealmMessageListeners)
1700
- this.closeRealmMessageListeners();
1701
- }
1702
- closeWalletObservables() {
1703
- if (this._providerMessage$ && !this._providerMessage$.closed)
1704
- this._providerMessage$.complete();
1705
- if (this._providerEvent$ && !this._providerEvent$.closed)
1706
- this._providerEvent$.complete();
1707
- if (this.closeWalletMessageListeners)
1708
- this.closeWalletMessageListeners();
1709
- }
1710
- setupAuthObservables() {
1711
- this._authMessage$ = new Subject();
1712
- }
1713
- setupAirObservables() {
1714
- this.airMessages$ = new Subject();
1715
- }
1716
- setupWalletObservables() {
1717
- this._providerMessage$ = new Subject();
1718
- this._providerEvent$ = new Subject();
1719
- }
1720
- async sendGetPartnerAccessTokenRequest(authIframe) {
1721
- const response = firstValueFrom(this.authMessage$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.GET_PARTNER_ACCESS_TOKEN_RESPONSE)));
1722
- const { origin } = new URL(authIframe.src);
1723
- authIframe.contentWindow.postMessage({ type: AirAuthMessageTypes.GET_PARTNER_ACCESS_TOKEN_REQUEST }, origin);
1724
- return response;
1678
+ this.eventSubject.next(new MessageEvent("message", {
1679
+ data: clonedMessage,
1680
+ origin: window.origin
1681
+ }));
1682
+ }
1683
+ deepClone(message) {
1684
+ try {
1685
+ return JSON.parse(JSON.stringify(message, bigIntReplacer));
1686
+ } catch (e) {
1687
+ log.warn("Error generating cloneable message", e);
1688
+ return message;
1725
1689
  }
1690
+ }
1726
1691
  }
1727
- var AirMessageService$1 = AirMessageService.instance;
1728
-
1729
- const BUILD_ENV = {
1730
- PRODUCTION: "production",
1731
- UAT: "uat",
1732
- STAGING: "staging",
1733
- DEVELOPMENT: "development",
1734
- };
1735
-
1736
- const AIR_URLS = {
1737
- [BUILD_ENV.DEVELOPMENT]: {
1738
- authUrl: "http://localhost:8100",
1739
- walletUrl: "http://localhost:8200",
1740
- logLevel: "debug",
1741
- },
1742
- [BUILD_ENV.UAT]: {
1743
- authUrl: "https://auth.uat.air3.com",
1744
- walletUrl: "https://account.uat.air3.com",
1745
- logLevel: "info",
1746
- },
1747
- [BUILD_ENV.STAGING]: {
1748
- authUrl: "https://auth.staging.air3.com",
1749
- walletUrl: "https://account.staging.air3.com",
1750
- logLevel: "info",
1751
- },
1752
- [BUILD_ENV.PRODUCTION]: {
1753
- authUrl: "https://auth.air3.com",
1754
- walletUrl: "https://account.air3.com",
1755
- logLevel: "error",
1756
- },
1757
- };
1758
- const isElement = (element) => element instanceof Element || element instanceof Document;
1759
- const randomId = () => Math.random().toString(36).slice(2);
1760
- const getWindowFeatures = (width, height) => {
1761
- const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
1762
- const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;
1763
- const w = window.innerWidth
1764
- ? window.innerWidth
1765
- : document.documentElement.clientWidth
1766
- ? document.documentElement.clientWidth
1767
- : window.screen.width;
1768
- const h = window.innerHeight
1769
- ? window.innerHeight
1770
- : document.documentElement.clientHeight
1771
- ? document.documentElement.clientHeight
1772
- : window.screen.height;
1773
- const systemZoom = 1; // No reliable estimate
1774
- const left = Math.abs((w - width) / 2 / systemZoom + dualScreenLeft);
1775
- const top = Math.abs((h - height) / 2 / systemZoom + dualScreenTop);
1776
- return `titlebar=0,toolbar=0,status=0,location=0,menubar=0,height=${height / systemZoom},width=${width / systemZoom},top=${top},left=${left}`;
1777
- };
1778
1692
 
1779
- var _AirWalletProvider_instances, _AirWalletProvider_isLoggedIn, _AirWalletProvider_ensureWallet, _AirWalletProvider_getWalletIframeController, _AirWalletProvider_eventListeners, _AirWalletProvider_emit;
1693
+ var AirWalletProviderMessageTypes;
1694
+ (function (AirWalletProviderMessageTypes) {
1695
+ AirWalletProviderMessageTypes["REQUEST"] = "JRPC_REQUEST";
1696
+ AirWalletProviderMessageTypes["RESPONSE"] = "JRPC_RESPONSE";
1697
+ AirWalletProviderMessageTypes["EVENT"] = "JRPC_EVENT";
1698
+ })(AirWalletProviderMessageTypes || (AirWalletProviderMessageTypes = {}));
1699
+
1700
+ var _a$2, _ProviderMessageService_instance;
1701
+ const ALLOWED_PROVIDER_MESSAGES = [
1702
+ AirWalletProviderMessageTypes.RESPONSE,
1703
+ AirWalletProviderMessageTypes.EVENT,
1704
+ ];
1705
+ class ProviderMessageService extends MessageServiceBase {
1706
+ static create() {
1707
+ if (__classPrivateFieldGet(this, _a$2, "f", _ProviderMessageService_instance))
1708
+ throw new Error("ProviderMessageService already created");
1709
+ __classPrivateFieldSet(this, _a$2, new _a$2("Embed Service: Provider Channel", ALLOWED_PROVIDER_MESSAGES), "f", _ProviderMessageService_instance);
1710
+ return __classPrivateFieldGet(this, _a$2, "f", _ProviderMessageService_instance);
1711
+ }
1712
+ async open(walletIframe) {
1713
+ const origin = new URL(walletIframe.src).origin;
1714
+ const window = walletIframe.contentWindow;
1715
+ await super._open({ window, origin });
1716
+ }
1717
+ async sendWalletProviderRequest(payload) {
1718
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletProviderMessageTypes.RESPONSE), filter((msg) => msg.payload.method === payload.method)));
1719
+ await this.sendMessage({
1720
+ type: AirWalletProviderMessageTypes.REQUEST,
1721
+ payload,
1722
+ });
1723
+ return response;
1724
+ }
1725
+ }
1726
+ _a$2 = ProviderMessageService;
1727
+ _ProviderMessageService_instance = { value: void 0 };
1728
+
1729
+ var _AirWalletProvider_instances, _AirWalletProvider_providerMessageService, _AirWalletProvider_isLoggedIn, _AirWalletProvider_ensureWallet, _AirWalletProvider_eventListeners, _AirWalletProvider_emit;
1780
1730
  class AirWalletProvider {
1781
- constructor({ isLoggedIn, ensureWallet, getWalletIframeController, }) {
1731
+ constructor({ isLoggedIn, ensureWallet, }) {
1782
1732
  _AirWalletProvider_instances.add(this);
1783
- _AirWalletProvider_isLoggedIn.set(this, undefined);
1784
- _AirWalletProvider_ensureWallet.set(this, undefined);
1785
- _AirWalletProvider_getWalletIframeController.set(this, undefined);
1786
- _AirWalletProvider_eventListeners.set(this, undefined);
1787
- this.startEventMessageListening = () => {
1788
- AirMessageService$1.providerEvent$.subscribe((message) => {
1733
+ _AirWalletProvider_providerMessageService.set(this, void 0);
1734
+ _AirWalletProvider_isLoggedIn.set(this, void 0);
1735
+ _AirWalletProvider_ensureWallet.set(this, void 0);
1736
+ _AirWalletProvider_eventListeners.set(this, void 0);
1737
+ this.startEventMessageListening = async (walletIframe) => {
1738
+ await __classPrivateFieldGet(this, _AirWalletProvider_providerMessageService, "f").open(walletIframe);
1739
+ __classPrivateFieldGet(this, _AirWalletProvider_providerMessageService, "f").messages$
1740
+ .pipe(filter((msg) => msg.type === AirWalletProviderMessageTypes.EVENT))
1741
+ .subscribe((message) => {
1789
1742
  __classPrivateFieldGet(this, _AirWalletProvider_instances, "m", _AirWalletProvider_emit).call(this, message.payload.event, ...[message.payload.data]);
1790
1743
  });
1791
1744
  };
1745
+ __classPrivateFieldSet(this, _AirWalletProvider_providerMessageService, ProviderMessageService.create(), "f");
1792
1746
  __classPrivateFieldSet(this, _AirWalletProvider_isLoggedIn, isLoggedIn, "f");
1793
1747
  __classPrivateFieldSet(this, _AirWalletProvider_ensureWallet, ensureWallet, "f");
1794
- __classPrivateFieldSet(this, _AirWalletProvider_getWalletIframeController, getWalletIframeController, "f");
1795
1748
  __classPrivateFieldSet(this, _AirWalletProvider_eventListeners, {
1796
1749
  connect: [],
1797
1750
  disconnect: [],
@@ -1820,14 +1773,20 @@ class AirWalletProvider {
1820
1773
  if (!__classPrivateFieldGet(this, _AirWalletProvider_isLoggedIn, "f").call(this)) {
1821
1774
  throw new UnauthorizedProviderError("User is not logged in");
1822
1775
  }
1776
+ const skipWalletLoginMethods = ['eth_chainId'];
1823
1777
  try {
1824
- await __classPrivateFieldGet(this, _AirWalletProvider_ensureWallet, "f").call(this);
1778
+ if (skipWalletLoginMethods.includes(method)) {
1779
+ await __classPrivateFieldGet(this, _AirWalletProvider_ensureWallet, "f").call(this, { skipWalletLogin: true });
1780
+ }
1781
+ else {
1782
+ await __classPrivateFieldGet(this, _AirWalletProvider_ensureWallet, "f").call(this);
1783
+ }
1825
1784
  }
1826
1785
  catch (error) {
1827
1786
  throw ensureProviderRpcError(error);
1828
1787
  }
1829
1788
  const requestId = randomId();
1830
- const response = await AirMessageService$1.sendWalletProviderRequest(__classPrivateFieldGet(this, _AirWalletProvider_getWalletIframeController, "f").call(this).iframeElement, {
1789
+ const response = await __classPrivateFieldGet(this, _AirWalletProvider_providerMessageService, "f").sendWalletProviderRequest({
1831
1790
  requestId,
1832
1791
  ...request,
1833
1792
  });
@@ -1857,13 +1816,13 @@ class AirWalletProvider {
1857
1816
  }, "f");
1858
1817
  }
1859
1818
  }
1860
- _AirWalletProvider_isLoggedIn = new WeakMap(), _AirWalletProvider_ensureWallet = new WeakMap(), _AirWalletProvider_getWalletIframeController = new WeakMap(), _AirWalletProvider_eventListeners = new WeakMap(), _AirWalletProvider_instances = new WeakSet(), _AirWalletProvider_emit = function _AirWalletProvider_emit(eventName, ...args) {
1819
+ _AirWalletProvider_providerMessageService = new WeakMap(), _AirWalletProvider_isLoggedIn = new WeakMap(), _AirWalletProvider_ensureWallet = new WeakMap(), _AirWalletProvider_eventListeners = new WeakMap(), _AirWalletProvider_instances = new WeakSet(), _AirWalletProvider_emit = function _AirWalletProvider_emit(eventName, ...args) {
1861
1820
  (__classPrivateFieldGet(this, _AirWalletProvider_eventListeners, "f")[eventName] || []).forEach((listener) => {
1862
1821
  try {
1863
1822
  return listener(...args);
1864
1823
  }
1865
1824
  catch (error) {
1866
- log$1.error(error);
1825
+ log.warn(error);
1867
1826
  }
1868
1827
  });
1869
1828
  };
@@ -1894,6 +1853,7 @@ class IframeController {
1894
1853
  iframe.style.margin = "0";
1895
1854
  iframe.style.padding = "0";
1896
1855
  iframe.style.display = "none";
1856
+ iframe.style.colorScheme = "auto";
1897
1857
  document.body.appendChild(iframe);
1898
1858
  this._iframeElement = iframe;
1899
1859
  return iframe;
@@ -1932,84 +1892,117 @@ IframeController.defaultState = {
1932
1892
  };
1933
1893
 
1934
1894
  class WindowController {
1935
- get messages$() {
1936
- return this._messages$.asObservable();
1937
- }
1938
- constructor(windowUrl, windowId) {
1939
- this._windowInstance = null;
1940
- this._messageHandler = null;
1941
- this._messages$ = new Subject();
1942
- this.windowUrl = windowUrl;
1943
- this.windowOrigin = new URL(windowUrl).origin;
1944
- this.windowId = windowId;
1945
- }
1946
- get windowInstance() {
1947
- return this._windowInstance;
1948
- }
1949
- openWindow() {
1950
- if (this._windowInstance && !this._windowInstance.closed) {
1951
- this._windowInstance.focus();
1952
- return this._windowInstance;
1953
- }
1954
- const windowInstance = window.open(this.windowUrl, this.windowId, getWindowFeatures(400, 600));
1955
- if (!windowInstance) {
1956
- throw new Error("Failed to open window. Popup might be blocked by the browser.");
1957
- }
1958
- this._windowInstance = windowInstance;
1959
- this._messageHandler = (ev) => {
1960
- if (ev.source !== windowInstance ||
1961
- ev.origin !== this.windowOrigin ||
1962
- !ev.data ||
1963
- !(ev.data instanceof Object)) {
1964
- return;
1965
- }
1966
- this._messages$.next(ev);
1967
- };
1968
- window.addEventListener("message", this._messageHandler);
1969
- const checkWindow = setInterval(() => {
1970
- if (!this._windowInstance || this._windowInstance?.closed) {
1971
- this.cleanup();
1972
- clearInterval(checkWindow);
1973
- }
1974
- }, 500);
1975
- return windowInstance;
1895
+ get messages$() {
1896
+ return this._messages$.asObservable();
1897
+ }
1898
+ constructor(windowId, windowUrl) {
1899
+ this._windowInstance = null;
1900
+ this._messageHandler = null;
1901
+ this._messages$ = new Subject();
1902
+ this.windowId = windowId;
1903
+ this.windowUrl = windowUrl;
1904
+ this.windowOrigin = new URL(windowUrl).origin;
1905
+ this._messageHandler = ev => {
1906
+ if (ev.source !== this._windowInstance || ev.origin !== this.windowOrigin || !ev.data || !(ev.data instanceof Object)) {
1907
+ return;
1908
+ }
1909
+ this._messages$.next(ev);
1910
+ };
1911
+ window.addEventListener("message", this._messageHandler);
1912
+ }
1913
+ get windowInstance() {
1914
+ return this._windowInstance;
1915
+ }
1916
+ async openWindow(onRetry) {
1917
+ let windowInstance = this.tryOpenWindow();
1918
+ if (!windowInstance) {
1919
+ await onRetry();
1920
+ windowInstance = this.tryOpenWindow();
1921
+ if (!windowInstance) {
1922
+ throw new AirError(WindowErrorName.WINDOW_BLOCKED);
1923
+ }
1976
1924
  }
1977
- postMessage(message, transfer) {
1978
- if (!this._windowInstance)
1979
- return;
1980
- this._windowInstance.postMessage(message, this.windowOrigin, transfer);
1925
+ const pendingWindowOpenCheck = new Promise((resolve, reject) => {
1926
+ setTimeout(() => {
1927
+ if (this.isWindowOpen(windowInstance)) {
1928
+ // only now are we scheduling the close event check since we're sure the window is open
1929
+ this.scheduleWindowClosedChecks(windowInstance);
1930
+ resolve("opened");
1931
+ } else {
1932
+ onRetry().then(() => {
1933
+ windowInstance = this.tryOpenWindow();
1934
+ if (windowInstance) {
1935
+ this._windowInstance = windowInstance;
1936
+ windowInstance.focus();
1937
+ this.scheduleWindowClosedChecks(windowInstance);
1938
+ resolve("retry");
1939
+ } else {
1940
+ reject(new AirError(WindowErrorName.WINDOW_BLOCKED));
1941
+ }
1942
+ }).catch(reject);
1943
+ }
1944
+ }, 1000);
1945
+ });
1946
+ this._windowInstance = windowInstance;
1947
+ windowInstance.focus();
1948
+ return {
1949
+ pendingWindowOpenCheck
1950
+ };
1951
+ }
1952
+ postMessage(message, transfer) {
1953
+ if (!this._windowInstance) return;
1954
+ this._windowInstance.postMessage(message, this.windowOrigin, transfer);
1955
+ }
1956
+ onMessage(callback) {
1957
+ const listener = ev => {
1958
+ if (ev.source !== this._windowInstance || ev.origin !== this.windowOrigin) return;
1959
+ callback(ev);
1960
+ };
1961
+ window.addEventListener("message", listener);
1962
+ const close = () => window.removeEventListener("message", listener);
1963
+ this.onClose(close);
1964
+ return {
1965
+ close
1966
+ };
1967
+ }
1968
+ cleanup() {
1969
+ if (this._windowInstance && !this._windowInstance.closed) {
1970
+ this._windowInstance.close();
1981
1971
  }
1982
- onMessage(callback) {
1983
- const listener = (ev) => {
1984
- if (ev.source !== this._windowInstance)
1985
- return;
1986
- callback(ev);
1987
- };
1988
- window.addEventListener("message", listener);
1989
- const close = () => window.removeEventListener("message", listener);
1990
- this.onClose(close);
1991
- return {
1992
- close,
1993
- };
1972
+ this._windowInstance = null;
1973
+ if (this._messageHandler) {
1974
+ window.removeEventListener("message", this._messageHandler);
1975
+ this._messageHandler = null;
1994
1976
  }
1995
- cleanup() {
1996
- if (this._windowInstance && !this._windowInstance.closed) {
1997
- this._windowInstance.close();
1998
- }
1999
- if (this._messageHandler) {
2000
- window.removeEventListener("message", this._messageHandler);
2001
- this._messageHandler = null;
2002
- }
2003
- if (this._messages$ && !this._messages$.closed) {
2004
- this._messages$.complete();
2005
- }
2006
- this._windowInstance = null;
1977
+ if (this._messages$ && !this._messages$.closed) {
1978
+ this._messages$.complete();
2007
1979
  }
2008
- onClose(callback) {
2009
- return this._messages$.subscribe({
2010
- complete: callback,
2011
- });
1980
+ }
1981
+ onClose(callback) {
1982
+ return this._messages$.subscribe({
1983
+ complete: callback
1984
+ });
1985
+ }
1986
+ isWindowOpen(windowInstance) {
1987
+ return !(!windowInstance || windowInstance.closed || typeof windowInstance.closed == "undefined");
1988
+ }
1989
+ tryOpenWindow() {
1990
+ const windowInstance = window.open(this.windowUrl, this.windowId, getWindowFeatures(425, 680));
1991
+ if (this.isWindowOpen(windowInstance)) {
1992
+ return windowInstance;
2012
1993
  }
1994
+ return null;
1995
+ }
1996
+ scheduleWindowClosedChecks(windowInstance) {
1997
+ const checkWindow = setInterval(() => {
1998
+ if (!windowInstance || windowInstance.closed) {
1999
+ clearInterval(checkWindow);
2000
+ if (windowInstance === this._windowInstance) {
2001
+ this.cleanup();
2002
+ }
2003
+ }
2004
+ }, 500);
2005
+ }
2013
2006
  }
2014
2007
 
2015
2008
  class WindowService {
@@ -2028,37 +2021,60 @@ class WindowService {
2028
2021
  if (!windowInstance) {
2029
2022
  throw new Error("Window instance not found");
2030
2023
  }
2031
- const response = firstValueFrom(windowController.messages$.pipe(filter((event) => event.data.type === AirMessageTypes.INITIALIZATION_RESPONSE)));
2032
- windowController.postMessage({ type: AirMessageTypes.INITIALIZATION_REQUEST, payload }, [port]);
2024
+ const response = firstValueFrom(windowController.messages$.pipe(filter((event) => event.data.type ===
2025
+ AirWalletMessageTypes.INITIALIZATION_RESPONSE)));
2026
+ windowController.postMessage({ type: AirWalletMessageTypes.INITIALIZATION_REQUEST, payload }, [
2027
+ port,
2028
+ ]);
2033
2029
  return (await response).data;
2034
2030
  }
2035
- async openAndInitializeWalletServiceWindow({ url, windowId, partnerId, enableLogging, port, }) {
2031
+ async openAndInitializeWalletServiceWindow({ url, windowId, partnerId, enableLogging, onRetry, sdkVersion, enableAutomation, }) {
2036
2032
  if (this.windowControllers.has(windowId)) {
2037
2033
  throw new Error("Window controller already exists");
2038
2034
  }
2039
- const windowController = new WindowController(url, windowId);
2040
- this.windowControllers.set(windowId, windowController);
2041
- windowController.openWindow();
2035
+ const windowController = new WindowController(windowId, url);
2036
+ const { pendingWindowOpenCheck } = await windowController.openWindow(onRetry);
2042
2037
  windowController.onClose(() => {
2043
2038
  this.removeWindowController(windowId);
2044
2039
  });
2045
- await new Promise((resolve, reject) => {
2046
- windowController.onMessage(async (ev) => {
2047
- if (ev.data === AirMessageTypes.SERVICE_STARTED) {
2048
- const { payload } = await this.sendWindowInitializationRequest(windowId, {
2049
- partnerId,
2050
- enableLogging,
2051
- }, port);
2052
- if (payload.success === false) {
2053
- reject(new AirServiceError(payload.errorName, payload.errorMessage));
2054
- }
2055
- else {
2056
- resolve();
2040
+ this.windowControllers.set(windowId, windowController);
2041
+ let channel = null;
2042
+ const initializeWindow = () => {
2043
+ return new Promise((resolve, reject) => {
2044
+ windowController.onMessage(async (ev) => {
2045
+ if (ev.data === AirWalletMessageTypes.SERVICE_STARTED) {
2046
+ try {
2047
+ channel = new MessageChannel();
2048
+ const { payload } = await this.sendWindowInitializationRequest(windowId, {
2049
+ partnerId,
2050
+ enableLogging,
2051
+ sdkVersion,
2052
+ enableAutomation,
2053
+ }, channel.port1);
2054
+ if (payload.success === false) {
2055
+ reject(new AirServiceError(payload.errorName, payload.errorMessage));
2056
+ }
2057
+ else {
2058
+ resolve();
2059
+ }
2060
+ }
2061
+ catch (e) {
2062
+ reject(e);
2063
+ }
2057
2064
  }
2058
- }
2065
+ });
2059
2066
  });
2060
- });
2061
- return windowController;
2067
+ };
2068
+ const initializeWindowPromise = initializeWindow();
2069
+ const result = await pendingWindowOpenCheck;
2070
+ if (result === "retry") {
2071
+ // we can ignore previous initialization attempt since a new window was opened
2072
+ await initializeWindow();
2073
+ }
2074
+ else {
2075
+ await initializeWindowPromise;
2076
+ }
2077
+ return { windowController, port: channel.port2 };
2062
2078
  }
2063
2079
  getWindowController(windowId) {
2064
2080
  return this.windowControllers.get(windowId);
@@ -2069,27 +2085,265 @@ class WindowService {
2069
2085
  }
2070
2086
  var WindowService$1 = WindowService.instance;
2071
2087
 
2072
- var _AirService_instances, _AirService_loginResult, _AirService_buildEnv, _AirService_enableLogging, _AirService_partnerId, _AirService_authIframeController, _AirService_isAuthInitialized, _AirService_airAuthListener, _AirService_walletIframeController, _AirService_walletInitialization, _AirService_walletLoggedInResult, _AirService_airWalletProvider, _AirService_ensureWallet, _AirService_initializeWallet, _AirService_subscribeToWalletEvents, _AirService_triggerEventListeners, _AirService_triggerAirAuthInitialized, _AirService_triggerAirAuthLoggedIn, _AirService_triggerAirAuthLoggedOut, _AirService_triggerWalletInitialized, _AirService_createLoginResult, _AirService_createWalletInitializedResult, _AirService_cleanUpAuth, _AirService_cleanUpWallet;
2088
+ var _a$1, _AuthMessageService_instance;
2089
+ const ALLOWED_AUTH_MESSAGES = [
2090
+ AirAuthMessageTypes.INITIALIZATION_RESPONSE,
2091
+ AirAuthMessageTypes.LOGIN_RESPONSE,
2092
+ AirAuthMessageTypes.SETUP_WALLET_REQUEST,
2093
+ AirAuthMessageTypes.LOGOUT_RESPONSE,
2094
+ AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE,
2095
+ AirAuthMessageTypes.CROSS_PARTNER_TOKEN_RESPONSE,
2096
+ AirAuthMessageTypes.PARTNER_ACCESS_TOKEN_RESPONSE,
2097
+ AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST,
2098
+ AirAuthMessageTypes.CREDENTIAL_SALT_RESPONSE,
2099
+ ];
2100
+ class AuthMessageService extends MessageServiceBase {
2101
+ static create() {
2102
+ if (__classPrivateFieldGet(this, _a$1, "f", _AuthMessageService_instance))
2103
+ throw new Error("AuthMessageService already created");
2104
+ __classPrivateFieldSet(this, _a$1, new _a$1("Embed Service: Auth Channel", ALLOWED_AUTH_MESSAGES), "f", _AuthMessageService_instance);
2105
+ return __classPrivateFieldGet(this, _a$1, "f", _AuthMessageService_instance);
2106
+ }
2107
+ async open(authIframe) {
2108
+ const origin = new URL(authIframe.src).origin;
2109
+ const window = authIframe.contentWindow;
2110
+ await super._open({ window, origin });
2111
+ }
2112
+ async initWalletCommunication() {
2113
+ await this.sendMessage({
2114
+ type: AirAuthMessageTypes.INIT_WALLET_COMMUNICATION,
2115
+ });
2116
+ }
2117
+ async sendPartnerUserInfoRequest() {
2118
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.PARTNER_USER_INFO_RESPONSE)));
2119
+ await this.sendMessage({
2120
+ type: AirAuthMessageTypes.PARTNER_USER_INFO_REQUEST,
2121
+ payload: { allowCache: false },
2122
+ });
2123
+ return response;
2124
+ }
2125
+ async sendLoginRequest(payload) {
2126
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.LOGIN_RESPONSE)));
2127
+ await this.sendMessage({ type: AirAuthMessageTypes.LOGIN_REQUEST, payload });
2128
+ return response;
2129
+ }
2130
+ async logout() {
2131
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.LOGOUT_RESPONSE)));
2132
+ await this.sendMessage({ type: AirAuthMessageTypes.LOGOUT_REQUEST });
2133
+ return response;
2134
+ }
2135
+ async resetWalletCommunication() {
2136
+ await this.sendMessage({ type: AirAuthMessageTypes.RESET_WALLET_COMMUNICATION });
2137
+ }
2138
+ async sendInitializationRequest(payload) {
2139
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.INITIALIZATION_RESPONSE)));
2140
+ await this.sendMessage({ type: AirAuthMessageTypes.INITIALIZATION_REQUEST, payload });
2141
+ return response;
2142
+ }
2143
+ async sendSetupWalletSuccessResponse() {
2144
+ await this.sendMessage({
2145
+ type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2146
+ payload: {
2147
+ success: true,
2148
+ },
2149
+ });
2150
+ }
2151
+ async sendSetupWalletErrorResponse(error) {
2152
+ await this.sendMessage(this.createErrorResponseMessage(AirAuthMessageTypes.SETUP_WALLET_RESPONSE, error));
2153
+ }
2154
+ async sendCrossPartnerTokenRequest(targetPartnerUrl) {
2155
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.CROSS_PARTNER_TOKEN_RESPONSE)));
2156
+ await this.sendMessage({
2157
+ type: AirAuthMessageTypes.CROSS_PARTNER_TOKEN_REQUEST,
2158
+ payload: {
2159
+ targetPartnerUrl,
2160
+ },
2161
+ });
2162
+ return response;
2163
+ }
2164
+ async sendPartnerAccessTokenRequest() {
2165
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.PARTNER_ACCESS_TOKEN_RESPONSE)));
2166
+ await this.sendMessage({ type: AirAuthMessageTypes.PARTNER_ACCESS_TOKEN_REQUEST });
2167
+ return response;
2168
+ }
2169
+ async sendCredentialSaltRequest() {
2170
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirAuthMessageTypes.CREDENTIAL_SALT_RESPONSE)));
2171
+ await this.sendMessage({ type: AirAuthMessageTypes.CREDENTIAL_SALT_REQUEST });
2172
+ return response;
2173
+ }
2174
+ }
2175
+ _a$1 = AuthMessageService;
2176
+ _AuthMessageService_instance = { value: void 0 };
2177
+
2178
+ var _a, _WalletMessageService_instance;
2179
+ const ALLOWED_WALLET_MESSAGES = [
2180
+ AirWalletMessageTypes.INITIALIZATION_RESPONSE,
2181
+ AirWalletMessageTypes.WALLET_INITIALIZED,
2182
+ AirWalletMessageTypes.WALLET_LOGIN_RESPONSE,
2183
+ AirWalletMessageTypes.SETUP_OR_UPDATE_MFA_RESPONSE,
2184
+ AirWalletMessageTypes.CLAIM_ID_RESPONSE,
2185
+ AirWalletMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_RESPONSE,
2186
+ AirWalletMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE,
2187
+ AirWalletMessageTypes.WALLET_INITIALIZED,
2188
+ AirWalletMessageTypes.WALLET_IFRAME_VISIBILITY_REQUEST,
2189
+ AirWalletMessageTypes.LOGOUT_RESPONSE,
2190
+ AirWalletMessageTypes.OPEN_WINDOW_REQUEST,
2191
+ AirWalletMessageTypes.OPEN_WINDOW_RETRY_RESPONSE,
2192
+ ];
2193
+ class WalletMessageService extends MessageServiceBase {
2194
+ static create() {
2195
+ if (__classPrivateFieldGet(this, _a, "f", _WalletMessageService_instance))
2196
+ throw new Error("WalletMessageService already created");
2197
+ __classPrivateFieldSet(this, _a, new _a("Embed Service: Wallet Channel", ALLOWED_WALLET_MESSAGES), "f", _WalletMessageService_instance);
2198
+ return __classPrivateFieldGet(this, _a, "f", _WalletMessageService_instance);
2199
+ }
2200
+ async open(walletIframe) {
2201
+ const origin = new URL(walletIframe.src).origin;
2202
+ const window = walletIframe.contentWindow;
2203
+ await super._open({ window, origin });
2204
+ }
2205
+ async initAuthCommunication(skipWalletLogin) {
2206
+ await this.sendMessage({
2207
+ type: AirWalletMessageTypes.INIT_AUTH_COMMUNICATION,
2208
+ payload: {
2209
+ skipWalletLogin,
2210
+ },
2211
+ });
2212
+ }
2213
+ async sendDeploySmartAccountRequest() {
2214
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.DEPLOY_SMART_ACCOUNT_RESPONSE)));
2215
+ await this.sendMessage({
2216
+ type: AirWalletMessageTypes.DEPLOY_SMART_ACCOUNT_REQUEST,
2217
+ });
2218
+ return response;
2219
+ }
2220
+ async sendIsSmartAccountDeployedRequest() {
2221
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_RESPONSE)));
2222
+ await this.sendMessage({
2223
+ type: AirWalletMessageTypes.IS_SMART_ACCOUNT_DEPLOYED_REQUEST,
2224
+ });
2225
+ return response;
2226
+ }
2227
+ async logout() {
2228
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.LOGOUT_RESPONSE)));
2229
+ await this.sendMessage({ type: AirWalletMessageTypes.LOGOUT_REQUEST });
2230
+ return response;
2231
+ }
2232
+ async sendInitializationRequest(payload) {
2233
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.INITIALIZATION_RESPONSE)));
2234
+ await this.sendMessage({ type: AirWalletMessageTypes.INITIALIZATION_REQUEST, payload });
2235
+ return response;
2236
+ }
2237
+ onInitialized() {
2238
+ return firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.WALLET_INITIALIZED)));
2239
+ }
2240
+ async sendLoginRequest() {
2241
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.WALLET_LOGIN_RESPONSE)));
2242
+ await this.sendMessage({
2243
+ type: AirWalletMessageTypes.WALLET_LOGIN_REQUEST,
2244
+ });
2245
+ return response;
2246
+ }
2247
+ async sendSetupMfaRequest() {
2248
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.SETUP_OR_UPDATE_MFA_RESPONSE)));
2249
+ await this.sendMessage({
2250
+ type: AirWalletMessageTypes.SETUP_OR_UPDATE_MFA_REQUEST,
2251
+ });
2252
+ return response;
2253
+ }
2254
+ async sendOpenWindowSuccessResponse(windowId, port) {
2255
+ await this.sendMessage({
2256
+ type: AirWalletMessageTypes.OPEN_WINDOW_RESPONSE,
2257
+ payload: {
2258
+ success: true,
2259
+ windowId,
2260
+ },
2261
+ }, [port]);
2262
+ }
2263
+ async sendOpenWindowErrorResponse(windowId, error) {
2264
+ const errorResponse = this.createErrorResponseMessage(AirWalletMessageTypes.OPEN_WINDOW_RESPONSE, error);
2265
+ await this.sendMessage({
2266
+ ...errorResponse,
2267
+ payload: { ...errorResponse.payload, windowId },
2268
+ });
2269
+ }
2270
+ async sendOpenWindowRetryRequest(windowId) {
2271
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.OPEN_WINDOW_RETRY_RESPONSE), filter((msg) => msg.payload.windowId === windowId)));
2272
+ await this.sendMessage({
2273
+ type: AirWalletMessageTypes.OPEN_WINDOW_RETRY_REQUEST,
2274
+ payload: { windowId },
2275
+ });
2276
+ return response;
2277
+ }
2278
+ async sendWindowClosed(windowId) {
2279
+ await this.sendMessage({
2280
+ type: AirWalletMessageTypes.WINDOW_CLOSED,
2281
+ payload: {
2282
+ windowId,
2283
+ },
2284
+ });
2285
+ }
2286
+ async sendClaimIdRequest(payload) {
2287
+ const response = firstValueFrom(this.messages$.pipe(filter((msg) => msg.type === AirWalletMessageTypes.CLAIM_ID_RESPONSE)));
2288
+ await this.sendMessage({ type: AirWalletMessageTypes.CLAIM_ID_REQUEST, payload });
2289
+ return response;
2290
+ }
2291
+ }
2292
+ _a = WalletMessageService;
2293
+ _WalletMessageService_instance = { value: void 0 };
2294
+
2295
+ const getLevelName = levelNum => {
2296
+ const levelNames = Object.keys(log.levels);
2297
+ if (levelNum >= 0 && levelNum < levelNames.length) {
2298
+ return levelNames[levelNum];
2299
+ }
2300
+ return "UNKNOWN";
2301
+ };
2302
+ const configureLogLevel = (environment, enableLogging) => {
2303
+ let level = log.levels.ERROR;
2304
+ if (environment === "development") {
2305
+ level = enableLogging ? log.levels.TRACE : log.levels.INFO;
2306
+ } else if (environment === "staging") {
2307
+ level = enableLogging ? log.levels.DEBUG : log.levels.INFO;
2308
+ } else if (environment === "uat") {
2309
+ level = enableLogging ? log.levels.INFO : log.levels.WARN;
2310
+ } else if (environment === "production") {
2311
+ // Be cautious with enabling more than WARN in prod
2312
+ level = enableLogging ? log.levels.WARN : log.levels.ERROR;
2313
+ }
2314
+ log.setLevel(level);
2315
+ log.info(`[${window?.location?.href}] LogLevel: ${getLevelName(log.getLevel())}`);
2316
+ };
2317
+
2318
+ var version = "1.3.0";
2319
+ var airkitPackage = {
2320
+ version: version};
2321
+
2322
+ var _AirService_instances, _AirService_loginResult, _AirService_buildEnv, _AirService_enableLogging, _AirService_partnerId, _AirService_authMessagingService, _AirService_authIframeController, _AirService_isAuthInitialized, _AirService_airAuthListener, _AirService_walletMessagingService, _AirService_walletIframeController, _AirService_walletInitialization, _AirService_walletLoggedInResult, _AirService_airWalletProvider, _AirService_ensureWallet, _AirService_initializeWallet, _AirService_subscribeToWalletEvents, _AirService_triggerEventListeners, _AirService_triggerAirAuthInitialized, _AirService_triggerAirAuthLoggedIn, _AirService_triggerAirAuthLoggedOut, _AirService_triggerWalletInitialized, _AirService_createLoginResult, _AirService_createWalletInitializedResult, _AirService_cleanUpAuth, _AirService_cleanUpWallet;
2323
+ const airKitVersion = airkitPackage.version;
2073
2324
  class AirService {
2074
2325
  constructor({ partnerId }) {
2075
2326
  _AirService_instances.add(this);
2076
- _AirService_loginResult.set(this, undefined);
2077
- _AirService_buildEnv.set(this, undefined);
2327
+ _AirService_loginResult.set(this, void 0);
2328
+ _AirService_buildEnv.set(this, void 0);
2078
2329
  _AirService_enableLogging.set(this, false);
2079
- _AirService_partnerId.set(this, undefined);
2330
+ _AirService_partnerId.set(this, void 0);
2080
2331
  //#modalZIndex: number; TODO implement z index overwrite
2081
- _AirService_authIframeController.set(this, undefined);
2332
+ _AirService_authMessagingService.set(this, void 0);
2333
+ _AirService_authIframeController.set(this, void 0);
2082
2334
  _AirService_isAuthInitialized.set(this, false);
2083
2335
  _AirService_airAuthListener.set(this, []);
2084
- _AirService_walletIframeController.set(this, undefined);
2085
- _AirService_walletInitialization.set(this, undefined);
2086
- _AirService_walletLoggedInResult.set(this, undefined);
2087
- _AirService_airWalletProvider.set(this, undefined);
2336
+ _AirService_walletMessagingService.set(this, void 0);
2337
+ _AirService_walletIframeController.set(this, void 0);
2338
+ _AirService_walletInitialization.set(this, void 0);
2339
+ _AirService_walletLoggedInResult.set(this, void 0);
2340
+ _AirService_airWalletProvider.set(this, void 0);
2088
2341
  __classPrivateFieldSet(this, _AirService_partnerId, partnerId, "f");
2342
+ __classPrivateFieldSet(this, _AirService_authMessagingService, AuthMessageService.create(), "f");
2343
+ __classPrivateFieldSet(this, _AirService_walletMessagingService, WalletMessageService.create(), "f");
2089
2344
  __classPrivateFieldSet(this, _AirService_airWalletProvider, new AirWalletProvider({
2090
2345
  isLoggedIn: () => this.isLoggedIn,
2091
2346
  ensureWallet: __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).bind(this),
2092
- getWalletIframeController: () => __classPrivateFieldGet(this, _AirService_walletIframeController, "f"),
2093
2347
  }), "f");
2094
2348
  // this.#modalZIndex = modalZIndex ?? 99999;
2095
2349
  }
@@ -2113,6 +2367,9 @@ class AirService {
2113
2367
  removeListener: provider.removeListener.bind(provider),
2114
2368
  };
2115
2369
  }
2370
+ shouldEnableAutomation() {
2371
+ return localStorage.getItem("automation") === "true" && __classPrivateFieldGet(this, _AirService_buildEnv, "f") !== "production";
2372
+ }
2116
2373
  async init({ buildEnv = BUILD_ENV.PRODUCTION, enableLogging = false, skipRehydration = false, }) {
2117
2374
  if (!__classPrivateFieldGet(this, _AirService_partnerId, "f"))
2118
2375
  throw new Error("Partner ID is required to initialize auth service");
@@ -2120,61 +2377,48 @@ class AirService {
2120
2377
  return;
2121
2378
  __classPrivateFieldSet(this, _AirService_buildEnv, buildEnv, "f");
2122
2379
  __classPrivateFieldSet(this, _AirService_enableLogging, enableLogging, "f");
2123
- const { authUrl, logLevel } = AIR_URLS[buildEnv];
2124
- log.setDefaultLevel(logLevel);
2125
- if (__classPrivateFieldGet(this, _AirService_enableLogging, "f"))
2126
- log.enableAll();
2127
- else
2128
- log.disableAll();
2380
+ const { authUrl } = AIR_URLS[buildEnv];
2381
+ configureLogLevel(buildEnv, enableLogging);
2129
2382
  const authIframeOrigin = new URL(authUrl).origin;
2130
- await AirMessageService$1.openAuthObservables({ authIframeOrigin });
2131
2383
  __classPrivateFieldSet(this, _AirService_authIframeController, new IframeController(authUrl, `air-auth-${randomId()}`), "f");
2132
- AirMessageService$1.authMessage$.subscribe(async (msg) => {
2133
- switch (msg.type) {
2134
- case AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST: {
2135
- const authIframeController = __classPrivateFieldGet(this, _AirService_authIframeController, "f");
2136
- authIframeController.setIframeVisibility(msg.payload.visible);
2137
- authIframeController.updateIframeState();
2138
- break;
2139
- }
2140
- case AirAuthMessageTypes.SETUP_WALLET_REQUEST: {
2141
- try {
2142
- await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this, { skipWalletLogin: true });
2143
- __classPrivateFieldGet(this, _AirService_authIframeController, "f").postMessage({
2144
- type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2145
- payload: {
2146
- success: true,
2147
- },
2148
- });
2384
+ try {
2385
+ __classPrivateFieldGet(this, _AirService_authIframeController, "f").createIframe();
2386
+ log.info(authUrl, "url loaded");
2387
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").open(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement);
2388
+ __classPrivateFieldGet(this, _AirService_authMessagingService, "f").messages$.subscribe(async (msg) => {
2389
+ switch (msg.type) {
2390
+ case AirAuthMessageTypes.IFRAME_VISIBILITY_REQUEST: {
2391
+ const authIframeController = __classPrivateFieldGet(this, _AirService_authIframeController, "f");
2392
+ authIframeController.setIframeVisibility(msg.payload.visible);
2393
+ authIframeController.updateIframeState();
2394
+ break;
2149
2395
  }
2150
- catch (err) {
2151
- log.error("Error initializing wallet", err);
2152
- const error = AirServiceError.from(err);
2153
- __classPrivateFieldGet(this, _AirService_authIframeController, "f").postMessage({
2154
- type: AirAuthMessageTypes.SETUP_WALLET_RESPONSE,
2155
- payload: {
2156
- success: false,
2157
- errorName: error.name ?? "UNKNOWN_ERROR",
2158
- errorMessage: error.message ?? "Unknown error occurred",
2159
- },
2160
- });
2396
+ case AirAuthMessageTypes.SETUP_WALLET_REQUEST: {
2397
+ try {
2398
+ await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this, { skipWalletLogin: true });
2399
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendSetupWalletSuccessResponse();
2400
+ }
2401
+ catch (err) {
2402
+ const error = ensureError(err);
2403
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendSetupWalletErrorResponse(error);
2404
+ }
2405
+ break;
2161
2406
  }
2162
- break;
2163
2407
  }
2164
- }
2165
- });
2166
- try {
2167
- __classPrivateFieldGet(this, _AirService_authIframeController, "f").createIframe();
2408
+ });
2168
2409
  const result = await new Promise((resolve, reject) => {
2169
2410
  const handleAuthMessage = async (ev) => {
2170
2411
  if (ev.origin !== authIframeOrigin)
2171
2412
  return;
2172
2413
  if (ev.data === AirAuthMessageTypes.AUTH_SETUP_COMPLETED) {
2173
2414
  window.removeEventListener("message", handleAuthMessage);
2174
- const { payload } = await AirMessageService$1.sendAuthInitializationRequest(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement, {
2415
+ const { payload } = await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendInitializationRequest({
2175
2416
  partnerId: __classPrivateFieldGet(this, _AirService_partnerId, "f"),
2176
2417
  skipRehydration,
2177
2418
  partnerDAppUrl: window.location.href,
2419
+ sdkVersion: airKitVersion,
2420
+ enableLogging: __classPrivateFieldGet(this, _AirService_enableLogging, "f"),
2421
+ enableAutomation: this.shouldEnableAutomation(),
2178
2422
  });
2179
2423
  if (payload.success === true) {
2180
2424
  resolve(payload);
@@ -2207,8 +2451,7 @@ class AirService {
2207
2451
  throw new Error("Service is not initialized");
2208
2452
  if (__classPrivateFieldGet(this, _AirService_loginResult, "f"))
2209
2453
  return __classPrivateFieldGet(this, _AirService_loginResult, "f");
2210
- const iframeController = __classPrivateFieldGet(this, _AirService_authIframeController, "f");
2211
- const { payload } = await AirMessageService$1.sendAuthLoginRequest(iframeController.iframeElement, {
2454
+ const { payload } = await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendLoginRequest({
2212
2455
  partnerLoginToken: options?.authToken,
2213
2456
  });
2214
2457
  if (payload.success === true) {
@@ -2216,7 +2459,7 @@ class AirService {
2216
2459
  __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_triggerAirAuthLoggedIn).call(this);
2217
2460
  return __classPrivateFieldGet(this, _AirService_loginResult, "f");
2218
2461
  }
2219
- throw new AirServiceError("UNKNOWN_ERROR", "Unknown error occurred");
2462
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2220
2463
  }
2221
2464
  /**
2222
2465
  * @experimental This method is experimental and will change in the future.
@@ -2227,7 +2470,7 @@ class AirService {
2227
2470
  await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2228
2471
  try {
2229
2472
  log.info("deploySmartAccount");
2230
- const { payload } = await AirMessageService$1.sendDeploySmartAccountRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement);
2473
+ const { payload } = await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendDeploySmartAccountRequest();
2231
2474
  if (payload.success === false) {
2232
2475
  throw new AirServiceError(payload.errorName, payload.errorMessage);
2233
2476
  }
@@ -2240,67 +2483,16 @@ class AirService {
2240
2483
  /**
2241
2484
  * @experimental This method is experimental and will change in the future.
2242
2485
  */
2243
- async grantPermission(policies) {
2244
- if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2245
- throw new Error("AirAuth is not initialized");
2246
- await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2247
- try {
2248
- log.info("grantPermission", policies);
2249
- const { payload } = await AirMessageService$1.sendGrantPermissionsRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, { policies });
2250
- if (payload.success === false) {
2251
- throw new AirServiceError(payload.errorName, payload.errorMessage);
2252
- }
2253
- return payload.sessionData;
2254
- }
2255
- catch (error) {
2256
- throw AirServiceError.from(error);
2257
- }
2258
- }
2259
- /**
2260
- * @experimental This method is experimental and will change in the future.
2261
- */
2262
- async listAllSessionKeyScopes() {
2486
+ async isSmartAccountDeployed() {
2263
2487
  if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2264
2488
  throw new Error("Service is not initialized");
2265
2489
  await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2266
2490
  try {
2267
- const { payload } = await AirMessageService$1.sendListAllSessionKeyScopesRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement);
2491
+ const { payload } = await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendIsSmartAccountDeployedRequest();
2268
2492
  if (payload.success === false) {
2269
2493
  throw new AirServiceError(payload.errorName, payload.errorMessage);
2270
2494
  }
2271
- return payload.sessionKeyScopes;
2272
- }
2273
- catch (error) {
2274
- throw AirServiceError.from(error);
2275
- }
2276
- }
2277
- /**
2278
- * @experimental This method is experimental and will change in the future.
2279
- */
2280
- async executeAction(params) {
2281
- if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2282
- throw new Error("Service is not initialized");
2283
- await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2284
- try {
2285
- log.info("executeAction", params);
2286
- const txHash = await AirMessageService$1.sendExecuteActionRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, params);
2287
- return txHash;
2288
- }
2289
- catch (error) {
2290
- throw AirServiceError.from(error);
2291
- }
2292
- }
2293
- /**
2294
- * @experimental This method is experimental and will change in the future.
2295
- */
2296
- async revokePermission(permissionId) {
2297
- if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2298
- throw new Error("Service is not initialized");
2299
- await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2300
- try {
2301
- log.info("revokePermission", permissionId);
2302
- const txHash = await AirMessageService$1.sendRevokePermissionsRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, permissionId);
2303
- return txHash;
2495
+ return payload.isDeployed;
2304
2496
  }
2305
2497
  catch (error) {
2306
2498
  throw AirServiceError.from(error);
@@ -2309,20 +2501,18 @@ class AirService {
2309
2501
  /**
2310
2502
  * @experimental This method is experimental and will change in the future.
2311
2503
  */
2312
- async isSmartAccountDeployed() {
2504
+ async getCredentialSalt() {
2313
2505
  if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2314
2506
  throw new Error("Service is not initialized");
2315
- await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2316
- try {
2317
- const { payload } = await AirMessageService$1.sendIsSmartAccountDeployedRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement);
2318
- if (payload.success === false) {
2319
- throw new AirServiceError(payload.errorName, payload.errorMessage);
2320
- }
2321
- return payload.isDeployed;
2322
- }
2323
- catch (error) {
2324
- throw AirServiceError.from(error);
2507
+ if (!this.isLoggedIn)
2508
+ throw new Error("No active session to get partner access token");
2509
+ const result = await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendCredentialSaltRequest();
2510
+ if (result.payload.success === false) {
2511
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2325
2512
  }
2513
+ return {
2514
+ credentialSalt: result.payload.credentialSalt,
2515
+ };
2326
2516
  }
2327
2517
  getProvider() {
2328
2518
  return this.provider;
@@ -2332,14 +2522,18 @@ class AirService {
2332
2522
  }
2333
2523
  async setupOrUpdateMfa() {
2334
2524
  await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this, { skipWalletLogin: true });
2335
- const result = await AirMessageService$1.sendSetupMfaRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement);
2525
+ const result = await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendSetupMfaRequest();
2336
2526
  if (result.payload.success === false) {
2337
2527
  throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2338
2528
  }
2529
+ __classPrivateFieldSet(this, _AirService_loginResult, {
2530
+ ...__classPrivateFieldGet(this, _AirService_loginResult, "f"),
2531
+ isMFASetup: true,
2532
+ }, "f");
2339
2533
  }
2340
2534
  async claimAirId(options) {
2341
2535
  await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_ensureWallet).call(this);
2342
- const result = await AirMessageService$1.sendClaimIdRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, options ?? {});
2536
+ const result = await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendClaimIdRequest(options ?? {});
2343
2537
  if (result.payload.success === true) {
2344
2538
  return { airId: result.payload.airId };
2345
2539
  }
@@ -2348,7 +2542,7 @@ class AirService {
2348
2542
  async getUserInfo() {
2349
2543
  if (!this.isLoggedIn)
2350
2544
  throw new Error("User not logged in");
2351
- const info = await AirMessageService$1.sendPartnerUserInfoRequest(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement);
2545
+ const info = await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendPartnerUserInfoRequest();
2352
2546
  if (info.payload.success === false) {
2353
2547
  throw new AirServiceError(info.payload.errorName, info.payload.errorMessage);
2354
2548
  }
@@ -2369,7 +2563,7 @@ class AirService {
2369
2563
  throw new Error("Service is not initialized");
2370
2564
  if (!this.isLoggedIn)
2371
2565
  throw new Error("No active session to generate token");
2372
- const result = await AirMessageService$1.sendCrossPartnerTokenRequest(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement, partnerUrl);
2566
+ const result = await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendCrossPartnerTokenRequest(partnerUrl);
2373
2567
  if (result.payload.success === false) {
2374
2568
  throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2375
2569
  }
@@ -2377,6 +2571,20 @@ class AirService {
2377
2571
  urlWithToken: result.payload.urlWithToken,
2378
2572
  };
2379
2573
  }
2574
+ async getAccessToken() {
2575
+ if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2576
+ throw new Error("Service is not initialized");
2577
+ if (!this.isLoggedIn)
2578
+ throw new Error("No active session to get partner access token");
2579
+ const result = await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").sendPartnerAccessTokenRequest();
2580
+ if (result.payload.success !== true) {
2581
+ throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2582
+ }
2583
+ if (!result.payload.partnerAccessToken) {
2584
+ throw new Error("Partner access token not found in response");
2585
+ }
2586
+ return { token: result.payload.partnerAccessToken };
2587
+ }
2380
2588
  async logout() {
2381
2589
  if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2382
2590
  throw new Error("Service is not initialized");
@@ -2384,7 +2592,7 @@ class AirService {
2384
2592
  throw new Error("No active session to logout");
2385
2593
  // Clear up wallet
2386
2594
  await __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_cleanUpWallet).call(this);
2387
- await AirMessageService$1.logoutAuth(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement);
2595
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").logout();
2388
2596
  __classPrivateFieldSet(this, _AirService_loginResult, undefined, "f");
2389
2597
  __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_triggerAirAuthLoggedOut).call(this);
2390
2598
  }
@@ -2404,22 +2612,8 @@ class AirService {
2404
2612
  clearEventListeners() {
2405
2613
  __classPrivateFieldSet(this, _AirService_airAuthListener, [], "f");
2406
2614
  }
2407
- async getPartnerAccessToken() {
2408
- if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
2409
- throw new Error("Service is not initialized");
2410
- if (!this.isLoggedIn)
2411
- throw new Error("No active session to get partner access token");
2412
- const result = await AirMessageService$1.sendGetPartnerAccessTokenRequest(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement);
2413
- if (result.payload.success === false) {
2414
- throw new AirServiceError(result.payload.errorName, result.payload.errorMessage);
2415
- }
2416
- if (!result.payload.partnerAccessToken) {
2417
- throw new Error("Partner access token not found in response");
2418
- }
2419
- return result.payload.partnerAccessToken;
2420
- }
2421
2615
  }
2422
- _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _AirService_enableLogging = new WeakMap(), _AirService_partnerId = new WeakMap(), _AirService_authIframeController = new WeakMap(), _AirService_isAuthInitialized = new WeakMap(), _AirService_airAuthListener = new WeakMap(), _AirService_walletIframeController = new WeakMap(), _AirService_walletInitialization = new WeakMap(), _AirService_walletLoggedInResult = new WeakMap(), _AirService_airWalletProvider = new WeakMap(), _AirService_instances = new WeakSet(), _AirService_ensureWallet = async function _AirService_ensureWallet(option) {
2616
+ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _AirService_enableLogging = new WeakMap(), _AirService_partnerId = new WeakMap(), _AirService_authMessagingService = new WeakMap(), _AirService_authIframeController = new WeakMap(), _AirService_isAuthInitialized = new WeakMap(), _AirService_airAuthListener = new WeakMap(), _AirService_walletMessagingService = new WeakMap(), _AirService_walletIframeController = new WeakMap(), _AirService_walletInitialization = new WeakMap(), _AirService_walletLoggedInResult = new WeakMap(), _AirService_airWalletProvider = new WeakMap(), _AirService_instances = new WeakSet(), _AirService_ensureWallet = async function _AirService_ensureWallet(option) {
2423
2617
  if (!this.isInitialized)
2424
2618
  throw new Error("Service not initialized");
2425
2619
  if (!this.isLoggedIn && !option?.skipWalletLogin)
@@ -2441,7 +2635,7 @@ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _
2441
2635
  }
2442
2636
  if (__classPrivateFieldGet(this, _AirService_walletLoggedInResult, "f"))
2443
2637
  return __classPrivateFieldGet(this, _AirService_walletLoggedInResult, "f");
2444
- const walletLoginResult = await AirMessageService$1.sendWalletLoginRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement);
2638
+ const walletLoginResult = await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendLoginRequest();
2445
2639
  if (walletLoginResult.payload.success !== true) {
2446
2640
  throw new AirServiceError(walletLoginResult.payload.errorName, walletLoginResult.payload.errorMessage);
2447
2641
  }
@@ -2450,22 +2644,19 @@ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _
2450
2644
  if (__classPrivateFieldGet(this, _AirService_walletInitialization, "f"))
2451
2645
  throw new Error("Already initializing");
2452
2646
  const { walletUrl } = AIR_URLS[__classPrivateFieldGet(this, _AirService_buildEnv, "f")];
2453
- log.info(walletUrl, "url loaded");
2454
2647
  const walletIframeOrigin = new URL(walletUrl).origin;
2455
- await AirMessageService$1.openWalletObservables({ walletIframeOrigin });
2456
2648
  try {
2457
- __classPrivateFieldSet(this, _AirService_walletIframeController, new IframeController(walletUrl, `air-wallet-${randomId()}`), "f");
2458
- __classPrivateFieldGet(this, _AirService_walletIframeController, "f").createIframe();
2459
- __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_subscribeToWalletEvents).call(this);
2460
- await new Promise((resolve, reject) => {
2461
- const handleAuthMessage = async (ev) => {
2649
+ const walletInitRequestPromise = new Promise((resolve, reject) => {
2650
+ const handleWalletMessage = async (ev) => {
2462
2651
  if (ev.origin !== walletIframeOrigin)
2463
2652
  return;
2464
- if (ev.data === AirMessageTypes.SERVICE_STARTED) {
2465
- window.removeEventListener("message", handleAuthMessage);
2466
- const { payload } = await AirMessageService$1.sendWalletInitializationRequest(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, {
2653
+ if (ev.data === AirWalletMessageTypes.SERVICE_STARTED) {
2654
+ window.removeEventListener("message", handleWalletMessage);
2655
+ const { payload } = await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendInitializationRequest({
2467
2656
  partnerId: __classPrivateFieldGet(this, _AirService_partnerId, "f"),
2468
2657
  enableLogging: __classPrivateFieldGet(this, _AirService_enableLogging, "f"),
2658
+ sdkVersion: airKitVersion,
2659
+ enableAutomation: this.shouldEnableAutomation(),
2469
2660
  });
2470
2661
  if (payload.success === true) {
2471
2662
  resolve();
@@ -2475,11 +2666,18 @@ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _
2475
2666
  }
2476
2667
  }
2477
2668
  };
2478
- window.addEventListener("message", handleAuthMessage);
2669
+ window.addEventListener("message", handleWalletMessage);
2479
2670
  });
2480
- __classPrivateFieldGet(this, _AirService_airWalletProvider, "f").startEventMessageListening();
2481
- const walletInitPromise = AirMessageService$1.onWalletInitialized();
2482
- AirMessageService$1.setupIframeCommunication(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement, __classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, option?.skipWalletLogin ?? false);
2671
+ __classPrivateFieldSet(this, _AirService_walletIframeController, new IframeController(walletUrl, `air-wallet-${randomId()}`), "f");
2672
+ __classPrivateFieldGet(this, _AirService_walletIframeController, "f").createIframe();
2673
+ log.info(walletUrl, "url loaded");
2674
+ await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").open(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement);
2675
+ __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_subscribeToWalletEvents).call(this);
2676
+ await __classPrivateFieldGet(this, _AirService_airWalletProvider, "f").startEventMessageListening(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement);
2677
+ const walletInitPromise = __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").onInitialized();
2678
+ await walletInitRequestPromise;
2679
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").initWalletCommunication();
2680
+ await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").initAuthCommunication(option?.skipWalletLogin ?? false);
2483
2681
  const walletInitResult = await walletInitPromise;
2484
2682
  if (walletInitResult.payload.success !== true) {
2485
2683
  throw new AirServiceError(walletInitResult.payload.errorName, walletInitResult.payload.errorMessage);
@@ -2496,37 +2694,44 @@ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _
2496
2694
  throw error;
2497
2695
  }
2498
2696
  }, _AirService_subscribeToWalletEvents = function _AirService_subscribeToWalletEvents() {
2499
- AirMessageService$1.messages$.subscribe(async (msg) => {
2697
+ __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").messages$.subscribe(async (msg) => {
2500
2698
  switch (msg.type) {
2501
- case AirMessageTypes.WALLET_IFRAME_VISIBILITY_REQUEST: {
2699
+ case AirWalletMessageTypes.WALLET_IFRAME_VISIBILITY_REQUEST: {
2502
2700
  const walletIframeController = __classPrivateFieldGet(this, _AirService_walletIframeController, "f");
2503
2701
  walletIframeController.setIframeVisibility(msg.payload.visible);
2504
2702
  walletIframeController.updateIframeState();
2505
2703
  break;
2506
2704
  }
2507
- case AirMessageTypes.WALLET_LOGIN_RESPONSE: {
2705
+ case AirWalletMessageTypes.WALLET_LOGIN_RESPONSE: {
2508
2706
  if (msg.payload.success === true && !__classPrivateFieldGet(this, _AirService_walletLoggedInResult, "f")) {
2509
2707
  __classPrivateFieldSet(this, _AirService_walletLoggedInResult, __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_createWalletInitializedResult).call(this, msg.payload), "f");
2510
2708
  __classPrivateFieldGet(this, _AirService_instances, "m", _AirService_triggerWalletInitialized).call(this, __classPrivateFieldGet(this, _AirService_walletLoggedInResult, "f"));
2511
2709
  }
2512
2710
  break;
2513
2711
  }
2514
- case AirMessageTypes.OPEN_WINDOW_REQUEST: {
2712
+ case AirWalletMessageTypes.OPEN_WINDOW_REQUEST: {
2515
2713
  try {
2516
- const channel = new MessageChannel();
2517
- const windowController = await WindowService$1.openAndInitializeWalletServiceWindow({
2714
+ const onRetry = async () => {
2715
+ const { payload } = await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendOpenWindowRetryRequest(msg.payload.windowId);
2716
+ if (payload.success === false) {
2717
+ throw new AirServiceError(payload.errorName, payload.errorMessage);
2718
+ }
2719
+ };
2720
+ const { windowController, port } = await WindowService$1.openAndInitializeWalletServiceWindow({
2518
2721
  url: msg.payload.url,
2519
2722
  windowId: msg.payload.windowId,
2520
2723
  partnerId: __classPrivateFieldGet(this, _AirService_partnerId, "f"),
2521
2724
  enableLogging: __classPrivateFieldGet(this, _AirService_enableLogging, "f"),
2522
- port: channel.port1,
2725
+ sdkVersion: airKitVersion,
2726
+ enableAutomation: this.shouldEnableAutomation(),
2727
+ onRetry,
2523
2728
  });
2524
- windowController.onClose(() => AirMessageService$1.sendWindowClosed(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, msg.payload.windowId));
2525
- AirMessageService$1.sendOpenWindowSuccessResponse(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, msg.payload.windowId, channel.port2);
2729
+ windowController.onClose(async () => await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendWindowClosed(msg.payload.windowId));
2730
+ await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendOpenWindowSuccessResponse(msg.payload.windowId, port);
2526
2731
  }
2527
2732
  catch (err) {
2528
2733
  const error = ensureError(err);
2529
- AirMessageService$1.sendOpenWindowErrorResponse(__classPrivateFieldGet(this, _AirService_walletIframeController, "f").iframeElement, msg.payload.windowId, error);
2734
+ await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").sendOpenWindowErrorResponse(msg.payload.windowId, error);
2530
2735
  }
2531
2736
  break;
2532
2737
  }
@@ -2571,7 +2776,7 @@ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _
2571
2776
  };
2572
2777
  }, _AirService_cleanUpAuth = async function _AirService_cleanUpAuth() {
2573
2778
  // Logout auth session
2574
- await AirMessageService$1.logoutAuth(__classPrivateFieldGet(this, _AirService_authIframeController, "f").iframeElement);
2779
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").logout();
2575
2780
  // Destroy the auth iframe
2576
2781
  const authIframeElement = __classPrivateFieldGet(this, _AirService_authIframeController, "f")?.iframeElement;
2577
2782
  if (isElement(authIframeElement) && window.document.body.contains(authIframeElement)) {
@@ -2579,7 +2784,7 @@ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _
2579
2784
  __classPrivateFieldSet(this, _AirService_authIframeController, undefined, "f");
2580
2785
  }
2581
2786
  // Close the message service
2582
- AirMessageService$1.closeAuthObservables();
2787
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").close();
2583
2788
  __classPrivateFieldSet(this, _AirService_isAuthInitialized, false, "f");
2584
2789
  }, _AirService_cleanUpWallet = async function _AirService_cleanUpWallet() {
2585
2790
  if (!__classPrivateFieldGet(this, _AirService_isAuthInitialized, "f"))
@@ -2587,18 +2792,18 @@ _AirService_loginResult = new WeakMap(), _AirService_buildEnv = new WeakMap(), _
2587
2792
  // Logout wallet and destroy the wallet iframe
2588
2793
  const walletIframeElement = __classPrivateFieldGet(this, _AirService_walletIframeController, "f")?.iframeElement;
2589
2794
  if (isElement(walletIframeElement) && window.document.body.contains(walletIframeElement)) {
2590
- await AirMessageService$1.logoutWallet(walletIframeElement);
2795
+ await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").logout();
2591
2796
  __classPrivateFieldGet(this, _AirService_walletIframeController, "f").destroy();
2592
2797
  __classPrivateFieldSet(this, _AirService_walletIframeController, undefined, "f");
2593
2798
  }
2594
2799
  const authIframeElement = __classPrivateFieldGet(this, _AirService_authIframeController, "f")?.iframeElement;
2595
2800
  if (isElement(authIframeElement) && window.document.body.contains(authIframeElement)) {
2596
- AirMessageService$1.sendResetAuthServiceWalletCommunication(authIframeElement);
2801
+ await __classPrivateFieldGet(this, _AirService_authMessagingService, "f").resetWalletCommunication();
2597
2802
  }
2598
2803
  // Close the message service
2599
- AirMessageService$1.closeAirObservables();
2804
+ await __classPrivateFieldGet(this, _AirService_walletMessagingService, "f").close();
2600
2805
  __classPrivateFieldSet(this, _AirService_walletLoggedInResult, undefined, "f");
2601
2806
  __classPrivateFieldSet(this, _AirService_walletInitialization, undefined, "f");
2602
2807
  };
2603
2808
 
2604
- export { AirService, AirServiceError, BUILD_ENV, ChainDisconnectedError, InternalRpcError, InvalidParamsRpcError, InvalidRequestRpcError, MethodNotFoundRpcError, ProviderDisconnectedError, SwitchChainError, UnauthorizedProviderError, UnsupportedProviderMethodError, UserRejectedRequestError, ensureProviderRpcError };
2809
+ export { AirService, AirServiceError, BUILD_ENV, ChainDisconnectedError, InternalRpcError, InvalidParamsRpcError, InvalidRequestRpcError, MethodNotFoundRpcError, ProviderDisconnectedError, ProviderRpcError, SwitchChainError, TransactionRejectedRpcError, UnauthorizedProviderError, UnsupportedProviderMethodError, UserRejectedRequestError, ensureProviderRpcError };