@formo/analytics 1.35.1 → 1.36.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 (95) hide show
  1. package/dist/cjs/src/FormoAnalytics.d.ts +90 -240
  2. package/dist/cjs/src/FormoAnalytics.js +432 -1840
  3. package/dist/cjs/src/constants/base.d.ts +0 -1
  4. package/dist/cjs/src/constants/base.js +1 -3
  5. package/dist/cjs/src/event/EventFactory.js +1 -1
  6. package/dist/cjs/src/event/EventManager.d.ts +3 -1
  7. package/dist/cjs/src/event/EventManager.js +5 -1
  8. package/dist/cjs/src/event/type.d.ts +1 -0
  9. package/dist/cjs/src/evm/EvmEventTracker.d.ts +175 -0
  10. package/dist/cjs/src/evm/EvmEventTracker.js +1030 -0
  11. package/dist/cjs/src/evm/EvmProviderRegistry.d.ts +132 -0
  12. package/dist/cjs/src/evm/EvmProviderRegistry.js +348 -0
  13. package/dist/cjs/src/evm/EvmRequestTracker.d.ts +120 -0
  14. package/dist/cjs/src/evm/EvmRequestTracker.js +756 -0
  15. package/dist/cjs/src/queue/EventQueue.d.ts +28 -0
  16. package/dist/cjs/src/queue/EventQueue.js +97 -19
  17. package/dist/cjs/src/queue/type.d.ts +1 -0
  18. package/dist/cjs/src/tracking/TrackingPolicy.d.ts +146 -0
  19. package/dist/cjs/src/tracking/TrackingPolicy.js +200 -0
  20. package/dist/cjs/src/utils/mergeDeepRight.d.ts +22 -0
  21. package/dist/cjs/src/utils/mergeDeepRight.js +54 -0
  22. package/dist/cjs/src/validators/address.d.ts +1 -1
  23. package/dist/cjs/src/version.d.ts +1 -1
  24. package/dist/cjs/src/version.js +1 -1
  25. package/dist/cjs/src/wagmi/WagmiEventHandler.d.ts +193 -1
  26. package/dist/cjs/src/wagmi/WagmiEventHandler.js +1317 -77
  27. package/dist/cjs/src/wagmi/types.d.ts +6 -0
  28. package/dist/cjs/src/wallet/WalletStateStore.d.ts +223 -0
  29. package/dist/cjs/src/wallet/WalletStateStore.js +515 -0
  30. package/dist/esm/src/FormoAnalytics.d.ts +90 -240
  31. package/dist/esm/src/FormoAnalytics.js +433 -1841
  32. package/dist/esm/src/constants/base.d.ts +0 -1
  33. package/dist/esm/src/constants/base.js +0 -2
  34. package/dist/esm/src/event/EventFactory.js +1 -1
  35. package/dist/esm/src/event/EventManager.d.ts +3 -1
  36. package/dist/esm/src/event/EventManager.js +5 -1
  37. package/dist/esm/src/event/type.d.ts +1 -0
  38. package/dist/esm/src/evm/EvmEventTracker.d.ts +175 -0
  39. package/dist/esm/src/evm/EvmEventTracker.js +1027 -0
  40. package/dist/esm/src/evm/EvmProviderRegistry.d.ts +132 -0
  41. package/dist/esm/src/evm/EvmProviderRegistry.js +345 -0
  42. package/dist/esm/src/evm/EvmRequestTracker.d.ts +120 -0
  43. package/dist/esm/src/evm/EvmRequestTracker.js +753 -0
  44. package/dist/esm/src/queue/EventQueue.d.ts +28 -0
  45. package/dist/esm/src/queue/EventQueue.js +97 -19
  46. package/dist/esm/src/queue/type.d.ts +1 -0
  47. package/dist/esm/src/tracking/TrackingPolicy.d.ts +146 -0
  48. package/dist/esm/src/tracking/TrackingPolicy.js +197 -0
  49. package/dist/esm/src/utils/mergeDeepRight.d.ts +22 -0
  50. package/dist/esm/src/utils/mergeDeepRight.js +51 -0
  51. package/dist/esm/src/version.d.ts +1 -1
  52. package/dist/esm/src/version.js +1 -1
  53. package/dist/esm/src/wagmi/WagmiEventHandler.d.ts +193 -1
  54. package/dist/esm/src/wagmi/WagmiEventHandler.js +1315 -76
  55. package/dist/esm/src/wagmi/types.d.ts +6 -0
  56. package/dist/esm/src/wallet/WalletStateStore.d.ts +223 -0
  57. package/dist/esm/src/wallet/WalletStateStore.js +512 -0
  58. package/dist/index.umd.min.js +1 -1
  59. package/package.json +5 -13
  60. package/dist/cjs/src/ramda/internal/_curry1.d.ts +0 -10
  61. package/dist/cjs/src/ramda/internal/_curry1.js +0 -26
  62. package/dist/cjs/src/ramda/internal/_curry2.d.ts +0 -10
  63. package/dist/cjs/src/ramda/internal/_curry2.js +0 -43
  64. package/dist/cjs/src/ramda/internal/_curry3.d.ts +0 -10
  65. package/dist/cjs/src/ramda/internal/_curry3.js +0 -74
  66. package/dist/cjs/src/ramda/internal/_has.d.ts +0 -2
  67. package/dist/cjs/src/ramda/internal/_has.js +0 -7
  68. package/dist/cjs/src/ramda/internal/_isObject.d.ts +0 -2
  69. package/dist/cjs/src/ramda/internal/_isObject.js +0 -7
  70. package/dist/cjs/src/ramda/internal/_isPlaceholder.d.ts +0 -2
  71. package/dist/cjs/src/ramda/internal/_isPlaceholder.js +0 -7
  72. package/dist/cjs/src/ramda/mergeDeepRight.d.ts +0 -3
  73. package/dist/cjs/src/ramda/mergeDeepRight.js +0 -14
  74. package/dist/cjs/src/ramda/mergeDeepWithKey.d.ts +0 -3
  75. package/dist/cjs/src/ramda/mergeDeepWithKey.js +0 -20
  76. package/dist/cjs/src/ramda/mergeWithKey.d.ts +0 -3
  77. package/dist/cjs/src/ramda/mergeWithKey.js +0 -26
  78. package/dist/esm/src/ramda/internal/_curry1.d.ts +0 -10
  79. package/dist/esm/src/ramda/internal/_curry1.js +0 -20
  80. package/dist/esm/src/ramda/internal/_curry2.d.ts +0 -10
  81. package/dist/esm/src/ramda/internal/_curry2.js +0 -37
  82. package/dist/esm/src/ramda/internal/_curry3.d.ts +0 -10
  83. package/dist/esm/src/ramda/internal/_curry3.js +0 -68
  84. package/dist/esm/src/ramda/internal/_has.d.ts +0 -2
  85. package/dist/esm/src/ramda/internal/_has.js +0 -4
  86. package/dist/esm/src/ramda/internal/_isObject.d.ts +0 -2
  87. package/dist/esm/src/ramda/internal/_isObject.js +0 -4
  88. package/dist/esm/src/ramda/internal/_isPlaceholder.d.ts +0 -2
  89. package/dist/esm/src/ramda/internal/_isPlaceholder.js +0 -4
  90. package/dist/esm/src/ramda/mergeDeepRight.d.ts +0 -3
  91. package/dist/esm/src/ramda/mergeDeepRight.js +0 -9
  92. package/dist/esm/src/ramda/mergeDeepWithKey.d.ts +0 -3
  93. package/dist/esm/src/ramda/mergeDeepWithKey.js +0 -15
  94. package/dist/esm/src/ramda/mergeWithKey.d.ts +0 -3
  95. package/dist/esm/src/ramda/mergeWithKey.js +0 -21
@@ -45,29 +45,20 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
45
45
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46
46
  }
47
47
  };
48
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
49
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
50
- if (ar || !(i in from)) {
51
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
52
- ar[i] = from[i];
53
- }
54
- }
55
- return to.concat(ar || Array.prototype.slice.call(from));
56
- };
57
- import { createStore } from "mipd";
58
- import { EVENTS_API_HOST, EventType, LOCAL_ANONYMOUS_ID_KEY, SESSION_USER_ID_KEY, SESSION_TRAFFIC_SOURCE_KEY, ACTIVE_WALLET_KEY, ACTIVE_WALLET_TTL_MS, CONSENT_OPT_OUT_KEY, } from "./constants";
48
+ import { EVENTS_API_HOST, EventType, LOCAL_ANONYMOUS_ID_KEY, SESSION_USER_ID_KEY, SESSION_TRAFFIC_SOURCE_KEY, ACTIVE_WALLET_KEY, CONSENT_OPT_OUT_KEY, } from "./constants";
59
49
  import { cookie, session, initStorageManager } from "./storage";
60
50
  import { getIdentityCookieDomain, getIdentityCookieSecurity, } from "./storage/cookiePolicy";
61
51
  import { EventManager } from "./event";
62
52
  import { EventQueue } from "./queue";
63
53
  import { logger, Logger } from "./logger";
64
54
  import { setConsentFlag, getConsentFlag, removeConsentFlag, } from "./consent";
65
- import { detectInjectedProviderInfo, isValidProvider } from "./provider";
66
55
  import { FormoAnalyticsSession, SESSION_WALLET_DETECTED_KEY, SESSION_WALLET_IDENTIFIED_KEY, } from "./session";
67
- import { SignatureStatus, TransactionStatus, WRAPPED_REQUEST_SYMBOL, WRAPPED_REQUEST_REF_SYMBOL, } from "./types";
68
56
  import { validateAddress, validateAndChecksumAddress } from "./utils/address";
69
- import { getTimezone } from "./utils/timezone";
70
- import { isLocalhost } from "./validators";
57
+ import { TrackingPolicy, } from "./tracking/TrackingPolicy";
58
+ import { WalletStateStore } from "./wallet/WalletStateStore";
59
+ import { EvmProviderRegistry } from "./evm/EvmProviderRegistry";
60
+ import { EvmEventTracker } from "./evm/EvmEventTracker";
61
+ import { EvmRequestTracker } from "./evm/EvmRequestTracker";
71
62
  import { parseChainId } from "./utils/chain";
72
63
  import { WagmiEventHandler } from "./wagmi";
73
64
  import { isSolanaChainId } from "./solana";
@@ -77,11 +68,6 @@ import { identifyPrivyUser } from "./privy/utils";
77
68
  /**
78
69
  * Constants for provider switching reasons
79
70
  */
80
- var PROVIDER_SWITCH_REASONS = {
81
- ADDRESS_MISMATCH: "Address mismatch indicates wallet switch",
82
- NO_ACCOUNTS: "Current provider has no accounts",
83
- CHECK_FAILED: "Could not check current provider accounts",
84
- };
85
71
  var FormoAnalytics = /** @class */ (function () {
86
72
  function FormoAnalytics(writeKey, options) {
87
73
  if (options === void 0) { options = {}; }
@@ -89,30 +75,7 @@ var FormoAnalytics = /** @class */ (function () {
89
75
  var _a, _b, _c;
90
76
  this.writeKey = writeKey;
91
77
  this.options = options;
92
- // Per-chain namespace state - isolates EVM and Solana connection state
93
- this._chainState = {
94
- evm: {},
95
- solana: {},
96
- };
97
- this._providerListenersMap = new Map();
98
- /**
99
- * EIP-6963 provider details discovered through the browser
100
- * This array contains all available providers with their metadata
101
- */
102
- this._providers = [];
103
- /**
104
- * Set of providers that have been tracked with event listeners
105
- * This is separate from _providers because:
106
- * - _providers contains all discovered providers (EIP-6963)
107
- * - _trackedProviders contains only providers that have been set up with listeners
108
- * - A provider can be discovered but not yet tracked (e.g., during initialization)
109
- * - A provider can be tracked but later removed from discovery
110
- */
111
- this._trackedProviders = new Set();
112
- // Flag to prevent concurrent processing of accountsChanged events
113
- this._processingAccountsChanged = false;
114
- // Set to efficiently track seen providers for deduplication and O(1) lookup
115
- this._seenProviders = new Set();
78
+ this._announcedConnect = new WeakMap();
116
79
  /**
117
80
  * Flag indicating if Wagmi mode is enabled
118
81
  * When true, EIP-1193 provider wrapping is skipped
@@ -165,6 +128,68 @@ var FormoAnalytics = /** @class */ (function () {
165
128
  enabled: ((_b = options.logger) === null || _b === void 0 ? void 0 : _b.enabled) || false,
166
129
  enabledLevels: ((_c = options.logger) === null || _c === void 0 ? void 0 : _c.levels) || [],
167
130
  });
131
+ this.evm = new EvmProviderRegistry({
132
+ activeProvider: function () { return _this.wallet.provider; },
133
+ activeChainId: function () { return _this.wallet.evmChainId; },
134
+ knownEvmAddress: function () { return _this.wallet.evmAddress; },
135
+ // Whether central state should follow a provider's chain report is the
136
+ // SDK's call, not the registry's: it depends on which namespace is
137
+ // active. Recording it per provider is unconditional; syncing is not.
138
+ onChainObserved: function (provider, chainId) {
139
+ // Guarded on EVM already being active. `set()` makes whichever
140
+ // namespace it touches active, so syncing unconditionally let a
141
+ // background EVM wallet's chain report steal the slot from a live
142
+ // Solana wallet, and every later page or track event was attributed
143
+ // to the wrong wallet entirely.
144
+ if (provider === _this.wallet.provider &&
145
+ _this.wallet.activeNamespace === "evm" &&
146
+ _this.wallet.evmChainId !== chainId) {
147
+ _this.wallet.set("evm", { chainId: chainId });
148
+ }
149
+ },
150
+ });
151
+ this.wallet = new WalletStateStore({
152
+ isPersistedIdentityPurgeRequired: function () {
153
+ return _this.trackingPolicy.isPersistedIdentityPurgeRequired();
154
+ },
155
+ isPageExcluded: function () { return _this.trackingPolicy.isPageExcluded(); },
156
+ isTrackingSuppressed: function () { return _this.trackingPolicy.isTrackingSuppressed(); },
157
+ crossSubdomainCookies: function () { return _this.crossSubdomainCookies; },
158
+ providerChainId: function (provider) { return _this.evm.chainIdOf(provider); },
159
+ // A provider that stops being active has, from this SDK's point of
160
+ // view, ended its connection, so the connect it reported must stop
161
+ // counting. Otherwise toggling between two installed wallets silently
162
+ // loses every connect after the first.
163
+ onProviderDisplaced: function (previous) {
164
+ return _this.evmEvents.forgetAnnouncedConnect(previous);
165
+ },
166
+ });
167
+ this.evmRequests = new EvmRequestTracker(this.wallet, this.evm, {
168
+ isAutocaptureEnabled: function (t) { return _this.isAutocaptureEnabled(t); },
169
+ signature: function (params, properties) { return _this.signature(params, properties); },
170
+ transaction: function (params, properties) { return _this.transaction(params, properties); },
171
+ });
172
+ this.evmEvents = new EvmEventTracker(this.wallet, this.evm, {
173
+ isAutocaptureEnabled: function (t) { return _this.isAutocaptureEnabled(t); },
174
+ isTrackingSuppressed: function () { return _this.isTrackingSuppressed(); },
175
+ willTrackEvent: function (chainId) { return _this.willTrackEvent(chainId); },
176
+ isWagmiMode: function () { return _this.isWagmiMode; },
177
+ connect: function (params, properties) { return _this.connect(params, properties); },
178
+ disconnect: function (params) { return _this.disconnect(params); },
179
+ chain: function (params, properties) { return _this.chain(params, properties); },
180
+ detect: function (params) { return _this.detect(params); },
181
+ registerRequestListeners: function (provider) {
182
+ return _this.evmRequests.registerRequestListeners(provider);
183
+ },
184
+ });
185
+ this.trackingPolicy = new TrackingPolicy({
186
+ // All three read lazily. `options` is public and mutable, and the
187
+ // central chain moves as wallets connect and switch, so the policy
188
+ // must see both at decision time rather than at construction.
189
+ options: function () { return _this.options; },
190
+ hasOptedOut: function () { return _this.hasOptedOutTracking(); },
191
+ currentChainId: function () { return _this.currentChainId; },
192
+ });
168
193
  this.eventManager = new EventManager(new EventQueue(this.config.writeKey, {
169
194
  apiHost: options.apiHost || EVENTS_API_HOST,
170
195
  flushAt: options.flushAt,
@@ -200,7 +225,7 @@ var FormoAnalytics = /** @class */ (function () {
200
225
  provider = window.ethereum;
201
226
  }
202
227
  if (provider) {
203
- this.trackEIP1193Provider(provider);
228
+ this.evmEvents.trackEIP1193Provider(provider);
204
229
  }
205
230
  }
206
231
  // Initialize Solana manager if Solana options are provided
@@ -211,51 +236,73 @@ var FormoAnalytics = /** @class */ (function () {
211
236
  // Seed currentAddress/currentChainId from the persisted snapshot before
212
237
  // the first page hit queues so reload-time track()/page() carry the
213
238
  // wallet even before wagmi/EIP-1193 reconnection completes.
214
- this.loadActiveWallet();
239
+ this.wallet.load();
215
240
  this.trackPageHit();
216
241
  this.trackPageHits();
217
242
  }
218
243
  Object.defineProperty(FormoAnalytics.prototype, "_provider", {
219
- // EVM state accessors - EVM listener paths must use these instead of
220
- // currentAddress/currentChainId to avoid cross-namespace reads.
221
244
  get: function () {
222
- return this._chainState.evm.provider;
245
+ return this.wallet.provider;
223
246
  },
224
247
  set: function (value) {
225
- this._chainState.evm.provider = value;
248
+ this.wallet.provider = value;
226
249
  },
227
250
  enumerable: false,
228
251
  configurable: true
229
252
  });
230
253
  Object.defineProperty(FormoAnalytics.prototype, "_evmAddress", {
231
254
  get: function () {
232
- return this._chainState.evm.address;
255
+ return this.wallet.evmAddress;
233
256
  },
234
257
  enumerable: false,
235
258
  configurable: true
236
259
  });
237
260
  Object.defineProperty(FormoAnalytics.prototype, "_evmChainId", {
238
261
  get: function () {
239
- return this._chainState.evm.chainId;
262
+ return this.wallet.evmChainId;
263
+ },
264
+ enumerable: false,
265
+ configurable: true
266
+ });
267
+ Object.defineProperty(FormoAnalytics.prototype, "currentAddress", {
268
+ /**
269
+ * The wallet later events are attributed to, derived from whichever
270
+ * namespace last claimed the slot. Read by the wagmi and Privy
271
+ * integrations; the store is the only writer.
272
+ */
273
+ get: function () {
274
+ return this.wallet.address;
275
+ },
276
+ /**
277
+ * These stay writable.
278
+ *
279
+ * Both were public mutable fields, so a consumer assigning one is using a
280
+ * documented public API. Getter-only replacements would break that
281
+ * silently: TypeScript rejects the assignment, and plain JavaScript throws
282
+ * on an accessor with no setter. The writes forward into the store, which
283
+ * keeps a single owner without turning a refactor into a breaking change.
284
+ */
285
+ set: function (value) {
286
+ this.wallet.setActiveAddress(value);
287
+ },
288
+ enumerable: false,
289
+ configurable: true
290
+ });
291
+ Object.defineProperty(FormoAnalytics.prototype, "currentChainId", {
292
+ get: function () {
293
+ return this.wallet.chainId;
294
+ },
295
+ set: function (value) {
296
+ this.wallet.setActiveChainId(value);
240
297
  },
241
298
  enumerable: false,
242
299
  configurable: true
243
300
  });
244
- /**
245
- * Helper method to check if a provider is different from the currently active one
246
- * @param provider The provider to check
247
- * @returns true if there's a provider mismatch, false otherwise
248
- */
249
- FormoAnalytics.prototype.isProviderMismatch = function (provider) {
250
- // Only consider it a mismatch if we have an active provider AND the provider is different
251
- // This allows legitimate provider switching while preventing race conditions
252
- return this._provider != null && this._provider !== provider;
253
- };
254
301
  FormoAnalytics.init = function (writeKey, options) {
255
302
  return __awaiter(this, void 0, void 0, function () {
256
- var analytics, _a;
257
- return __generator(this, function (_b) {
258
- switch (_b.label) {
303
+ var analytics, discovered;
304
+ return __generator(this, function (_a) {
305
+ switch (_a.label) {
259
306
  case 0:
260
307
  initStorageManager(writeKey);
261
308
  analytics = new FormoAnalytics(writeKey, options);
@@ -264,20 +311,17 @@ var FormoAnalytics = /** @class */ (function () {
264
311
  return [3 /*break*/, 5];
265
312
  case 1:
266
313
  if (!!analytics.isWagmiMode) return [3 /*break*/, 4];
267
- // Auto-detect wallet provider
268
- _a = analytics;
269
- return [4 /*yield*/, analytics.getProviders()];
314
+ return [4 /*yield*/, analytics.evmEvents.getProviders()];
270
315
  case 2:
271
- // Auto-detect wallet provider
272
- _a._providers = _b.sent();
273
- return [4 /*yield*/, analytics.detectWallets(analytics._providers)];
316
+ discovered = _a.sent();
317
+ return [4 /*yield*/, analytics.evmEvents.detectWallets(discovered)];
274
318
  case 3:
275
- _b.sent();
276
- analytics.trackProviders(analytics._providers);
319
+ _a.sent();
320
+ analytics.evmEvents.trackProviders(discovered);
277
321
  return [3 /*break*/, 5];
278
322
  case 4:
279
323
  logger.info("FormoAnalytics: Skipping provider detection (Wagmi mode)");
280
- _b.label = 5;
324
+ _a.label = 5;
281
325
  case 5: return [2 /*return*/, analytics];
282
326
  }
283
327
  });
@@ -318,11 +362,7 @@ var FormoAnalytics = /** @class */ (function () {
318
362
  // address on subsequent track()/page() events for the rest of the
319
363
  // page lifetime, because they fall back to currentAddress. Keep the
320
364
  // EVM provider reference so tracking can resume on the next connect.
321
- this.currentAddress = undefined;
322
- this.currentChainId = undefined;
323
- var evmProvider = this._chainState.evm.provider;
324
- this._chainState = { evm: { provider: evmProvider }, solana: {} };
325
- this._activeNamespace = undefined;
365
+ this.wallet.reset();
326
366
  cookie().remove(LOCAL_ANONYMOUS_ID_KEY);
327
367
  cookie().remove(SESSION_USER_ID_KEY);
328
368
  cookie().remove(SESSION_WALLET_DETECTED_KEY);
@@ -340,8 +380,19 @@ var FormoAnalytics = /** @class */ (function () {
340
380
  */
341
381
  FormoAnalytics.prototype.cleanup = function () {
342
382
  logger.debug("FormoAnalytics: Cleaning up resources");
343
- // Drop buffered events so a torn-down instance can't flush later.
344
- this.eventManager.clear();
383
+ // Close the queue, don't just empty it. clear() only drops what is
384
+ // buffered at this instant; asynchronous work already in flight (event
385
+ // creation is async on every emit path) would still enqueue afterwards,
386
+ // and an empty queue flushes immediately. close() is terminal, so a
387
+ // continuation that outlives this instance cannot send with its stale
388
+ // options. See issue #339.
389
+ this.eventManager.close();
390
+ // Stop any receipt or batch-status polling: a torn-down instance must
391
+ // not keep asking a wallet about transactions nobody is listening for.
392
+ this.evmRequests.cleanup();
393
+ // Stop reacting to wallet announcements: a disposed instance must not
394
+ // wrap new providers or emit detect events.
395
+ this.evmEvents.cleanup();
345
396
  // Clean up Wagmi handler if present
346
397
  if (this.wagmiHandler) {
347
398
  this.wagmiHandler.cleanup();
@@ -354,9 +405,9 @@ var FormoAnalytics = /** @class */ (function () {
354
405
  }
355
406
  // Clean up EIP-1193 providers if not in Wagmi mode
356
407
  if (!this.isWagmiMode) {
357
- for (var _i = 0, _a = Array.from(this._trackedProviders); _i < _a.length; _i++) {
408
+ for (var _i = 0, _a = this.evm.trackedProviders(); _i < _a.length; _i++) {
358
409
  var provider = _a[_i];
359
- this.untrackProvider(provider);
410
+ this.evmEvents.untrackProvider(provider);
360
411
  }
361
412
  }
362
413
  // Tear down page-hit hooks: remove window listeners and silence the
@@ -413,6 +464,11 @@ var FormoAnalytics = /** @class */ (function () {
413
464
  logger.info("connect() skipped: tracking is suppressed for this visitor or environment");
414
465
  return [2 /*return*/];
415
466
  }
467
+ // A new wallet now owns this namespace. Anything already tearing down
468
+ // the previous session must not undo this. An emitted connect always
469
+ // counts, even when the address is the one already there: a wallet that
470
+ // disconnects and reconnects leaves identical state.
471
+ this.wallet.observe(this.wallet.namespaceOf(chainId));
416
472
  this.setChainState(chainId, { address: validAddress });
417
473
  return [4 /*yield*/, this.trackEvent(EventType.CONNECT, {
418
474
  chainId: chainId,
@@ -436,7 +492,7 @@ var FormoAnalytics = /** @class */ (function () {
436
492
  */
437
493
  FormoAnalytics.prototype.disconnect = function (params, properties, context, callback) {
438
494
  return __awaiter(this, void 0, void 0, function () {
439
- var chainId, address, isSolana, providerInfo, disconnectProperties;
495
+ var chainId, address, isSolana, providerInfo, disconnectProperties, namespace, before;
440
496
  return __generator(this, function (_a) {
441
497
  switch (_a.label) {
442
498
  case 0:
@@ -456,9 +512,25 @@ var FormoAnalytics = /** @class */ (function () {
456
512
  providerName: providerInfo.name,
457
513
  rdns: providerInfo.rdns,
458
514
  })), properties);
515
+ namespace = this.wallet.namespaceOf(chainId);
516
+ // Every teardown announces itself here, before anything is awaited,
517
+ // whichever path reached it - a provider event or a direct call from the
518
+ // host app. A connect observation that began earlier is invalidated; one
519
+ // that begins after this point is a genuine reconnect and still reports.
520
+ this.wallet.beginDisconnect(namespace);
521
+ before = this.wallet.snapshot(namespace);
459
522
  return [4 /*yield*/, this.trackEvent(EventType.DISCONNECT, __assign(__assign({}, (chainId && { chainId: chainId })), (address && { address: address })), disconnectProperties, context, callback)];
460
523
  case 1:
461
524
  _a.sent();
525
+ // If a wallet claimed this namespace while the event was being built, a
526
+ // new session owns it and this cleanup is stale. Running it anyway would
527
+ // wipe that session's state AND its reported-connect record, so a later
528
+ // wallet signal would emit a second connect for a connection that is
529
+ // already reported. See issue #344.
530
+ if (!this.wallet.isUnchangedSince(namespace, before)) {
531
+ logger.info("Disconnect: A new session claimed this namespace while the event was in flight; leaving its state intact");
532
+ return [2 /*return*/];
533
+ }
462
534
  // Clear the disconnecting chain's namespace state.
463
535
  // Per-chain isolation ensures a Solana disconnect never wipes EVM state (and vice versa).
464
536
  this.clearChainState(chainId);
@@ -468,6 +540,78 @@ var FormoAnalytics = /** @class */ (function () {
468
540
  });
469
541
  });
470
542
  };
543
+ /** @see WalletStateStore.set */
544
+ FormoAnalytics.prototype.setChainState = function (namespaceOrChainId, update) {
545
+ this.wallet.set(namespaceOrChainId, update);
546
+ };
547
+ /** @see WalletStateStore.clear */
548
+ FormoAnalytics.prototype.clearChainState = function (namespaceOrChainId) {
549
+ this.wallet.clear(namespaceOrChainId);
550
+ };
551
+ /**
552
+ * Record validated wallet/chain state WITHOUT emitting an event.
553
+ *
554
+ * Integrations must call this on every connect / chain change / disconnect,
555
+ * even when the matching autocapture event is disabled, or the exclusion
556
+ * gate (which keys off the central chain, not the event payload) can be
557
+ * bypassed. Stays on the class because integrations bind to it.
558
+ * @see WalletStateStore.syncWalletState
559
+ */
560
+ FormoAnalytics.prototype.syncWalletState = function (params) {
561
+ this.wallet.syncWalletState(params);
562
+ };
563
+ /** @see WalletStateStore.clearProvider */
564
+ FormoAnalytics.prototype.clearActiveProvider = function () {
565
+ this.wallet.clearProvider();
566
+ };
567
+ /** @see WalletStateStore.backfill */
568
+ FormoAnalytics.prototype.backfillActiveWallet = function (address, chainId, provider) {
569
+ this.wallet.backfill(address, chainId, provider);
570
+ };
571
+ /** @see WalletStateStore.clearStaleEvmWalletOnSwitchWhileSuppressed */
572
+ FormoAnalytics.prototype.clearStaleEvmWalletOnSwitchWhileSuppressed = function (address) {
573
+ this.wallet.clearStaleEvmWalletOnSwitchWhileSuppressed(address);
574
+ };
575
+ /** @see EvmProviderRegistry.addListener */
576
+ FormoAnalytics.prototype.addProviderListener = function (provider, event, listener) {
577
+ this.evm.addListener(provider, event, listener);
578
+ };
579
+ /** @see EvmProviderRegistry.removeListeners */
580
+ FormoAnalytics.prototype.removeProviderListeners = function (provider) {
581
+ this.evm.removeListeners(provider);
582
+ };
583
+ /** @see EvmProviderRegistry.infoFor */
584
+ FormoAnalytics.prototype.getProviderInfo = function (provider) {
585
+ return this.evm.infoFor(provider);
586
+ };
587
+ /** @see EvmProviderRegistry.isWrapped */
588
+ FormoAnalytics.prototype.isProviderAlreadyWrapped = function (provider, currentRequest) {
589
+ return this.evm.isWrapped(provider, currentRequest);
590
+ };
591
+ /** @see EvmProviderRegistry.resolveChainId */
592
+ FormoAnalytics.prototype.resolveChainIdForProvider = function (provider) {
593
+ return this.evm.resolveChainId(provider);
594
+ };
595
+ /** @see EvmProviderRegistry.rememberChain */
596
+ FormoAnalytics.prototype.rememberProviderChain = function (provider, chainId) {
597
+ this.evm.rememberChain(provider, chainId);
598
+ };
599
+ /** @see EvmProviderRegistry.addressOf */
600
+ FormoAnalytics.prototype.getAddress = function (provider) {
601
+ return __awaiter(this, void 0, void 0, function () {
602
+ return __generator(this, function (_a) {
603
+ return [2 /*return*/, this.evm.addressOf(provider)];
604
+ });
605
+ });
606
+ };
607
+ /** @see EvmProviderRegistry.accountsOf */
608
+ FormoAnalytics.prototype.getAccounts = function (provider) {
609
+ return __awaiter(this, void 0, void 0, function () {
610
+ return __generator(this, function (_a) {
611
+ return [2 /*return*/, this.evm.accountsOf(provider)];
612
+ });
613
+ });
614
+ };
471
615
  /**
472
616
  * Emits a chain network change event.
473
617
  * @param {ChainID} params.chainId
@@ -609,14 +753,14 @@ var FormoAnalytics = /** @class */ (function () {
609
753
  // valid (activating a Solana wallet while an excluded EVM chain id is
610
754
  // still current). By the time the Privy path reaches this guard it has
611
755
  // already reconciled, so each inner identify is judged on the right chain.
612
- if (this.isTrackingSuppressed() || this.isCurrentChainExcluded()) {
756
+ if (this.isTrackingSuppressed() || this.trackingPolicy.isChainExcluded()) {
613
757
  logger.info("identify() skipped: tracking is suppressed for this visitor, environment, or chain");
614
758
  return [2 /*return*/];
615
759
  }
616
760
  if (!!params) return [3 /*break*/, 12];
617
761
  // If no params provided, auto-identify
618
- logger.info("Auto-identifying with providers:", this._providers.map(function (p) { return p.info.name; }));
619
- _i = 0, _a = this._providers;
762
+ logger.info("Auto-identifying with providers:", this.evm.all.map(function (p) { return p.info.name; }));
763
+ _i = 0, _a = this.evm.all;
620
764
  _d.label = 3;
621
765
  case 3:
622
766
  if (!(_i < _a.length)) return [3 /*break*/, 11];
@@ -688,8 +832,7 @@ var FormoAnalytics = /** @class */ (function () {
688
832
  // attribution. Gating address and userId together prevents leaving the
689
833
  // active address paired with a different wallet's user id.
690
834
  if (setActive !== false) {
691
- this.currentAddress = validAddress;
692
- this.persistActiveWallet();
835
+ this.wallet.setActiveAddress(validAddress);
693
836
  if (userId) {
694
837
  this.currentUserId = userId;
695
838
  domain = getIdentityCookieDomain(this.crossSubdomainCookies);
@@ -776,8 +919,7 @@ var FormoAnalytics = /** @class */ (function () {
776
919
  return;
777
920
  var currentIsSolana = isSolanaChainId(this.currentChainId);
778
921
  if (walletIsSolana !== currentIsSolana) {
779
- this.currentChainId = undefined;
780
- this.persistActiveWallet();
922
+ this.wallet.setActiveChainId(undefined);
781
923
  }
782
924
  };
783
925
  /**
@@ -843,6 +985,18 @@ var FormoAnalytics = /** @class */ (function () {
843
985
  * Opt out of tracking.
844
986
  * @returns {void}
845
987
  */
988
+ /**
989
+ * Whether an event carrying this chain would currently be sent.
990
+ *
991
+ * Exposed for integrations that keep their own "already reported" state.
992
+ * `syncWalletState()` can accept a wallet that `trackEvent()` then drops -
993
+ * `tracking: false`, or a chain in `excludeChains` - and an integration that
994
+ * marked it as reported would stay silent about that wallet even after the
995
+ * configuration changed to allow it.
996
+ */
997
+ FormoAnalytics.prototype.willTrackEvent = function (chainId) {
998
+ return this.shouldTrack(chainId);
999
+ };
846
1000
  FormoAnalytics.prototype.optOutTracking = function () {
847
1001
  logger.info("Opting out of tracking");
848
1002
  // Set opt-out flag in persistent storage using direct cookie access
@@ -860,9 +1014,15 @@ var FormoAnalytics = /** @class */ (function () {
860
1014
  * @returns {void}
861
1015
  */
862
1016
  FormoAnalytics.prototype.optInTracking = function () {
1017
+ var _a;
863
1018
  logger.info("Opting back into tracking");
864
1019
  // Remove opt-out flag
865
1020
  removeConsentFlag(this.writeKey, CONSENT_OPT_OUT_KEY);
1021
+ // A wallet connected while opted out was declined by syncWalletState, and
1022
+ // an unchanged wagmi connection produces no status or chain update to
1023
+ // retry on. Without this, opting back in leaves that wallet invisible for
1024
+ // the rest of the page load.
1025
+ (_a = this.wagmiHandler) === null || _a === void 0 ? void 0 : _a.retryAdoption();
866
1026
  logger.info("Successfully opted back into tracking");
867
1027
  };
868
1028
  /**
@@ -875,1305 +1035,211 @@ var FormoAnalytics = /** @class */ (function () {
875
1035
  /*
876
1036
  SDK tracking and event listener functions
877
1037
  */
1038
+ FormoAnalytics.prototype.onLocationChange = function () {
1039
+ return __awaiter(this, void 0, void 0, function () {
1040
+ var _a;
1041
+ return __generator(this, function (_b) {
1042
+ if (this._currentUrl !== window.location.href) {
1043
+ this._currentUrl = window.location.href;
1044
+ // Host/path exclusions are evaluated per navigation, so a SPA can leave
1045
+ // an excluded route and become trackable without any wallet event
1046
+ // firing. The wagmi handler only observes *changes*, so an unchanged
1047
+ // connection it was forced to decline earlier would stay invisible for
1048
+ // the rest of the page load. Give it a chance to adopt it now.
1049
+ (_a = this.wagmiHandler) === null || _a === void 0 ? void 0 : _a.retryAdoption();
1050
+ this.trackPageHit();
1051
+ }
1052
+ return [2 /*return*/];
1053
+ });
1054
+ });
1055
+ };
1056
+ FormoAnalytics.prototype.trackPageHits = function () {
1057
+ var _this = this;
1058
+ // Install a single, instance-agnostic wrapper around history.pushState /
1059
+ // replaceState so concurrent SDK instances (React Strict Mode, HMR) don't
1060
+ // each stack their own wrapper - which would dispatch N synthetic events
1061
+ // per navigation and produce O(N^2) onLocationChange calls. The wrapper
1062
+ // dispatches once; per-instance bookkeeping is done by per-instance
1063
+ // listeners that each register/unregister themselves.
1064
+ FormoAnalytics.installHistoryHooksOnce();
1065
+ this._onPopStateListener = function () { return _this.onLocationChange(); };
1066
+ this._onLocationChangeListener = function () { return _this.onLocationChange(); };
1067
+ window.addEventListener("popstate", this._onPopStateListener);
1068
+ window.addEventListener("locationchange", this._onLocationChangeListener);
1069
+ };
878
1070
  /**
879
- * Track an EIP-1193 provider by wrapping its request method and adding event listeners
880
- * Note: This is only used in non-Wagmi mode. When Wagmi is enabled, all tracking
881
- * happens through Wagmi's connector system instead of EIP-1193/EIP-6963.
882
- * @param provider The EIP-1193 provider to track
1071
+ * Wrap history.pushState / replaceState exactly once per `history` object,
1072
+ * regardless of how many SDK instances are constructed. Uses a Symbol
1073
+ * marker so we recognize our own wrapper across module reloads in HMR.
883
1074
  */
884
- FormoAnalytics.prototype.trackEIP1193Provider = function (provider) {
885
- logger.info("trackEIP1193Provider", provider);
886
- // Defensive check: Skip provider tracking in Wagmi mode
887
- // This should never be called in Wagmi mode due to guards in init(),
888
- // but we check here for safety in case of future code changes
889
- if (this.isWagmiMode) {
890
- logger.debug("trackEIP1193Provider: Skipping EIP-1193 provider tracking (Wagmi mode - using connector system instead)");
1075
+ FormoAnalytics.installHistoryHooksOnce = function () {
1076
+ if (typeof history === "undefined" || typeof window === "undefined")
891
1077
  return;
892
- }
893
- try {
894
- // Validate provider exists and has required methods
895
- if (!isValidProvider(provider)) {
896
- logger.warn("trackEIP1193Provider: Invalid provider - missing required methods");
897
- return;
898
- }
899
- if (this._trackedProviders.has(provider)) {
900
- logger.warn("trackEIP1193Provider: Provider already tracked");
901
- return;
902
- }
903
- // CRITICAL: Always register accountsChanged for state management
904
- // This ensures currentAddress, currentChainId, and _provider are always up-to-date
905
- // Event emission is controlled conditionally inside the handlers
906
- this.registerAccountsChangedListener(provider);
907
- // Register other listeners based on autocapture configuration
908
- if (this.isAutocaptureEnabled("chain")) {
909
- this.registerChainChangedListener(provider);
910
- }
911
- if (this.isAutocaptureEnabled("connect")) {
912
- this.registerConnectListener(provider);
913
- }
914
- if (this.isAutocaptureEnabled("signature") || this.isAutocaptureEnabled("transaction")) {
915
- this.registerRequestListeners(provider);
916
- }
917
- else {
918
- logger.debug("TrackProvider: Skipping request wrapping (both signature and transaction autocapture disabled)");
919
- }
920
- if (this.isAutocaptureEnabled("disconnect")) {
921
- this.registerDisconnectListener(provider);
922
- }
923
- // Only add to tracked providers after all listeners are successfully registered
924
- this._trackedProviders.add(provider);
925
- }
926
- catch (error) {
927
- logger.error("Error tracking provider:", error);
928
- }
929
- };
930
- FormoAnalytics.prototype.trackProviders = function (providers) {
931
- try {
932
- for (var _i = 0, providers_1 = providers; _i < providers_1.length; _i++) {
933
- var eip6963ProviderDetail = providers_1[_i];
934
- var provider = eip6963ProviderDetail === null || eip6963ProviderDetail === void 0 ? void 0 : eip6963ProviderDetail.provider;
935
- if (provider && !this._trackedProviders.has(provider)) {
936
- this.trackEIP1193Provider(provider);
937
- }
1078
+ var marker = Symbol.for("formo.historyWrapped");
1079
+ if (history[marker])
1080
+ return;
1081
+ history[marker] = true;
1082
+ var dispatch = function () { return window.dispatchEvent(new window.Event("locationchange")); };
1083
+ var oldPushState = history.pushState;
1084
+ history.pushState = function pushState() {
1085
+ var args = [];
1086
+ for (var _i = 0; _i < arguments.length; _i++) {
1087
+ args[_i] = arguments[_i];
938
1088
  }
939
- }
940
- catch (error) {
941
- logger.error("Failed to track EIP-6963 providers during initialization:", error);
942
- }
943
- };
944
- FormoAnalytics.prototype.addProviderListener = function (provider, event, listener) {
945
- var map = this._providerListenersMap.get(provider) || {};
946
- map[event] = listener;
947
- this._providerListenersMap.set(provider, map);
948
- };
949
- FormoAnalytics.prototype.registerAccountsChangedListener = function (provider) {
950
- var _this = this;
951
- logger.info("registerAccountsChangedListener");
952
- var listener = function () {
1089
+ var ret = oldPushState.apply(this, args);
1090
+ dispatch();
1091
+ return ret;
1092
+ };
1093
+ var oldReplaceState = history.replaceState;
1094
+ history.replaceState = function replaceState() {
953
1095
  var args = [];
954
1096
  for (var _i = 0; _i < arguments.length; _i++) {
955
1097
  args[_i] = arguments[_i];
956
1098
  }
957
- return _this.onAccountsChanged(provider, args[0]);
1099
+ var ret = oldReplaceState.apply(this, args);
1100
+ dispatch();
1101
+ return ret;
958
1102
  };
959
- provider.on("accountsChanged", listener);
960
- this.addProviderListener(provider, "accountsChanged", listener);
961
1103
  };
962
- FormoAnalytics.prototype.onAccountsChanged = function (provider, accounts) {
1104
+ FormoAnalytics.prototype.trackPageHit = function (category, name, properties, context, callback) {
1105
+ return __awaiter(this, void 0, void 0, function () {
1106
+ var _this = this;
1107
+ return __generator(this, function (_a) {
1108
+ if (!this.shouldTrack()) {
1109
+ logger.info("Track page hit: Skipping event due to tracking configuration");
1110
+ return [2 /*return*/];
1111
+ }
1112
+ setTimeout(function () {
1113
+ // Drop in-flight page hits from an SDK instance that was torn down
1114
+ // between scheduling and firing (e.g. provider remount in React Strict
1115
+ // Mode / HMR). Otherwise the orphan instance would queue a page event
1116
+ // here with its stale, never-populated `currentAddress`.
1117
+ if (_this._pageHooksDisposed)
1118
+ return;
1119
+ (function () { return __awaiter(_this, void 0, void 0, function () {
1120
+ var e_2;
1121
+ return __generator(this, function (_a) {
1122
+ switch (_a.label) {
1123
+ case 0:
1124
+ _a.trys.push([0, 2, , 3]);
1125
+ return [4 /*yield*/, this.trackEvent(EventType.PAGE, {
1126
+ category: category,
1127
+ name: name,
1128
+ }, properties, context, callback)];
1129
+ case 1:
1130
+ _a.sent();
1131
+ return [3 /*break*/, 3];
1132
+ case 2:
1133
+ e_2 = _a.sent();
1134
+ logger.error("Formo: Failed to track page hit", e_2);
1135
+ return [3 /*break*/, 3];
1136
+ case 3: return [2 /*return*/];
1137
+ }
1138
+ });
1139
+ }); })();
1140
+ }, 300);
1141
+ return [2 /*return*/];
1142
+ });
1143
+ });
1144
+ };
1145
+ FormoAnalytics.prototype.trackEvent = function (type, payload, properties, context, callback) {
963
1146
  return __awaiter(this, void 0, void 0, function () {
1147
+ var error_1;
964
1148
  return __generator(this, function (_a) {
965
1149
  switch (_a.label) {
966
1150
  case 0:
967
- logger.info("onAccountsChanged", accounts);
968
- // Prevent concurrent processing of accountsChanged events to avoid race conditions
969
- if (this._processingAccountsChanged) {
970
- logger.debug("OnAccountsChanged: Already processing accountsChanged, skipping", {
971
- provider: this.getProviderInfo(provider).name,
972
- });
1151
+ _a.trys.push([0, 2, , 3]);
1152
+ // Gate on the chain the event actually carries. `connect`, `disconnect`,
1153
+ // `chain`, `signature` and `transaction` all put one in the payload, and
1154
+ // it is authoritative: it can name a provider or a wagmi mutation chain
1155
+ // that is not the active one. Events without a chain (page, track,
1156
+ // identify) fall back to the central value.
1157
+ if (!this.shouldTrack(payload === null || payload === void 0 ? void 0 : payload.chainId)) {
1158
+ logger.info("Skipping ".concat(type, " event due to tracking configuration"));
973
1159
  return [2 /*return*/];
974
1160
  }
975
- this._processingAccountsChanged = true;
976
- _a.label = 1;
1161
+ return [4 /*yield*/, this.eventManager.addEvent(__assign(__assign({ type: type }, payload), { properties: properties, context: context, callback: callback }), this.currentAddress, this.currentUserId)];
977
1162
  case 1:
978
- _a.trys.push([1, , 3, 4]);
979
- return [4 /*yield*/, this._handleAccountsChanged(provider, accounts)];
980
- case 2:
981
1163
  _a.sent();
982
- return [3 /*break*/, 4];
983
- case 3:
984
- this._processingAccountsChanged = false;
985
- return [7 /*endfinally*/];
986
- case 4: return [2 /*return*/];
1164
+ return [3 /*break*/, 3];
1165
+ case 2:
1166
+ error_1 = _a.sent();
1167
+ logger.error("Error tracking event:", error_1);
1168
+ return [3 /*break*/, 3];
1169
+ case 3: return [2 /*return*/];
987
1170
  }
988
1171
  });
989
1172
  });
990
1173
  };
991
1174
  /**
992
- * Handles changes to the accounts of a given EIP-1193 provider.
1175
+ * Visitor-level tracking suppression.
993
1176
  *
994
- * @param provider - The EIP-1193 provider whose accounts have changed.
995
- * @param accounts - The new array of account addresses. An empty array indicates a disconnect.
996
- * @returns A promise that resolves when the account change has been processed.
1177
+ * True when the SDK must not persist identity/session/chain state or send
1178
+ * events for this visitor. Public entry points that write state before
1179
+ * reaching the `shouldTrack()` gate (identify / connect / detect) check this
1180
+ * first, so a suppressed visitor leaves no cookies or session state.
997
1181
  *
998
- * If the accounts array is empty and the provider is the active provider, this method triggers
999
- * a disconnect flow. Otherwise, it updates the state to reflect the new accounts as needed.
1182
+ * The rule lives in `TrackingPolicy`; this stays on the class because it is
1183
+ * part of the surface integrations bind to.
1184
+ * @internal Also read by `identifyPrivyUser` (via a structural cast) so the
1185
+ * Privy sync skips chain reconciliation and emission for suppressed visitors.
1186
+ */
1187
+ FormoAnalytics.prototype.isTrackingSuppressed = function () {
1188
+ return this.trackingPolicy.isTrackingSuppressed();
1189
+ };
1190
+ /** @see TrackingPolicy.shouldTrack */
1191
+ FormoAnalytics.prototype.shouldTrack = function (eventChainId) {
1192
+ return this.trackingPolicy.shouldTrack({ chainId: eventChainId });
1193
+ };
1194
+ /**
1195
+ * Check if a specific wallet event type is enabled for autocapture
1196
+ * @param eventType The wallet event type to check
1197
+ * @returns {boolean} True if the event type should be autocaptured
1000
1198
  */
1001
- FormoAnalytics.prototype._handleAccountsChanged = function (provider, accounts) {
1199
+ FormoAnalytics.prototype.isAutocaptureEnabled = function (eventType) {
1200
+ return this.trackingPolicy.isAutocaptureEnabled(eventType);
1201
+ };
1202
+ Object.defineProperty(FormoAnalytics.prototype, "providers", {
1203
+ /*
1204
+ Utility functions
1205
+ */
1206
+ get: function () {
1207
+ return this.evm.all;
1208
+ },
1209
+ enumerable: false,
1210
+ configurable: true
1211
+ });
1212
+ Object.defineProperty(FormoAnalytics.prototype, "provider", {
1213
+ get: function () {
1214
+ return this._provider;
1215
+ },
1216
+ enumerable: false,
1217
+ configurable: true
1218
+ });
1219
+ Object.defineProperty(FormoAnalytics.prototype, "solana", {
1220
+ /**
1221
+ * Access the Solana integration manager.
1222
+ * Lazily creates one if not already initialized.
1223
+ *
1224
+ * @example
1225
+ * ```tsx
1226
+ * formo.solana.setStore(client.store);
1227
+ * formo.solana.setCluster("devnet");
1228
+ * // For signatures, use formo.signature() directly
1229
+ * ```
1230
+ */
1231
+ get: function () {
1232
+ if (!this.solanaManager) {
1233
+ this.solanaManager = new SolanaManager(this);
1234
+ }
1235
+ return this.solanaManager;
1236
+ },
1237
+ enumerable: false,
1238
+ configurable: true
1239
+ });
1240
+ FormoAnalytics.prototype.getCurrentChainId = function (provider) {
1002
1241
  return __awaiter(this, void 0, void 0, function () {
1003
- var error_1, address, currentStoredAddress, newProviderAddress, activeProviderAccounts, error_2, nextChainId, wasDisconnected, providerInfo, effectiveChainId;
1004
- return __generator(this, function (_a) {
1005
- switch (_a.label) {
1006
- case 0:
1007
- if (!(accounts.length === 0)) return [3 /*break*/, 9];
1008
- if (!(this._provider === provider)) return [3 /*break*/, 7];
1009
- logger.info("OnAccountsChanged: Detecting disconnect, current state:", {
1010
- evmAddress: this._evmAddress,
1011
- evmChainId: this._evmChainId,
1012
- providerMatch: this._provider === provider,
1013
- });
1014
- if (!this.isAutocaptureEnabled("disconnect")) return [3 /*break*/, 5];
1015
- _a.label = 1;
1016
- case 1:
1017
- _a.trys.push([1, 3, , 4]);
1018
- // Pass EVM state explicitly to ensure we have the data for the disconnect event
1019
- return [4 /*yield*/, this.disconnect({
1020
- chainId: this._evmChainId,
1021
- address: this._evmAddress,
1022
- })];
1023
- case 2:
1024
- // Pass EVM state explicitly to ensure we have the data for the disconnect event
1025
- _a.sent();
1026
- return [3 /*break*/, 4];
1027
- case 3:
1028
- error_1 = _a.sent();
1029
- logger.error("Failed to disconnect provider on accountsChanged", error_1);
1030
- return [3 /*break*/, 4];
1031
- case 4: return [3 /*break*/, 6];
1032
- case 5:
1033
- logger.debug("OnAccountsChanged: Disconnect event skipped (autocapture.disconnect: false)");
1034
- // Still clear state even if not tracking the event
1035
- this.clearChainState('evm');
1036
- _a.label = 6;
1037
- case 6: return [3 /*break*/, 8];
1038
- case 7:
1039
- logger.info("OnAccountsChanged: Ignoring disconnect for non-active provider");
1040
- _a.label = 8;
1041
- case 8: return [2 /*return*/];
1042
- case 9:
1043
- address = validateAndChecksumAddress(accounts[0]);
1044
- if (!address) {
1045
- logger.warn("onAccountsChanged: Invalid address received", accounts[0]);
1046
- return [2 /*return*/];
1047
- }
1048
- if (!(this._provider && this._provider !== provider)) return [3 /*break*/, 25];
1049
- currentStoredAddress = this._evmAddress;
1050
- newProviderAddress = validateAndChecksumAddress(address);
1051
- logger.info("OnAccountsChanged: Different provider attempting to connect", {
1052
- activeProvider: this.getProviderInfo(this._provider).name,
1053
- eventProvider: this.getProviderInfo(provider).name,
1054
- currentStoredAddress: currentStoredAddress,
1055
- newProviderAddress: newProviderAddress,
1056
- });
1057
- _a.label = 10;
1058
- case 10:
1059
- _a.trys.push([10, 21, , 25]);
1060
- return [4 /*yield*/, this.getAccounts(this._provider)];
1061
- case 11:
1062
- activeProviderAccounts = _a.sent();
1063
- logger.info("OnAccountsChanged: Checking current provider accounts", {
1064
- activeProvider: this.getProviderInfo(this._provider).name,
1065
- accountsLength: activeProviderAccounts
1066
- ? activeProviderAccounts.length
1067
- : 0,
1068
- accounts: activeProviderAccounts,
1069
- });
1070
- if (!(activeProviderAccounts && activeProviderAccounts.length > 0)) return [3 /*break*/, 17];
1071
- if (!(newProviderAddress &&
1072
- currentStoredAddress &&
1073
- newProviderAddress !== currentStoredAddress)) return [3 /*break*/, 15];
1074
- logger.info("OnAccountsChanged: Different address detected, switching providers despite current provider having accounts", {
1075
- activeProvider: this.getProviderInfo(this._provider).name,
1076
- eventProvider: this.getProviderInfo(provider).name,
1077
- currentAddress: currentStoredAddress,
1078
- newAddress: newProviderAddress,
1079
- reason: PROVIDER_SWITCH_REASONS.ADDRESS_MISMATCH,
1080
- });
1081
- if (!this.isAutocaptureEnabled("disconnect")) return [3 /*break*/, 13];
1082
- return [4 /*yield*/, this.disconnect({
1083
- chainId: this._evmChainId,
1084
- address: this._evmAddress,
1085
- })];
1086
- case 12:
1087
- _a.sent();
1088
- return [3 /*break*/, 14];
1089
- case 13:
1090
- logger.debug("OnAccountsChanged: Disconnect event skipped during provider switch (autocapture.disconnect: false)");
1091
- // Still clear state even if not tracking the event
1092
- this.clearChainState('evm');
1093
- _a.label = 14;
1094
- case 14:
1095
- // Clear state and let the new provider become active
1096
- this.clearActiveProvider();
1097
- return [3 /*break*/, 16];
1098
- case 15:
1099
- logger.info("OnAccountsChanged: Current provider still has accounts and same address, ignoring new provider", {
1100
- activeProvider: this.getProviderInfo(this._provider).name,
1101
- eventProvider: this.getProviderInfo(provider).name,
1102
- activeProviderAccountsCount: activeProviderAccounts.length,
1103
- currentAddress: currentStoredAddress,
1104
- newAddress: newProviderAddress,
1105
- });
1106
- return [2 /*return*/];
1107
- case 16: return [3 /*break*/, 20];
1108
- case 17:
1109
- logger.info("OnAccountsChanged: Current provider has no accounts, switching to new provider", {
1110
- oldProvider: this.getProviderInfo(this._provider).name,
1111
- newProvider: this.getProviderInfo(provider).name,
1112
- reason: PROVIDER_SWITCH_REASONS.NO_ACCOUNTS,
1113
- });
1114
- if (!this.isAutocaptureEnabled("disconnect")) return [3 /*break*/, 19];
1115
- return [4 /*yield*/, this.disconnect({
1116
- chainId: this._evmChainId,
1117
- address: this._evmAddress,
1118
- })];
1119
- case 18:
1120
- _a.sent();
1121
- return [3 /*break*/, 20];
1122
- case 19:
1123
- logger.debug("OnAccountsChanged: Disconnect event skipped for old provider (autocapture.disconnect: false)");
1124
- // Still clear state even if not tracking the event
1125
- this.clearChainState('evm');
1126
- _a.label = 20;
1127
- case 20: return [3 /*break*/, 25];
1128
- case 21:
1129
- error_2 = _a.sent();
1130
- logger.warn("OnAccountsChanged: Could not check current provider accounts, switching to new provider", {
1131
- error: error_2 instanceof Error ? error_2.message : String(error_2),
1132
- errorType: error_2 instanceof Error ? error_2.constructor.name : typeof error_2,
1133
- oldProvider: this._provider
1134
- ? this.getProviderInfo(this._provider).name
1135
- : "unknown",
1136
- newProvider: this.getProviderInfo(provider).name,
1137
- reason: PROVIDER_SWITCH_REASONS.CHECK_FAILED,
1138
- });
1139
- if (!this.isAutocaptureEnabled("disconnect")) return [3 /*break*/, 23];
1140
- return [4 /*yield*/, this.disconnect({
1141
- chainId: this._evmChainId,
1142
- address: this._evmAddress,
1143
- })];
1144
- case 22:
1145
- _a.sent();
1146
- return [3 /*break*/, 24];
1147
- case 23:
1148
- logger.debug("OnAccountsChanged: Disconnect event skipped for failed provider check (autocapture.disconnect: false)");
1149
- // Still clear state even if not tracking the event
1150
- this.clearChainState('evm');
1151
- _a.label = 24;
1152
- case 24: return [3 /*break*/, 25];
1153
- case 25:
1154
- // Set provider if none exists (first connection)
1155
- if (!this._provider) {
1156
- this._provider = provider;
1157
- }
1158
- // If both the provider and address are the same, no-op
1159
- if (this._provider === provider && address === this._evmAddress) {
1160
- return [2 /*return*/];
1161
- }
1162
- return [4 /*yield*/, this.getCurrentChainId(provider)];
1163
- case 26:
1164
- nextChainId = _a.sent();
1165
- wasDisconnected = !this._evmAddress;
1166
- // Update state regardless of whether connect *event* tracking is enabled,
1167
- // so disconnect events keep valid address/chainId values. (excludeChains is
1168
- // NOT suppression - it still updates state so currentChainId can gate
1169
- // events.)
1170
- if (this.isTrackingSuppressed()) {
1171
- this.clearStaleEvmWalletOnSwitchWhileSuppressed(address);
1172
- }
1173
- else {
1174
- this.setChainState('evm', { address: address, chainId: nextChainId });
1175
- }
1176
- providerInfo = this.getProviderInfo(provider);
1177
- effectiveChainId = nextChainId || 0;
1178
- if (this.isAutocaptureEnabled("connect")) {
1179
- logger.info("OnAccountsChanged: Detected wallet connection, emitting connect event", {
1180
- chainId: nextChainId,
1181
- address: address,
1182
- wasDisconnected: wasDisconnected,
1183
- providerName: providerInfo.name,
1184
- rdns: providerInfo.rdns,
1185
- hasChainId: !!nextChainId,
1186
- });
1187
- if (effectiveChainId === 0) {
1188
- logger.info("OnAccountsChanged: Using fallback chainId 0 for connect event");
1189
- }
1190
- this.connect({
1191
- chainId: effectiveChainId,
1192
- address: address,
1193
- }, {
1194
- providerName: providerInfo.name,
1195
- rdns: providerInfo.rdns,
1196
- }).catch(function (error) {
1197
- logger.error("Failed to track connect event during account change:", error);
1198
- });
1199
- }
1200
- else {
1201
- logger.debug("OnAccountsChanged: Connect event skipped (autocapture.connect: false)", {
1202
- chainId: nextChainId,
1203
- address: address,
1204
- providerName: providerInfo.name,
1205
- });
1206
- }
1207
- return [2 /*return*/];
1208
- }
1209
- });
1210
- });
1211
- };
1212
- FormoAnalytics.prototype.registerChainChangedListener = function (provider) {
1213
- var _this = this;
1214
- logger.info("registerChainChangedListener");
1215
- var listener = function () {
1216
- var args = [];
1217
- for (var _i = 0; _i < arguments.length; _i++) {
1218
- args[_i] = arguments[_i];
1219
- }
1220
- return _this.onChainChanged(provider, args[0]);
1221
- };
1222
- provider.on("chainChanged", listener);
1223
- this.addProviderListener(provider, "chainChanged", listener);
1224
- };
1225
- FormoAnalytics.prototype.onChainChanged = function (provider, chainIdHex) {
1226
- return __awaiter(this, void 0, void 0, function () {
1227
- var nextChainId;
1228
- return __generator(this, function (_a) {
1229
- logger.info("onChainChanged", chainIdHex);
1230
- nextChainId = parseChainId(chainIdHex);
1231
- // Only handle chain changes for the active provider (or if none is set yet)
1232
- if (this.isProviderMismatch(provider)) {
1233
- this.handleProviderMismatch(provider);
1234
- }
1235
- // Chain changes only matter for connected users
1236
- if (!this._evmAddress) {
1237
- logger.info("OnChainChanged: No current address, user appears disconnected");
1238
- return [2 /*return*/, Promise.resolve()];
1239
- }
1240
- // Set provider if none exists
1241
- if (!this._provider) {
1242
- this._provider = provider;
1243
- }
1244
- this.setChainState('evm', { chainId: nextChainId });
1245
- try {
1246
- // This is just a chain change since we already confirmed _evmAddress exists
1247
- if (this.isAutocaptureEnabled("chain")) {
1248
- return [2 /*return*/, this.chain({
1249
- chainId: nextChainId,
1250
- address: this._evmAddress,
1251
- })];
1252
- }
1253
- else {
1254
- logger.debug("OnChainChanged: Chain event skipped (autocapture.chain: false)", {
1255
- chainId: this._evmChainId,
1256
- address: this._evmAddress,
1257
- });
1258
- }
1259
- }
1260
- catch (error) {
1261
- logger.error("OnChainChanged: Failed to emit chain event:", error);
1262
- }
1263
- return [2 /*return*/];
1264
- });
1265
- });
1266
- };
1267
- FormoAnalytics.prototype.registerConnectListener = function (provider) {
1268
- var _this = this;
1269
- logger.info("registerConnectListener");
1270
- var listener = function () {
1271
- var args = [];
1272
- for (var _i = 0; _i < arguments.length; _i++) {
1273
- args[_i] = arguments[_i];
1274
- }
1275
- var connection = args[0];
1276
- _this.onConnected(provider, connection);
1277
- };
1278
- provider.on("connect", listener);
1279
- this.addProviderListener(provider, "connect", listener);
1280
- };
1281
- FormoAnalytics.prototype.registerDisconnectListener = function (provider) {
1282
- var _this = this;
1283
- logger.info("registerDisconnectListener");
1284
- var listener = function (_error) { return __awaiter(_this, void 0, void 0, function () {
1285
- var e_2;
1286
- return __generator(this, function (_a) {
1287
- switch (_a.label) {
1288
- case 0:
1289
- if (this._provider !== provider)
1290
- return [2 /*return*/];
1291
- logger.info("OnDisconnect: Wallet disconnect event received, current state:", {
1292
- currentAddress: this._evmAddress,
1293
- currentChainId: this._evmChainId,
1294
- });
1295
- if (!this.isAutocaptureEnabled("disconnect")) return [3 /*break*/, 5];
1296
- _a.label = 1;
1297
- case 1:
1298
- _a.trys.push([1, 3, , 4]);
1299
- // Pass current state explicitly to ensure we have the data for the disconnect event
1300
- return [4 /*yield*/, this.disconnect({
1301
- chainId: this._evmChainId,
1302
- address: this._evmAddress,
1303
- })];
1304
- case 2:
1305
- // Pass current state explicitly to ensure we have the data for the disconnect event
1306
- _a.sent();
1307
- return [3 /*break*/, 4];
1308
- case 3:
1309
- e_2 = _a.sent();
1310
- logger.error("Error during disconnect in disconnect listener", e_2);
1311
- return [3 /*break*/, 4];
1312
- case 4: return [3 /*break*/, 6];
1313
- case 5:
1314
- logger.debug("OnDisconnect: Disconnect event skipped (autocapture.disconnect: false)");
1315
- // Still clear state even if not tracking the event
1316
- this.clearChainState('evm');
1317
- _a.label = 6;
1318
- case 6: return [2 /*return*/];
1319
- }
1320
- });
1321
- }); };
1322
- provider.on("disconnect", listener);
1323
- this.addProviderListener(provider, "disconnect", listener);
1324
- };
1325
- FormoAnalytics.prototype.onConnected = function (provider, connection) {
1326
- return __awaiter(this, void 0, void 0, function () {
1327
- var chainId, address, wasDisconnected, isActiveProvider, providerInfo, effectiveChainId, providerInfo, e_3;
1328
- return __generator(this, function (_a) {
1329
- switch (_a.label) {
1330
- case 0:
1331
- logger.info("onConnected", connection);
1332
- _a.label = 1;
1333
- case 1:
1334
- _a.trys.push([1, 3, , 4]);
1335
- if (!(connection === null || connection === void 0 ? void 0 : connection.chainId) || typeof connection.chainId !== "string")
1336
- return [2 /*return*/];
1337
- chainId = parseChainId(connection.chainId);
1338
- return [4 /*yield*/, this.getAddress(provider)];
1339
- case 2:
1340
- address = _a.sent();
1341
- if (chainId && address) {
1342
- wasDisconnected = !this._evmAddress;
1343
- // Set provider if none exists
1344
- if (!this._provider) {
1345
- this._provider = provider;
1346
- }
1347
- isActiveProvider = this._provider === provider;
1348
- // Update state from active provider so disconnect events keep valid
1349
- // address/chainId values - except while suppressed, where we must not
1350
- // LEARN identity (only drop a stale EVM wallet on a switch).
1351
- if (isActiveProvider) {
1352
- if (this.isTrackingSuppressed()) {
1353
- this.clearStaleEvmWalletOnSwitchWhileSuppressed(address);
1354
- }
1355
- else {
1356
- this.setChainState('evm', {
1357
- chainId: chainId,
1358
- address: validateAndChecksumAddress(address) || undefined,
1359
- });
1360
- }
1361
- }
1362
- // Conditionally emit connect event based on tracking configuration
1363
- if (isActiveProvider && this._evmAddress) {
1364
- providerInfo = this.getProviderInfo(provider);
1365
- effectiveChainId = chainId || 0;
1366
- if (this.isAutocaptureEnabled("connect")) {
1367
- logger.info("OnConnected: Detected wallet connection, emitting connect event", {
1368
- chainId: chainId,
1369
- wasDisconnected: wasDisconnected,
1370
- providerName: providerInfo.name,
1371
- rdns: providerInfo.rdns,
1372
- hasChainId: !!chainId,
1373
- isActiveProvider: isActiveProvider,
1374
- });
1375
- if (effectiveChainId === 0) {
1376
- logger.info("OnConnected: Using fallback chainId 0 for connect event");
1377
- }
1378
- this.connect({
1379
- chainId: effectiveChainId,
1380
- address: address,
1381
- }, {
1382
- providerName: providerInfo.name,
1383
- rdns: providerInfo.rdns,
1384
- }).catch(function (error) {
1385
- logger.error("Failed to track connect event during provider connection:", error);
1386
- });
1387
- }
1388
- else {
1389
- logger.debug("OnConnected: Connect event skipped (autocapture.connect: false)", {
1390
- chainId: chainId,
1391
- address: address,
1392
- providerName: providerInfo.name,
1393
- });
1394
- }
1395
- }
1396
- else if (address && !isActiveProvider) {
1397
- providerInfo = this.getProviderInfo(provider);
1398
- logger.debug("OnConnected: Skipping connect event for non-active provider", {
1399
- chainId: chainId,
1400
- providerName: providerInfo.name,
1401
- rdns: providerInfo.rdns,
1402
- isActiveProvider: isActiveProvider,
1403
- activeProviderInfo: this._provider
1404
- ? this.getProviderInfo(this._provider)
1405
- : null,
1406
- });
1407
- }
1408
- }
1409
- return [3 /*break*/, 4];
1410
- case 3:
1411
- e_3 = _a.sent();
1412
- logger.error("Error handling connect event", e_3);
1413
- return [3 /*break*/, 4];
1414
- case 4: return [2 /*return*/];
1415
- }
1416
- });
1417
- });
1418
- };
1419
- FormoAnalytics.prototype.registerRequestListeners = function (provider) {
1420
- var _this = this;
1421
- logger.info("registerRequestListeners");
1422
- if (!provider) {
1423
- logger.error("Provider not found for request (signature, transaction) tracking");
1424
- return;
1425
- }
1426
- // Check if the provider is already wrapped with our SDK's wrapper
1427
- var currentRequest = provider.request;
1428
- if (this.isProviderAlreadyWrapped(provider, currentRequest)) {
1429
- logger.info("Provider already wrapped with our SDK; skipping request wrapping.");
1430
- return;
1431
- }
1432
- var request = provider.request.bind(provider);
1433
- var wrappedRequest = function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
1434
- var capturedChainId_1, _c, response_1, error_3, rpcError, transactionHash_1, error_4, rpcError;
1435
- var _this = this;
1436
- var method = _b.method, params = _b.params;
1437
- return __generator(this, function (_d) {
1438
- switch (_d.label) {
1439
- case 0:
1440
- if (!(Array.isArray(params) &&
1441
- ["eth_signTypedData_v4", "personal_sign"].includes(method))) return [3 /*break*/, 6];
1442
- if (!this.isAutocaptureEnabled("signature")) {
1443
- logger.debug("Signature event skipped (autocapture.signature: false)", { method: method });
1444
- return [2 /*return*/, request({ method: method, params: params })];
1445
- }
1446
- _c = this._evmChainId;
1447
- if (_c) return [3 /*break*/, 2];
1448
- return [4 /*yield*/, this.getCurrentChainId(provider)];
1449
- case 1:
1450
- _c = (_d.sent());
1451
- _d.label = 2;
1452
- case 2:
1453
- capturedChainId_1 = _c;
1454
- // Fire-and-forget tracking
1455
- (function () { return __awaiter(_this, void 0, void 0, function () {
1456
- return __generator(this, function (_a) {
1457
- try {
1458
- this.signature(__assign({ status: SignatureStatus.REQUESTED }, this.buildSignatureEventPayload(method, params, undefined, capturedChainId_1)));
1459
- }
1460
- catch (e) {
1461
- logger.error("Formo: Failed to track signature request", e);
1462
- }
1463
- return [2 /*return*/];
1464
- });
1465
- }); })();
1466
- _d.label = 3;
1467
- case 3:
1468
- _d.trys.push([3, 5, , 6]);
1469
- return [4 /*yield*/, request({ method: method, params: params })];
1470
- case 4:
1471
- response_1 = (_d.sent());
1472
- // Track signature confirmation only for truthy responses
1473
- if (response_1) {
1474
- (function () { return __awaiter(_this, void 0, void 0, function () {
1475
- return __generator(this, function (_a) {
1476
- try {
1477
- this.signature(__assign({ status: SignatureStatus.CONFIRMED }, this.buildSignatureEventPayload(method, params, response_1, capturedChainId_1)));
1478
- }
1479
- catch (e) {
1480
- logger.error("Formo: Failed to track signature confirmation", e);
1481
- }
1482
- return [2 /*return*/];
1483
- });
1484
- }); })();
1485
- }
1486
- return [2 /*return*/, response_1];
1487
- case 5:
1488
- error_3 = _d.sent();
1489
- rpcError = error_3;
1490
- if ((rpcError === null || rpcError === void 0 ? void 0 : rpcError.code) === 4001) {
1491
- // Use the already cast rpcError to avoid duplication
1492
- (function () { return __awaiter(_this, void 0, void 0, function () {
1493
- return __generator(this, function (_a) {
1494
- try {
1495
- this.signature(__assign({ status: SignatureStatus.REJECTED }, this.buildSignatureEventPayload(method, params, undefined, capturedChainId_1)));
1496
- }
1497
- catch (e) {
1498
- logger.error("Formo: Failed to track signature rejection", e);
1499
- }
1500
- return [2 /*return*/];
1501
- });
1502
- }); })();
1503
- }
1504
- throw error_3;
1505
- case 6:
1506
- if (!(Array.isArray(params) &&
1507
- method === "eth_sendTransaction" &&
1508
- params[0])) return [3 /*break*/, 10];
1509
- if (!this.isAutocaptureEnabled("transaction")) {
1510
- logger.debug("Transaction event skipped (autocapture.transaction: false)", { method: method });
1511
- return [2 /*return*/, request({ method: method, params: params })];
1512
- }
1513
- (function () { return __awaiter(_this, void 0, void 0, function () {
1514
- var payload, e_4;
1515
- return __generator(this, function (_a) {
1516
- switch (_a.label) {
1517
- case 0:
1518
- _a.trys.push([0, 2, , 3]);
1519
- return [4 /*yield*/, this.buildTransactionEventPayload(params, provider)];
1520
- case 1:
1521
- payload = _a.sent();
1522
- this.transaction(__assign({ status: TransactionStatus.STARTED }, payload));
1523
- return [3 /*break*/, 3];
1524
- case 2:
1525
- e_4 = _a.sent();
1526
- logger.error("Formo: Failed to track transaction start", e_4);
1527
- return [3 /*break*/, 3];
1528
- case 3: return [2 /*return*/];
1529
- }
1530
- });
1531
- }); })();
1532
- _d.label = 7;
1533
- case 7:
1534
- _d.trys.push([7, 9, , 10]);
1535
- return [4 /*yield*/, request({
1536
- method: method,
1537
- params: params,
1538
- })];
1539
- case 8:
1540
- transactionHash_1 = (_d.sent());
1541
- (function () { return __awaiter(_this, void 0, void 0, function () {
1542
- var payload, e_5;
1543
- return __generator(this, function (_a) {
1544
- switch (_a.label) {
1545
- case 0:
1546
- _a.trys.push([0, 2, , 3]);
1547
- return [4 /*yield*/, this.buildTransactionEventPayload(params, provider)];
1548
- case 1:
1549
- payload = _a.sent();
1550
- this.transaction(__assign(__assign({ status: TransactionStatus.BROADCASTED }, payload), { transactionHash: transactionHash_1 }));
1551
- // Start async polling for transaction receipt
1552
- this.pollTransactionReceipt(provider, transactionHash_1, payload);
1553
- return [3 /*break*/, 3];
1554
- case 2:
1555
- e_5 = _a.sent();
1556
- logger.error("Formo: Failed to track transaction broadcast", e_5);
1557
- return [3 /*break*/, 3];
1558
- case 3: return [2 /*return*/];
1559
- }
1560
- });
1561
- }); })();
1562
- return [2 /*return*/, transactionHash_1];
1563
- case 9:
1564
- error_4 = _d.sent();
1565
- rpcError = error_4;
1566
- if ((rpcError === null || rpcError === void 0 ? void 0 : rpcError.code) === 4001) {
1567
- // Use the already cast rpcError to avoid duplication
1568
- (function () { return __awaiter(_this, void 0, void 0, function () {
1569
- var payload, e_6;
1570
- return __generator(this, function (_a) {
1571
- switch (_a.label) {
1572
- case 0:
1573
- _a.trys.push([0, 2, , 3]);
1574
- return [4 /*yield*/, this.buildTransactionEventPayload(params, provider)];
1575
- case 1:
1576
- payload = _a.sent();
1577
- this.transaction(__assign({ status: TransactionStatus.REJECTED }, payload));
1578
- return [3 /*break*/, 3];
1579
- case 2:
1580
- e_6 = _a.sent();
1581
- logger.error("Formo: Failed to track transaction rejection", e_6);
1582
- return [3 /*break*/, 3];
1583
- case 3: return [2 /*return*/];
1584
- }
1585
- });
1586
- }); })();
1587
- }
1588
- throw error_4;
1589
- case 10: return [2 /*return*/, request({ method: method, params: params })];
1590
- }
1591
- });
1592
- }); };
1593
- // Mark the wrapper so we can detect if request is replaced externally and keep a reference on provider
1594
- wrappedRequest[WRAPPED_REQUEST_SYMBOL] = true;
1595
- provider[WRAPPED_REQUEST_REF_SYMBOL] =
1596
- wrappedRequest;
1597
- try {
1598
- // Attempt to assign the wrapped request function (rely on try-catch for mutability errors)
1599
- provider.request = wrappedRequest;
1600
- }
1601
- catch (e) {
1602
- logger.warn("Failed to wrap provider.request; skipping", e);
1603
- }
1604
- };
1605
- FormoAnalytics.prototype.onLocationChange = function () {
1606
- return __awaiter(this, void 0, void 0, function () {
1607
- return __generator(this, function (_a) {
1608
- if (this._currentUrl !== window.location.href) {
1609
- this._currentUrl = window.location.href;
1610
- this.trackPageHit();
1611
- }
1612
- return [2 /*return*/];
1613
- });
1614
- });
1615
- };
1616
- FormoAnalytics.prototype.trackPageHits = function () {
1617
- var _this = this;
1618
- // Install a single, instance-agnostic wrapper around history.pushState /
1619
- // replaceState so concurrent SDK instances (React Strict Mode, HMR) don't
1620
- // each stack their own wrapper - which would dispatch N synthetic events
1621
- // per navigation and produce O(N^2) onLocationChange calls. The wrapper
1622
- // dispatches once; per-instance bookkeeping is done by per-instance
1623
- // listeners that each register/unregister themselves.
1624
- FormoAnalytics.installHistoryHooksOnce();
1625
- this._onPopStateListener = function () { return _this.onLocationChange(); };
1626
- this._onLocationChangeListener = function () { return _this.onLocationChange(); };
1627
- window.addEventListener("popstate", this._onPopStateListener);
1628
- window.addEventListener("locationchange", this._onLocationChangeListener);
1629
- };
1630
- /**
1631
- * Wrap history.pushState / replaceState exactly once per `history` object,
1632
- * regardless of how many SDK instances are constructed. Uses a Symbol
1633
- * marker so we recognize our own wrapper across module reloads in HMR.
1634
- */
1635
- FormoAnalytics.installHistoryHooksOnce = function () {
1636
- if (typeof history === "undefined" || typeof window === "undefined")
1637
- return;
1638
- var marker = Symbol.for("formo.historyWrapped");
1639
- if (history[marker])
1640
- return;
1641
- history[marker] = true;
1642
- var dispatch = function () { return window.dispatchEvent(new window.Event("locationchange")); };
1643
- var oldPushState = history.pushState;
1644
- history.pushState = function pushState() {
1645
- var args = [];
1646
- for (var _i = 0; _i < arguments.length; _i++) {
1647
- args[_i] = arguments[_i];
1648
- }
1649
- var ret = oldPushState.apply(this, args);
1650
- dispatch();
1651
- return ret;
1652
- };
1653
- var oldReplaceState = history.replaceState;
1654
- history.replaceState = function replaceState() {
1655
- var args = [];
1656
- for (var _i = 0; _i < arguments.length; _i++) {
1657
- args[_i] = arguments[_i];
1658
- }
1659
- var ret = oldReplaceState.apply(this, args);
1660
- dispatch();
1661
- return ret;
1662
- };
1663
- };
1664
- FormoAnalytics.prototype.trackPageHit = function (category, name, properties, context, callback) {
1665
- return __awaiter(this, void 0, void 0, function () {
1666
- var _this = this;
1667
- return __generator(this, function (_a) {
1668
- if (!this.shouldTrack()) {
1669
- logger.info("Track page hit: Skipping event due to tracking configuration");
1670
- return [2 /*return*/];
1671
- }
1672
- setTimeout(function () {
1673
- // Drop in-flight page hits from an SDK instance that was torn down
1674
- // between scheduling and firing (e.g. provider remount in React Strict
1675
- // Mode / HMR). Otherwise the orphan instance would queue a page event
1676
- // here with its stale, never-populated `currentAddress`.
1677
- if (_this._pageHooksDisposed)
1678
- return;
1679
- (function () { return __awaiter(_this, void 0, void 0, function () {
1680
- var e_7;
1681
- return __generator(this, function (_a) {
1682
- switch (_a.label) {
1683
- case 0:
1684
- _a.trys.push([0, 2, , 3]);
1685
- return [4 /*yield*/, this.trackEvent(EventType.PAGE, {
1686
- category: category,
1687
- name: name,
1688
- }, properties, context, callback)];
1689
- case 1:
1690
- _a.sent();
1691
- return [3 /*break*/, 3];
1692
- case 2:
1693
- e_7 = _a.sent();
1694
- logger.error("Formo: Failed to track page hit", e_7);
1695
- return [3 /*break*/, 3];
1696
- case 3: return [2 /*return*/];
1697
- }
1698
- });
1699
- }); })();
1700
- }, 300);
1701
- return [2 /*return*/];
1702
- });
1703
- });
1704
- };
1705
- FormoAnalytics.prototype.trackEvent = function (type, payload, properties, context, callback) {
1706
- return __awaiter(this, void 0, void 0, function () {
1707
- var error_5;
1708
- return __generator(this, function (_a) {
1709
- switch (_a.label) {
1710
- case 0:
1711
- _a.trys.push([0, 2, , 3]);
1712
- if (!this.shouldTrack()) {
1713
- logger.info("Skipping ".concat(type, " event due to tracking configuration"));
1714
- return [2 /*return*/];
1715
- }
1716
- return [4 /*yield*/, this.eventManager.addEvent(__assign(__assign({ type: type }, payload), { properties: properties, context: context, callback: callback }), this.currentAddress, this.currentUserId)];
1717
- case 1:
1718
- _a.sent();
1719
- return [3 /*break*/, 3];
1720
- case 2:
1721
- error_5 = _a.sent();
1722
- logger.error("Error tracking event:", error_5);
1723
- return [3 /*break*/, 3];
1724
- case 3: return [2 /*return*/];
1725
- }
1726
- });
1727
- });
1728
- };
1729
- /**
1730
- * Visitor-level tracking suppression.
1731
- *
1732
- * Returns true when the SDK must not persist any identity/session/chain
1733
- * state or send any events for this visitor - i.e. an explicit opt-out or a
1734
- * jurisdiction/timezone exclusion. Public entry points that write state
1735
- * before reaching the `shouldTrack()` event gate (identify/connect/detect)
1736
- * check this first so suppressed visitors leave no cookies or session state.
1737
- * @returns {boolean} True if all tracking and persistence must be suppressed
1738
- * @internal Also read by `identifyPrivyUser` (via a structural cast) so the
1739
- * Privy sync skips chain reconciliation and emission for suppressed visitors.
1740
- */
1741
- FormoAnalytics.prototype.isTrackingSuppressed = function () {
1742
- return this.hasOptedOutTracking() || this.isCurrentEnvironmentExcluded();
1743
- };
1744
- /**
1745
- * Whether the current chain id is in `tracking.excludeChains`.
1746
- *
1747
- * Split out from `shouldTrack()` so `identify()` can check it *before*
1748
- * mutating identity state. `trackEvent()` drops an excluded event silently
1749
- * and returns void, but `identify()` marks the wallet as identified first, so
1750
- * without this guard an identify on an excluded chain is dedup-marked and
1751
- * then discarded, and the wallet never re-emits for the rest of the session
1752
- * even after switching to an allowed chain. On the Privy path that loses the
1753
- * user's whole cluster at once rather than a single wallet.
1754
- *
1755
- * Mirrors the chain rule in `shouldTrack()`: only applies when `tracking` is
1756
- * an options object with `excludeChains` set, and only once a chain id is
1757
- * known.
1758
- */
1759
- FormoAnalytics.prototype.isCurrentChainExcluded = function () {
1760
- if (this.options.tracking === null ||
1761
- typeof this.options.tracking !== "object" ||
1762
- Array.isArray(this.options.tracking)) {
1763
- return false;
1764
- }
1765
- var _a = this.options.tracking.excludeChains, excludeChains = _a === void 0 ? [] : _a;
1766
- return (excludeChains.length > 0 &&
1767
- !!this.currentChainId &&
1768
- excludeChains.includes(this.currentChainId));
1769
- };
1770
- /**
1771
- * Whether the current environment is excluded from tracking - the visitor's
1772
- * timezone, the current hostname, or the current pathname matches a
1773
- * configured exclusion.
1774
- *
1775
- * Timezone is visitor/session-level (stable for the session); host/path are
1776
- * current-page-level and transient - if a SPA navigates to an allowed path,
1777
- * tracking resumes for future actions. Used as the "do not write identity or
1778
- * send events" gate at every entry point that would persist state before the
1779
- * `shouldTrack()` event gate.
1780
- * @returns {boolean} True if the current environment is excluded
1781
- */
1782
- FormoAnalytics.prototype.isCurrentEnvironmentExcluded = function () {
1783
- return (this.isTimezoneExcluded() ||
1784
- this.isHostExcluded() ||
1785
- this.isPathExcluded());
1786
- };
1787
- /**
1788
- * Whether the current hostname matches a configured `tracking.excludeHosts`
1789
- * entry (exact match). Current-page-level - see isCurrentEnvironmentExcluded.
1790
- * @returns {boolean} True if the current hostname is excluded
1791
- */
1792
- FormoAnalytics.prototype.isHostExcluded = function () {
1793
- var tracking = this.options.tracking;
1794
- if (tracking === null ||
1795
- typeof tracking !== "object" ||
1796
- Array.isArray(tracking)) {
1797
- return false;
1798
- }
1799
- if (typeof window === "undefined") {
1800
- return false;
1801
- }
1802
- var _a = tracking.excludeHosts, excludeHosts = _a === void 0 ? [] : _a;
1803
- return excludeHosts.includes(window.location.hostname);
1804
- };
1805
- /**
1806
- * Whether the current pathname matches a configured `tracking.excludePaths`
1807
- * entry (exact match). Current-page-level - see isCurrentEnvironmentExcluded.
1808
- * @returns {boolean} True if the current pathname is excluded
1809
- */
1810
- FormoAnalytics.prototype.isPathExcluded = function () {
1811
- var tracking = this.options.tracking;
1812
- if (tracking === null ||
1813
- typeof tracking !== "object" ||
1814
- Array.isArray(tracking)) {
1815
- return false;
1816
- }
1817
- if (typeof window === "undefined") {
1818
- return false;
1819
- }
1820
- var _a = tracking.excludePaths, excludePaths = _a === void 0 ? [] : _a;
1821
- return excludePaths.includes(window.location.pathname);
1822
- };
1823
- /**
1824
- * Whether the current call is in a visitor-level suppression state - opt-out
1825
- * or excluded timezone - for which any persisted identity cookie should be
1826
- * actively purged (not merely skipped). Host/path exclusions are
1827
- * deliberately excluded here: they are transient current-page states, so a
1828
- * cookie legitimately written on an allowed page must survive a visit to an
1829
- * excluded route.
1830
- * @returns {boolean} True if persisted identity must be purged
1831
- */
1832
- FormoAnalytics.prototype.isPersistedIdentityPurgeRequired = function () {
1833
- return this.hasOptedOutTracking() || this.isTimezoneExcluded();
1834
- };
1835
- /**
1836
- * Whether the visitor's browser-resolved timezone matches a configured
1837
- * `tracking.excludeTimezones` entry (case-insensitive). Client-side and
1838
- * best-effort - see TrackingOptions.excludeTimezones.
1839
- * @returns {boolean} True if the current timezone is excluded
1840
- */
1841
- FormoAnalytics.prototype.isTimezoneExcluded = function () {
1842
- var tracking = this.options.tracking;
1843
- if (tracking === null ||
1844
- typeof tracking !== "object" ||
1845
- Array.isArray(tracking)) {
1846
- return false;
1847
- }
1848
- var _a = tracking.excludeTimezones, excludeTimezones = _a === void 0 ? [] : _a;
1849
- if (excludeTimezones.length === 0) {
1850
- return false;
1851
- }
1852
- var timezone = getTimezone();
1853
- if (!timezone) {
1854
- return false;
1855
- }
1856
- var lowerTimezone = timezone.toLowerCase();
1857
- return excludeTimezones.some(function (tz) { return typeof tz === "string" && tz.toLowerCase() === lowerTimezone; });
1858
- };
1859
- /**
1860
- * Determines if tracking should be enabled based on configuration and consent
1861
- * @returns {boolean} True if tracking should be enabled
1862
- */
1863
- FormoAnalytics.prototype.shouldTrack = function () {
1864
- // First check if user has opted out of tracking
1865
- if (this.hasOptedOutTracking()) {
1866
- return false;
1867
- }
1868
- // Check if tracking is explicitly provided as a boolean
1869
- if (typeof this.options.tracking === "boolean") {
1870
- return this.options.tracking;
1871
- }
1872
- // Handle object configuration with exclusion rules
1873
- if (this.options.tracking !== null &&
1874
- typeof this.options.tracking === "object" &&
1875
- !Array.isArray(this.options.tracking)) {
1876
- var _a = this.options.tracking.excludeChains, excludeChains = _a === void 0 ? [] : _a;
1877
- // Environment exclusions (timezone / host / path) - no identify / connect
1878
- // / track events while excluded. Host/path are exact-match.
1879
- if (this.isCurrentEnvironmentExcluded()) {
1880
- return false;
1881
- }
1882
- // Check chainId exclusions
1883
- if (excludeChains.length > 0 &&
1884
- this.currentChainId &&
1885
- excludeChains.includes(this.currentChainId)) {
1886
- return false;
1887
- }
1888
- // If nothing is excluded, tracking is enabled
1889
- return true;
1890
- }
1891
- // Default behavior: track everywhere except localhost
1892
- return !isLocalhost();
1893
- };
1894
- /**
1895
- * Check if a specific wallet event type is enabled for autocapture
1896
- * @param eventType The wallet event type to check
1897
- * @returns {boolean} True if the event type should be autocaptured
1898
- */
1899
- FormoAnalytics.prototype.isAutocaptureEnabled = function (eventType) {
1900
- // If no configuration provided, default to enabled
1901
- if (this.options.autocapture === undefined) {
1902
- return true;
1903
- }
1904
- // If boolean, return that value for all events
1905
- if (typeof this.options.autocapture === "boolean") {
1906
- return this.options.autocapture;
1907
- }
1908
- // If it's an object, check the specific event configuration
1909
- if (this.options.autocapture !== null &&
1910
- typeof this.options.autocapture === "object") {
1911
- var eventConfig = this.options.autocapture[eventType];
1912
- // Default to true if not explicitly set to false
1913
- return eventConfig !== false;
1914
- }
1915
- // Default to enabled if no specific configuration
1916
- return true;
1917
- };
1918
- /*
1919
- Utility functions
1920
- */
1921
- /**
1922
- * Get provider information for a given provider
1923
- * @param provider The provider to get info for
1924
- * @returns Provider information
1925
- */
1926
- FormoAnalytics.prototype.getProviderInfo = function (provider) {
1927
- // First check if provider is in our EIP-6963 providers list
1928
- var eip6963Provider = this._providers.find(function (p) { return p.provider === provider; });
1929
- if (eip6963Provider) {
1930
- return {
1931
- name: eip6963Provider.info.name,
1932
- rdns: eip6963Provider.info.rdns,
1933
- };
1934
- }
1935
- // Fallback to injected provider detection
1936
- var injectedInfo = detectInjectedProviderInfo(provider);
1937
- return {
1938
- name: injectedInfo.name,
1939
- rdns: injectedInfo.rdns,
1940
- };
1941
- };
1942
- FormoAnalytics.prototype.getProviders = function () {
1943
- return __awaiter(this, void 0, void 0, function () {
1944
- var store, providers, injected_1, injectedProviderInfo, injectedDetail, uniqueProviders, _i, uniqueProviders_1, detail;
1945
- var _this = this;
1946
- return __generator(this, function (_a) {
1947
- store = createStore();
1948
- providers = store.getProviders();
1949
- store.subscribe(function (providerDetails) {
1950
- providers = providerDetails;
1951
- // Process newly added providers with proper deduplication
1952
- var newlyAddedDetails = providerDetails.filter(function (detail) {
1953
- var provider = detail === null || detail === void 0 ? void 0 : detail.provider;
1954
- return provider && !_this._seenProviders.has(provider);
1955
- });
1956
- // Add new providers to the array without overwriting existing ones
1957
- for (var _i = 0, newlyAddedDetails_1 = newlyAddedDetails; _i < newlyAddedDetails_1.length; _i++) {
1958
- var detail = newlyAddedDetails_1[_i];
1959
- _this.safeAddProviderDetail(detail);
1960
- }
1961
- // Track listeners for newly discovered providers only
1962
- var newDetails = providerDetails.filter(function (detail) {
1963
- var p = detail === null || detail === void 0 ? void 0 : detail.provider;
1964
- return !!p && !_this._trackedProviders.has(p);
1965
- });
1966
- if (newDetails.length > 0) {
1967
- _this.trackProviders(newDetails);
1968
- // Detect newly discovered wallets (session de-dupes) with error handling
1969
- (function () { return __awaiter(_this, void 0, void 0, function () {
1970
- var e_8;
1971
- return __generator(this, function (_a) {
1972
- switch (_a.label) {
1973
- case 0:
1974
- _a.trys.push([0, 2, , 3]);
1975
- return [4 /*yield*/, this.detectWallets(newDetails)];
1976
- case 1:
1977
- _a.sent();
1978
- return [3 /*break*/, 3];
1979
- case 2:
1980
- e_8 = _a.sent();
1981
- logger.error("Formo: Failed to detect wallets", e_8);
1982
- return [3 /*break*/, 3];
1983
- case 3: return [2 /*return*/];
1984
- }
1985
- });
1986
- }); })();
1987
- }
1988
- // Clean up providers that are no longer available
1989
- _this.cleanupUnavailableProviders();
1990
- });
1991
- // Fallback to injected provider if no providers are found
1992
- if (providers.length === 0) {
1993
- injected_1 = typeof window !== "undefined" ? window.ethereum : undefined;
1994
- if (injected_1) {
1995
- // If we have already detected and cached the injected provider, and it's the same instance, return the cached result
1996
- if (this._injectedProviderDetail &&
1997
- this._injectedProviderDetail.provider === injected_1) {
1998
- // Ensure it's tracked
1999
- if (!this._trackedProviders.has(injected_1)) {
2000
- this.trackEIP1193Provider(injected_1);
2001
- }
2002
- // Merge with existing providers instead of overwriting
2003
- if (!this._providers.some(function (existing) { return existing.provider === injected_1; })) {
2004
- this._providers = __spreadArray(__spreadArray([], this._providers, true), [
2005
- this._injectedProviderDetail,
2006
- ], false);
2007
- }
2008
- return [2 /*return*/, this._providers];
2009
- }
2010
- // Re-check if the injected provider is already tracked just before tracking
2011
- if (!this._trackedProviders.has(injected_1)) {
2012
- this.trackEIP1193Provider(injected_1);
2013
- }
2014
- injectedProviderInfo = detectInjectedProviderInfo(injected_1);
2015
- injectedDetail = {
2016
- provider: injected_1,
2017
- info: injectedProviderInfo,
2018
- };
2019
- // Cache the detected injected provider detail
2020
- this._injectedProviderDetail = injectedDetail;
2021
- // Merge with existing providers instead of overwriting
2022
- this.safeAddProviderDetail(injectedDetail);
2023
- }
2024
- return [2 /*return*/, this._providers];
2025
- }
2026
- uniqueProviders = providers.filter(function (detail) {
2027
- var provider = detail === null || detail === void 0 ? void 0 : detail.provider;
2028
- return provider && !_this._seenProviders.has(provider);
2029
- });
2030
- // Add to seen providers and instances, ensuring no duplicates in _providers
2031
- for (_i = 0, uniqueProviders_1 = uniqueProviders; _i < uniqueProviders_1.length; _i++) {
2032
- detail = uniqueProviders_1[_i];
2033
- this.safeAddProviderDetail(detail);
2034
- }
2035
- return [2 /*return*/, this._providers];
2036
- });
2037
- });
2038
- };
2039
- Object.defineProperty(FormoAnalytics.prototype, "providers", {
2040
- get: function () {
2041
- return this._providers;
2042
- },
2043
- enumerable: false,
2044
- configurable: true
2045
- });
2046
- FormoAnalytics.prototype.detectWallets = function (providers) {
2047
- return __awaiter(this, void 0, void 0, function () {
2048
- var _i, providers_2, eip6963ProviderDetail, err_2;
2049
- return __generator(this, function (_a) {
2050
- switch (_a.label) {
2051
- case 0:
2052
- _a.trys.push([0, 5, , 6]);
2053
- _i = 0, providers_2 = providers;
2054
- _a.label = 1;
2055
- case 1:
2056
- if (!(_i < providers_2.length)) return [3 /*break*/, 4];
2057
- eip6963ProviderDetail = providers_2[_i];
2058
- return [4 /*yield*/, this.detect({
2059
- providerName: eip6963ProviderDetail === null || eip6963ProviderDetail === void 0 ? void 0 : eip6963ProviderDetail.info.name,
2060
- rdns: eip6963ProviderDetail === null || eip6963ProviderDetail === void 0 ? void 0 : eip6963ProviderDetail.info.rdns,
2061
- })];
2062
- case 2:
2063
- _a.sent();
2064
- _a.label = 3;
2065
- case 3:
2066
- _i++;
2067
- return [3 /*break*/, 1];
2068
- case 4: return [3 /*break*/, 6];
2069
- case 5:
2070
- err_2 = _a.sent();
2071
- logger.error("Error detect all wallets:", err_2);
2072
- return [3 /*break*/, 6];
2073
- case 6: return [2 /*return*/];
2074
- }
2075
- });
2076
- });
2077
- };
2078
- Object.defineProperty(FormoAnalytics.prototype, "provider", {
2079
- get: function () {
2080
- return this._provider;
2081
- },
2082
- enumerable: false,
2083
- configurable: true
2084
- });
2085
- Object.defineProperty(FormoAnalytics.prototype, "solana", {
2086
- /**
2087
- * Access the Solana integration manager.
2088
- * Lazily creates one if not already initialized.
2089
- *
2090
- * @example
2091
- * ```tsx
2092
- * formo.solana.setStore(client.store);
2093
- * formo.solana.setCluster("devnet");
2094
- * // For signatures, use formo.signature() directly
2095
- * ```
2096
- */
2097
- get: function () {
2098
- if (!this.solanaManager) {
2099
- this.solanaManager = new SolanaManager(this);
2100
- }
2101
- return this.solanaManager;
2102
- },
2103
- enumerable: false,
2104
- configurable: true
2105
- });
2106
- FormoAnalytics.prototype.getAddress = function (provider) {
2107
- return __awaiter(this, void 0, void 0, function () {
2108
- var p, accounts, err_3, code;
2109
- return __generator(this, function (_a) {
2110
- switch (_a.label) {
2111
- case 0:
2112
- // Use EVM-specific state to avoid returning a Solana address in an EVM context
2113
- if (this._chainState.evm.address)
2114
- return [2 /*return*/, this._chainState.evm.address];
2115
- p = provider || this.provider;
2116
- if (!p) {
2117
- logger.info("The provider is not set");
2118
- return [2 /*return*/, null];
2119
- }
2120
- _a.label = 1;
2121
- case 1:
2122
- _a.trys.push([1, 3, , 4]);
2123
- return [4 /*yield*/, this.getAccounts(p)];
2124
- case 2:
2125
- accounts = _a.sent();
2126
- if (accounts && accounts.length > 0) {
2127
- return [2 /*return*/, validateAndChecksumAddress(accounts[0]) || null];
2128
- }
2129
- return [3 /*break*/, 4];
2130
- case 3:
2131
- err_3 = _a.sent();
2132
- code = err_3 === null || err_3 === void 0 ? void 0 : err_3.code;
2133
- if (code !== 4001) {
2134
- logger.error("FormoAnalytics::getAccounts: eth_accounts threw an error", err_3);
2135
- }
2136
- return [2 /*return*/, null];
2137
- case 4: return [2 /*return*/, null];
2138
- }
2139
- });
2140
- });
2141
- };
2142
- FormoAnalytics.prototype.getAccounts = function (provider) {
2143
- return __awaiter(this, void 0, void 0, function () {
2144
- var p, res, err_4, code;
2145
- return __generator(this, function (_a) {
2146
- switch (_a.label) {
2147
- case 0:
2148
- p = provider || this.provider;
2149
- _a.label = 1;
2150
- case 1:
2151
- _a.trys.push([1, 3, , 4]);
2152
- return [4 /*yield*/, (p === null || p === void 0 ? void 0 : p.request({
2153
- method: "eth_accounts",
2154
- }))];
2155
- case 2:
2156
- res = _a.sent();
2157
- if (!res || res.length === 0)
2158
- return [2 /*return*/, null];
2159
- return [2 /*return*/, res
2160
- .map(function (e) { return validateAndChecksumAddress(e); })
2161
- .filter(function (e) { return e !== undefined; })];
2162
- case 3:
2163
- err_4 = _a.sent();
2164
- code = err_4 === null || err_4 === void 0 ? void 0 : err_4.code;
2165
- if (code !== 4001) {
2166
- logger.error("FormoAnalytics::getAccounts: eth_accounts threw an error", err_4);
2167
- }
2168
- return [2 /*return*/, null];
2169
- case 4: return [2 /*return*/];
2170
- }
2171
- });
2172
- });
2173
- };
2174
- FormoAnalytics.prototype.getCurrentChainId = function (provider) {
2175
- return __awaiter(this, void 0, void 0, function () {
2176
- var p, chainIdHex, err_5;
1242
+ var p, chainIdHex, err_2;
2177
1243
  return __generator(this, function (_a) {
2178
1244
  switch (_a.label) {
2179
1245
  case 0:
@@ -2196,500 +1262,26 @@ var FormoAnalytics = /** @class */ (function () {
2196
1262
  }
2197
1263
  return [2 /*return*/, parseChainId(chainIdHex)];
2198
1264
  case 3:
2199
- err_5 = _a.sent();
2200
- logger.error("eth_chainId threw an error:", err_5);
1265
+ err_2 = _a.sent();
1266
+ logger.error("eth_chainId threw an error:", err_2);
2201
1267
  return [2 /*return*/, 0];
2202
1268
  case 4: return [2 /*return*/];
2203
1269
  }
2204
1270
  });
2205
1271
  });
2206
1272
  };
2207
- FormoAnalytics.prototype.buildSignatureEventPayload = function (method, params,
2208
- // Intentionally not read. Kept for positional call-site arity.
2209
- _response, chainId) {
2210
- var _a;
2211
- var rawAddress = method === "personal_sign"
2212
- ? params[1]
2213
- : params[0];
2214
- var validAddress = validateAndChecksumAddress(rawAddress);
2215
- if (!validAddress) {
2216
- throw new Error("Invalid address in signature payload: ".concat(rawAddress));
2217
- }
2218
- var effectiveChainId = (_a = chainId !== null && chainId !== void 0 ? chainId : this._evmChainId) !== null && _a !== void 0 ? _a : undefined;
2219
- this.backfillActiveWallet(validAddress, effectiveChainId);
2220
- var basePayload = {
2221
- chainId: effectiveChainId,
2222
- address: validAddress,
2223
- };
2224
- if (method === "personal_sign") {
2225
- var message = Buffer.from(params[0].slice(2), "hex").toString("utf8");
2226
- return __assign(__assign({}, basePayload), { message: message });
2227
- }
2228
- // eth_signTypedData*: params[1] is the full EIP-712 struct.
2229
- return __assign(__assign({}, basePayload), { message: params[1] });
2230
- };
2231
- FormoAnalytics.prototype.buildTransactionEventPayload = function (params, provider) {
2232
- return __awaiter(this, void 0, void 0, function () {
2233
- var _a, data, from, to, value, validAddress, chainId, _b;
2234
- return __generator(this, function (_c) {
2235
- switch (_c.label) {
2236
- case 0:
2237
- _a = params[0], data = _a.data, from = _a.from, to = _a.to, value = _a.value;
2238
- validAddress = validateAndChecksumAddress(from);
2239
- if (!validAddress) {
2240
- throw new Error("Invalid address in transaction payload: ".concat(from));
2241
- }
2242
- _b = this._evmChainId;
2243
- if (_b) return [3 /*break*/, 2];
2244
- return [4 /*yield*/, this.getCurrentChainId(provider)];
2245
- case 1:
2246
- _b = (_c.sent());
2247
- _c.label = 2;
2248
- case 2:
2249
- chainId = _b;
2250
- this.backfillActiveWallet(validAddress, chainId);
2251
- return [2 /*return*/, {
2252
- chainId: chainId,
2253
- data: data,
2254
- address: validAddress,
2255
- to: to,
2256
- value: value,
2257
- }];
2258
- }
2259
- });
2260
- });
2261
- };
2262
- /**
2263
- * Persist an EVM address discovered through autocapture (signature / transaction)
2264
- * as the current EVM address when none is currently set. This lets subsequent
2265
- * track()/page() calls carry the address even when the underlying wallet never
2266
- * fires an EIP-1193 `accountsChanged` event (embedded wallets, smart accounts,
2267
- * social-login wrappers). If `accountsChanged` later fires it overwrites this
2268
- * value in the normal way; existing connections are never clobbered.
2269
- */
2270
- FormoAnalytics.prototype.backfillActiveWallet = function (address, chainId) {
2271
- // Never learn identity while suppressed (opt-out / timezone / excluded host
2272
- // or path). A signature/transaction observed on an excluded route must not
2273
- // populate currentAddress for later allowed-page events. backfill only ever
2274
- // *adds* an address (it no-ops when one is already known), so there is no
2275
- // stale state to clear here.
2276
- if (this.isTrackingSuppressed())
2277
- return;
2278
- if (this._evmAddress)
2279
- return;
2280
- this.setChainState('evm', { address: address, chainId: chainId });
2281
- };
2282
- /**
2283
- * Apply an EVM autocapture connect/switch while tracking is suppressed
2284
- * (opt-out / timezone / excluded host or path): never LEARN the wallet, but
2285
- * if it is a switch away from an already-learned EVM wallet, drop the stale
2286
- * one (which also clears the active-wallet cookie) so it can't attach to a
2287
- * later allowed-page event.
2288
- */
2289
- FormoAnalytics.prototype.clearStaleEvmWalletOnSwitchWhileSuppressed = function (address) {
2290
- var evmAddress = this._chainState.evm.address;
2291
- var incoming = validateAndChecksumAddress(address);
2292
- if (evmAddress && incoming && incoming !== evmAddress) {
2293
- this.clearChainState('evm');
2294
- }
2295
- };
2296
- /**
2297
- * Polls for transaction receipt and emits tx.status = CONFIRMED or REVERTED.
2298
- */
2299
- FormoAnalytics.prototype.pollTransactionReceipt = function (provider_1, transactionHash_2, payload_1) {
2300
- return __awaiter(this, arguments, void 0, function (provider, transactionHash, payload, maxAttempts, intervalMs) {
2301
- var attempts, poll;
2302
- var _this = this;
2303
- if (maxAttempts === void 0) { maxAttempts = 10; }
2304
- if (intervalMs === void 0) { intervalMs = 3000; }
2305
- return __generator(this, function (_a) {
2306
- attempts = 0;
2307
- if (!provider)
2308
- return [2 /*return*/];
2309
- poll = function () { return __awaiter(_this, void 0, void 0, function () {
2310
- var receipt, e_9;
2311
- return __generator(this, function (_a) {
2312
- switch (_a.label) {
2313
- case 0:
2314
- _a.trys.push([0, 2, , 3]);
2315
- return [4 /*yield*/, provider.request({
2316
- method: "eth_getTransactionReceipt",
2317
- params: [transactionHash],
2318
- })];
2319
- case 1:
2320
- receipt = (_a.sent());
2321
- if (receipt) {
2322
- // status: 1 = success, 0 = reverted
2323
- if (receipt.status === "0x1" || receipt.status === 1) {
2324
- this.transaction(__assign(__assign({ status: TransactionStatus.CONFIRMED }, payload), { transactionHash: transactionHash }));
2325
- return [2 /*return*/];
2326
- }
2327
- else if (receipt.status === "0x0" || receipt.status === 0) {
2328
- this.transaction(__assign(__assign({ status: TransactionStatus.REVERTED }, payload), { transactionHash: transactionHash }));
2329
- return [2 /*return*/];
2330
- }
2331
- }
2332
- return [3 /*break*/, 3];
2333
- case 2:
2334
- e_9 = _a.sent();
2335
- logger.error("Error polling transaction receipt", e_9);
2336
- return [3 /*break*/, 3];
2337
- case 3:
2338
- attempts++;
2339
- if (attempts < maxAttempts) {
2340
- setTimeout(poll, intervalMs);
2341
- }
2342
- return [2 /*return*/];
2343
- }
2344
- });
2345
- }); };
2346
- poll();
2347
- return [2 /*return*/];
2348
- });
2349
- });
2350
- };
2351
- FormoAnalytics.prototype.removeProviderListeners = function (provider) {
2352
- var listeners = this._providerListenersMap.get(provider);
2353
- if (!listeners)
2354
- return;
2355
- for (var _i = 0, _a = Object.entries(listeners); _i < _a.length; _i++) {
2356
- var _b = _a[_i], event_1 = _b[0], fn = _b[1];
2357
- try {
2358
- provider.removeListener(event_1, fn);
2359
- }
2360
- catch (e) {
2361
- logger.warn("Failed to remove listener for ".concat(String(event_1)), e);
2362
- }
2363
- }
2364
- this._providerListenersMap.delete(provider);
2365
- };
2366
1273
  // Explicitly untrack a provider: remove listeners, clear wrapper flag
2367
1274
  // and tracking
2368
- FormoAnalytics.prototype.untrackProvider = function (provider) {
2369
- try {
2370
- this.removeProviderListeners(provider);
2371
- this._trackedProviders.delete(provider);
2372
- if (this._provider === provider) {
2373
- this.clearActiveProvider();
2374
- }
2375
- }
2376
- catch (e) {
2377
- logger.warn("Failed to untrack provider", e);
2378
- }
2379
- };
2380
1275
  // Debug/monitoring helpers
2381
1276
  FormoAnalytics.prototype.getTrackedProvidersCount = function () {
2382
- return this._trackedProviders.size;
1277
+ return this.evm.counts.trackedProviders;
2383
1278
  };
2384
1279
  /**
2385
1280
  * Get current provider state for debugging
2386
1281
  * @returns Object containing current provider state information
2387
1282
  */
2388
1283
  FormoAnalytics.prototype.getProviderState = function () {
2389
- return {
2390
- totalProviders: this._providers.length,
2391
- trackedProviders: this._trackedProviders.size,
2392
- seenProviders: this._seenProviders.size,
2393
- activeProvider: !!this._provider,
2394
- };
2395
- };
2396
- /**
2397
- * Clean up providers that are no longer available
2398
- * This helps maintain consistent state and prevents memory leaks
2399
- */
2400
- FormoAnalytics.prototype.cleanupUnavailableProviders = function () {
2401
- // Remove providers that are no longer in the current providers list
2402
- var currentProviderInstances = new Set(this._providers.map(function (detail) { return detail.provider; }));
2403
- for (var _i = 0, _a = Array.from(this._trackedProviders); _i < _a.length; _i++) {
2404
- var provider = _a[_i];
2405
- if (!currentProviderInstances.has(provider)) {
2406
- logger.info("Cleaning up unavailable provider: ".concat(provider.constructor.name));
2407
- this.untrackProvider(provider);
2408
- }
2409
- }
2410
- };
2411
- /**
2412
- * Helper method to check if a provider is already wrapped
2413
- * @param provider The provider to check
2414
- * @param currentRequest The current request function
2415
- * @returns true if the provider is already wrapped
2416
- */
2417
- FormoAnalytics.prototype.isProviderAlreadyWrapped = function (provider, currentRequest) {
2418
- return !!(currentRequest &&
2419
- typeof currentRequest === "function" &&
2420
- currentRequest[WRAPPED_REQUEST_SYMBOL] &&
2421
- provider[WRAPPED_REQUEST_REF_SYMBOL] ===
2422
- currentRequest);
2423
- };
2424
- /**
2425
- * Handle provider mismatch by switching to the new provider and invalidating old tokens
2426
- * @param provider The new provider to switch to
2427
- */
2428
- FormoAnalytics.prototype.handleProviderMismatch = function (provider) {
2429
- // If this is a different provider, allow the switch
2430
- if (this._provider) {
2431
- // Clear any provider-specific state when switching
2432
- this.setChainState('evm', { address: undefined, chainId: undefined, provider: provider });
2433
- }
2434
- else {
2435
- this._provider = provider;
2436
- }
2437
- };
2438
- /**
2439
- * Determine which namespace a chainId belongs to.
2440
- */
2441
- FormoAnalytics.prototype.getNamespace = function (chainId) {
2442
- return isSolanaChainId(chainId) ? 'solana' : 'evm';
2443
- };
2444
- /**
2445
- * Update per-chain state and sync the derived currentAddress/currentChainId.
2446
- * Accepts either a namespace string ('evm'/'solana') or a chainId number
2447
- * to resolve the namespace automatically. When a chainId number is passed,
2448
- * it is also stored as the namespace's chainId (unless explicitly overridden
2449
- * in the update object).
2450
- */
2451
- FormoAnalytics.prototype.setChainState = function (namespaceOrChainId, update) {
2452
- var namespace = typeof namespaceOrChainId === 'string'
2453
- ? namespaceOrChainId
2454
- : this.getNamespace(namespaceOrChainId);
2455
- var ns = this._chainState[namespace];
2456
- if ('address' in update)
2457
- ns.address = update.address;
2458
- if ('chainId' in update) {
2459
- ns.chainId = update.chainId;
2460
- }
2461
- else if (typeof namespaceOrChainId === 'number') {
2462
- ns.chainId = namespaceOrChainId;
2463
- }
2464
- if (namespace === 'evm' && 'provider' in update) {
2465
- ns.provider = update.provider;
2466
- }
2467
- this._activeNamespace = namespace;
2468
- this.syncDerivedState();
2469
- };
2470
- /**
2471
- * Clear per-chain state for a given namespace (or chainId) and sync derived state.
2472
- */
2473
- FormoAnalytics.prototype.clearChainState = function (namespaceOrChainId) {
2474
- var namespace = typeof namespaceOrChainId === 'string'
2475
- ? namespaceOrChainId
2476
- : this.getNamespace(namespaceOrChainId);
2477
- if (namespace === 'evm') {
2478
- this._chainState.evm = {};
2479
- }
2480
- else {
2481
- this._chainState.solana = {};
2482
- }
2483
- this.syncDerivedState();
2484
- };
2485
- /**
2486
- * Sync validated wallet/chain state into the SDK's central state
2487
- * WITHOUT emitting an event.
2488
- *
2489
- * Integrations (e.g. the wagmi handler) must call this on every
2490
- * connect / chain-change / disconnect - even when the corresponding
2491
- * autocapture event is disabled. Otherwise `currentChainId` stays
2492
- * stale/undefined and `shouldTrack()`'s `tracking.excludeChains`
2493
- * check (which keys off `currentChainId`, not the event payload) can
2494
- * be bypassed, letting wallet activity on an excluded chain still be
2495
- * collected.
2496
- *
2497
- * - valid `address` present → record per-chain + derived state
2498
- * - `address` absent → clear chain state (disconnect)
2499
- */
2500
- FormoAnalytics.prototype.syncWalletState = function (params) {
2501
- var chainId = params.chainId, address = params.address;
2502
- if (this.isTrackingSuppressed()) {
2503
- // While suppressed (opt-out / timezone / excluded host or path) we must
2504
- // never LEARN a new wallet - but we must still CLEAR stale identity.
2505
- // Otherwise a disconnect or wallet switch observed on a suppressed route
2506
- // would leave the previously-learned address in memory and in the
2507
- // active-wallet cookie, attaching it to later allowed-page events.
2508
- if (!address) {
2509
- // Disconnect: drop the affected namespace(s).
2510
- if (chainId !== undefined && chainId !== null) {
2511
- this.clearChainState(chainId);
2512
- }
2513
- else {
2514
- this.clearChainState("evm");
2515
- this.clearChainState("solana");
2516
- }
2517
- return;
2518
- }
2519
- // Address present: a switch away from the wallet already learned in this
2520
- // namespace invalidates it. Drop the stale one without learning the new
2521
- // address; a fresh connect (nothing learned yet) or a re-confirmation of
2522
- // the same address is a no-op.
2523
- if (chainId === null || chainId === undefined)
2524
- return;
2525
- var namespace = this.getNamespace(chainId);
2526
- var namespaceAddress = this._chainState[namespace].address;
2527
- var validIncoming = validateAddress(address, chainId);
2528
- if (namespaceAddress &&
2529
- validIncoming &&
2530
- validIncoming !== namespaceAddress) {
2531
- this.clearChainState(chainId);
2532
- }
2533
- return;
2534
- }
2535
- if (!address) {
2536
- if (chainId !== undefined && chainId !== null) {
2537
- this.clearChainState(chainId);
2538
- }
2539
- else {
2540
- this.clearChainState("evm");
2541
- this.clearChainState("solana");
2542
- }
2543
- return;
2544
- }
2545
- if (chainId === null || chainId === undefined)
2546
- return;
2547
- var validAddress = validateAddress(address, chainId);
2548
- if (!validAddress) {
2549
- logger.warn("syncWalletState: invalid address (\"".concat(address, "\") for chain ").concat(chainId));
2550
- return;
2551
- }
2552
- this.setChainState(chainId, { address: validAddress });
2553
- };
2554
- /**
2555
- * Synchronize currentAddress/currentChainId from the active namespace.
2556
- * Last-connected-chain-wins: _activeNamespace takes precedence.
2557
- */
2558
- FormoAnalytics.prototype.syncDerivedState = function () {
2559
- var active = this._activeNamespace;
2560
- if (active) {
2561
- var state = this._chainState[active];
2562
- if (state.address || state.chainId) {
2563
- this.currentAddress = state.address;
2564
- this.currentChainId = state.chainId;
2565
- this.persistActiveWallet();
2566
- return;
2567
- }
2568
- }
2569
- // Fall through to the other namespace
2570
- var other = active === 'evm' ? 'solana' : 'evm';
2571
- var otherState = this._chainState[other];
2572
- if (otherState.address || otherState.chainId) {
2573
- this.currentAddress = otherState.address;
2574
- this.currentChainId = otherState.chainId;
2575
- this._activeNamespace = other;
2576
- this.persistActiveWallet();
2577
- return;
2578
- }
2579
- this.currentAddress = undefined;
2580
- this.currentChainId = undefined;
2581
- this.persistActiveWallet();
2582
- };
2583
- /**
2584
- * Persist (or clear) the current wallet snapshot in a cookie so that the
2585
- * SDK can repopulate `currentAddress`/`currentChainId` at init on the next
2586
- * page load - closing the gap between page-show and wagmi/EIP-1193
2587
- * reconnection during which track()/page() events would otherwise ship
2588
- * with an empty address.
2589
- */
2590
- FormoAnalytics.prototype.persistActiveWallet = function () {
2591
- try {
2592
- // Visitor-level suppression (opt-out or excluded timezone): purge any
2593
- // prior snapshot - these are stable for the session, so deletion is safe.
2594
- if (this.isPersistedIdentityPurgeRequired()) {
2595
- cookie().remove(ACTIVE_WALLET_KEY);
2596
- return;
2597
- }
2598
- if (this.currentAddress) {
2599
- // Current-page exclusion (host/path): do not write a new snapshot while
2600
- // on an excluded route, but leave any existing cookie intact. A cookie
2601
- // written on an allowed page must survive a transient visit to an
2602
- // excluded one (passive navigation does not call this method).
2603
- if (this.isHostExcluded() || this.isPathExcluded()) {
2604
- return;
2605
- }
2606
- var value = JSON.stringify(__assign({ address: this.currentAddress }, (this.currentChainId !== undefined && { chainId: this.currentChainId })));
2607
- var domain = getIdentityCookieDomain(this.crossSubdomainCookies);
2608
- cookie().set(ACTIVE_WALLET_KEY, value, __assign(__assign({ path: "/", expires: new Date(Date.now() + ACTIVE_WALLET_TTL_MS).toUTCString() }, getIdentityCookieSecurity()), (domain ? { domain: domain } : {})));
2609
- }
2610
- else {
2611
- // No active wallet → clear the snapshot. This runs even on an excluded
2612
- // route, so a disconnect/switch observed while suppressed actively
2613
- // removes stale identity instead of leaving it for later allowed events.
2614
- cookie().remove(ACTIVE_WALLET_KEY);
2615
- }
2616
- }
2617
- catch (err) {
2618
- logger.warn("Failed to persist current wallet snapshot", err);
2619
- }
2620
- };
2621
- /**
2622
- * Seed `currentAddress`/`currentChainId` from the persisted snapshot, if
2623
- * any. Called once during construction before the first page hit fires.
2624
- */
2625
- FormoAnalytics.prototype.loadActiveWallet = function () {
2626
- try {
2627
- // Visitor-level suppression (opt-out or excluded timezone): never restore
2628
- // identity into memory; drop the stale snapshot.
2629
- if (this.isPersistedIdentityPurgeRequired()) {
2630
- cookie().remove(ACTIVE_WALLET_KEY);
2631
- return;
2632
- }
2633
- // Current-page exclusion (host/path): don't restore into memory while on
2634
- // an excluded route, but keep the cookie so a later allowed-page load can
2635
- // restore it.
2636
- if (this.isHostExcluded() || this.isPathExcluded()) {
2637
- return;
2638
- }
2639
- var raw = cookie().get(ACTIVE_WALLET_KEY);
2640
- if (!raw)
2641
- return;
2642
- var parsed = JSON.parse(raw);
2643
- if (!(parsed === null || parsed === void 0 ? void 0 : parsed.address))
2644
- return;
2645
- var namespace = isSolanaChainId(parsed.chainId) ? "solana" : "evm";
2646
- var validated = validateAddress(parsed.address, parsed.chainId);
2647
- if (!validated) {
2648
- cookie().remove(ACTIVE_WALLET_KEY);
2649
- return;
2650
- }
2651
- var ns = this._chainState[namespace];
2652
- ns.address = validated;
2653
- if (parsed.chainId !== undefined)
2654
- ns.chainId = parsed.chainId;
2655
- this._activeNamespace = namespace;
2656
- this.currentAddress = validated;
2657
- this.currentChainId = parsed.chainId;
2658
- }
2659
- catch (err) {
2660
- logger.warn("Failed to restore persisted wallet snapshot", err);
2661
- cookie().remove(ACTIVE_WALLET_KEY);
2662
- }
2663
- };
2664
- /**
2665
- * Helper method to clear the active provider state
2666
- * Centralizes provider clearing logic for consistency
2667
- */
2668
- FormoAnalytics.prototype.clearActiveProvider = function () {
2669
- this._provider = undefined;
2670
- };
2671
- /**
2672
- * Helper method to safely add a provider detail to _providers array, ensuring no duplicates
2673
- * @param detail The provider detail to add
2674
- * @returns true if the provider was added, false if it was already present
2675
- */
2676
- FormoAnalytics.prototype.safeAddProviderDetail = function (detail) {
2677
- var provider = detail === null || detail === void 0 ? void 0 : detail.provider;
2678
- if (!provider)
2679
- return false;
2680
- // Check if provider already exists in _providers array
2681
- var alreadyExists = this._providers.some(function (existing) { return existing.provider === provider; });
2682
- if (!alreadyExists) {
2683
- // Add to providers array and mark as seen
2684
- this._providers = __spreadArray(__spreadArray([], this._providers, true), [detail], false);
2685
- this._seenProviders.add(provider);
2686
- return true;
2687
- }
2688
- else {
2689
- // Ensure provider is marked as seen even if it already exists in _providers
2690
- this._seenProviders.add(provider);
2691
- return false;
2692
- }
1284
+ return __assign(__assign({}, this.evm.counts), { activeProvider: !!this._provider });
2693
1285
  };
2694
1286
  return FormoAnalytics;
2695
1287
  }());