@paypay/mini-app-js-sdk 2.41.0 → 2.48.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 (61) hide show
  1. package/dist/client/clientUtils.d.ts +2 -1
  2. package/dist/client/communicationWithCore.d.ts +16 -0
  3. package/dist/client/functions/copyToClipboard.d.ts +2 -0
  4. package/dist/client/functions/coreWindowBridgeFunctions.d.ts +12 -0
  5. package/dist/client/functions/getKycPassportInfo.d.ts +3 -0
  6. package/dist/client/functions/logout.d.ts +6 -0
  7. package/dist/client/functions/renderCoupons.d.ts +6 -0
  8. package/dist/client/functions/scanCode.d.ts +2 -0
  9. package/dist/client/functions/setTitle.d.ts +2 -0
  10. package/dist/client/functions/share.d.ts +2 -0
  11. package/dist/client/functions/storageFunctions.d.ts +6 -0
  12. package/dist/client/functions/verifyMultiFactorAuthResult.d.ts +3 -0
  13. package/dist/client/index.d.ts +4 -54
  14. package/dist/client/types.d.ts +37 -2
  15. package/dist/client/{clientFunctions → windowBridgeFunctions}/storageFunctions.d.ts +10 -0
  16. package/dist/client/{clientFunctions → windowBridgeFunctions}/urlFunctions.d.ts +1 -0
  17. package/dist/core/coreFunctions/fetchCoupons.d.ts +4 -0
  18. package/dist/core/coreFunctions/getLoginUrl.d.ts +5 -1
  19. package/dist/core/coreFunctions/index.d.ts +17 -7
  20. package/dist/core/coreFunctions/logEvent.d.ts +4 -0
  21. package/dist/core/coreFunctions/markAsReady.d.ts +4 -0
  22. package/dist/core/coreFunctions/middlewares/initRequired.d.ts +2 -0
  23. package/dist/core/coreFunctions/middlewares/loginRequired.d.ts +2 -0
  24. package/dist/core/coreUtils.d.ts +1 -1
  25. package/dist/core/index.d.ts +1 -1
  26. package/dist/environment-variables.d.ts +0 -1
  27. package/dist/jsbridge-core/jsbridge.d.ts +4 -5
  28. package/dist/mini-app-api.d.ts +4 -4
  29. package/dist/mini-app-js-sdk.browser.js +2 -2
  30. package/dist/mini-app-js-sdk.es.js +865 -1493
  31. package/dist/model/bridge/getPlatformInformation.d.ts +1 -1
  32. package/dist/model/bridge/getTopBarHeight.d.ts +1 -1
  33. package/dist/model/bridge/renderPayButton.d.ts +0 -6
  34. package/dist/model/miniAppError.d.ts +2 -5
  35. package/dist/package/lottie/lottie.d.ts +6 -6
  36. package/dist/types/checkPaymentMethod.d.ts +1 -1
  37. package/dist/types/getKycInformation.d.ts +3 -3
  38. package/dist/types/getKycPassportInfo.d.ts +2 -2
  39. package/dist/types/getPlatformInformation.d.ts +0 -1
  40. package/dist/types/init.d.ts +2 -3
  41. package/dist/types/makePayment.d.ts +421 -1
  42. package/dist/types/topup.d.ts +1 -1
  43. package/dist/types.d.ts +8 -2
  44. package/dist/utils/analytics.d.ts +1 -0
  45. package/dist/utils/api.d.ts +0 -1
  46. package/dist/utils/getAppDetail.d.ts +1 -0
  47. package/dist/utils/helper.d.ts +7 -4
  48. package/dist/utils/minimumAppVersion.d.ts +0 -5
  49. package/dist/utils/minimumJSSDKVersion.d.ts +1 -0
  50. package/dist/utils/storage.d.ts +0 -2
  51. package/dist/utils/windowBridge.d.ts +24 -3
  52. package/dist/views/coupon/components/Arrow/index.d.ts +5 -5
  53. package/dist/views/coupon/components/CouponAction/index.d.ts +27 -7
  54. package/dist/views/coupon/components/CouponContainer/index.d.ts +3 -3
  55. package/dist/views/coupon/index.d.ts +27 -7
  56. package/dist/views/registerPaymentFeatures/types.d.ts +1 -1
  57. package/package.json +55 -67
  58. package/dist/composition-api/useShowUpdateWarningKycPassport.d.ts +0 -4
  59. package/dist/model/makePayment.d.ts +0 -430
  60. package/dist/types/getLoginUrl.d.ts +0 -8
  61. /package/dist/client/{clientFunctions → windowBridgeFunctions}/index.d.ts +0 -0
@@ -1,4 +1,4 @@
1
- (function(){"use strict";try{if(typeof document!="undefined"){var p=document.createElement("style");p.appendChild(document.createTextNode(".ppmna-reset-css{all:initial}.ppmna-reset-css *{text-align:unset;color:unset;background:initial;background-color:transparent;margin:revert;padding:revert;font-weight:revert;font-style:unset;font-size:unset;-webkit-user-select:none;user-select:none;border:unset;border-radius:revert;vertical-align:unset;word-break:unset;outline:none;box-sizing:content-box}.ppmna-reset-css * img{display:inline-block}.ppmna-reset-css * input,.ppmna-reset-css * select{-webkit-user-select:auto;user-select:auto}.ppmna-reset-css * li{list-style:none}.ppmna-reset-css * :where(*:not(svg,svg *)){all:revert}.pp-smartButtonWrapper .pp-smartBtn{display:flex;align-items:center;border-radius:8px;border:none;font-size:14px;font-weight:600;line-height:22px;color:#fff;padding:0;width:100%;height:44px;margin:auto;-webkit-tap-highlight-color:transparent;text-decoration:none;box-sizing:border-box}.pp-smartButtonWrapper .pp-smartBtn.pp-sm .pp-leftSection .pp-btnContent{flex-direction:column}.pp-smartButtonWrapper .pp-smartBtn.pp-light{background:#fff;color:#242323}.pp-smartButtonWrapper .pp-smartBtn.pp-dark{background:#000}.pp-smartButtonWrapper .pp-smartBtn.pp-red{background:#ff0033}.pp-smartButtonWrapper .pp-smartBtn.pp-login{min-width:180px}.pp-smartButtonWrapper .pp-smartBtn.pp-login.pp-sm{width:180px!important}.pp-smartButtonWrapper .pp-smartBtn.pp-login.pp-light{border:1px solid #e4e4e8}.pp-smartButtonWrapper .pp-smartBtn.pp-login.pp-light .pp-userProfile{margin-right:4px}.pp-smartButtonWrapper .pp-smartBtn.pp-login .pp-leftSection .pp-btnContent{display:grid}.pp-smartButtonWrapper .pp-smartBtn.pp-pay{min-width:160px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-light{border:1px solid #dddddd}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-light .pp-cashbackInfo{color:#ff954c;background:#fff0e5}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-red .pp-cashbackInfo{color:#f03}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-ja .pp-cashbackInfo{padding:2px 16px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm{width:160px!important}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm.pp-cashback{height:66px;flex-direction:column;justify-content:center}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm .pp-cashbackInfo{margin:8px 0 0}.pp-smartButtonWrapper .pp-smartBtn.pp-pay .pp-leftSection .pp-img{width:24px;height:24px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-shortText{font-size:16px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm .pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-cashback .pp-leftSection .pp-btnContent,.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-shortText .pp-leftSection .pp-btnContent{margin-left:4px}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection{display:flex;justify-content:center;align-items:center;width:100%;box-sizing:border-box;padding:0 8px}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection .pp-img{width:20px;height:20px;display:inline-block}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection .pp-btnContent{margin-left:8px}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection .pp-btnContent .pp-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pp-smartButtonWrapper .pp-smartBtn .pp-cashbackInfo{font-size:12px;color:#242323;background:#fff;line-height:14px;padding:2px 8px;border-radius:9px;margin-left:8px}.pp-smartButtonWrapper .pp-smartBtn .pp-userProfile{width:34px;height:34px;border-radius:50%;margin-right:5px}.pp-smartButtonWrapper.pp-button{padding:0;margin:0;background:none;border:none;width:100%;border-radius:8px;-webkit-tap-highlight-color:transparent;font-family:revert!important}.pp-smartButtonWrapper.pp-button *{font-family:revert!important}")),document.head.appendChild(p)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();
1
+ !function(){"use strict";try{if("undefined"!=typeof document){var p=document.createElement("style");p.appendChild(document.createTextNode(".ppmna-reset-css{all:initial}.ppmna-reset-css *{text-align:unset;color:unset;background:initial;background-color:transparent;margin:revert;padding:revert;font-weight:revert;font-style:unset;font-size:unset;-webkit-user-select:none;user-select:none;border:unset;border-radius:revert;vertical-align:unset;word-break:unset;outline:none;box-sizing:content-box}.ppmna-reset-css * img{display:inline-block}.ppmna-reset-css * input,.ppmna-reset-css * select{-webkit-user-select:auto;user-select:auto}.ppmna-reset-css * li{list-style:none}.ppmna-reset-css * :where(*:not(svg,svg *)){all:revert}.pp-smartButtonWrapper .pp-smartBtn{display:flex;align-items:center;border-radius:8px;border:none;font-size:14px;font-weight:600;line-height:22px;color:#fff;padding:0;width:100%;height:44px;margin:auto;-webkit-tap-highlight-color:transparent;text-decoration:none;box-sizing:border-box}.pp-smartButtonWrapper .pp-smartBtn.pp-sm .pp-leftSection .pp-btnContent{flex-direction:column}.pp-smartButtonWrapper .pp-smartBtn.pp-light{background:#fff;color:#242323}.pp-smartButtonWrapper .pp-smartBtn.pp-dark{background:#000}.pp-smartButtonWrapper .pp-smartBtn.pp-red{background:#f03}.pp-smartButtonWrapper .pp-smartBtn.pp-login{min-width:180px}.pp-smartButtonWrapper .pp-smartBtn.pp-login.pp-sm{width:180px!important}.pp-smartButtonWrapper .pp-smartBtn.pp-login.pp-light{border:1px solid #e4e4e8}.pp-smartButtonWrapper .pp-smartBtn.pp-login.pp-light .pp-userProfile{margin-right:4px}.pp-smartButtonWrapper .pp-smartBtn.pp-login .pp-leftSection .pp-btnContent{display:grid}.pp-smartButtonWrapper .pp-smartBtn.pp-pay{min-width:160px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-light{border:1px solid #dddddd}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-light .pp-cashbackInfo{color:#ff954c;background:#fff0e5}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-red .pp-cashbackInfo{color:#f03}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-ja .pp-cashbackInfo{padding:2px 16px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm{width:160px!important}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm.pp-cashback{height:66px;flex-direction:column;justify-content:center}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm .pp-cashbackInfo{margin:8px 0 0}.pp-smartButtonWrapper .pp-smartBtn.pp-pay .pp-leftSection .pp-img{width:24px;height:24px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-shortText{font-size:16px}.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-sm .pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-cashback .pp-leftSection .pp-btnContent,.pp-smartButtonWrapper .pp-smartBtn.pp-pay.pp-shortText .pp-leftSection .pp-btnContent{margin-left:4px}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection{display:flex;justify-content:center;align-items:center;width:100%;box-sizing:border-box;padding:0 8px}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection .pp-img{width:20px;height:20px;display:inline-block}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection .pp-btnContent{margin-left:8px}.pp-smartButtonWrapper .pp-smartBtn .pp-leftSection .pp-btnContent .pp-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pp-smartButtonWrapper .pp-smartBtn .pp-cashbackInfo{font-size:12px;color:#242323;background:#fff;line-height:14px;padding:2px 8px;border-radius:9px;margin-left:8px}.pp-smartButtonWrapper .pp-smartBtn .pp-userProfile{width:34px;height:34px;border-radius:50%;margin-right:5px}.pp-smartButtonWrapper.pp-button{padding:0;margin:0;background:none;border:none;width:100%;border-radius:8px;-webkit-tap-highlight-color:transparent;font-family:revert!important}.pp-smartButtonWrapper.pp-button *{font-family:revert!important}")),document.head.appendChild(p)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}}();
2
2
  var __defProp = Object.defineProperty;
3
3
  var __defProps = Object.defineProperties;
4
4
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
@@ -38,7 +38,7 @@ var __async = (__this, __arguments, generator) => {
38
38
  step((generator = generator.apply(__this, __arguments)).next());
39
39
  });
40
40
  };
41
- /*! js-cookie v3.0.1 | MIT */
41
+ /*! js-cookie v3.0.5 | MIT */
42
42
  function assign(target) {
43
43
  for (var i = 1; i < arguments.length; i++) {
44
44
  var source = arguments[i];
@@ -63,7 +63,7 @@ var defaultConverter = {
63
63
  }
64
64
  };
65
65
  function init$1(converter, defaultAttributes) {
66
- function set(key, value, attributes) {
66
+ function set(name, value, attributes) {
67
67
  if (typeof document === "undefined") {
68
68
  return;
69
69
  }
@@ -74,7 +74,7 @@ function init$1(converter, defaultAttributes) {
74
74
  if (attributes.expires) {
75
75
  attributes.expires = attributes.expires.toUTCString();
76
76
  }
77
- key = encodeURIComponent(key).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
77
+ name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
78
78
  var stringifiedAttributes = "";
79
79
  for (var attributeName in attributes) {
80
80
  if (!attributes[attributeName]) {
@@ -86,10 +86,10 @@ function init$1(converter, defaultAttributes) {
86
86
  }
87
87
  stringifiedAttributes += "=" + attributes[attributeName].split(";")[0];
88
88
  }
89
- return document.cookie = key + "=" + converter.write(value, key) + stringifiedAttributes;
89
+ return document.cookie = name + "=" + converter.write(value, name) + stringifiedAttributes;
90
90
  }
91
- function get(key) {
92
- if (typeof document === "undefined" || arguments.length && !key) {
91
+ function get(name) {
92
+ if (typeof document === "undefined" || arguments.length && !name) {
93
93
  return;
94
94
  }
95
95
  var cookies = document.cookie ? document.cookie.split("; ") : [];
@@ -98,23 +98,23 @@ function init$1(converter, defaultAttributes) {
98
98
  var parts = cookies[i].split("=");
99
99
  var value = parts.slice(1).join("=");
100
100
  try {
101
- var foundKey = decodeURIComponent(parts[0]);
102
- jar[foundKey] = converter.read(value, foundKey);
103
- if (key === foundKey) {
101
+ var found = decodeURIComponent(parts[0]);
102
+ jar[found] = converter.read(value, found);
103
+ if (name === found) {
104
104
  break;
105
105
  }
106
106
  } catch (e) {
107
107
  }
108
108
  }
109
- return key ? jar[key] : jar;
109
+ return name ? jar[name] : jar;
110
110
  }
111
111
  return Object.create(
112
112
  {
113
113
  set,
114
114
  get,
115
- remove: function(key, attributes) {
115
+ remove: function(name, attributes) {
116
116
  set(
117
- key,
117
+ name,
118
118
  "",
119
119
  assign({}, attributes, {
120
120
  expires: -1
@@ -155,6 +155,7 @@ var PpLocalStorageKey = /* @__PURE__ */ ((PpLocalStorageKey2) => {
155
155
  PpLocalStorageKey2["claimCouponImmediately"] = "ppjssdk.claimCouponImmediately";
156
156
  PpLocalStorageKey2["merchant"] = "ppjssdk.merchant";
157
157
  PpLocalStorageKey2["consumedOTT"] = "ppjssdk.consumedOTT";
158
+ PpLocalStorageKey2["initializedAt"] = "ppjssdk.initializedAt";
158
159
  return PpLocalStorageKey2;
159
160
  })(PpLocalStorageKey || {});
160
161
  const PPFunctionResult = {
@@ -299,52 +300,6 @@ const smartPaymentSupportedFunctions = [
299
300
  "renderCoupons",
300
301
  "getLoginUrl"
301
302
  ];
302
- function url(path) {
303
- return "https://image.paypay.ne.jp/miniapps/mini-app-sdk/" + path;
304
- }
305
- const img_paypayRec = url("icon-paypay-rec.svg");
306
- const img_paypayRecWhite = url("icon-paypay-rec-white.svg");
307
- var getRandomValues;
308
- var rnds8 = new Uint8Array(16);
309
- function rng() {
310
- if (!getRandomValues) {
311
- getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== "undefined" && typeof msCrypto.getRandomValues === "function" && msCrypto.getRandomValues.bind(msCrypto);
312
- if (!getRandomValues) {
313
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
314
- }
315
- }
316
- return getRandomValues(rnds8);
317
- }
318
- const REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
319
- function validate(uuid) {
320
- return typeof uuid === "string" && REGEX.test(uuid);
321
- }
322
- var byteToHex = [];
323
- for (var i = 0; i < 256; ++i) {
324
- byteToHex.push((i + 256).toString(16).substr(1));
325
- }
326
- function stringify(arr) {
327
- var offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
328
- var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
329
- if (!validate(uuid)) {
330
- throw TypeError("Stringified UUID is invalid");
331
- }
332
- return uuid;
333
- }
334
- function v4(options, buf, offset) {
335
- options = options || {};
336
- var rnds = options.random || (options.rng || rng)();
337
- rnds[6] = rnds[6] & 15 | 64;
338
- rnds[8] = rnds[8] & 63 | 128;
339
- if (buf) {
340
- offset = offset || 0;
341
- for (var i = 0; i < 16; ++i) {
342
- buf[offset + i] = rnds[i];
343
- }
344
- return buf;
345
- }
346
- return stringify(rnds);
347
- }
348
303
  class PPError extends Error {
349
304
  constructor(message, errorCode) {
350
305
  super(message);
@@ -421,10 +376,11 @@ var MiniAppErrorType = /* @__PURE__ */ ((MiniAppErrorType2) => {
421
376
  MiniAppErrorType2["merchantTimeout"] = "MERCHANT_TIMEOUT";
422
377
  MiniAppErrorType2["rateLimitExceeded"] = "RATE_LIMIT_EXCEEDED";
423
378
  MiniAppErrorType2["sdkUpgradeRequired"] = "SDK_UPGRADE_REQUIRED";
379
+ MiniAppErrorType2["authorizationNeeded"] = "AUTHORIZATION_NEEDED";
424
380
  return MiniAppErrorType2;
425
381
  })(MiniAppErrorType || {});
426
- const JS_SDK_VERSION = "2.41.0";
427
- const REVISION = "86fe469";
382
+ const JS_SDK_VERSION = "2.48.0";
383
+ const REVISION = "765ecbf";
428
384
  const coreBaseUrl = new URL("https://mini-app-sdk-core.paypay.ne.jp/");
429
385
  const CORE_IFRAME_ORIGIN = coreBaseUrl.origin;
430
386
  const CORE_IFRAME_URL = new URL(
@@ -436,36 +392,25 @@ const COUPON_IFRAME_URL = new URL(
436
392
  coreBaseUrl
437
393
  ).href;
438
394
  const SENTRY_DSN = "https://377b45f154b1fb17d8e98a6ffb67030a@o4505819519320064.ingest.sentry.io/4506579323453440";
439
- const GA_API_SECRET = "fgPKRkdQQvq7XbV4qw3MOQ";
440
- const GA_MEASUREMENT_ID = "G-M64Q2828RR";
441
- const objectToString = Object.prototype.toString;
442
- function isBuiltin(wat, className) {
443
- return objectToString.call(wat) === `[object ${className}]`;
444
- }
445
- function isPlainObject(wat) {
446
- return isBuiltin(wat, "Object");
447
- }
448
- function isThenable(wat) {
449
- return Boolean(wat && wat.then && typeof wat.then === "function");
450
- }
451
- function isGlobalObj(obj) {
452
- return obj && obj.Math == Math ? obj : void 0;
453
- }
454
- const GLOBAL_OBJ = typeof globalThis == "object" && isGlobalObj(globalThis) || // eslint-disable-next-line no-restricted-globals
455
- typeof window == "object" && isGlobalObj(window) || typeof self == "object" && isGlobalObj(self) || typeof global == "object" && isGlobalObj(global) || function() {
456
- return this;
457
- }() || {};
458
- function getGlobalObject() {
459
- return GLOBAL_OBJ;
460
- }
395
+ const SDK_VERSION = "8.45.1";
396
+ const GLOBAL_OBJ = globalThis;
461
397
  function getGlobalSingleton(name, creator, obj) {
462
- const gbl = obj || GLOBAL_OBJ;
398
+ const gbl = GLOBAL_OBJ;
463
399
  const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {};
464
- const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());
465
- return singleton;
400
+ const versionedCarrier = __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};
401
+ return versionedCarrier[name] || (versionedCarrier[name] = creator());
466
402
  }
403
+ const DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
467
404
  const PREFIX = "Sentry Logger ";
468
- const CONSOLE_LEVELS = ["debug", "info", "warn", "error", "log", "assert", "trace"];
405
+ const CONSOLE_LEVELS = [
406
+ "debug",
407
+ "info",
408
+ "warn",
409
+ "error",
410
+ "log",
411
+ "assert",
412
+ "trace"
413
+ ];
469
414
  const originalConsoleMethods = {};
470
415
  function consoleSandbox(callback) {
471
416
  if (!("console" in GLOBAL_OBJ)) {
@@ -498,7 +443,7 @@ function makeLogger() {
498
443
  },
499
444
  isEnabled: () => enabled
500
445
  };
501
- if (typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__) {
446
+ if (DEBUG_BUILD) {
502
447
  CONSOLE_LEVELS.forEach((name) => {
503
448
  logger2[name] = (...args) => {
504
449
  if (enabled) {
@@ -515,241 +460,56 @@ function makeLogger() {
515
460
  }
516
461
  return logger2;
517
462
  }
518
- const logger = makeLogger();
519
- function dropUndefinedKeys(inputValue) {
520
- const memoizationMap = /* @__PURE__ */ new Map();
521
- return _dropUndefinedKeys(inputValue, memoizationMap);
463
+ const logger = getGlobalSingleton("logger", makeLogger);
464
+ function getMainCarrier() {
465
+ getSentryCarrier(GLOBAL_OBJ);
466
+ return GLOBAL_OBJ;
522
467
  }
523
- function _dropUndefinedKeys(inputValue, memoizationMap) {
524
- if (isPlainObject(inputValue)) {
525
- const memoVal = memoizationMap.get(inputValue);
526
- if (memoVal !== void 0) {
527
- return memoVal;
528
- }
529
- const returnValue = {};
530
- memoizationMap.set(inputValue, returnValue);
531
- for (const key of Object.keys(inputValue)) {
532
- if (typeof inputValue[key] !== "undefined") {
533
- returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);
534
- }
535
- }
536
- return returnValue;
537
- }
538
- if (Array.isArray(inputValue)) {
539
- const memoVal = memoizationMap.get(inputValue);
540
- if (memoVal !== void 0) {
541
- return memoVal;
542
- }
543
- const returnValue = [];
544
- memoizationMap.set(inputValue, returnValue);
545
- inputValue.forEach((item) => {
546
- returnValue.push(_dropUndefinedKeys(item, memoizationMap));
547
- });
548
- return returnValue;
549
- }
550
- return inputValue;
468
+ function getSentryCarrier(carrier) {
469
+ const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
470
+ __SENTRY__.version = __SENTRY__.version || SDK_VERSION;
471
+ return __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};
551
472
  }
552
- function uuid4() {
553
- const gbl = GLOBAL_OBJ;
554
- const crypto2 = gbl.crypto || gbl.msCrypto;
555
- let getRandomByte = () => Math.random() * 16;
556
- try {
557
- if (crypto2 && crypto2.randomUUID) {
558
- return crypto2.randomUUID().replace(/-/g, "");
559
- }
560
- if (crypto2 && crypto2.getRandomValues) {
561
- getRandomByte = () => crypto2.getRandomValues(new Uint8Array(1))[0];
562
- }
563
- } catch (_) {
564
- }
565
- return ([1e7] + 1e3 + 4e3 + 8e3 + 1e11).replace(
566
- /[018]/g,
567
- (c) => (
568
- // eslint-disable-next-line no-bitwise
569
- (c ^ (getRandomByte() & 15) >> c / 4).toString(16)
570
- )
571
- );
473
+ const objectToString = Object.prototype.toString;
474
+ function isBuiltin(wat, className) {
475
+ return objectToString.call(wat) === `[object ${className}]`;
572
476
  }
573
- function arrayify(maybeArray) {
574
- return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
575
- }
576
- function isBrowserBundle() {
577
- return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__;
578
- }
579
- function isNodeEnv() {
580
- return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
581
- }
582
- function dynamicRequire(mod, request) {
583
- return mod.require(request);
584
- }
585
- var States;
586
- (function(States2) {
587
- const PENDING = 0;
588
- States2[States2["PENDING"] = PENDING] = "PENDING";
589
- const RESOLVED = 1;
590
- States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED";
591
- const REJECTED = 2;
592
- States2[States2["REJECTED"] = REJECTED] = "REJECTED";
593
- })(States || (States = {}));
594
- class SyncPromise {
595
- constructor(executor) {
596
- SyncPromise.prototype.__init.call(this);
597
- SyncPromise.prototype.__init2.call(this);
598
- SyncPromise.prototype.__init3.call(this);
599
- SyncPromise.prototype.__init4.call(this);
600
- this._state = States.PENDING;
601
- this._handlers = [];
602
- try {
603
- executor(this._resolve, this._reject);
604
- } catch (e) {
605
- this._reject(e);
606
- }
607
- }
608
- /** JSDoc */
609
- then(onfulfilled, onrejected) {
610
- return new SyncPromise((resolve, reject) => {
611
- this._handlers.push([
612
- false,
613
- (result) => {
614
- if (!onfulfilled) {
615
- resolve(result);
616
- } else {
617
- try {
618
- resolve(onfulfilled(result));
619
- } catch (e) {
620
- reject(e);
621
- }
622
- }
623
- },
624
- (reason) => {
625
- if (!onrejected) {
626
- reject(reason);
627
- } else {
628
- try {
629
- resolve(onrejected(reason));
630
- } catch (e) {
631
- reject(e);
632
- }
633
- }
634
- }
635
- ]);
636
- this._executeHandlers();
637
- });
638
- }
639
- /** JSDoc */
640
- catch(onrejected) {
641
- return this.then((val) => val, onrejected);
642
- }
643
- /** JSDoc */
644
- finally(onfinally) {
645
- return new SyncPromise((resolve, reject) => {
646
- let val;
647
- let isRejected;
648
- return this.then(
649
- (value) => {
650
- isRejected = false;
651
- val = value;
652
- if (onfinally) {
653
- onfinally();
654
- }
655
- },
656
- (reason) => {
657
- isRejected = true;
658
- val = reason;
659
- if (onfinally) {
660
- onfinally();
661
- }
662
- }
663
- ).then(() => {
664
- if (isRejected) {
665
- reject(val);
666
- return;
667
- }
668
- resolve(val);
669
- });
477
+ function isPlainObject(wat) {
478
+ return isBuiltin(wat, "Object");
479
+ }
480
+ function isThenable(wat) {
481
+ return Boolean(wat && wat.then && typeof wat.then === "function");
482
+ }
483
+ function addNonEnumerableProperty(obj, name, value) {
484
+ try {
485
+ Object.defineProperty(obj, name, {
486
+ // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
487
+ value,
488
+ writable: true,
489
+ configurable: true
670
490
  });
671
- }
672
- /** JSDoc */
673
- __init() {
674
- this._resolve = (value) => {
675
- this._setResult(States.RESOLVED, value);
676
- };
677
- }
678
- /** JSDoc */
679
- __init2() {
680
- this._reject = (reason) => {
681
- this._setResult(States.REJECTED, reason);
682
- };
683
- }
684
- /** JSDoc */
685
- __init3() {
686
- this._setResult = (state, value) => {
687
- if (this._state !== States.PENDING) {
688
- return;
689
- }
690
- if (isThenable(value)) {
691
- void value.then(this._resolve, this._reject);
692
- return;
693
- }
694
- this._state = state;
695
- this._value = value;
696
- this._executeHandlers();
697
- };
698
- }
699
- /** JSDoc */
700
- __init4() {
701
- this._executeHandlers = () => {
702
- if (this._state === States.PENDING) {
703
- return;
704
- }
705
- const cachedHandlers = this._handlers.slice();
706
- this._handlers = [];
707
- cachedHandlers.forEach((handler) => {
708
- if (handler[0]) {
709
- return;
710
- }
711
- if (this._state === States.RESOLVED) {
712
- handler[1](this._value);
713
- }
714
- if (this._state === States.REJECTED) {
715
- handler[2](this._value);
716
- }
717
- handler[0] = true;
718
- });
719
- };
491
+ } catch (o_O) {
492
+ DEBUG_BUILD && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj);
720
493
  }
721
494
  }
722
- const WINDOW = getGlobalObject();
723
- const dateTimestampSource = {
724
- nowSeconds: () => Date.now() / 1e3
725
- };
726
- function getBrowserPerformance() {
727
- const { performance } = WINDOW;
495
+ const ONE_SECOND_IN_MS = 1e3;
496
+ function dateTimestampInSeconds() {
497
+ return Date.now() / ONE_SECOND_IN_MS;
498
+ }
499
+ function createUnixTimestampInSecondsFunc() {
500
+ const { performance } = GLOBAL_OBJ;
728
501
  if (!performance || !performance.now) {
729
- return void 0;
502
+ return dateTimestampInSeconds;
730
503
  }
731
- const timeOrigin = Date.now() - performance.now();
732
- return {
733
- now: () => performance.now(),
734
- timeOrigin
504
+ const approxStartingTimeOrigin = Date.now() - performance.now();
505
+ const timeOrigin = performance.timeOrigin == void 0 ? approxStartingTimeOrigin : performance.timeOrigin;
506
+ return () => {
507
+ return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;
735
508
  };
736
509
  }
737
- function getNodePerformance() {
738
- try {
739
- const perfHooks = dynamicRequire(module, "perf_hooks");
740
- return perfHooks.performance;
741
- } catch (_) {
742
- return void 0;
743
- }
744
- }
745
- const platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();
746
- const timestampSource = platformPerformance === void 0 ? dateTimestampSource : {
747
- nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1e3
748
- };
749
- const dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);
750
- const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);
510
+ const timestampInSeconds = createUnixTimestampInSecondsFunc();
751
511
  (() => {
752
- const { performance } = WINDOW;
512
+ const { performance } = GLOBAL_OBJ;
753
513
  if (!performance || !performance.now) {
754
514
  return void 0;
755
515
  }
@@ -771,43 +531,30 @@ const timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);
771
531
  }
772
532
  return dateNow;
773
533
  })();
774
- const DEFAULT_ENVIRONMENT = "production";
775
- function getGlobalEventProcessors() {
776
- return getGlobalSingleton("globalEventProcessors", () => []);
777
- }
778
- function notifyEventProcessors(processors, event, hint, index = 0) {
779
- return new SyncPromise((resolve, reject) => {
780
- const processor = processors[index];
781
- if (event === null || typeof processor !== "function") {
782
- resolve(event);
783
- } else {
784
- const result = processor(__spreadValues({}, event), hint);
785
- (typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__) && processor.id && result === null && logger.log(`Event processor "${processor.id}" dropped event`);
786
- if (isThenable(result)) {
787
- void result.then((final) => notifyEventProcessors(processors, final, hint, index + 1).then(resolve)).then(null, reject);
788
- } else {
789
- void notifyEventProcessors(processors, result, hint, index + 1).then(resolve).then(null, reject);
790
- }
534
+ function uuid4() {
535
+ const gbl = GLOBAL_OBJ;
536
+ const crypto = gbl.crypto || gbl.msCrypto;
537
+ let getRandomByte = () => Math.random() * 16;
538
+ try {
539
+ if (crypto && crypto.randomUUID) {
540
+ return crypto.randomUUID().replace(/-/g, "");
541
+ }
542
+ if (crypto && crypto.getRandomValues) {
543
+ getRandomByte = () => {
544
+ const typedArray = new Uint8Array(1);
545
+ crypto.getRandomValues(typedArray);
546
+ return typedArray[0];
547
+ };
791
548
  }
792
- });
793
- }
794
- function makeSession(context) {
795
- const startingTime = timestampInSeconds();
796
- const session = {
797
- sid: uuid4(),
798
- init: true,
799
- timestamp: startingTime,
800
- started: startingTime,
801
- duration: 0,
802
- status: "ok",
803
- errors: 0,
804
- ignoreDuration: false,
805
- toJSON: () => sessionToJSON(session)
806
- };
807
- if (context) {
808
- updateSession(session, context);
549
+ } catch (_) {
809
550
  }
810
- return session;
551
+ return ("10000000100040008000" + 1e11).replace(
552
+ /[018]/g,
553
+ (c) => (
554
+ // eslint-disable-next-line no-bitwise
555
+ (c ^ (getRandomByte() & 15) >> c / 4).toString(16)
556
+ )
557
+ );
811
558
  }
812
559
  function updateSession(session, context = {}) {
813
560
  if (context.user) {
@@ -864,40 +611,43 @@ function updateSession(session, context = {}) {
864
611
  session.status = context.status;
865
612
  }
866
613
  }
867
- function closeSession(session, status) {
868
- let context = {};
869
- if (status) {
870
- context = { status };
871
- } else if (session.status === "ok") {
872
- context = { status: "exited" };
873
- }
874
- updateSession(session, context);
875
- }
876
- function sessionToJSON(session) {
877
- return dropUndefinedKeys({
878
- sid: `${session.sid}`,
879
- init: session.init,
880
- // Make sure that sec is converted to ms for date constructor
881
- started: new Date(session.started * 1e3).toISOString(),
882
- timestamp: new Date(session.timestamp * 1e3).toISOString(),
883
- status: session.status,
884
- errors: session.errors,
885
- did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : void 0,
886
- duration: session.duration,
887
- abnormal_mechanism: session.abnormal_mechanism,
888
- attrs: {
889
- release: session.release,
890
- environment: session.environment,
891
- ip_address: session.ipAddress,
892
- user_agent: session.userAgent
614
+ function generateTraceId() {
615
+ return uuid4();
616
+ }
617
+ function generateSpanId() {
618
+ return uuid4().substring(16);
619
+ }
620
+ function merge(initialObj, mergeObj, levels = 2) {
621
+ if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) {
622
+ return mergeObj;
623
+ }
624
+ if (initialObj && mergeObj && Object.keys(mergeObj).length === 0) {
625
+ return initialObj;
626
+ }
627
+ const output = __spreadValues({}, initialObj);
628
+ for (const key in mergeObj) {
629
+ if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {
630
+ output[key] = merge(output[key], mergeObj[key], levels - 1);
893
631
  }
894
- });
632
+ }
633
+ return output;
634
+ }
635
+ const SCOPE_SPAN_FIELD = "_sentrySpan";
636
+ function _setSpanForScope(scope, span) {
637
+ if (span) {
638
+ addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, span);
639
+ } else {
640
+ delete scope[SCOPE_SPAN_FIELD];
641
+ }
642
+ }
643
+ function _getSpanForScope(scope) {
644
+ return scope[SCOPE_SPAN_FIELD];
895
645
  }
896
646
  const DEFAULT_MAX_BREADCRUMBS = 100;
897
- class Scope {
647
+ class ScopeClass {
898
648
  /** Flag if notifying is happening. */
899
649
  /** Callback for client to receive scope changes. */
900
- /** Callback list that will be called after {@link applyToEvent}. */
650
+ /** Callback list that will be called during event processing. */
901
651
  /** Array of breadcrumbs. */
902
652
  /** User */
903
653
  /** Tags */
@@ -911,11 +661,17 @@ class Scope {
911
661
  */
912
662
  /** Fingerprint */
913
663
  /** Severity */
914
- // eslint-disable-next-line deprecation/deprecation
915
- /** Transaction Name */
916
- /** Span */
664
+ /**
665
+ * Transaction Name
666
+ *
667
+ * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.
668
+ * It's purpose is to assign a transaction to the scope that's added to non-transaction events.
669
+ */
917
670
  /** Session */
918
671
  /** Request Mode Session Status */
672
+ // eslint-disable-next-line deprecation/deprecation
673
+ /** The client on this scope */
674
+ /** Contains the last event id of a captured event. */
919
675
  // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.
920
676
  constructor() {
921
677
  this._notifyingListeners = false;
@@ -928,36 +684,66 @@ class Scope {
928
684
  this._extra = {};
929
685
  this._contexts = {};
930
686
  this._sdkProcessingMetadata = {};
931
- this._propagationContext = generatePropagationContext();
687
+ this._propagationContext = {
688
+ traceId: generateTraceId(),
689
+ spanId: generateSpanId()
690
+ };
932
691
  }
933
692
  /**
934
- * Inherit values from the parent scope.
935
- * @param scope to clone.
693
+ * @inheritDoc
936
694
  */
937
- static clone(scope) {
938
- const newScope = new Scope();
939
- if (scope) {
940
- newScope._breadcrumbs = [...scope._breadcrumbs];
941
- newScope._tags = __spreadValues({}, scope._tags);
942
- newScope._extra = __spreadValues({}, scope._extra);
943
- newScope._contexts = __spreadValues({}, scope._contexts);
944
- newScope._user = scope._user;
945
- newScope._level = scope._level;
946
- newScope._span = scope._span;
947
- newScope._session = scope._session;
948
- newScope._transactionName = scope._transactionName;
949
- newScope._fingerprint = scope._fingerprint;
950
- newScope._eventProcessors = [...scope._eventProcessors];
951
- newScope._requestSession = scope._requestSession;
952
- newScope._attachments = [...scope._attachments];
953
- newScope._sdkProcessingMetadata = __spreadValues({}, scope._sdkProcessingMetadata);
954
- newScope._propagationContext = __spreadValues({}, scope._propagationContext);
695
+ clone() {
696
+ const newScope = new ScopeClass();
697
+ newScope._breadcrumbs = [...this._breadcrumbs];
698
+ newScope._tags = __spreadValues({}, this._tags);
699
+ newScope._extra = __spreadValues({}, this._extra);
700
+ newScope._contexts = __spreadValues({}, this._contexts);
701
+ if (this._contexts.flags) {
702
+ newScope._contexts.flags = {
703
+ values: [...this._contexts.flags.values]
704
+ };
955
705
  }
706
+ newScope._user = this._user;
707
+ newScope._level = this._level;
708
+ newScope._session = this._session;
709
+ newScope._transactionName = this._transactionName;
710
+ newScope._fingerprint = this._fingerprint;
711
+ newScope._eventProcessors = [...this._eventProcessors];
712
+ newScope._requestSession = this._requestSession;
713
+ newScope._attachments = [...this._attachments];
714
+ newScope._sdkProcessingMetadata = __spreadValues({}, this._sdkProcessingMetadata);
715
+ newScope._propagationContext = __spreadValues({}, this._propagationContext);
716
+ newScope._client = this._client;
717
+ newScope._lastEventId = this._lastEventId;
718
+ _setSpanForScope(newScope, _getSpanForScope(this));
956
719
  return newScope;
957
720
  }
958
721
  /**
959
- * Add internal on change listener. Used for sub SDKs that need to store the scope.
960
- * @hidden
722
+ * @inheritDoc
723
+ */
724
+ setClient(client2) {
725
+ this._client = client2;
726
+ }
727
+ /**
728
+ * @inheritDoc
729
+ */
730
+ setLastEventId(lastEventId) {
731
+ this._lastEventId = lastEventId;
732
+ }
733
+ /**
734
+ * @inheritDoc
735
+ */
736
+ getClient() {
737
+ return this._client;
738
+ }
739
+ /**
740
+ * @inheritDoc
741
+ */
742
+ lastEventId() {
743
+ return this._lastEventId;
744
+ }
745
+ /**
746
+ * @inheritDoc
961
747
  */
962
748
  addScopeListener(callback) {
963
749
  this._scopeListeners.push(callback);
@@ -973,7 +759,12 @@ class Scope {
973
759
  * @inheritDoc
974
760
  */
975
761
  setUser(user) {
976
- this._user = user || {};
762
+ this._user = user || {
763
+ email: void 0,
764
+ id: void 0,
765
+ ip_address: void 0,
766
+ username: void 0
767
+ };
977
768
  if (this._session) {
978
769
  updateSession(this._session, { user });
979
770
  }
@@ -989,12 +780,14 @@ class Scope {
989
780
  /**
990
781
  * @inheritDoc
991
782
  */
783
+ // eslint-disable-next-line deprecation/deprecation
992
784
  getRequestSession() {
993
785
  return this._requestSession;
994
786
  }
995
787
  /**
996
788
  * @inheritDoc
997
789
  */
790
+ // eslint-disable-next-line deprecation/deprecation
998
791
  setRequestSession(requestSession) {
999
792
  this._requestSession = requestSession;
1000
793
  return this;
@@ -1067,27 +860,6 @@ class Scope {
1067
860
  this._notifyScopeListeners();
1068
861
  return this;
1069
862
  }
1070
- /**
1071
- * @inheritDoc
1072
- */
1073
- setSpan(span) {
1074
- this._span = span;
1075
- this._notifyScopeListeners();
1076
- return this;
1077
- }
1078
- /**
1079
- * @inheritDoc
1080
- */
1081
- getSpan() {
1082
- return this._span;
1083
- }
1084
- /**
1085
- * @inheritDoc
1086
- */
1087
- getTransaction() {
1088
- const span = this.getSpan();
1089
- return span && span.transaction;
1090
- }
1091
863
  /**
1092
864
  * @inheritDoc
1093
865
  */
@@ -1113,49 +885,29 @@ class Scope {
1113
885
  if (!captureContext) {
1114
886
  return this;
1115
887
  }
1116
- if (typeof captureContext === "function") {
1117
- const updatedScope = captureContext(this);
1118
- return updatedScope instanceof Scope ? updatedScope : this;
888
+ const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext;
889
+ const [scopeInstance, requestSession] = scopeToMerge instanceof Scope ? (
890
+ // eslint-disable-next-line deprecation/deprecation
891
+ [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()]
892
+ ) : isPlainObject(scopeToMerge) ? [captureContext, captureContext.requestSession] : [];
893
+ const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};
894
+ this._tags = __spreadValues(__spreadValues({}, this._tags), tags);
895
+ this._extra = __spreadValues(__spreadValues({}, this._extra), extra);
896
+ this._contexts = __spreadValues(__spreadValues({}, this._contexts), contexts);
897
+ if (user && Object.keys(user).length) {
898
+ this._user = user;
899
+ }
900
+ if (level) {
901
+ this._level = level;
1119
902
  }
1120
- if (captureContext instanceof Scope) {
1121
- this._tags = __spreadValues(__spreadValues({}, this._tags), captureContext._tags);
1122
- this._extra = __spreadValues(__spreadValues({}, this._extra), captureContext._extra);
1123
- this._contexts = __spreadValues(__spreadValues({}, this._contexts), captureContext._contexts);
1124
- if (captureContext._user && Object.keys(captureContext._user).length) {
1125
- this._user = captureContext._user;
1126
- }
1127
- if (captureContext._level) {
1128
- this._level = captureContext._level;
1129
- }
1130
- if (captureContext._fingerprint) {
1131
- this._fingerprint = captureContext._fingerprint;
1132
- }
1133
- if (captureContext._requestSession) {
1134
- this._requestSession = captureContext._requestSession;
1135
- }
1136
- if (captureContext._propagationContext) {
1137
- this._propagationContext = captureContext._propagationContext;
1138
- }
1139
- } else if (isPlainObject(captureContext)) {
1140
- captureContext = captureContext;
1141
- this._tags = __spreadValues(__spreadValues({}, this._tags), captureContext.tags);
1142
- this._extra = __spreadValues(__spreadValues({}, this._extra), captureContext.extra);
1143
- this._contexts = __spreadValues(__spreadValues({}, this._contexts), captureContext.contexts);
1144
- if (captureContext.user) {
1145
- this._user = captureContext.user;
1146
- }
1147
- if (captureContext.level) {
1148
- this._level = captureContext.level;
1149
- }
1150
- if (captureContext.fingerprint) {
1151
- this._fingerprint = captureContext.fingerprint;
1152
- }
1153
- if (captureContext.requestSession) {
1154
- this._requestSession = captureContext.requestSession;
1155
- }
1156
- if (captureContext.propagationContext) {
1157
- this._propagationContext = captureContext.propagationContext;
1158
- }
903
+ if (fingerprint.length) {
904
+ this._fingerprint = fingerprint;
905
+ }
906
+ if (propagationContext) {
907
+ this._propagationContext = propagationContext;
908
+ }
909
+ if (requestSession) {
910
+ this._requestSession = requestSession;
1159
911
  }
1160
912
  return this;
1161
913
  }
@@ -1172,11 +924,11 @@ class Scope {
1172
924
  this._transactionName = void 0;
1173
925
  this._fingerprint = void 0;
1174
926
  this._requestSession = void 0;
1175
- this._span = void 0;
1176
927
  this._session = void 0;
1177
- this._notifyScopeListeners();
928
+ _setSpanForScope(this, void 0);
1178
929
  this._attachments = [];
1179
- this._propagationContext = generatePropagationContext();
930
+ this.setPropagationContext({ traceId: generateTraceId() });
931
+ this._notifyScopeListeners();
1180
932
  return this;
1181
933
  }
1182
934
  /**
@@ -1217,12 +969,6 @@ class Scope {
1217
969
  this._attachments.push(attachment);
1218
970
  return this;
1219
971
  }
1220
- /**
1221
- * @inheritDoc
1222
- */
1223
- getAttachments() {
1224
- return this._attachments;
1225
- }
1226
972
  /**
1227
973
  * @inheritDoc
1228
974
  */
@@ -1230,70 +976,39 @@ class Scope {
1230
976
  this._attachments = [];
1231
977
  return this;
1232
978
  }
1233
- /**
1234
- * Applies data from the scope to the event and runs all event processors on it.
1235
- *
1236
- * @param event Event
1237
- * @param hint Object containing additional information about the original exception, for use by the event processors.
1238
- * @hidden
1239
- */
1240
- applyToEvent(event, hint = {}, additionalEventProcessors) {
1241
- if (this._extra && Object.keys(this._extra).length) {
1242
- event.extra = __spreadValues(__spreadValues({}, this._extra), event.extra);
1243
- }
1244
- if (this._tags && Object.keys(this._tags).length) {
1245
- event.tags = __spreadValues(__spreadValues({}, this._tags), event.tags);
1246
- }
1247
- if (this._user && Object.keys(this._user).length) {
1248
- event.user = __spreadValues(__spreadValues({}, this._user), event.user);
1249
- }
1250
- if (this._contexts && Object.keys(this._contexts).length) {
1251
- event.contexts = __spreadValues(__spreadValues({}, this._contexts), event.contexts);
1252
- }
1253
- if (this._level) {
1254
- event.level = this._level;
1255
- }
1256
- if (this._transactionName) {
1257
- event.transaction = this._transactionName;
1258
- }
1259
- if (this._span) {
1260
- event.contexts = __spreadValues({ trace: this._span.getTraceContext() }, event.contexts);
1261
- const transaction = this._span.transaction;
1262
- if (transaction) {
1263
- event.sdkProcessingMetadata = __spreadValues({
1264
- dynamicSamplingContext: transaction.getDynamicSamplingContext()
1265
- }, event.sdkProcessingMetadata);
1266
- const transactionName = transaction.name;
1267
- if (transactionName) {
1268
- event.tags = __spreadValues({ transaction: transactionName }, event.tags);
1269
- }
1270
- }
1271
- }
1272
- this._applyFingerprint(event);
1273
- const scopeBreadcrumbs = this._getBreadcrumbs();
1274
- const breadcrumbs = [...event.breadcrumbs || [], ...scopeBreadcrumbs];
1275
- event.breadcrumbs = breadcrumbs.length > 0 ? breadcrumbs : void 0;
1276
- event.sdkProcessingMetadata = __spreadProps(__spreadValues(__spreadValues({}, event.sdkProcessingMetadata), this._sdkProcessingMetadata), {
1277
- propagationContext: this._propagationContext
1278
- });
1279
- return notifyEventProcessors(
1280
- [...additionalEventProcessors || [], ...getGlobalEventProcessors(), ...this._eventProcessors],
1281
- event,
1282
- hint
1283
- );
979
+ /** @inheritDoc */
980
+ getScopeData() {
981
+ return {
982
+ breadcrumbs: this._breadcrumbs,
983
+ attachments: this._attachments,
984
+ contexts: this._contexts,
985
+ tags: this._tags,
986
+ extra: this._extra,
987
+ user: this._user,
988
+ level: this._level,
989
+ fingerprint: this._fingerprint || [],
990
+ eventProcessors: this._eventProcessors,
991
+ propagationContext: this._propagationContext,
992
+ sdkProcessingMetadata: this._sdkProcessingMetadata,
993
+ transactionName: this._transactionName,
994
+ span: _getSpanForScope(this)
995
+ };
1284
996
  }
1285
997
  /**
1286
- * Add data which will be accessible during event processing but won't get sent to Sentry
998
+ * @inheritDoc
1287
999
  */
1288
1000
  setSDKProcessingMetadata(newData) {
1289
- this._sdkProcessingMetadata = __spreadValues(__spreadValues({}, this._sdkProcessingMetadata), newData);
1001
+ this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);
1290
1002
  return this;
1291
1003
  }
1292
1004
  /**
1293
1005
  * @inheritDoc
1294
1006
  */
1295
1007
  setPropagationContext(context) {
1296
- this._propagationContext = context;
1008
+ this._propagationContext = __spreadValues({
1009
+ // eslint-disable-next-line deprecation/deprecation
1010
+ spanId: generateSpanId()
1011
+ }, context);
1297
1012
  return this;
1298
1013
  }
1299
1014
  /**
@@ -1303,10 +1018,61 @@ class Scope {
1303
1018
  return this._propagationContext;
1304
1019
  }
1305
1020
  /**
1306
- * Get the breadcrumbs for this scope.
1021
+ * @inheritDoc
1022
+ */
1023
+ captureException(exception, hint) {
1024
+ const eventId = hint && hint.event_id ? hint.event_id : uuid4();
1025
+ if (!this._client) {
1026
+ logger.warn("No client configured on scope - will not capture exception!");
1027
+ return eventId;
1028
+ }
1029
+ const syntheticException = new Error("Sentry syntheticException");
1030
+ this._client.captureException(
1031
+ exception,
1032
+ __spreadProps(__spreadValues({
1033
+ originalException: exception,
1034
+ syntheticException
1035
+ }, hint), {
1036
+ event_id: eventId
1037
+ }),
1038
+ this
1039
+ );
1040
+ return eventId;
1041
+ }
1042
+ /**
1043
+ * @inheritDoc
1044
+ */
1045
+ captureMessage(message, level, hint) {
1046
+ const eventId = hint && hint.event_id ? hint.event_id : uuid4();
1047
+ if (!this._client) {
1048
+ logger.warn("No client configured on scope - will not capture message!");
1049
+ return eventId;
1050
+ }
1051
+ const syntheticException = new Error(message);
1052
+ this._client.captureMessage(
1053
+ message,
1054
+ level,
1055
+ __spreadProps(__spreadValues({
1056
+ originalException: message,
1057
+ syntheticException
1058
+ }, hint), {
1059
+ event_id: eventId
1060
+ }),
1061
+ this
1062
+ );
1063
+ return eventId;
1064
+ }
1065
+ /**
1066
+ * @inheritDoc
1307
1067
  */
1308
- _getBreadcrumbs() {
1309
- return this._breadcrumbs;
1068
+ captureEvent(event, hint) {
1069
+ const eventId = hint && hint.event_id ? hint.event_id : uuid4();
1070
+ if (!this._client) {
1071
+ logger.warn("No client configured on scope - will not capture event!");
1072
+ return eventId;
1073
+ }
1074
+ this._client.captureEvent(event, __spreadProps(__spreadValues({}, hint), { event_id: eventId }), this);
1075
+ return eventId;
1310
1076
  }
1311
1077
  /**
1312
1078
  * This will be called on every set call.
@@ -1320,423 +1086,173 @@ class Scope {
1320
1086
  this._notifyingListeners = false;
1321
1087
  }
1322
1088
  }
1323
- /**
1324
- * Applies fingerprint from the scope to the event if there's one,
1325
- * uses message if there's one instead or get rid of empty fingerprint
1326
- */
1327
- _applyFingerprint(event) {
1328
- event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];
1329
- if (this._fingerprint) {
1330
- event.fingerprint = event.fingerprint.concat(this._fingerprint);
1331
- }
1332
- if (event.fingerprint && !event.fingerprint.length) {
1333
- delete event.fingerprint;
1334
- }
1335
- }
1336
1089
  }
1337
- function generatePropagationContext() {
1338
- return {
1339
- traceId: uuid4(),
1340
- spanId: uuid4().substring(16)
1341
- };
1090
+ const Scope = ScopeClass;
1091
+ function getDefaultCurrentScope() {
1092
+ return getGlobalSingleton("defaultCurrentScope", () => new Scope());
1342
1093
  }
1343
- const API_VERSION = 4;
1344
- const DEFAULT_BREADCRUMBS = 100;
1345
- class Hub {
1346
- /** Is a {@link Layer}[] containing the client and scope */
1347
- /** Contains the last event id of a captured event. */
1348
- /**
1349
- * Creates a new instance of the hub, will push one {@link Layer} into the
1350
- * internal stack on creation.
1351
- *
1352
- * @param client bound to the hub.
1353
- * @param scope bound to the hub.
1354
- * @param version number, higher number means higher priority.
1355
- */
1356
- constructor(client2, scope = new Scope(), _version = API_VERSION) {
1357
- this._version = _version;
1358
- this._stack = [{ scope }];
1359
- if (client2) {
1360
- this.bindClient(client2);
1094
+ function getDefaultIsolationScope() {
1095
+ return getGlobalSingleton("defaultIsolationScope", () => new Scope());
1096
+ }
1097
+ class AsyncContextStack {
1098
+ constructor(scope, isolationScope) {
1099
+ let assignedScope;
1100
+ if (!scope) {
1101
+ assignedScope = new Scope();
1102
+ } else {
1103
+ assignedScope = scope;
1104
+ }
1105
+ let assignedIsolationScope;
1106
+ if (!isolationScope) {
1107
+ assignedIsolationScope = new Scope();
1108
+ } else {
1109
+ assignedIsolationScope = isolationScope;
1361
1110
  }
1111
+ this._stack = [{ scope: assignedScope }];
1112
+ this._isolationScope = assignedIsolationScope;
1362
1113
  }
1363
1114
  /**
1364
- * @inheritDoc
1365
- */
1366
- isOlderThan(version) {
1367
- return this._version < version;
1368
- }
1369
- /**
1370
- * @inheritDoc
1371
- */
1372
- bindClient(client2) {
1373
- const top = this.getStackTop();
1374
- top.client = client2;
1375
- if (client2 && client2.setupIntegrations) {
1376
- client2.setupIntegrations();
1377
- }
1378
- }
1379
- /**
1380
- * @inheritDoc
1381
- */
1382
- pushScope() {
1383
- const scope = Scope.clone(this.getScope());
1384
- this.getStack().push({
1385
- client: this.getClient(),
1386
- scope
1387
- });
1388
- return scope;
1389
- }
1390
- /**
1391
- * @inheritDoc
1392
- */
1393
- popScope() {
1394
- if (this.getStack().length <= 1)
1395
- return false;
1396
- return !!this.getStack().pop();
1397
- }
1398
- /**
1399
- * @inheritDoc
1115
+ * Fork a scope for the stack.
1400
1116
  */
1401
1117
  withScope(callback) {
1402
- const scope = this.pushScope();
1118
+ const scope = this._pushScope();
1119
+ let maybePromiseResult;
1403
1120
  try {
1404
- callback(scope);
1405
- } finally {
1406
- this.popScope();
1121
+ maybePromiseResult = callback(scope);
1122
+ } catch (e) {
1123
+ this._popScope();
1124
+ throw e;
1125
+ }
1126
+ if (isThenable(maybePromiseResult)) {
1127
+ return maybePromiseResult.then(
1128
+ (res) => {
1129
+ this._popScope();
1130
+ return res;
1131
+ },
1132
+ (e) => {
1133
+ this._popScope();
1134
+ throw e;
1135
+ }
1136
+ );
1407
1137
  }
1138
+ this._popScope();
1139
+ return maybePromiseResult;
1408
1140
  }
1409
1141
  /**
1410
- * @inheritDoc
1142
+ * Get the client of the stack.
1411
1143
  */
1412
1144
  getClient() {
1413
1145
  return this.getStackTop().client;
1414
1146
  }
1415
- /** Returns the scope of the top stack. */
1147
+ /**
1148
+ * Returns the scope of the top stack.
1149
+ */
1416
1150
  getScope() {
1417
1151
  return this.getStackTop().scope;
1418
1152
  }
1419
- /** Returns the scope stack for domains or the process. */
1420
- getStack() {
1421
- return this._stack;
1422
- }
1423
- /** Returns the topmost scope layer in the order domain > local > process. */
1424
- getStackTop() {
1425
- return this._stack[this._stack.length - 1];
1426
- }
1427
1153
  /**
1428
- * @inheritDoc
1154
+ * Get the isolation scope for the stack.
1429
1155
  */
1430
- captureException(exception, hint) {
1431
- const eventId = this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4();
1432
- const syntheticException = new Error("Sentry syntheticException");
1433
- this._withClient((client2, scope) => {
1434
- client2.captureException(
1435
- exception,
1436
- __spreadProps(__spreadValues({
1437
- originalException: exception,
1438
- syntheticException
1439
- }, hint), {
1440
- event_id: eventId
1441
- }),
1442
- scope
1443
- );
1444
- });
1445
- return eventId;
1156
+ getIsolationScope() {
1157
+ return this._isolationScope;
1446
1158
  }
1447
1159
  /**
1448
- * @inheritDoc
1160
+ * Returns the topmost scope layer in the order domain > local > process.
1449
1161
  */
1450
- captureMessage(message, level, hint) {
1451
- const eventId = this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4();
1452
- const syntheticException = new Error(message);
1453
- this._withClient((client2, scope) => {
1454
- client2.captureMessage(
1455
- message,
1456
- level,
1457
- __spreadProps(__spreadValues({
1458
- originalException: message,
1459
- syntheticException
1460
- }, hint), {
1461
- event_id: eventId
1462
- }),
1463
- scope
1464
- );
1465
- });
1466
- return eventId;
1162
+ getStackTop() {
1163
+ return this._stack[this._stack.length - 1];
1467
1164
  }
1468
1165
  /**
1469
- * @inheritDoc
1166
+ * Push a scope to the stack.
1470
1167
  */
1471
- captureEvent(event, hint) {
1472
- const eventId = hint && hint.event_id ? hint.event_id : uuid4();
1473
- if (!event.type) {
1474
- this._lastEventId = eventId;
1475
- }
1476
- this._withClient((client2, scope) => {
1477
- client2.captureEvent(event, __spreadProps(__spreadValues({}, hint), { event_id: eventId }), scope);
1168
+ _pushScope() {
1169
+ const scope = this.getScope().clone();
1170
+ this._stack.push({
1171
+ client: this.getClient(),
1172
+ scope
1478
1173
  });
1479
- return eventId;
1480
- }
1481
- /**
1482
- * @inheritDoc
1483
- */
1484
- lastEventId() {
1485
- return this._lastEventId;
1486
- }
1487
- /**
1488
- * @inheritDoc
1489
- */
1490
- addBreadcrumb(breadcrumb, hint) {
1491
- const { scope, client: client2 } = this.getStackTop();
1492
- if (!client2)
1493
- return;
1494
- const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client2.getOptions && client2.getOptions() || {};
1495
- if (maxBreadcrumbs <= 0)
1496
- return;
1497
- const timestamp = dateTimestampInSeconds();
1498
- const mergedBreadcrumb = __spreadValues({ timestamp }, breadcrumb);
1499
- const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb;
1500
- if (finalBreadcrumb === null)
1501
- return;
1502
- if (client2.emit) {
1503
- client2.emit("beforeAddBreadcrumb", finalBreadcrumb, hint);
1504
- }
1505
- scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
1506
- }
1507
- /**
1508
- * @inheritDoc
1509
- */
1510
- setUser(user) {
1511
- this.getScope().setUser(user);
1512
- }
1513
- /**
1514
- * @inheritDoc
1515
- */
1516
- setTags(tags) {
1517
- this.getScope().setTags(tags);
1518
- }
1519
- /**
1520
- * @inheritDoc
1521
- */
1522
- setExtras(extras) {
1523
- this.getScope().setExtras(extras);
1524
- }
1525
- /**
1526
- * @inheritDoc
1527
- */
1528
- setTag(key, value) {
1529
- this.getScope().setTag(key, value);
1530
- }
1531
- /**
1532
- * @inheritDoc
1533
- */
1534
- setExtra(key, extra) {
1535
- this.getScope().setExtra(key, extra);
1536
- }
1537
- /**
1538
- * @inheritDoc
1539
- */
1540
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1541
- setContext(name, context) {
1542
- this.getScope().setContext(name, context);
1543
- }
1544
- /**
1545
- * @inheritDoc
1546
- */
1547
- configureScope(callback) {
1548
- const { scope, client: client2 } = this.getStackTop();
1549
- if (client2) {
1550
- callback(scope);
1551
- }
1552
- }
1553
- /**
1554
- * @inheritDoc
1555
- */
1556
- run(callback) {
1557
- const oldHub = makeMain(this);
1558
- try {
1559
- callback(this);
1560
- } finally {
1561
- makeMain(oldHub);
1562
- }
1563
- }
1564
- /**
1565
- * @inheritDoc
1566
- */
1567
- getIntegration(integration) {
1568
- const client2 = this.getClient();
1569
- if (!client2)
1570
- return null;
1571
- try {
1572
- return client2.getIntegration(integration);
1573
- } catch (_oO) {
1574
- (typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__) && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);
1575
- return null;
1576
- }
1577
- }
1578
- /**
1579
- * @inheritDoc
1580
- */
1581
- startTransaction(context, customSamplingContext) {
1582
- const result = this._callExtensionMethod("startTransaction", context, customSamplingContext);
1583
- if ((typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__) && !result) {
1584
- const client2 = this.getClient();
1585
- if (!client2) {
1586
- console.warn(
1587
- "Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'"
1588
- );
1589
- } else {
1590
- console.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':
1591
- Sentry.addTracingExtensions();
1592
- Sentry.init({...});
1593
- `);
1594
- }
1595
- }
1596
- return result;
1597
- }
1598
- /**
1599
- * @inheritDoc
1600
- */
1601
- traceHeaders() {
1602
- return this._callExtensionMethod("traceHeaders");
1603
- }
1604
- /**
1605
- * @inheritDoc
1606
- */
1607
- captureSession(endSession = false) {
1608
- if (endSession) {
1609
- return this.endSession();
1610
- }
1611
- this._sendSessionUpdate();
1612
- }
1613
- /**
1614
- * @inheritDoc
1615
- */
1616
- endSession() {
1617
- const layer = this.getStackTop();
1618
- const scope = layer.scope;
1619
- const session = scope.getSession();
1620
- if (session) {
1621
- closeSession(session);
1622
- }
1623
- this._sendSessionUpdate();
1624
- scope.setSession();
1625
- }
1626
- /**
1627
- * @inheritDoc
1628
- */
1629
- startSession(context) {
1630
- const { scope, client: client2 } = this.getStackTop();
1631
- const { release, environment = DEFAULT_ENVIRONMENT } = client2 && client2.getOptions() || {};
1632
- const { userAgent } = GLOBAL_OBJ.navigator || {};
1633
- const session = makeSession(__spreadValues(__spreadValues({
1634
- release,
1635
- environment,
1636
- user: scope.getUser()
1637
- }, userAgent && { userAgent }), context));
1638
- const currentSession = scope.getSession && scope.getSession();
1639
- if (currentSession && currentSession.status === "ok") {
1640
- updateSession(currentSession, { status: "exited" });
1641
- }
1642
- this.endSession();
1643
- scope.setSession(session);
1644
- return session;
1645
- }
1646
- /**
1647
- * Returns if default PII should be sent to Sentry and propagated in ourgoing requests
1648
- * when Tracing is used.
1649
- */
1650
- shouldSendDefaultPii() {
1651
- const client2 = this.getClient();
1652
- const options = client2 && client2.getOptions();
1653
- return Boolean(options && options.sendDefaultPii);
1654
- }
1655
- /**
1656
- * Sends the current Session on the scope
1657
- */
1658
- _sendSessionUpdate() {
1659
- const { scope, client: client2 } = this.getStackTop();
1660
- const session = scope.getSession();
1661
- if (session && client2 && client2.captureSession) {
1662
- client2.captureSession(session);
1663
- }
1664
- }
1665
- /**
1666
- * Internal helper function to call a method on the top client if it exists.
1667
- *
1668
- * @param method The method to call on the client.
1669
- * @param args Arguments to pass to the client function.
1670
- */
1671
- _withClient(callback) {
1672
- const { scope, client: client2 } = this.getStackTop();
1673
- if (client2) {
1674
- callback(client2, scope);
1675
- }
1174
+ return scope;
1676
1175
  }
1677
1176
  /**
1678
- * Calls global extension method and binding current instance to the function call
1177
+ * Pop a scope from the stack.
1679
1178
  */
1680
- // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)
1681
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1682
- _callExtensionMethod(method, ...args) {
1683
- const carrier = getMainCarrier();
1684
- const sentry = carrier.__SENTRY__;
1685
- if (sentry && sentry.extensions && typeof sentry.extensions[method] === "function") {
1686
- return sentry.extensions[method].apply(this, args);
1687
- }
1688
- (typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__) && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);
1179
+ _popScope() {
1180
+ if (this._stack.length <= 1) return false;
1181
+ return !!this._stack.pop();
1689
1182
  }
1690
1183
  }
1691
- function getMainCarrier() {
1692
- GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {
1693
- extensions: {},
1694
- hub: void 0
1695
- };
1696
- return GLOBAL_OBJ;
1697
- }
1698
- function makeMain(hub) {
1184
+ function getAsyncContextStack() {
1699
1185
  const registry = getMainCarrier();
1700
- const oldHub = getHubFromCarrier(registry);
1701
- setHubOnCarrier(registry, hub);
1702
- return oldHub;
1186
+ const sentry = getSentryCarrier(registry);
1187
+ return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope());
1703
1188
  }
1704
- function getCurrentHub() {
1705
- const registry = getMainCarrier();
1706
- if (registry.__SENTRY__ && registry.__SENTRY__.acs) {
1707
- const hub = registry.__SENTRY__.acs.getCurrentHub();
1708
- if (hub) {
1709
- return hub;
1710
- }
1711
- }
1712
- return getGlobalHub(registry);
1189
+ function withScope(callback) {
1190
+ return getAsyncContextStack().withScope(callback);
1191
+ }
1192
+ function withSetScope(scope, callback) {
1193
+ const stack = getAsyncContextStack();
1194
+ return stack.withScope(() => {
1195
+ stack.getStackTop().scope = scope;
1196
+ return callback(scope);
1197
+ });
1713
1198
  }
1714
- function getGlobalHub(registry = getMainCarrier()) {
1715
- if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {
1716
- setHubOnCarrier(registry, new Hub());
1199
+ function withIsolationScope(callback) {
1200
+ return getAsyncContextStack().withScope(() => {
1201
+ return callback(getAsyncContextStack().getIsolationScope());
1202
+ });
1203
+ }
1204
+ function getStackAsyncContextStrategy() {
1205
+ return {
1206
+ withIsolationScope,
1207
+ withScope,
1208
+ withSetScope,
1209
+ withSetIsolationScope: (_isolationScope, callback) => {
1210
+ return withIsolationScope(callback);
1211
+ },
1212
+ getCurrentScope: () => getAsyncContextStack().getScope(),
1213
+ getIsolationScope: () => getAsyncContextStack().getIsolationScope()
1214
+ };
1215
+ }
1216
+ function getAsyncContextStrategy(carrier) {
1217
+ const sentry = getSentryCarrier(carrier);
1218
+ if (sentry.acs) {
1219
+ return sentry.acs;
1717
1220
  }
1718
- return getHubFromCarrier(registry);
1221
+ return getStackAsyncContextStrategy();
1719
1222
  }
1720
- function hasHubOnCarrier(carrier) {
1721
- return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);
1223
+ function getCurrentScope() {
1224
+ const carrier = getMainCarrier();
1225
+ const acs = getAsyncContextStrategy(carrier);
1226
+ return acs.getCurrentScope();
1722
1227
  }
1723
- function getHubFromCarrier(carrier) {
1724
- return getGlobalSingleton("hub", () => new Hub(), carrier);
1228
+ function getIsolationScope() {
1229
+ const carrier = getMainCarrier();
1230
+ const acs = getAsyncContextStrategy(carrier);
1231
+ return acs.getIsolationScope();
1725
1232
  }
1726
- function setHubOnCarrier(carrier, hub) {
1727
- if (!carrier)
1728
- return false;
1729
- const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
1730
- __SENTRY__.hub = hub;
1731
- return true;
1233
+ function getClient$1() {
1234
+ return getCurrentScope().getClient();
1732
1235
  }
1733
1236
  function captureMessage(message, captureContext) {
1734
- const level = typeof captureContext === "string" ? captureContext : void 0;
1735
- const context = typeof captureContext !== "string" ? { captureContext } : void 0;
1736
- return getCurrentHub().captureMessage(message, level, context);
1237
+ const level = captureContext;
1238
+ const context = void 0;
1239
+ return getCurrentScope().captureMessage(message, level, context);
1737
1240
  }
1738
- function addBreadcrumb(breadcrumb) {
1739
- getCurrentHub().addBreadcrumb(breadcrumb);
1241
+ const DEFAULT_BREADCRUMBS = 100;
1242
+ function addBreadcrumb(breadcrumb, hint) {
1243
+ const client2 = getClient$1();
1244
+ const isolationScope = getIsolationScope();
1245
+ if (!client2) return;
1246
+ const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client2.getOptions();
1247
+ if (maxBreadcrumbs <= 0) return;
1248
+ const timestamp = dateTimestampInSeconds();
1249
+ const mergedBreadcrumb = __spreadValues({ timestamp }, breadcrumb);
1250
+ const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb;
1251
+ if (finalBreadcrumb === null) return;
1252
+ if (client2.emit) {
1253
+ client2.emit("beforeAddBreadcrumb", finalBreadcrumb, hint);
1254
+ }
1255
+ isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
1740
1256
  }
1741
1257
  const errorsToIgnore = [
1742
1258
  MiniAppErrorType.sdkNotInitialized,
@@ -1759,11 +1275,30 @@ function addBreadcrumbToSentry(breadcrumb) {
1759
1275
  addBreadcrumb(breadcrumb);
1760
1276
  }
1761
1277
  }
1278
+ function middlewareHandler(middlewares, message, messageHandler, params) {
1279
+ let index = -1;
1280
+ const next = (_params) => __async(this, null, function* () {
1281
+ ++index;
1282
+ if (index < middlewares.length) {
1283
+ const nextMiddleware = middlewares[index];
1284
+ return yield nextMiddleware(message, _params, next);
1285
+ }
1286
+ return messageHandler(..._params);
1287
+ });
1288
+ return next(params);
1289
+ }
1290
+ const deepClone = (obj) => {
1291
+ if (typeof obj !== "object" || obj === null) {
1292
+ return obj;
1293
+ }
1294
+ return JSON.parse(JSON.stringify(obj));
1295
+ };
1762
1296
  class WindowBridge {
1763
- constructor(functions, allowedOrigins) {
1297
+ constructor(functions, allowedOrigins, middlewares = []) {
1764
1298
  this.deferredCallbacks = {};
1765
1299
  this.functions = functions;
1766
1300
  this.allowedOrigins = allowedOrigins;
1301
+ this.middlewares = middlewares;
1767
1302
  this.messageEventHandler = this.messageEventHandler.bind(this);
1768
1303
  this.subscribeToMessageEvent();
1769
1304
  }
@@ -1787,7 +1322,7 @@ class WindowBridge {
1787
1322
  if (!((_a = receivedMessageEvent.data) == null ? void 0 : _a.forWindowBridge)) {
1788
1323
  return;
1789
1324
  }
1790
- if (this.allowedOrigins && !this.allowedOrigins.includes(receivedMessageEvent.origin)) {
1325
+ if (this.allowedOrigins && receivedMessageEvent.data.type === "request" && !this.allowedOrigins.includes(receivedMessageEvent.origin)) {
1791
1326
  return this.sendErrorResponse(
1792
1327
  receivedMessageEvent,
1793
1328
  `${receivedMessageEvent.origin} is not allowed to make requests`,
@@ -1806,6 +1341,7 @@ class WindowBridge {
1806
1341
  }
1807
1342
  handleRequest(receivedMessageEvent) {
1808
1343
  return __async(this, null, function* () {
1344
+ var _a;
1809
1345
  const functionName = receivedMessageEvent.data.functionName;
1810
1346
  const functionToInvoke = this.functions[functionName];
1811
1347
  if (!functionToInvoke) {
@@ -1818,14 +1354,21 @@ class WindowBridge {
1818
1354
  try {
1819
1355
  this.sendSuccessResponse(
1820
1356
  receivedMessageEvent,
1821
- yield functionToInvoke(...receivedMessageEvent.data.params)
1357
+ yield middlewareHandler(
1358
+ [...this.middlewares, ...(_a = functionToInvoke.middlewares) != null ? _a : []],
1359
+ receivedMessageEvent,
1360
+ functionToInvoke,
1361
+ deepClone(receivedMessageEvent.data.params)
1362
+ )
1822
1363
  );
1823
1364
  } catch (error) {
1824
- let message = "Some error ocurred while processing the request";
1365
+ let message = "Some error occurred while processing the request";
1825
1366
  let errorCode = MiniAppErrorType.unknown;
1826
1367
  if (error instanceof PPError) {
1827
1368
  message = error.message;
1828
1369
  errorCode = error.errorCode;
1370
+ } else {
1371
+ console.error(error);
1829
1372
  }
1830
1373
  this.sendErrorResponse(receivedMessageEvent, message, errorCode);
1831
1374
  }
@@ -1877,7 +1420,7 @@ class WindowBridge {
1877
1420
  type: "response",
1878
1421
  key: receivedMessageEvent.data.key,
1879
1422
  functionName: receivedMessageEvent.data.functionName
1880
- }, data),
1423
+ }, deepClone(data)),
1881
1424
  // Just a hack to overcome weird function overload mismatch
1882
1425
  receivedMessageEvent.origin
1883
1426
  );
@@ -1888,13 +1431,13 @@ class WindowBridge {
1888
1431
  * @param allowedOrigins a list of allowed origins from where request can be accepted
1889
1432
  * @returns `WindowBridge` instance
1890
1433
  */
1891
- static init(functions, allowedOrigins) {
1434
+ static init(functions, allowedOrigins, middlewares = []) {
1892
1435
  if (this._instance) {
1893
1436
  throw new Error(
1894
1437
  "WindowBridge already initialized, you can't call WindowBridge.init more than once"
1895
1438
  );
1896
1439
  }
1897
- this._instance = new this(functions, allowedOrigins);
1440
+ this._instance = new this(functions, allowedOrigins, middlewares);
1898
1441
  return this._instance;
1899
1442
  }
1900
1443
  /**
@@ -1958,7 +1501,7 @@ class WindowBridge {
1958
1501
  type: "request",
1959
1502
  functionName: functionNameString,
1960
1503
  key,
1961
- params: JSON.parse(JSON.stringify(params))
1504
+ params: deepClone(params)
1962
1505
  },
1963
1506
  targetWindowOrigin
1964
1507
  );
@@ -1977,17 +1520,22 @@ class WindowBridge {
1977
1520
  });
1978
1521
  }
1979
1522
  }
1980
- let clientId = "";
1981
- function getCurrentClientId() {
1982
- return clientId;
1983
- }
1984
- const KEY_INITIALIZED_AT = "ppjssdk.initializedAt";
1985
1523
  class LocalStorageProxy {
1986
1524
  constructor() {
1525
+ var _a;
1987
1526
  this.useLocalStorage = true;
1988
1527
  this.memoryStorage = {};
1989
1528
  try {
1990
- localStorage.setItem(KEY_INITIALIZED_AT, Date.now().toString());
1529
+ localStorage.setItem(
1530
+ PpLocalStorageKey.initializedAt,
1531
+ Date.now().toString()
1532
+ );
1533
+ for (let i = 0; i < localStorage.length; i++) {
1534
+ const key = localStorage.key(i);
1535
+ if (key != null) {
1536
+ this.memoryStorage[key] = (_a = localStorage.getItem(key)) != null ? _a : "";
1537
+ }
1538
+ }
1991
1539
  } catch (e) {
1992
1540
  this.useLocalStorage = false;
1993
1541
  }
@@ -1996,7 +1544,7 @@ class LocalStorageProxy {
1996
1544
  var _a;
1997
1545
  if (this.useLocalStorage) {
1998
1546
  try {
1999
- if (localStorage.getItem(KEY_INITIALIZED_AT) != null) {
1547
+ if (localStorage.getItem(PpLocalStorageKey.initializedAt) != null) {
2000
1548
  return localStorage.getItem(key);
2001
1549
  } else {
2002
1550
  console.debug("local storage value has lost unexpectedly.");
@@ -2033,257 +1581,77 @@ class LocalStorageProxy {
2033
1581
  clear() {
2034
1582
  try {
2035
1583
  localStorage.clear();
2036
- localStorage.setItem(KEY_INITIALIZED_AT, Date.now().toString());
1584
+ localStorage.setItem(
1585
+ PpLocalStorageKey.initializedAt,
1586
+ Date.now().toString()
1587
+ );
2037
1588
  } catch (e) {
2038
1589
  }
2039
1590
  this.memoryStorage = {};
2040
1591
  }
2041
1592
  }
2042
- const storage = new LocalStorageProxy();
2043
- function getKeyWithClientId(baseKey, clientId2) {
2044
- return `${baseKey}.${clientId2 != null ? clientId2 : getCurrentClientId()}`;
2045
- }
2046
- function saveLocalStorage(key, value) {
2047
- removeLocalStorage$1(key);
2048
- if (value) {
2049
- return storage.setItem(key, value);
2050
- }
2051
- }
2052
- function removeLocalStorage$1(key) {
2053
- storage.removeItem(key);
2054
- }
2055
- function saveClientUUID(uuid) {
2056
- saveLocalStorage(getKeyWithClientId(PpLocalStorageKey.clientUUID), uuid);
2057
- }
2058
- function getClientUUID() {
2059
- let uuid = storage.getItem(getKeyWithClientId(PpLocalStorageKey.clientUUID)) || "";
2060
- if (!validate(uuid)) {
2061
- uuid = v4();
2062
- saveClientUUID(uuid);
2063
- }
2064
- return uuid;
2065
- }
2066
- function getAppDetail(clientId2) {
2067
- const val = storage.getItem(
2068
- getKeyWithClientId(PpLocalStorageKey.appDetail, clientId2)
2069
- );
2070
- if (val == null) {
2071
- return null;
2072
- }
2073
- return JSON.parse(val);
2074
- }
2075
- let timeoutId = null;
2076
- let eventsQueue = [];
2077
- function sendEvents() {
2078
- var _a;
2079
- const events = eventsQueue;
2080
- eventsQueue = [];
2081
- timeoutId = null;
2082
- const url2 = `https://www.google-analytics.com/mp/collect?api_secret=${GA_API_SECRET}&measurement_id=${GA_MEASUREMENT_ID}`;
2083
- const body = JSON.stringify({
2084
- client_id: getClientUUID(),
2085
- events,
2086
- user_id: (_a = getAppDetail()) == null ? void 0 : _a.externalUserId
2087
- });
2088
- if (navigator.sendBeacon) {
2089
- navigator.sendBeacon(url2, body);
2090
- } else {
2091
- void fetch(url2, {
2092
- method: "POST",
2093
- keepalive: true,
2094
- body
2095
- }).catch(console.warn);
2096
- }
2097
- }
2098
- getRandomString();
2099
- document.addEventListener("visibilitychange", () => {
2100
- if (document.visibilityState === "hidden") {
2101
- if (eventsQueue.length > 0) {
2102
- if (timeoutId) {
2103
- clearTimeout(timeoutId);
2104
- }
2105
- sendEvents();
2106
- }
2107
- }
2108
- });
2109
- ({
2110
- UNAUTHORIZED: MiniAppErrorType.notAuthorized,
2111
- BAD_REQUEST: MiniAppErrorType.badRequest,
2112
- MISSING_REQUEST_PARAMS: MiniAppErrorType.badRequestInsufficientParameter,
2113
- OP_OUT_OF_SCOPE: MiniAppErrorType.insufficientScope,
2114
- MINI_APP_SCOPE_NOT_FOUND: MiniAppErrorType.insufficientScope
2115
- });
2116
- function getAppVersion() {
2117
- var _a, _b, _c, _d;
2118
- let appVersion = null;
2119
- const appVersionSplit = navigator.userAgent.split(" PayPayMiniApp/");
2120
- if (appVersionSplit.length > 1) {
2121
- const versionData = (_a = appVersionSplit[1].split(" ")[0]) != null ? _a : null;
2122
- appVersion = versionData ? versionData.split("-")[0] : appVersion;
2123
- appVersion = (_d = (_c = (_b = appVersion == null ? void 0 : appVersion.split(".")) == null ? void 0 : _b.slice(0, 3)) == null ? void 0 : _c.join(".")) != null ? _d : null;
2124
- }
2125
- return appVersion;
2126
- }
2127
- function semVerCompare(a, b) {
2128
- const [majorA, minorA, patchA] = a.split(".").map((v) => Number.parseInt(v));
2129
- const [majorB, minorB, patchB] = b.split(".").map((v) => Number.parseInt(v));
2130
- if (majorA !== majorB) {
2131
- return majorA > majorB;
2132
- }
2133
- if (minorA !== minorB) {
2134
- return minorA > minorB;
2135
- }
2136
- return patchA > patchB;
2137
- }
2138
- function checkVersion(minVersion) {
2139
- const appVersion = getAppVersion();
2140
- if (!appVersion) {
2141
- return false;
2142
- }
2143
- if (minVersion === appVersion) {
2144
- return true;
2145
- }
2146
- return semVerCompare(appVersion, minVersion);
1593
+ new LocalStorageProxy();
1594
+ function isFunction(val) {
1595
+ return typeof val === "function";
2147
1596
  }
2148
1597
  function getRandomString() {
2149
1598
  return Math.random().toString(36).substring(7);
2150
1599
  }
2151
- function checkIFrameOrigin(origin) {
2152
- return origin === CORE_IFRAME_ORIGIN;
2153
- }
2154
- function getIconUrl(theme) {
2155
- return theme === "red" ? img_paypayRecWhite : img_paypayRec;
1600
+ function setCookie({ name, value, options }) {
1601
+ return api.set(name, value, options);
2156
1602
  }
2157
- function convertToString(str) {
2158
- return str ? String(str) : "";
1603
+ function getCookie({ name }) {
1604
+ return api.get(name);
2159
1605
  }
2160
- function getRefreshToken(clientId2) {
2161
- const refreshTokenWithClientId = api.get(
2162
- `${PpLocalStorageKey.refreshToken}.${clientId2}`
2163
- );
2164
- return refreshTokenWithClientId || api.get(PpLocalStorageKey.refreshToken) || "";
1606
+ function removeCookie({ name, options }) {
1607
+ return api.remove(name, options);
2165
1608
  }
2166
- function getCodeVerifier(clientId2) {
2167
- return api.get(`${PpLocalStorageKey.codeVerifier}.${clientId2}`) || api.get(PpLocalStorageKey.codeVerifier) || "";
1609
+ function setLocalStorage({
1610
+ name,
1611
+ value
1612
+ }) {
1613
+ return localStorage.setItem(name, value);
2168
1614
  }
2169
- function exposeClientJsBridge(jsBridge) {
2170
- if (window.hasOwnProperty(jsBridgeNamespace) && window[jsBridgeNamespace] === jsBridge) {
2171
- return false;
2172
- }
2173
- window[jsBridgeNamespace] = jsBridge;
2174
- return true;
1615
+ function getLocalStorage({ name }) {
1616
+ return localStorage.getItem(name);
2175
1617
  }
2176
- function consoleDebugInfo(params) {
2177
- console.debug(...params);
1618
+ function removeLocalStorage({ name }) {
1619
+ return localStorage.removeItem(name);
2178
1620
  }
2179
- function isSupportedMiniapp(functionName) {
2180
- return miniAppSupportedFunctions.includes(functionName);
1621
+ function setSessionStorage({
1622
+ name,
1623
+ value
1624
+ }) {
1625
+ return sessionStorage.setItem(name, value);
2181
1626
  }
2182
- function isSupportedSmartpayment(functionName) {
2183
- return smartPaymentSupportedFunctions.includes(
2184
- functionName
2185
- );
1627
+ function getSessionStorage({ name }) {
1628
+ return sessionStorage.getItem(name);
2186
1629
  }
2187
- let runningFunctions = [];
2188
- function isFunctionRunning() {
2189
- return runningFunctions.length > 0;
1630
+ function removeSessionStorage({ name }) {
1631
+ return sessionStorage.removeItem(name);
2190
1632
  }
2191
- function functionEnd(messageId) {
2192
- runningFunctions = runningFunctions.filter((val) => {
2193
- return val !== messageId;
2194
- });
1633
+ function removeQueryParametersFromUrl(removeParams) {
1634
+ const url = new URL(window.location.href);
1635
+ removeParams.forEach((param) => url.searchParams.delete(param));
1636
+ const newURL = `${url.pathname}${url.search}`;
1637
+ history.replaceState(history.state, "", newURL);
2195
1638
  }
2196
- function functionStart() {
2197
- const messageId = getRandomString();
2198
- runningFunctions.push(messageId);
2199
- return messageId;
2200
- }
2201
- function promiseToCallback(functionName, target, getCore2, getLoggingParams) {
2202
- return function(params = {}) {
2203
- const core2 = getCore2();
2204
- const loggingParams = getLoggingParams == null ? void 0 : getLoggingParams(params);
2205
- void core2.logEvent(__spreadValues({
2206
- event_action: `pp_${functionName}_called`,
2207
- event_category_suffix: functionName
2208
- }, loggingParams));
2209
- target(params).then((result) => {
2210
- var _a;
2211
- void core2.logEvent(__spreadValues({
2212
- event_action: `pp_${functionName}_success`,
2213
- event_category_suffix: functionName
2214
- }, loggingParams));
2215
- (_a = params.success) == null ? void 0 : _a.call(params, result);
2216
- }).catch((error) => {
2217
- var _a;
2218
- console.error(error.message);
2219
- void core2.logEvent(__spreadValues({
2220
- event_action: `pp_${functionName}_fail`,
2221
- event_category_suffix: functionName,
2222
- error_value: error.errorCode
2223
- }, loggingParams));
2224
- (_a = params.fail) == null ? void 0 : _a.call(params, { errorCode: error.errorCode });
2225
- }).finally(() => {
2226
- var _a;
2227
- (_a = params.complete) == null ? void 0 : _a.call(params);
2228
- });
2229
- };
2230
- }
2231
- var MiniAppStatusType = /* @__PURE__ */ ((MiniAppStatusType2) => {
2232
- MiniAppStatusType2["validToken"] = "TOKEN_VALID";
2233
- MiniAppStatusType2["initialized"] = "INITIALIZED";
2234
- MiniAppStatusType2["emailRegistered"] = "EMAIL_REGISTERED";
2235
- MiniAppStatusType2["emailNotVerified"] = "EMAIL_NOT_VERIFIED";
2236
- MiniAppStatusType2["success"] = "SUCCESS";
2237
- MiniAppStatusType2["loggedOut"] = "LOGGED_OUT";
2238
- MiniAppStatusType2["connected"] = "CONNECTED";
2239
- return MiniAppStatusType2;
2240
- })(MiniAppStatusType || {});
2241
- const style = "";
2242
- const MinVersion = {
2243
- PRE_TRANSACTION_AUTO_CHARGE: "3.43.0",
2244
- FALLBACK_PAYMENT_METHOD: "3.61.0",
2245
- OS_HOME_SCREEN_ICON: "3.71.0",
2246
- START_MULTIFACTOR_AUTH_ANDROID_FIX: "3.67.0",
2247
- KYC_PASSPORT: "3.72.0",
2248
- PERFORMANCE_MEASUREMENT: "4.47.0",
2249
- START_MULTIFACTOR_AUTH_PIN_FALLBACK: "4.63.0"
2250
- };
2251
- function setCookie({ name, value, options }) {
2252
- return api.set(name, value, options);
2253
- }
2254
- function getCookie({ name }) {
2255
- return api.get(name);
2256
- }
2257
- function removeCookie({ name, options }) {
2258
- return api.remove(name, options);
2259
- }
2260
- function setLocalStorage({
2261
- name,
2262
- value
2263
- }) {
2264
- return localStorage.setItem(name, value);
2265
- }
2266
- function getLocalStorage({ name }) {
2267
- return localStorage.getItem(name);
2268
- }
2269
- function removeLocalStorage({ name }) {
2270
- return localStorage.removeItem(name);
2271
- }
2272
- function removeQueryParametersFromUrl(removeParams) {
2273
- const url2 = new URL(window.location.href);
2274
- removeParams.forEach((param) => url2.searchParams.delete(param));
2275
- const newURL = `${url2.pathname}${url2.search}`;
2276
- history.replaceState(null, "", newURL);
1639
+ function getUrl() {
1640
+ return window.location.href;
2277
1641
  }
2278
1642
  const clientWindowBridgeFunctions = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
2279
1643
  __proto__: null,
2280
1644
  getCookie,
2281
1645
  getLocalStorage,
1646
+ getSessionStorage,
1647
+ getUrl,
2282
1648
  removeCookie,
2283
1649
  removeLocalStorage,
2284
1650
  removeQueryParametersFromUrl,
1651
+ removeSessionStorage,
2285
1652
  setCookie,
2286
- setLocalStorage
1653
+ setLocalStorage,
1654
+ setSessionStorage
2287
1655
  }, Symbol.toStringTag, { value: "Module" }));
2288
1656
  const IFRAME_NAME = "ppmna-iframe";
2289
1657
  const IFRAME_CONTAINER_NAME = "ppsdk-container";
@@ -2348,6 +1716,7 @@ function createIframe() {
2348
1716
  iframe.setAttribute("allow", "geolocation");
2349
1717
  iframe.onload = () => {
2350
1718
  resolve(iframe);
1719
+ iframe.onerror = null;
2351
1720
  };
2352
1721
  iframe.onerror = reject;
2353
1722
  iframe.style.all = "initial";
@@ -2362,22 +1731,168 @@ function createIframe() {
2362
1731
  }
2363
1732
  });
2364
1733
  }
2365
- let useAllFunctions = false;
1734
+ WindowBridge.init(clientWindowBridgeFunctions, [CORE_IFRAME_ORIGIN]);
1735
+ const coreFunctions = WindowBridge.getTargetWindowFunctionProxy(
1736
+ getCoreIframeWindow,
1737
+ CORE_IFRAME_ORIGIN
1738
+ );
1739
+ function receiveMessageFromIframe(messageData, params, eventHandler) {
1740
+ var _a, _b, _c;
1741
+ if (messageData.result === PPFunctionResult.fail) {
1742
+ (_a = params == null ? void 0 : params.fail) == null ? void 0 : _a.call(params, messageData.data);
1743
+ }
1744
+ if (messageData.result === PPFunctionResult.success) {
1745
+ (_b = params == null ? void 0 : params.success) == null ? void 0 : _b.call(params, messageData == null ? void 0 : messageData.data);
1746
+ }
1747
+ if (messageData.result === PPFunctionResult.complete) {
1748
+ (_c = params == null ? void 0 : params.complete) == null ? void 0 : _c.call(params);
1749
+ removeEventListener("message", eventHandler);
1750
+ functionEnd(messageData.messageId);
1751
+ if (!isFunctionRunning()) {
1752
+ showCoreIframe(false);
1753
+ }
1754
+ }
1755
+ }
1756
+ function postMessageToCore(messageData) {
1757
+ return __async(this, null, function* () {
1758
+ var _a;
1759
+ const iframe = yield getCoreIframe().catch(() => void 0);
1760
+ (_a = iframe == null ? void 0 : iframe.contentWindow) == null ? void 0 : _a.postMessage(
1761
+ JSON.parse(JSON.stringify(messageData)),
1762
+ CORE_IFRAME_ORIGIN
1763
+ );
1764
+ });
1765
+ }
1766
+ function triggerPostMessageToCore(type, showIframeFlag, params, postMessageParams) {
1767
+ const messageId = functionStart();
1768
+ const fnMessageHandler = (e) => {
1769
+ if (!checkIFrameOrigin(e.origin)) {
1770
+ return;
1771
+ }
1772
+ if (e.data.name === type) {
1773
+ if (e.data.messageId === messageId) {
1774
+ receiveMessageFromIframe(e.data, params, fnMessageHandler);
1775
+ }
1776
+ }
1777
+ };
1778
+ addEventListener("message", fnMessageHandler);
1779
+ void postMessageToCore({
1780
+ name: type,
1781
+ params: postMessageParams,
1782
+ messageId
1783
+ });
1784
+ }
1785
+ function checkIFrameOrigin(origin) {
1786
+ return origin === CORE_IFRAME_ORIGIN;
1787
+ }
1788
+ function getRefreshToken(clientId) {
1789
+ const refreshTokenWithClientId = api.get(
1790
+ `${PpLocalStorageKey.refreshToken}.${clientId}`
1791
+ );
1792
+ return refreshTokenWithClientId || api.get(PpLocalStorageKey.refreshToken) || "";
1793
+ }
1794
+ function getCodeVerifier(clientId) {
1795
+ return api.get(`${PpLocalStorageKey.codeVerifier}.${clientId}`) || api.get(PpLocalStorageKey.codeVerifier) || "";
1796
+ }
1797
+ function exposeClientJsBridge(jsBridge) {
1798
+ if (window.hasOwnProperty(jsBridgeNamespace) && window[jsBridgeNamespace] === jsBridge) {
1799
+ return false;
1800
+ }
1801
+ window[jsBridgeNamespace] = jsBridge;
1802
+ return true;
1803
+ }
1804
+ function consoleDebugInfo(params) {
1805
+ console.debug(...params);
1806
+ }
1807
+ function isSupportedMiniapp(functionName) {
1808
+ return miniAppSupportedFunctions.includes(functionName);
1809
+ }
1810
+ function isSupportedSmartpayment(functionName) {
1811
+ return smartPaymentSupportedFunctions.includes(
1812
+ functionName
1813
+ );
1814
+ }
1815
+ let runningFunctions = [];
1816
+ function isFunctionRunning() {
1817
+ return runningFunctions.length > 0;
1818
+ }
1819
+ function functionEnd(messageId) {
1820
+ runningFunctions = runningFunctions.filter((val) => {
1821
+ return val !== messageId;
1822
+ });
1823
+ }
1824
+ function functionStart() {
1825
+ const messageId = getRandomString();
1826
+ runningFunctions.push(messageId);
1827
+ return messageId;
1828
+ }
1829
+ function promiseToCallback(functionName, target, getLoggingParams) {
1830
+ return function(params = {}) {
1831
+ const loggingParams = getLoggingParams == null ? void 0 : getLoggingParams(params);
1832
+ void coreFunctions.logEvent(__spreadValues({
1833
+ event_action: `pp_${functionName}_called`,
1834
+ event_category_suffix: functionName
1835
+ }, loggingParams));
1836
+ const resultPromise = target(params);
1837
+ resultPromise.then((result) => {
1838
+ var _a;
1839
+ void coreFunctions.logEvent(__spreadValues({
1840
+ event_action: `pp_${functionName}_success`,
1841
+ event_category_suffix: functionName
1842
+ }, loggingParams));
1843
+ (_a = params.success) == null ? void 0 : _a.call(params, result);
1844
+ }).catch((error) => {
1845
+ var _a;
1846
+ console.error(error.message);
1847
+ void coreFunctions.logEvent(__spreadValues({
1848
+ event_action: `pp_${functionName}_fail`,
1849
+ event_category_suffix: functionName,
1850
+ error_value: error.errorCode
1851
+ }, loggingParams));
1852
+ (_a = params.fail) == null ? void 0 : _a.call(params, { errorCode: error.errorCode });
1853
+ }).finally(() => {
1854
+ var _a;
1855
+ (_a = params.complete) == null ? void 0 : _a.call(params);
1856
+ });
1857
+ return resultPromise;
1858
+ };
1859
+ }
1860
+ const INIT_STATUS_CODE_REMAP = {
1861
+ [MiniAppErrorType.sdkNotInitialized]: MiniAppErrorType.authorizationNeeded,
1862
+ [MiniAppErrorType.tokenNotFound]: MiniAppErrorType.authorizationNeeded,
1863
+ [MiniAppErrorType.tokenExpired]: MiniAppErrorType.tokenExpired
1864
+ };
1865
+ function callbackToPromise(target, functionName) {
1866
+ return (params = {}) => {
1867
+ return new Promise((resolve, reject) => {
1868
+ target(__spreadProps(__spreadValues({}, params), {
1869
+ success: (result) => {
1870
+ var _a;
1871
+ resolve(result);
1872
+ (_a = params.success) == null ? void 0 : _a.call(params, result);
1873
+ },
1874
+ fail: (error) => {
1875
+ var _a;
1876
+ if (functionName === "init" && INIT_STATUS_CODE_REMAP[error.errorCode]) {
1877
+ resolve({
1878
+ statusCode: INIT_STATUS_CODE_REMAP[error.errorCode]
1879
+ });
1880
+ } else {
1881
+ reject(error);
1882
+ }
1883
+ (_a = params.fail) == null ? void 0 : _a.call(params, error);
1884
+ }
1885
+ }));
1886
+ });
1887
+ };
1888
+ }
2366
1889
  let clientSdkType;
2367
1890
  let initDonePromise;
2368
- WindowBridge.init(clientWindowBridgeFunctions, [CORE_IFRAME_ORIGIN]);
2369
1891
  void getCoreIframe();
2370
1892
  function clearInternalInitSyncState() {
2371
1893
  initDonePromise = Promise.resolve(false);
2372
1894
  }
2373
1895
  clearInternalInitSyncState();
2374
- const core = WindowBridge.getTargetWindowFunctionProxy(
2375
- getCoreIframeWindow,
2376
- CORE_IFRAME_ORIGIN
2377
- );
2378
- function getCore() {
2379
- return core;
2380
- }
2381
1896
  const commonMessageHandler = (e) => {
2382
1897
  var _a;
2383
1898
  if ((_a = e.data) == null ? void 0 : _a.forWindowBridge) {
@@ -2419,8 +1934,7 @@ addEventListener("popstate", () => {
2419
1934
  function init(params) {
2420
1935
  const refreshToken = getRefreshToken(params.clientId);
2421
1936
  const codeVerifier = getCodeVerifier(params.clientId);
2422
- const clientVersion = "2.41.0";
2423
- useAllFunctions = !!params.useAllFunctions;
1937
+ const clientVersion = "2.48.0";
2424
1938
  const initParams = {
2425
1939
  env: params.env,
2426
1940
  mode: params.mode,
@@ -2455,86 +1969,171 @@ function init(params) {
2455
1969
  });
2456
1970
  initDonePromise = nextInitDonePromise;
2457
1971
  }
2458
- function verifyMultiFactorAuthResult(params) {
2459
- const url2 = new URL(window.location.href);
2460
- triggerPostMessageToCore(
2461
- PPFunctionName.verifyMultiFactorAuthResult,
2462
- false,
2463
- params,
2464
- __spreadProps(__spreadValues({}, params), { sessionId: url2.searchParams.get("ppSessionId") })
2465
- );
2466
- }
2467
- function getKycPassportInfo(params) {
2468
- const url2 = window.location.href;
2469
- triggerPostMessageToCore(PPFunctionName.getKycPassportInfo, false, params, __spreadProps(__spreadValues({}, params), {
2470
- url: url2
2471
- }));
2472
- }
2473
- function share(params) {
2474
- if (!(navigator == null ? void 0 : navigator.share)) {
2475
- triggerPostMessageToCore(PPFunctionName.share, false, params, params);
1972
+ const clientJsBridge = {
1973
+ _handleMessageFromNative: (json) => {
1974
+ void getCoreIframe().then((iframe) => {
1975
+ var _a;
1976
+ (_a = iframe == null ? void 0 : iframe.contentWindow) == null ? void 0 : _a.postMessage(
1977
+ JSON.parse(
1978
+ JSON.stringify({
1979
+ name: PPFunctionName.handleMessageFromNative,
1980
+ params: {
1981
+ json
1982
+ }
1983
+ })
1984
+ ),
1985
+ CORE_IFRAME_ORIGIN
1986
+ );
1987
+ });
1988
+ }
1989
+ };
1990
+ exposeClientJsBridge(clientJsBridge);
1991
+ const initExemptedFunctions = [
1992
+ "init",
1993
+ "setTitle",
1994
+ "copyToClipboard",
1995
+ "getSessionData",
1996
+ "setSessionData",
1997
+ "getStorageData",
1998
+ "setStorageData",
1999
+ "removeStorageData",
2000
+ "getLoginUrl"
2001
+ ];
2002
+ const autoInitFunctions = ["renderCoupons"];
2003
+ function executePendingFunctionCalls(client2) {
2004
+ const pendingFunctionCalls = window._ppcs;
2005
+ if (!pendingFunctionCalls) {
2476
2006
  return;
2477
2007
  }
2478
- const data = {
2479
- //url: params.imageUrl,
2480
- //TODO: -> we need to download the imageUrl and try to attach it to `files`
2481
- text: params == null ? void 0 : params.text
2482
- };
2483
- navigator.share(data).then(() => {
2484
- var _a, _b;
2485
- (_a = params == null ? void 0 : params.success) == null ? void 0 : _a.call(params);
2486
- (_b = params == null ? void 0 : params.complete) == null ? void 0 : _b.call(params);
2487
- }).catch(() => {
2488
- var _a, _b;
2489
- (_a = params == null ? void 0 : params.fail) == null ? void 0 : _a.call(params, { errorCode: MiniAppErrorType.unknown });
2490
- (_b = params == null ? void 0 : params.complete) == null ? void 0 : _b.call(params);
2491
- });
2008
+ window._ppcs = void 0;
2009
+ for (const [functionName, params, resolve] of pendingFunctionCalls) {
2010
+ const resultPromise = client2[functionName](params);
2011
+ if (resolve) {
2012
+ resolve(resultPromise);
2013
+ }
2014
+ }
2492
2015
  }
2493
- function setTitle(params) {
2494
- var _a, _b;
2495
- document.title = (params == null ? void 0 : params.title) || "";
2496
- (_a = params == null ? void 0 : params.success) == null ? void 0 : _a.call(params);
2497
- (_b = params == null ? void 0 : params.complete) == null ? void 0 : _b.call(params);
2016
+ const clientProperties = {
2017
+ version: "2.48.0",
2018
+ revision: "765ecbf"
2019
+ };
2020
+ function isInitClientParams(params) {
2021
+ return params.clientId !== void 0;
2498
2022
  }
2499
- function render(params) {
2500
- var _a;
2501
- if (!(params == null ? void 0 : params.containerId) || !document.getElementById(params == null ? void 0 : params.containerId)) {
2502
- (_a = params == null ? void 0 : params.fail) == null ? void 0 : _a.call(params, {
2503
- errorCode: MiniAppErrorType.badRequestInsufficientParameter
2504
- });
2505
- return console.error("Invalid container Id");
2506
- }
2507
- const messageId = functionStart();
2508
- const getRenderMessageHandler = (e) => {
2509
- var _a2, _b, _c;
2510
- if (!checkIFrameOrigin(e.origin) || e.data.name !== PPFunctionName.render || e.data.messageId !== messageId) {
2511
- return;
2512
- }
2513
- const info = (_a2 = e.data) == null ? void 0 : _a2.data;
2514
- const data = (_b = e.data) == null ? void 0 : _b.data;
2515
- if (e.data.result === PPFunctionResult.success) {
2516
- renderButton(data, params);
2517
- if (info.type === "pay" && (data == null ? void 0 : data.isJustLoggedIn) && params.autoInvoke && (data == null ? void 0 : data.isLoggedIn)) {
2518
- triggerPostMessageToCore(PPFunctionName.makePayment, true, params, __spreadValues({}, params.orderInfo));
2023
+ function getClient({
2024
+ sdkType,
2025
+ clientFunctions: clientFunctions2
2026
+ }) {
2027
+ clientSdkType = sdkType;
2028
+ const isSupportedFunction = sdkType === SdkType.MiniApp ? isSupportedMiniapp : isSupportedSmartpayment;
2029
+ const client2 = new Proxy(
2030
+ __spreadProps(__spreadValues({}, clientFunctions2), { init }),
2031
+ {
2032
+ get(target, prop) {
2033
+ if (prop in clientProperties) {
2034
+ return clientProperties[prop];
2035
+ }
2036
+ const functionName = prop;
2037
+ if (!isSupportedFunction(functionName)) {
2038
+ throw new Error(
2039
+ `${functionName} is not supported by ${sdkType} JS SDK`
2040
+ );
2041
+ }
2042
+ function callSdkFunction(params) {
2043
+ return __async(this, null, function* () {
2044
+ var _a, _b;
2045
+ if (!initExemptedFunctions.includes(functionName) && !(yield initDonePromise)) {
2046
+ if (autoInitFunctions.includes(functionName) && isInitClientParams(params)) {
2047
+ init({
2048
+ clientId: params.clientId,
2049
+ env: params.env
2050
+ });
2051
+ yield initDonePromise;
2052
+ } else {
2053
+ (_a = params.fail) == null ? void 0 : _a.call(params, {
2054
+ errorCode: MiniAppErrorType.sdkNotInitialized
2055
+ });
2056
+ (_b = params.complete) == null ? void 0 : _b.call(params);
2057
+ return;
2058
+ }
2059
+ }
2060
+ const fn = target[functionName];
2061
+ if (fn && isFunction(fn)) {
2062
+ return fn(params);
2063
+ }
2064
+ triggerPostMessageToCore(
2065
+ prop,
2066
+ false,
2067
+ params,
2068
+ params
2069
+ );
2070
+ });
2071
+ }
2072
+ return callbackToPromise(callSdkFunction, functionName);
2519
2073
  }
2520
2074
  }
2521
- if (e.data.result === PPFunctionResult.fail) {
2522
- (_c = params == null ? void 0 : params.fail) == null ? void 0 : _c.call(params, e.data.data);
2523
- }
2524
- if (e.data.result === PPFunctionResult.complete) {
2525
- functionEnd(e.data.messageId);
2526
- removeEventListener("message", getRenderMessageHandler);
2527
- }
2528
- };
2529
- addEventListener("message", getRenderMessageHandler);
2530
- void postMessageToCore({
2531
- name: PPFunctionName.render,
2532
- params: __spreadProps(__spreadValues({}, params), {
2533
- redirectUrl: params.redirectUrl || window.location.href
2534
- }),
2535
- messageId
2536
- });
2075
+ );
2076
+ window._pp = client2;
2077
+ executePendingFunctionCalls(client2);
2078
+ return client2;
2079
+ }
2080
+ function copyToClipboard(params) {
2081
+ var _a, _b, _c;
2082
+ const textarea = document.createElement("textarea");
2083
+ textarea.setAttribute("readonly", "true");
2084
+ textarea.setAttribute("contenteditable", "true");
2085
+ textarea.value = params.value;
2086
+ document.body.appendChild(textarea);
2087
+ textarea.select();
2088
+ textarea.setSelectionRange(0, textarea.value.length);
2089
+ const result = document.execCommand("copy");
2090
+ document.body.removeChild(textarea);
2091
+ if (result) {
2092
+ (_a = params == null ? void 0 : params.success) == null ? void 0 : _a.call(params);
2093
+ } else {
2094
+ (_b = params == null ? void 0 : params.fail) == null ? void 0 : _b.call(params, { errorCode: MiniAppErrorType.other });
2095
+ }
2096
+ (_c = params.complete) == null ? void 0 : _c.call(params);
2097
+ }
2098
+ promiseToCallback(
2099
+ "getLoginUrl",
2100
+ coreFunctions.getLoginUrl
2101
+ );
2102
+ const getPaymentSettings = promiseToCallback(
2103
+ "getPaymentSettings",
2104
+ coreFunctions.getPaymentSettings
2105
+ );
2106
+ const markAsReady = promiseToCallback(
2107
+ "markAsReady",
2108
+ coreFunctions.markAsReady
2109
+ );
2110
+ function getKycPassportInfo(params) {
2111
+ const url = window.location.href;
2112
+ triggerPostMessageToCore(PPFunctionName.getKycPassportInfo, false, params, __spreadProps(__spreadValues({}, params), {
2113
+ url
2114
+ }));
2537
2115
  }
2116
+ var MiniAppStatusType = /* @__PURE__ */ ((MiniAppStatusType2) => {
2117
+ MiniAppStatusType2["validToken"] = "TOKEN_VALID";
2118
+ MiniAppStatusType2["initialized"] = "INITIALIZED";
2119
+ MiniAppStatusType2["emailRegistered"] = "EMAIL_REGISTERED";
2120
+ MiniAppStatusType2["emailNotVerified"] = "EMAIL_NOT_VERIFIED";
2121
+ MiniAppStatusType2["success"] = "SUCCESS";
2122
+ MiniAppStatusType2["loggedOut"] = "LOGGED_OUT";
2123
+ MiniAppStatusType2["connected"] = "CONNECTED";
2124
+ return MiniAppStatusType2;
2125
+ })(MiniAppStatusType || {});
2126
+ const logout = promiseToCallback("logout", () => __async(void 0, null, function* () {
2127
+ try {
2128
+ yield coreFunctions.logout();
2129
+ return { statusCode: MiniAppStatusType.loggedOut };
2130
+ } catch (error) {
2131
+ throw new PPError(
2132
+ `An error ocurred while trying to logout the user, error=${error}`,
2133
+ MiniAppErrorType.unknown
2134
+ );
2135
+ }
2136
+ }));
2538
2137
  const renderCoupons = promiseToCallback(
2539
2138
  "renderCoupons",
2540
2139
  (params) => __async(void 0, null, function* () {
@@ -2553,7 +2152,7 @@ const renderCoupons = promiseToCallback(
2553
2152
  MiniAppErrorType.badRequestInsufficientParameter
2554
2153
  );
2555
2154
  }
2556
- const coupons = yield core.fetchCoupons({
2155
+ const coupons = yield coreFunctions.fetchCoupons({
2557
2156
  merchantId,
2558
2157
  couponId,
2559
2158
  postLoginRedirectUrl,
@@ -2565,7 +2164,7 @@ const renderCoupons = promiseToCallback(
2565
2164
  iframeElement.style.cssText = "width:100%;height: 0;border: none;transition: height 300ms ease-in;display: block;";
2566
2165
  yield new Promise((resolve, reject) => {
2567
2166
  iframeElement.onload = () => resolve(true);
2568
- iframeElement.onerror = () => reject(false);
2167
+ iframeElement.onerror = () => reject(new Error("Failed to load coupon iframe"));
2569
2168
  containerElement.innerHTML = "";
2570
2169
  containerElement.append(iframeElement);
2571
2170
  });
@@ -2597,7 +2196,6 @@ const renderCoupons = promiseToCallback(
2597
2196
  );
2598
2197
  }
2599
2198
  }),
2600
- getCore,
2601
2199
  (params) => ({
2602
2200
  event_label2: params.couponId,
2603
2201
  merchant_id: params.merchant
@@ -2615,6 +2213,32 @@ function scanCode(params) {
2615
2213
  scanCodeParams
2616
2214
  );
2617
2215
  }
2216
+ function setTitle(params) {
2217
+ var _a, _b, _c;
2218
+ document.title = (_a = params == null ? void 0 : params.title) != null ? _a : "";
2219
+ (_b = params == null ? void 0 : params.success) == null ? void 0 : _b.call(params);
2220
+ (_c = params == null ? void 0 : params.complete) == null ? void 0 : _c.call(params);
2221
+ }
2222
+ function share(params) {
2223
+ if (!(navigator == null ? void 0 : navigator.share)) {
2224
+ triggerPostMessageToCore(PPFunctionName.share, false, params, params);
2225
+ return;
2226
+ }
2227
+ const data = {
2228
+ //url: params.imageUrl,
2229
+ //TODO: -> we need to download the imageUrl and try to attach it to `files`
2230
+ text: params == null ? void 0 : params.text
2231
+ };
2232
+ navigator.share(data).then(() => {
2233
+ var _a, _b;
2234
+ (_a = params == null ? void 0 : params.success) == null ? void 0 : _a.call(params);
2235
+ (_b = params == null ? void 0 : params.complete) == null ? void 0 : _b.call(params);
2236
+ }).catch(() => {
2237
+ var _a, _b;
2238
+ (_a = params == null ? void 0 : params.fail) == null ? void 0 : _a.call(params, { errorCode: MiniAppErrorType.unknown });
2239
+ (_b = params == null ? void 0 : params.complete) == null ? void 0 : _b.call(params);
2240
+ });
2241
+ }
2618
2242
  function getSessionData(params) {
2619
2243
  var _a, _b;
2620
2244
  const value = sessionStorage.getItem(params == null ? void 0 : params.key);
@@ -2645,199 +2269,19 @@ function removeStorageData(params) {
2645
2269
  (_a = params == null ? void 0 : params.success) == null ? void 0 : _a.call(params);
2646
2270
  (_b = params == null ? void 0 : params.complete) == null ? void 0 : _b.call(params);
2647
2271
  }
2648
- const logout = promiseToCallback(
2649
- "logout",
2650
- () => __async(void 0, null, function* () {
2651
- try {
2652
- yield core.logout();
2653
- return { statusCode: MiniAppStatusType.loggedOut };
2654
- } catch (error) {
2655
- throw new PPError(
2656
- `An error ocurred while trying to logout the user, error=${error}`,
2657
- MiniAppErrorType.unknown
2658
- );
2659
- }
2660
- }),
2661
- getCore
2662
- );
2663
- const getPaymentSettings = promiseToCallback(
2664
- "getPaymentSettings",
2665
- core.getPaymentSettings,
2666
- getCore
2667
- );
2668
- const getLoginUrl = promiseToCallback(
2669
- "getLoginUrl",
2670
- (params) => {
2671
- return core.getLoginUrl({
2672
- redirectUrl: params.redirectUrl || location.href,
2673
- redirectType: params.redirectType
2674
- });
2675
- },
2676
- getCore
2677
- );
2678
- function copyToClipboard(params) {
2679
- var _a, _b, _c;
2680
- const textarea = document.createElement("textarea");
2681
- textarea.setAttribute("readonly", "true");
2682
- textarea.setAttribute("contenteditable", "true");
2683
- textarea.value = params.value;
2684
- document.body.appendChild(textarea);
2685
- textarea.select();
2686
- textarea.setSelectionRange(0, textarea.value.length);
2687
- const result = document.execCommand("copy");
2688
- document.body.removeChild(textarea);
2689
- result ? (_a = params == null ? void 0 : params.success) == null ? void 0 : _a.call(params) : (_b = params == null ? void 0 : params.fail) == null ? void 0 : _b.call(params, { errorCode: MiniAppErrorType.other });
2690
- (_c = params.complete) == null ? void 0 : _c.call(params);
2691
- }
2692
- function receiveMessageFromIframe(messageData, params, eventHandler) {
2693
- var _a, _b, _c;
2694
- if (messageData.result === PPFunctionResult.fail) {
2695
- (_a = params == null ? void 0 : params.fail) == null ? void 0 : _a.call(params, messageData.data);
2696
- }
2697
- if (messageData.result === PPFunctionResult.success) {
2698
- (_b = params == null ? void 0 : params.success) == null ? void 0 : _b.call(params, messageData == null ? void 0 : messageData.data);
2699
- }
2700
- if (messageData.result === PPFunctionResult.complete) {
2701
- (_c = params == null ? void 0 : params.complete) == null ? void 0 : _c.call(params);
2702
- removeEventListener("message", eventHandler);
2703
- functionEnd(messageData.messageId);
2704
- if (!isFunctionRunning()) {
2705
- showCoreIframe(false);
2706
- }
2707
- }
2708
- }
2709
- function postMessageToCore(messageData) {
2710
- return __async(this, null, function* () {
2711
- var _a;
2712
- const iframe = yield getCoreIframe().catch(() => void 0);
2713
- (_a = iframe == null ? void 0 : iframe.contentWindow) == null ? void 0 : _a.postMessage(
2714
- JSON.parse(JSON.stringify(messageData)),
2715
- CORE_IFRAME_ORIGIN
2716
- );
2717
- });
2718
- }
2719
- function triggerPostMessageToCore(type, showIframeFlag, params, postMessageParams) {
2720
- const messageId = functionStart();
2721
- if (showIframeFlag) {
2722
- showCoreIframe(true);
2723
- }
2724
- const fnMessageHandler = (e) => {
2725
- if (!checkIFrameOrigin(e.origin)) {
2726
- return;
2727
- }
2728
- if (e.data.name === type) {
2729
- if (e.data.messageId === messageId) {
2730
- receiveMessageFromIframe(e.data, params, fnMessageHandler);
2731
- }
2732
- }
2733
- };
2734
- addEventListener("message", fnMessageHandler);
2735
- void postMessageToCore({
2736
- name: type,
2737
- params: postMessageParams,
2738
- messageId
2739
- });
2740
- }
2741
- function renderButton(data, params) {
2742
- var _a, _b, _c, _d, _e, _f, _g;
2743
- const container = document.getElementById(params.containerId);
2744
- const button = document.createElement("button");
2745
- button.className = "ppmna-reset-css pp-smartButtonWrapper pp-button";
2746
- const iconUrl = getIconUrl(params == null ? void 0 : params.theme);
2747
- const cashbackClass = ((_b = (_a = data == null ? void 0 : data.data) == null ? void 0 : _a.cashbackInfo) == null ? void 0 : _b.length) ? "pp-cashback" : "";
2748
- const shortTextClass = params.isShortText ? "pp-shortText" : "";
2749
- const buttonSize = (_c = params == null ? void 0 : params.buttonSize) != null ? _c : "lg";
2750
- const theme = (_d = params == null ? void 0 : params.theme) != null ? _d : "light";
2751
- const aTag = document.createElement("a");
2752
- aTag.className = `pp-smartBtn pp-${theme} pp-${buttonSize} pp-${convertToString(
2753
- params.type
2754
- )} pp-${data.preferredLanguage} ${cashbackClass} ${shortTextClass}`;
2755
- aTag.href = convertToString(data.data.loginUrl);
2756
- const leftSpan = document.createElement("span");
2757
- leftSpan.className = "pp-leftSection";
2758
- const iconImg = document.createElement("img");
2759
- iconImg.className = "pp-img";
2760
- iconImg.src = iconUrl;
2761
- iconImg.alt = "";
2762
- leftSpan.appendChild(iconImg);
2763
- const btnSpan = document.createElement("span");
2764
- btnSpan.className = "pp-btnContent";
2765
- const titleSpan = document.createElement("span");
2766
- titleSpan.className = "pp-title";
2767
- titleSpan.innerText = (_e = data == null ? void 0 : data.data) == null ? void 0 : _e.title;
2768
- btnSpan.appendChild(titleSpan);
2769
- leftSpan.appendChild(btnSpan);
2770
- aTag.append(leftSpan);
2771
- const cashbackSpan = document.createElement("span");
2772
- if ((_f = data == null ? void 0 : data.data) == null ? void 0 : _f.cashbackInfo) {
2773
- cashbackSpan.className = "pp-cashbackInfo";
2774
- cashbackSpan.innerText = (_g = data == null ? void 0 : data.data) == null ? void 0 : _g.cashbackInfo;
2775
- btnSpan.append(cashbackSpan);
2776
- }
2777
- if (data.data.avatarUrl) {
2778
- const avatarImg = document.createElement("img");
2779
- avatarImg.className = "pp-userProfile";
2780
- avatarImg.src = data.data.avatarUrl;
2781
- avatarImg.addEventListener("error", function(e) {
2782
- var _a2;
2783
- const el = e.target;
2784
- (_a2 = el == null ? void 0 : el.parentNode) == null ? void 0 : _a2.removeChild(el);
2785
- });
2786
- aTag.append(avatarImg);
2787
- }
2788
- button.append(aTag);
2789
- if (container) {
2790
- container.innerHTML = "";
2791
- container.appendChild(button);
2792
- if (params.type === "pay" && (data == null ? void 0 : data.isLoggedIn)) {
2793
- button.addEventListener("click", (e) => {
2794
- var _a2;
2795
- e.preventDefault();
2796
- if (params == null ? void 0 : params.callback) {
2797
- (_a2 = params == null ? void 0 : params.callback) == null ? void 0 : _a2.call(params);
2798
- } else if (params.orderInfo) {
2799
- triggerPostMessageToCore(PPFunctionName.makePayment, true, params, __spreadValues({}, params.orderInfo));
2800
- }
2801
- });
2802
- }
2803
- }
2272
+ function verifyMultiFactorAuthResult(params) {
2273
+ const url = new URL(window.location.href);
2274
+ triggerPostMessageToCore(
2275
+ PPFunctionName.verifyMultiFactorAuthResult,
2276
+ false,
2277
+ params,
2278
+ __spreadProps(__spreadValues({}, params), { sessionId: url.searchParams.get("ppSessionId") })
2279
+ );
2804
2280
  }
2805
- const markAsReady = promiseToCallback(
2806
- "markAsReady",
2807
- () => __async(void 0, null, function* () {
2808
- if (checkVersion(MinVersion.PERFORMANCE_MEASUREMENT)) {
2809
- window.location.href = "paypay://miniappPerformance/ready";
2810
- }
2811
- yield core.markAsReady();
2812
- }),
2813
- getCore
2814
- );
2815
- const clientJsBridge = {
2816
- _handleMessageFromNative: (json) => {
2817
- void getCoreIframe().then((iframe) => {
2818
- var _a;
2819
- (_a = iframe == null ? void 0 : iframe.contentWindow) == null ? void 0 : _a.postMessage(
2820
- JSON.parse(
2821
- JSON.stringify({
2822
- name: PPFunctionName.handleMessageFromNative,
2823
- params: {
2824
- json
2825
- }
2826
- })
2827
- ),
2828
- CORE_IFRAME_ORIGIN
2829
- );
2830
- });
2831
- }
2832
- };
2833
- exposeClientJsBridge(clientJsBridge);
2834
2281
  const clientFunctions = {
2835
- // functions that run on client, or need special treatment on client
2836
- init,
2837
2282
  verifyMultiFactorAuthResult,
2838
2283
  share,
2839
2284
  setTitle,
2840
- render,
2841
2285
  renderCoupons,
2842
2286
  scanCode,
2843
2287
  copyToClipboard,
@@ -2849,81 +2293,9 @@ const clientFunctions = {
2849
2293
  getKycPassportInfo,
2850
2294
  logout,
2851
2295
  getPaymentSettings,
2852
- getLoginUrl,
2853
2296
  markAsReady
2854
2297
  };
2855
- const initExemptedFunctions = [
2856
- "init",
2857
- "setTitle",
2858
- "copyToClipboard",
2859
- "getSessionData",
2860
- "setSessionData",
2861
- "getStorageData",
2862
- "setStorageData",
2863
- "removeStorageData",
2864
- "getLoginUrl"
2865
- ];
2866
- const autoInitFunctions = ["renderCoupons"];
2867
- function executePendingFunctionCalls(client2) {
2868
- const pendingFunctionCalls = window._ppcs;
2869
- if (!pendingFunctionCalls) {
2870
- return;
2871
- }
2872
- window._ppcs = void 0;
2873
- for (const [functionName, params] of pendingFunctionCalls) {
2874
- client2[functionName](params);
2875
- }
2876
- }
2877
- const clientProperties = {
2878
- version: "2.41.0",
2879
- revision: "86fe469"
2880
- };
2881
- function getClient({ sdkType }) {
2882
- clientSdkType = sdkType;
2883
- const isSupportedFunction = sdkType === SdkType.MiniApp ? isSupportedMiniapp : isSupportedSmartpayment;
2884
- const proxy = new Proxy(clientFunctions, {
2885
- get(target, prop) {
2886
- if (prop in clientProperties) {
2887
- return clientProperties[prop];
2888
- }
2889
- const functionName = prop;
2890
- if (!useAllFunctions) {
2891
- if (!isSupportedFunction(functionName)) {
2892
- throw new Error(
2893
- `${functionName} is not supported by ${sdkType} JS SDK`
2894
- );
2895
- }
2896
- }
2897
- return (params) => __async(this, null, function* () {
2898
- var _a, _b;
2899
- if (!initExemptedFunctions.includes(functionName) && !(yield initDonePromise)) {
2900
- if (autoInitFunctions.includes(functionName) && params.clientId) {
2901
- init({ clientId: params.clientId, env: params.env });
2902
- yield initDonePromise;
2903
- } else {
2904
- (_a = params.fail) == null ? void 0 : _a.call(params, { errorCode: MiniAppErrorType.sdkNotInitialized });
2905
- (_b = params.complete) == null ? void 0 : _b.call(params);
2906
- return;
2907
- }
2908
- }
2909
- if (Object.prototype.hasOwnProperty.call(target, functionName)) {
2910
- return target[functionName](params);
2911
- }
2912
- triggerPostMessageToCore(
2913
- prop,
2914
- false,
2915
- params,
2916
- params
2917
- );
2918
- });
2919
- }
2920
- });
2921
- const client2 = proxy;
2922
- window._pp = client2;
2923
- executePendingFunctionCalls(client2);
2924
- return client2;
2925
- }
2926
- const client = getClient({ sdkType: SdkType.MiniApp });
2298
+ const client = getClient({ sdkType: SdkType.MiniApp, clientFunctions });
2927
2299
  const miniAppSdk = client;
2928
2300
  export {
2929
2301
  miniAppSdk as default