@dynamic-labs/global-wallet-client 4.9.10 → 4.9.12

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 (34) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/package.cjs +1 -1
  3. package/package.js +1 -1
  4. package/package.json +7 -7
  5. package/src/lib/actions/connectAction/createConnectAction.cjs +1 -3
  6. package/src/lib/actions/connectAction/createConnectAction.js +2 -4
  7. package/src/lib/constants/logger.cjs +10 -0
  8. package/src/lib/constants/logger.js +6 -0
  9. package/src/lib/functions/createPopupOpener/createPopupOpener.cjs +41 -107
  10. package/src/lib/functions/createPopupOpener/createPopupOpener.js +42 -108
  11. package/src/lib/functions/createPopupOpener/utils/mapErrorFromPopup.d.ts +1 -1
  12. package/src/lib/functions/mergeAndEncryptParams/index.d.ts +1 -0
  13. package/src/lib/functions/mergeAndEncryptParams/mergeAndEncryptParams.cjs +23 -0
  14. package/src/lib/functions/mergeAndEncryptParams/mergeAndEncryptParams.d.ts +2 -0
  15. package/src/lib/functions/mergeAndEncryptParams/mergeAndEncryptParams.js +19 -0
  16. package/src/lib/functions/mergeURLSearchParams/index.d.ts +1 -0
  17. package/src/lib/functions/mergeURLSearchParams/mergeURLSearchParams.cjs +17 -0
  18. package/src/lib/functions/mergeURLSearchParams/mergeURLSearchParams.d.ts +6 -0
  19. package/src/lib/functions/mergeURLSearchParams/mergeURLSearchParams.js +13 -0
  20. package/src/lib/functions/waitForPopupResponse/index.d.ts +1 -0
  21. package/src/lib/functions/waitForPopupResponse/waitForPopupResponse.cjs +61 -0
  22. package/src/lib/functions/waitForPopupResponse/waitForPopupResponse.d.ts +9 -0
  23. package/src/lib/functions/waitForPopupResponse/waitForPopupResponse.js +57 -0
  24. package/src/lib/store/createClientStore.cjs +1 -23
  25. package/src/lib/store/createClientStore.d.ts +0 -14
  26. package/src/lib/store/createClientStore.js +1 -23
  27. package/src/lib/errors/UnknownError.cjs +0 -12
  28. package/src/lib/errors/UnknownError.js +0 -8
  29. package/src/lib/functions/createEncryptedMessageEncoder/createEncryptedMessageEncoder.cjs +0 -19
  30. package/src/lib/functions/createEncryptedMessageEncoder/createEncryptedMessageEncoder.js +0 -15
  31. package/src/lib/functions/createPopupMessageClient/createPopupMessageClient.cjs +0 -74
  32. package/src/lib/functions/createPopupMessageClient/createPopupMessageClient.js +0 -70
  33. package/src/lib/functions/createPopupOpener/utils/mapErrorFromPopup.cjs +0 -25
  34. package/src/lib/functions/createPopupOpener/utils/mapErrorFromPopup.js +0 -21
package/CHANGELOG.md CHANGED
@@ -1,4 +1,21 @@
1
1
 
2
+ ### [4.9.12](https://github.com/dynamic-labs/dynamic-auth/compare/v4.9.11...v4.9.12) (2025-03-28)
3
+
4
+
5
+ ### Bug Fixes
6
+
7
+ * prevent event subscription from throwing a page error ([#8393](https://github.com/dynamic-labs/dynamic-auth/issues/8393)) ([eda85cd](https://github.com/dynamic-labs/dynamic-auth/commit/eda85cdeed4cc208e20618882cf3e5a54b176356))
8
+ * global wallet popup in rainbowkit reopening ([#8395](https://github.com/dynamic-labs/dynamic-auth/issues/8395)) ([5473e87](https://github.com/dynamic-labs/dynamic-auth/commit/5473e87834c5a2102f7d87fc649590726bc390c7))
9
+ * notify user when sei is not enable in keplr ([#8396](https://github.com/dynamic-labs/dynamic-auth/issues/8396)) ([79aea59](https://github.com/dynamic-labs/dynamic-auth/commit/79aea59bde82dabbe070a1f0fc5ac484a696e7ac))
10
+ * respect tokenBalance order from backend for SendBalance view ([#8398](https://github.com/dynamic-labs/dynamic-auth/issues/8398)) ([fdb0e1c](https://github.com/dynamic-labs/dynamic-auth/commit/fdb0e1cc2f1614326f506dfdb1726f4c5baf9c0c))
11
+
12
+ ### [4.9.11](https://github.com/dynamic-labs/dynamic-auth/compare/v4.9.10...v4.9.11) (2025-03-26)
13
+
14
+
15
+ ### Bug Fixes
16
+
17
+ * ensure global wallet users can disconnect from dapp ([#8389](https://github.com/dynamic-labs/dynamic-auth/issues/8389)) ([79e5892](https://github.com/dynamic-labs/dynamic-auth/commit/79e58921de673757dc0662977ed4eb391aaaf632))
18
+
2
19
  ### [4.9.10](https://github.com/dynamic-labs/dynamic-auth/compare/v4.9.9...v4.9.10) (2025-03-26)
3
20
 
4
21
 
package/package.cjs CHANGED
@@ -3,6 +3,6 @@
3
3
 
4
4
  Object.defineProperty(exports, '__esModule', { value: true });
5
5
 
6
- var version = "4.9.10";
6
+ var version = "4.9.12";
7
7
 
8
8
  exports.version = version;
package/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  'use client'
2
- var version = "4.9.10";
2
+ var version = "4.9.12";
3
3
 
4
4
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dynamic-labs/global-wallet-client",
3
- "version": "4.9.10",
3
+ "version": "4.9.12",
4
4
  "description": "Core package for building Dynamic's Global Wallet",
5
5
  "author": "Dynamic Labs, Inc.",
6
6
  "license": "MIT",
@@ -39,12 +39,12 @@
39
39
  },
40
40
  "homepage": "https://www.dynamic.xyz/",
41
41
  "dependencies": {
42
- "@dynamic-labs/assert-package-version": "4.9.10",
43
- "@dynamic-labs/logger": "4.9.10",
44
- "@dynamic-labs/message-transport": "4.9.10",
45
- "@dynamic-labs/store": "4.9.10",
46
- "@dynamic-labs/types": "4.9.10",
47
- "@dynamic-labs/utils": "4.9.10",
42
+ "@dynamic-labs/assert-package-version": "4.9.12",
43
+ "@dynamic-labs/logger": "4.9.12",
44
+ "@dynamic-labs/message-transport": "4.9.12",
45
+ "@dynamic-labs/store": "4.9.12",
46
+ "@dynamic-labs/types": "4.9.12",
47
+ "@dynamic-labs/utils": "4.9.12",
48
48
  "eventemitter3": "5.0.1"
49
49
  },
50
50
  "peerDependencies": {
@@ -18,9 +18,7 @@ const createConnectAction = ({ store, openPopup, onConnect }) => (_a) => _tslib.
18
18
  });
19
19
  const { encryptedMessage, expiresAt, iv, providerPublicKey } = data;
20
20
  const sharedSecret = yield utils.deriveSharedSecret(keyPair.privateKey, yield utils.convertPublicKeyHexToCryptoKey(providerPublicKey));
21
- const { sessionAuthCode } = store;
22
- utils.assertDefined(sessionAuthCode, 'Session auth code is required');
23
- const message = yield utils.decryptMessage(sharedSecret, encryptedMessage, iv, sessionAuthCode);
21
+ const message = yield utils.decryptMessage(sharedSecret, encryptedMessage, iv);
24
22
  const { ethereum, solana, wallets } = JSON.parse(message);
25
23
  store.setInitialConnectionState({
26
24
  connection: {
@@ -1,6 +1,6 @@
1
1
  'use client'
2
2
  import { __awaiter } from '../../../../_virtual/_tslib.js';
3
- import { createKeyPair, convertPublicKeyCryptoKeyToHex, deriveSharedSecret, convertPublicKeyHexToCryptoKey, assertDefined, decryptMessage } from '@dynamic-labs/utils';
3
+ import { createKeyPair, convertPublicKeyCryptoKeyToHex, deriveSharedSecret, convertPublicKeyHexToCryptoKey, decryptMessage } from '@dynamic-labs/utils';
4
4
 
5
5
  const createConnectAction = ({ store, openPopup, onConnect }) => (_a) => __awaiter(void 0, [_a], void 0, function* ({ chain }) {
6
6
  store.clear();
@@ -14,9 +14,7 @@ const createConnectAction = ({ store, openPopup, onConnect }) => (_a) => __await
14
14
  });
15
15
  const { encryptedMessage, expiresAt, iv, providerPublicKey } = data;
16
16
  const sharedSecret = yield deriveSharedSecret(keyPair.privateKey, yield convertPublicKeyHexToCryptoKey(providerPublicKey));
17
- const { sessionAuthCode } = store;
18
- assertDefined(sessionAuthCode, 'Session auth code is required');
19
- const message = yield decryptMessage(sharedSecret, encryptedMessage, iv, sessionAuthCode);
17
+ const message = yield decryptMessage(sharedSecret, encryptedMessage, iv);
20
18
  const { ethereum, solana, wallets } = JSON.parse(message);
21
19
  store.setInitialConnectionState({
22
20
  connection: {
@@ -0,0 +1,10 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var logger$1 = require('@dynamic-labs/logger');
7
+
8
+ const logger = new logger$1.Logger('@dynamic-labs/global-wallet-client');
9
+
10
+ exports.logger = logger;
@@ -0,0 +1,6 @@
1
+ 'use client'
2
+ import { Logger } from '@dynamic-labs/logger';
3
+
4
+ const logger = new Logger('@dynamic-labs/global-wallet-client');
5
+
6
+ export { logger };
@@ -5,146 +5,80 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
 
6
6
  var _tslib = require('../../../../_virtual/_tslib.cjs');
7
7
  var utils = require('@dynamic-labs/utils');
8
+ var waitForPopupResponse = require('../waitForPopupResponse/waitForPopupResponse.cjs');
8
9
  var onPopupClose = require('../onPopupClose/onPopupClose.cjs');
10
+ var mergeAndEncryptParams = require('../mergeAndEncryptParams/mergeAndEncryptParams.cjs');
9
11
  var getCenteredPopupFeatures = require('../getCenteredPopupFeatures/getCenteredPopupFeatures.cjs');
10
- var createPopupMessageClient = require('../createPopupMessageClient/createPopupMessageClient.cjs');
11
- var createEncryptedMessageEncoder = require('../createEncryptedMessageEncoder/createEncryptedMessageEncoder.cjs');
12
12
  var PopupClosedError = require('../../errors/PopupClosedError.cjs');
13
- var mapErrorFromPopup = require('./utils/mapErrorFromPopup.cjs');
14
13
 
15
14
  const createPopupOpener = ({ environmentId, popupUrl, popupWidth = 420, popupHeight = 640, store, popupActionTimeout = 1000, // Wait page up to 1 second for new actions before closing
16
15
  onError, }) => {
17
16
  let popup = null;
17
+ let didOpenPopup = false;
18
18
  let lastActionId = null;
19
- let clientSessionKeyPair = null;
20
19
  const closePopup = () => {
21
20
  popup === null || popup === void 0 ? void 0 : popup.close();
22
21
  popup = null;
22
+ didOpenPopup = false;
23
23
  lastActionId = null;
24
24
  };
25
- // TODO update definition here to use name and args
26
25
  return (_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ params, pathname, }) {
27
- clientSessionKeyPair = clientSessionKeyPair !== null && clientSessionKeyPair !== void 0 ? clientSessionKeyPair : (yield utils.createKeyPair());
28
26
  // Used as a unique identifier for the action
29
- const actionId = new Date().getTime().toString();
27
+ const actionId = new Date().getTime();
30
28
  lastActionId = actionId;
31
29
  const popupFinalUrl = new URL(popupUrl);
32
30
  const activeConnection = store.getActiveConnection();
31
+ const resultDeferredPromise = new utils.DeferredPromise();
33
32
  // Setup popup URL and data
33
+ popupFinalUrl.hash = `/${pathname}`;
34
34
  popupFinalUrl.searchParams.set('provider_env_id', environmentId);
35
+ // TODO: use PlatformService
35
36
  popupFinalUrl.searchParams.set('requester_origin', window.location.origin);
36
- popupFinalUrl.searchParams.set('client_session_public_key', yield utils.convertPublicKeyCryptoKeyToHex(clientSessionKeyPair.publicKey));
37
- /**
38
- * Open a new popup centered on the screen
39
- */
40
- const initializePopup = () => {
37
+ if (popup === null) {
41
38
  const features = getCenteredPopupFeatures.getCenteredPopupFeatures({
42
39
  height: popupHeight,
43
40
  width: popupWidth,
44
41
  });
45
42
  // Open popup
46
- const popup = window.open('', '_blank', features);
47
- if (popup === null) {
48
- throw new Error('Failed to open popup');
49
- }
50
- popup.location = popupFinalUrl.href;
51
- return popup;
52
- };
53
- /**
54
- * Perform the initial handshake with the popup to get the session public key and nonce
55
- */
56
- const popupHandshake = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
57
- utils.assertDefined(clientSessionKeyPair, 'Client session key pair is not set');
58
- utils.assertDefined(popup, 'Popup is not defined');
59
- const popupMessageClient = createPopupMessageClient.createPopupMessageClient(popup, popupFinalUrl.origin);
60
- const [[popupSessionPublicKey], [nonce]] = yield Promise.all([
61
- popupMessageClient.waitForMessage('sendPopupSessionPublicKey', 20000),
62
- popupMessageClient.waitForMessage('sendPopupNonce', 20000),
63
- ]);
64
- const sessionSharedSecret = yield utils.deriveSharedSecret(clientSessionKeyPair.privateKey, yield utils.convertPublicKeyHexToCryptoKey(popupSessionPublicKey));
65
- store.setSessionAuthCode(new TextEncoder().encode(yield utils.generateHMAC(sessionSharedSecret, nonce)));
66
- });
67
- /**
68
- * Watch for the popup to close
69
- */
70
- const watchForPopupClose = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
71
- utils.assertDefined(popup, 'Popup is not defined');
72
- return new Promise((_, reject) => {
73
- utils.assertDefined(popup, 'Popup is not defined');
74
- onPopupClose.onPopupClose(popup, () => {
75
- reject(new PopupClosedError.PopupClosedError());
76
- });
77
- });
78
- });
79
- /**
80
- * Wait for the action response from the popup
81
- */
82
- const waitForActionResponse = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
83
- utils.assertDefined(popup, 'Popup is not defined');
84
- utils.assertDefined(store.sessionAuthCode, 'Session auth code is not set');
85
- const resultDeferredPromise = new utils.DeferredPromise();
86
- /**
87
- * Recreate the popup message if the encryption is available
88
- */
89
- const encoder = activeConnection
90
- ? createEncryptedMessageEncoder.createEncryptedMessageEncoder(activeConnection, store.sessionAuthCode)
91
- : undefined;
92
- const popupMessageClient = createPopupMessageClient.createPopupMessageClient(popup, popupFinalUrl.origin, encoder);
93
- void popupMessageClient.postMessage('sendAction', {
94
- id: actionId,
95
- name: pathname,
96
- params,
97
- });
98
- /**
99
- * Listen for action resolved
100
- */
101
- const cleanUpActionResolvedListener = popupMessageClient.listenForMessage('actionResolved', ({ data, id }) => {
102
- if (id === actionId) {
103
- resultDeferredPromise.resolve(data);
43
+ popup = window.open('', '_blank', features);
44
+ }
45
+ // Encrypt params if active connection is present
46
+ if (params) {
47
+ yield mergeAndEncryptParams.mergeAndEncryptParams(popupFinalUrl, params, activeConnection);
48
+ }
49
+ if (popup === null) {
50
+ throw new Error('Failed to open popup');
51
+ }
52
+ waitForPopupResponse.waitForPopupResponse({
53
+ decode: (data) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
54
+ if (activeConnection && utils.isEncryptedMessage(data)) {
55
+ const decryptedData = yield utils.decryptMessage(activeConnection.sharedSecret, data.encryptedMessage, data.iv);
56
+ return JSON.parse(decryptedData);
104
57
  }
105
- });
106
- /**
107
- * Listen for action rejected
108
- */
109
- const cleanUpActionRejectedListener = popupMessageClient.listenForMessage('actionRejected', ({ serializedError, id }) => {
110
- if (id !== actionId)
111
- return;
112
- resultDeferredPromise.reject(mapErrorFromPopup.mapErrorFromPopup(serializedError));
113
- });
114
- /**
115
- * Listen for a global error
116
- */
117
- const cleanUpSendErrorListener = popupMessageClient.listenForMessage('sendError', (serializedError) => resultDeferredPromise.reject(mapErrorFromPopup.mapErrorFromPopup(serializedError)));
118
- return resultDeferredPromise.promise.finally(() => {
119
- cleanUpActionResolvedListener();
120
- cleanUpActionRejectedListener();
121
- cleanUpSendErrorListener();
122
- });
58
+ return data;
59
+ }),
60
+ onError: (error) => resultDeferredPromise.reject(error),
61
+ onResponse: (response) => resultDeferredPromise.resolve(response.data),
62
+ popupUrl: popupFinalUrl.toString(),
63
+ });
64
+ onPopupClose.onPopupClose(popup, () => {
65
+ resultDeferredPromise.reject(new PopupClosedError.PopupClosedError());
123
66
  });
124
- // This array will contain all parallel promises
125
- const promises = [];
126
67
  /**
127
- * If no popup is present, it means this is a fresh new popup
128
- * This block will create a new popup, perform the handshake and wait for the action response
68
+ * Assign action to popup
129
69
  */
130
- if (popup === null) {
131
- popup = initializePopup();
132
- promises.push(watchForPopupClose());
133
- promises.push(popupHandshake().then(waitForActionResponse));
70
+ if (didOpenPopup) {
71
+ popup === null || popup === void 0 ? void 0 : popup.postMessage({
72
+ actionPath: popupFinalUrl.search + popupFinalUrl.hash,
73
+ event: 'new-action',
74
+ }, popupFinalUrl.origin);
134
75
  }
135
76
  else {
136
- /**
137
- * If a popup is present, it means this is a re-use of the same popup
138
- * This block will watch for the popup to close and wait for the action response
139
- */
140
- promises.push(watchForPopupClose());
141
- promises.push(waitForActionResponse());
77
+ // Load popup
78
+ popup.location = popupFinalUrl.href;
142
79
  }
143
- /**
144
- * Return the promise and setup the popup cleanup
145
- * and error handling
146
- */
147
- return Promise.race(promises)
80
+ didOpenPopup = true;
81
+ return resultDeferredPromise.promise
148
82
  .catch((err) => {
149
83
  onError === null || onError === void 0 ? void 0 : onError(err);
150
84
  closePopup();
@@ -1,146 +1,80 @@
1
1
  'use client'
2
2
  import { __awaiter } from '../../../../_virtual/_tslib.js';
3
- import { createKeyPair, convertPublicKeyCryptoKeyToHex, assertDefined, deriveSharedSecret, convertPublicKeyHexToCryptoKey, generateHMAC, DeferredPromise } from '@dynamic-labs/utils';
3
+ import { DeferredPromise, isEncryptedMessage, decryptMessage } from '@dynamic-labs/utils';
4
+ import { waitForPopupResponse } from '../waitForPopupResponse/waitForPopupResponse.js';
4
5
  import { onPopupClose } from '../onPopupClose/onPopupClose.js';
6
+ import { mergeAndEncryptParams } from '../mergeAndEncryptParams/mergeAndEncryptParams.js';
5
7
  import { getCenteredPopupFeatures } from '../getCenteredPopupFeatures/getCenteredPopupFeatures.js';
6
- import { createPopupMessageClient } from '../createPopupMessageClient/createPopupMessageClient.js';
7
- import { createEncryptedMessageEncoder } from '../createEncryptedMessageEncoder/createEncryptedMessageEncoder.js';
8
8
  import { PopupClosedError } from '../../errors/PopupClosedError.js';
9
- import { mapErrorFromPopup } from './utils/mapErrorFromPopup.js';
10
9
 
11
10
  const createPopupOpener = ({ environmentId, popupUrl, popupWidth = 420, popupHeight = 640, store, popupActionTimeout = 1000, // Wait page up to 1 second for new actions before closing
12
11
  onError, }) => {
13
12
  let popup = null;
13
+ let didOpenPopup = false;
14
14
  let lastActionId = null;
15
- let clientSessionKeyPair = null;
16
15
  const closePopup = () => {
17
16
  popup === null || popup === void 0 ? void 0 : popup.close();
18
17
  popup = null;
18
+ didOpenPopup = false;
19
19
  lastActionId = null;
20
20
  };
21
- // TODO update definition here to use name and args
22
21
  return (_a) => __awaiter(void 0, [_a], void 0, function* ({ params, pathname, }) {
23
- clientSessionKeyPair = clientSessionKeyPair !== null && clientSessionKeyPair !== void 0 ? clientSessionKeyPair : (yield createKeyPair());
24
22
  // Used as a unique identifier for the action
25
- const actionId = new Date().getTime().toString();
23
+ const actionId = new Date().getTime();
26
24
  lastActionId = actionId;
27
25
  const popupFinalUrl = new URL(popupUrl);
28
26
  const activeConnection = store.getActiveConnection();
27
+ const resultDeferredPromise = new DeferredPromise();
29
28
  // Setup popup URL and data
29
+ popupFinalUrl.hash = `/${pathname}`;
30
30
  popupFinalUrl.searchParams.set('provider_env_id', environmentId);
31
+ // TODO: use PlatformService
31
32
  popupFinalUrl.searchParams.set('requester_origin', window.location.origin);
32
- popupFinalUrl.searchParams.set('client_session_public_key', yield convertPublicKeyCryptoKeyToHex(clientSessionKeyPair.publicKey));
33
- /**
34
- * Open a new popup centered on the screen
35
- */
36
- const initializePopup = () => {
33
+ if (popup === null) {
37
34
  const features = getCenteredPopupFeatures({
38
35
  height: popupHeight,
39
36
  width: popupWidth,
40
37
  });
41
38
  // Open popup
42
- const popup = window.open('', '_blank', features);
43
- if (popup === null) {
44
- throw new Error('Failed to open popup');
45
- }
46
- popup.location = popupFinalUrl.href;
47
- return popup;
48
- };
49
- /**
50
- * Perform the initial handshake with the popup to get the session public key and nonce
51
- */
52
- const popupHandshake = () => __awaiter(void 0, void 0, void 0, function* () {
53
- assertDefined(clientSessionKeyPair, 'Client session key pair is not set');
54
- assertDefined(popup, 'Popup is not defined');
55
- const popupMessageClient = createPopupMessageClient(popup, popupFinalUrl.origin);
56
- const [[popupSessionPublicKey], [nonce]] = yield Promise.all([
57
- popupMessageClient.waitForMessage('sendPopupSessionPublicKey', 20000),
58
- popupMessageClient.waitForMessage('sendPopupNonce', 20000),
59
- ]);
60
- const sessionSharedSecret = yield deriveSharedSecret(clientSessionKeyPair.privateKey, yield convertPublicKeyHexToCryptoKey(popupSessionPublicKey));
61
- store.setSessionAuthCode(new TextEncoder().encode(yield generateHMAC(sessionSharedSecret, nonce)));
62
- });
63
- /**
64
- * Watch for the popup to close
65
- */
66
- const watchForPopupClose = () => __awaiter(void 0, void 0, void 0, function* () {
67
- assertDefined(popup, 'Popup is not defined');
68
- return new Promise((_, reject) => {
69
- assertDefined(popup, 'Popup is not defined');
70
- onPopupClose(popup, () => {
71
- reject(new PopupClosedError());
72
- });
73
- });
74
- });
75
- /**
76
- * Wait for the action response from the popup
77
- */
78
- const waitForActionResponse = () => __awaiter(void 0, void 0, void 0, function* () {
79
- assertDefined(popup, 'Popup is not defined');
80
- assertDefined(store.sessionAuthCode, 'Session auth code is not set');
81
- const resultDeferredPromise = new DeferredPromise();
82
- /**
83
- * Recreate the popup message if the encryption is available
84
- */
85
- const encoder = activeConnection
86
- ? createEncryptedMessageEncoder(activeConnection, store.sessionAuthCode)
87
- : undefined;
88
- const popupMessageClient = createPopupMessageClient(popup, popupFinalUrl.origin, encoder);
89
- void popupMessageClient.postMessage('sendAction', {
90
- id: actionId,
91
- name: pathname,
92
- params,
93
- });
94
- /**
95
- * Listen for action resolved
96
- */
97
- const cleanUpActionResolvedListener = popupMessageClient.listenForMessage('actionResolved', ({ data, id }) => {
98
- if (id === actionId) {
99
- resultDeferredPromise.resolve(data);
39
+ popup = window.open('', '_blank', features);
40
+ }
41
+ // Encrypt params if active connection is present
42
+ if (params) {
43
+ yield mergeAndEncryptParams(popupFinalUrl, params, activeConnection);
44
+ }
45
+ if (popup === null) {
46
+ throw new Error('Failed to open popup');
47
+ }
48
+ waitForPopupResponse({
49
+ decode: (data) => __awaiter(void 0, void 0, void 0, function* () {
50
+ if (activeConnection && isEncryptedMessage(data)) {
51
+ const decryptedData = yield decryptMessage(activeConnection.sharedSecret, data.encryptedMessage, data.iv);
52
+ return JSON.parse(decryptedData);
100
53
  }
101
- });
102
- /**
103
- * Listen for action rejected
104
- */
105
- const cleanUpActionRejectedListener = popupMessageClient.listenForMessage('actionRejected', ({ serializedError, id }) => {
106
- if (id !== actionId)
107
- return;
108
- resultDeferredPromise.reject(mapErrorFromPopup(serializedError));
109
- });
110
- /**
111
- * Listen for a global error
112
- */
113
- const cleanUpSendErrorListener = popupMessageClient.listenForMessage('sendError', (serializedError) => resultDeferredPromise.reject(mapErrorFromPopup(serializedError)));
114
- return resultDeferredPromise.promise.finally(() => {
115
- cleanUpActionResolvedListener();
116
- cleanUpActionRejectedListener();
117
- cleanUpSendErrorListener();
118
- });
54
+ return data;
55
+ }),
56
+ onError: (error) => resultDeferredPromise.reject(error),
57
+ onResponse: (response) => resultDeferredPromise.resolve(response.data),
58
+ popupUrl: popupFinalUrl.toString(),
59
+ });
60
+ onPopupClose(popup, () => {
61
+ resultDeferredPromise.reject(new PopupClosedError());
119
62
  });
120
- // This array will contain all parallel promises
121
- const promises = [];
122
63
  /**
123
- * If no popup is present, it means this is a fresh new popup
124
- * This block will create a new popup, perform the handshake and wait for the action response
64
+ * Assign action to popup
125
65
  */
126
- if (popup === null) {
127
- popup = initializePopup();
128
- promises.push(watchForPopupClose());
129
- promises.push(popupHandshake().then(waitForActionResponse));
66
+ if (didOpenPopup) {
67
+ popup === null || popup === void 0 ? void 0 : popup.postMessage({
68
+ actionPath: popupFinalUrl.search + popupFinalUrl.hash,
69
+ event: 'new-action',
70
+ }, popupFinalUrl.origin);
130
71
  }
131
72
  else {
132
- /**
133
- * If a popup is present, it means this is a re-use of the same popup
134
- * This block will watch for the popup to close and wait for the action response
135
- */
136
- promises.push(watchForPopupClose());
137
- promises.push(waitForActionResponse());
73
+ // Load popup
74
+ popup.location = popupFinalUrl.href;
138
75
  }
139
- /**
140
- * Return the promise and setup the popup cleanup
141
- * and error handling
142
- */
143
- return Promise.race(promises)
76
+ didOpenPopup = true;
77
+ return resultDeferredPromise.promise
144
78
  .catch((err) => {
145
79
  onError === null || onError === void 0 ? void 0 : onError(err);
146
80
  closePopup();
@@ -1,4 +1,4 @@
1
1
  import { SerializedError } from '@dynamic-labs/message-transport';
2
2
  import { DisconnectError } from '../../../errors/DisconnectError';
3
3
  import { UnknownError } from '../../../errors/UnknownError';
4
- export declare const mapErrorFromPopup: (serializedError: SerializedError) => DisconnectError | unknown[] | UnknownError;
4
+ export declare const mapErrorFromPopup: (serializedError: SerializedError) => UnknownError | unknown[] | DisconnectError;
@@ -0,0 +1 @@
1
+ export { mergeAndEncryptParams } from './mergeAndEncryptParams';
@@ -0,0 +1,23 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var _tslib = require('../../../../_virtual/_tslib.cjs');
7
+ var utils = require('@dynamic-labs/utils');
8
+ var mergeURLSearchParams = require('../mergeURLSearchParams/mergeURLSearchParams.cjs');
9
+
10
+ const mergeAndEncryptParams = (url, params, activeConnection) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
11
+ if (activeConnection) {
12
+ const encryptedParams = yield utils.encryptMessage(activeConnection.sharedSecret, JSON.stringify(params));
13
+ mergeURLSearchParams.mergeURLSearchParams(url.searchParams, new URLSearchParams({
14
+ encrypted_message: encryptedParams.encryptedMessage,
15
+ iv: encryptedParams.iv,
16
+ }));
17
+ }
18
+ else {
19
+ mergeURLSearchParams.mergeURLSearchParams(url.searchParams, new URLSearchParams(params));
20
+ }
21
+ });
22
+
23
+ exports.mergeAndEncryptParams = mergeAndEncryptParams;
@@ -0,0 +1,2 @@
1
+ import { GlobalWalletConnection } from '@dynamic-labs/types';
2
+ export declare const mergeAndEncryptParams: (url: URL, params: Record<string, string>, activeConnection: GlobalWalletConnection | null) => Promise<void>;
@@ -0,0 +1,19 @@
1
+ 'use client'
2
+ import { __awaiter } from '../../../../_virtual/_tslib.js';
3
+ import { encryptMessage } from '@dynamic-labs/utils';
4
+ import { mergeURLSearchParams } from '../mergeURLSearchParams/mergeURLSearchParams.js';
5
+
6
+ const mergeAndEncryptParams = (url, params, activeConnection) => __awaiter(void 0, void 0, void 0, function* () {
7
+ if (activeConnection) {
8
+ const encryptedParams = yield encryptMessage(activeConnection.sharedSecret, JSON.stringify(params));
9
+ mergeURLSearchParams(url.searchParams, new URLSearchParams({
10
+ encrypted_message: encryptedParams.encryptedMessage,
11
+ iv: encryptedParams.iv,
12
+ }));
13
+ }
14
+ else {
15
+ mergeURLSearchParams(url.searchParams, new URLSearchParams(params));
16
+ }
17
+ });
18
+
19
+ export { mergeAndEncryptParams };
@@ -0,0 +1 @@
1
+ export { mergeURLSearchParams } from './mergeURLSearchParams';
@@ -0,0 +1,17 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ /**
7
+ * Merges URL search parameters from a source into a target URLSearchParams object
8
+ * @param target - The URLSearchParams object to merge into
9
+ * @param source - The URLSearchParams object to merge from
10
+ */
11
+ const mergeURLSearchParams = (target, source) => {
12
+ source.forEach((value, key) => {
13
+ target.set(key, value);
14
+ });
15
+ };
16
+
17
+ exports.mergeURLSearchParams = mergeURLSearchParams;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Merges URL search parameters from a source into a target URLSearchParams object
3
+ * @param target - The URLSearchParams object to merge into
4
+ * @param source - The URLSearchParams object to merge from
5
+ */
6
+ export declare const mergeURLSearchParams: (target: URLSearchParams, source: URLSearchParams) => void;
@@ -0,0 +1,13 @@
1
+ 'use client'
2
+ /**
3
+ * Merges URL search parameters from a source into a target URLSearchParams object
4
+ * @param target - The URLSearchParams object to merge into
5
+ * @param source - The URLSearchParams object to merge from
6
+ */
7
+ const mergeURLSearchParams = (target, source) => {
8
+ source.forEach((value, key) => {
9
+ target.set(key, value);
10
+ });
11
+ };
12
+
13
+ export { mergeURLSearchParams };
@@ -0,0 +1 @@
1
+ export { waitForPopupResponse } from './waitForPopupResponse';
@@ -0,0 +1,61 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var _tslib = require('../../../../_virtual/_tslib.cjs');
7
+ var logger = require('../../constants/logger.cjs');
8
+ var DisconnectError = require('../../errors/DisconnectError.cjs');
9
+
10
+ const waitForPopupResponse = ({ popupUrl, decode, onResponse, onError, }) => {
11
+ const handleOnWindowEvent = (event) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
12
+ if (event.origin !== new URL(popupUrl).origin)
13
+ return;
14
+ let parsedData = null;
15
+ try {
16
+ parsedData = JSON.parse(event.data);
17
+ }
18
+ catch (err) {
19
+ logger.logger.debug('Error parsing data from WebExtension iFrame event', err);
20
+ return;
21
+ }
22
+ const decodedMessage = decode ? yield decode(parsedData) : parsedData;
23
+ const { error, success } = parseData(decodedMessage);
24
+ if (!error && !success) {
25
+ logger.logger.debug('Error validating event data schema from popup response event', parsedData);
26
+ return;
27
+ }
28
+ if (success) {
29
+ onResponse(success);
30
+ }
31
+ else {
32
+ if (DisconnectError.DisconnectError.isDisconnectError(error)) {
33
+ onError(new DisconnectError.DisconnectError());
34
+ }
35
+ else {
36
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
37
+ onError(new Error(error.message));
38
+ }
39
+ }
40
+ });
41
+ window.addEventListener('message', handleOnWindowEvent);
42
+ return () => {
43
+ window.removeEventListener('message', handleOnWindowEvent);
44
+ };
45
+ };
46
+ const parseData = (data) => {
47
+ if (!data || typeof data !== 'object') {
48
+ return {};
49
+ }
50
+ // Check if it's a success response
51
+ if (data.name && data.data) {
52
+ return { success: data };
53
+ }
54
+ // Check if it's an error response
55
+ if (data.message) {
56
+ return { error: data };
57
+ }
58
+ return {};
59
+ };
60
+
61
+ exports.waitForPopupResponse = waitForPopupResponse;
@@ -0,0 +1,9 @@
1
+ import { IPopupActionSuccessResponse } from '@dynamic-labs/types';
2
+ type WaitForPopupResponseProps = {
3
+ popupUrl: string;
4
+ decode?: (data: any) => Promise<any>;
5
+ onResponse: (response: IPopupActionSuccessResponse) => void;
6
+ onError: (error: Error) => void;
7
+ };
8
+ export declare const waitForPopupResponse: ({ popupUrl, decode, onResponse, onError, }: WaitForPopupResponseProps) => () => void;
9
+ export {};
@@ -0,0 +1,57 @@
1
+ 'use client'
2
+ import { __awaiter } from '../../../../_virtual/_tslib.js';
3
+ import { logger } from '../../constants/logger.js';
4
+ import { DisconnectError } from '../../errors/DisconnectError.js';
5
+
6
+ const waitForPopupResponse = ({ popupUrl, decode, onResponse, onError, }) => {
7
+ const handleOnWindowEvent = (event) => __awaiter(void 0, void 0, void 0, function* () {
8
+ if (event.origin !== new URL(popupUrl).origin)
9
+ return;
10
+ let parsedData = null;
11
+ try {
12
+ parsedData = JSON.parse(event.data);
13
+ }
14
+ catch (err) {
15
+ logger.debug('Error parsing data from WebExtension iFrame event', err);
16
+ return;
17
+ }
18
+ const decodedMessage = decode ? yield decode(parsedData) : parsedData;
19
+ const { error, success } = parseData(decodedMessage);
20
+ if (!error && !success) {
21
+ logger.debug('Error validating event data schema from popup response event', parsedData);
22
+ return;
23
+ }
24
+ if (success) {
25
+ onResponse(success);
26
+ }
27
+ else {
28
+ if (DisconnectError.isDisconnectError(error)) {
29
+ onError(new DisconnectError());
30
+ }
31
+ else {
32
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
33
+ onError(new Error(error.message));
34
+ }
35
+ }
36
+ });
37
+ window.addEventListener('message', handleOnWindowEvent);
38
+ return () => {
39
+ window.removeEventListener('message', handleOnWindowEvent);
40
+ };
41
+ };
42
+ const parseData = (data) => {
43
+ if (!data || typeof data !== 'object') {
44
+ return {};
45
+ }
46
+ // Check if it's a success response
47
+ if (data.name && data.data) {
48
+ return { success: data };
49
+ }
50
+ // Check if it's an error response
51
+ if (data.message) {
52
+ return { error: data };
53
+ }
54
+ return {};
55
+ };
56
+
57
+ export { waitForPopupResponse };
@@ -8,20 +8,11 @@ var store = require('@dynamic-labs/store');
8
8
  const createClientStore = ({ storage = localStorage, } = {}) => {
9
9
  const store$1 = store.persist({
10
10
  name: 'global-wallet-client',
11
- /**
12
- * The client should not persist sessionAuthCode
13
- */
14
- partialize: (state) => ({
15
- connection: state.connection,
16
- ethereum: state.ethereum,
17
- solana: state.solana,
18
- wallets: state.wallets,
19
- }),
11
+ partialize: (state) => state,
20
12
  storage,
21
13
  store: store.createStore(() => ({
22
14
  connection: null,
23
15
  ethereum: null,
24
- sessionAuthCode: null,
25
16
  solana: null,
26
17
  wallets: [],
27
18
  })),
@@ -56,12 +47,6 @@ const createClientStore = ({ storage = localStorage, } = {}) => {
56
47
  }
57
48
  return connection;
58
49
  },
59
- /**
60
- * Retrieves the session auth code
61
- */
62
- get sessionAuthCode() {
63
- return store$1.getState().sessionAuthCode;
64
- },
65
50
  /**
66
51
  * Updates current connection, wallets
67
52
  * Used when the popup confirm a connection
@@ -70,13 +55,6 @@ const createClientStore = ({ storage = localStorage, } = {}) => {
70
55
  setInitialConnectionState: ({ connection, wallets, ethereum, solana, }) => {
71
56
  store$1.setState({ connection, ethereum, solana, wallets });
72
57
  },
73
- /**
74
- * Updates the session auth code
75
- * @param {BufferSource} sessionAuthCode - The session auth code to store
76
- */
77
- setSessionAuthCode: (sessionAuthCode) => {
78
- store$1.setState({ sessionAuthCode });
79
- },
80
58
  /**
81
59
  * Get all Solana wallets connected to the current connection
82
60
  */
@@ -26,11 +26,6 @@ type ClientStoreState = {
26
26
  solana: {
27
27
  currentNetwork: string;
28
28
  } | null;
29
- /**
30
- * Session Auth Code
31
- * Used to decrypt and encrypt messages between client and popup
32
- */
33
- sessionAuthCode: BufferSource | null;
34
29
  };
35
30
  export declare const createClientStore: ({ storage, }?: CreateClientStoreProps) => {
36
31
  /**
@@ -51,21 +46,12 @@ export declare const createClientStore: ({ storage, }?: CreateClientStoreProps)
51
46
  * @returns {Connection | null} The current connection or null if no connection exists or it has expired
52
47
  */
53
48
  getActiveConnection: () => GlobalWalletConnection | null;
54
- /**
55
- * Retrieves the session auth code
56
- */
57
- readonly sessionAuthCode: BufferSource | null;
58
49
  /**
59
50
  * Updates current connection, wallets
60
51
  * Used when the popup confirm a connection
61
52
  * @param {GlobalWalletConnection | null} connection - The connection to store, or null to clear it
62
53
  */
63
54
  setInitialConnectionState: ({ connection, wallets, ethereum, solana, }: Pick<ClientStoreState, 'connection' | 'wallets' | 'ethereum' | 'solana'>) => void;
64
- /**
65
- * Updates the session auth code
66
- * @param {BufferSource} sessionAuthCode - The session auth code to store
67
- */
68
- setSessionAuthCode: (sessionAuthCode: BufferSource) => void;
69
55
  /**
70
56
  * Get all Solana wallets connected to the current connection
71
57
  */
@@ -4,20 +4,11 @@ import { persist, createStore } from '@dynamic-labs/store';
4
4
  const createClientStore = ({ storage = localStorage, } = {}) => {
5
5
  const store = persist({
6
6
  name: 'global-wallet-client',
7
- /**
8
- * The client should not persist sessionAuthCode
9
- */
10
- partialize: (state) => ({
11
- connection: state.connection,
12
- ethereum: state.ethereum,
13
- solana: state.solana,
14
- wallets: state.wallets,
15
- }),
7
+ partialize: (state) => state,
16
8
  storage,
17
9
  store: createStore(() => ({
18
10
  connection: null,
19
11
  ethereum: null,
20
- sessionAuthCode: null,
21
12
  solana: null,
22
13
  wallets: [],
23
14
  })),
@@ -52,12 +43,6 @@ const createClientStore = ({ storage = localStorage, } = {}) => {
52
43
  }
53
44
  return connection;
54
45
  },
55
- /**
56
- * Retrieves the session auth code
57
- */
58
- get sessionAuthCode() {
59
- return store.getState().sessionAuthCode;
60
- },
61
46
  /**
62
47
  * Updates current connection, wallets
63
48
  * Used when the popup confirm a connection
@@ -66,13 +51,6 @@ const createClientStore = ({ storage = localStorage, } = {}) => {
66
51
  setInitialConnectionState: ({ connection, wallets, ethereum, solana, }) => {
67
52
  store.setState({ connection, ethereum, solana, wallets });
68
53
  },
69
- /**
70
- * Updates the session auth code
71
- * @param {BufferSource} sessionAuthCode - The session auth code to store
72
- */
73
- setSessionAuthCode: (sessionAuthCode) => {
74
- store.setState({ sessionAuthCode });
75
- },
76
54
  /**
77
55
  * Get all Solana wallets connected to the current connection
78
56
  */
@@ -1,12 +0,0 @@
1
- 'use client'
2
- 'use strict';
3
-
4
- Object.defineProperty(exports, '__esModule', { value: true });
5
-
6
- class UnknownError extends Error {
7
- constructor() {
8
- super('Unknown error');
9
- }
10
- }
11
-
12
- exports.UnknownError = UnknownError;
@@ -1,8 +0,0 @@
1
- 'use client'
2
- class UnknownError extends Error {
3
- constructor() {
4
- super('Unknown error');
5
- }
6
- }
7
-
8
- export { UnknownError };
@@ -1,19 +0,0 @@
1
- 'use client'
2
- 'use strict';
3
-
4
- Object.defineProperty(exports, '__esModule', { value: true });
5
-
6
- var _tslib = require('../../../../_virtual/_tslib.cjs');
7
- var utils = require('@dynamic-labs/utils');
8
-
9
- const createEncryptedMessageEncoder = (activeConnection, additionalData) => ({
10
- decode: (data) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
11
- utils.assertDefined(data.encryptedMessage, 'Encrypted message is not defined');
12
- utils.assertDefined(data.iv, 'IV is not defined');
13
- const decryptedData = yield utils.decryptMessage(activeConnection.sharedSecret, data.encryptedMessage, data.iv, additionalData);
14
- return JSON.parse(decryptedData);
15
- }),
16
- encode: (message) => utils.encryptMessage(activeConnection.sharedSecret, JSON.stringify(message), additionalData),
17
- });
18
-
19
- exports.createEncryptedMessageEncoder = createEncryptedMessageEncoder;
@@ -1,15 +0,0 @@
1
- 'use client'
2
- import { __awaiter } from '../../../../_virtual/_tslib.js';
3
- import { assertDefined, decryptMessage, encryptMessage } from '@dynamic-labs/utils';
4
-
5
- const createEncryptedMessageEncoder = (activeConnection, additionalData) => ({
6
- decode: (data) => __awaiter(void 0, void 0, void 0, function* () {
7
- assertDefined(data.encryptedMessage, 'Encrypted message is not defined');
8
- assertDefined(data.iv, 'IV is not defined');
9
- const decryptedData = yield decryptMessage(activeConnection.sharedSecret, data.encryptedMessage, data.iv, additionalData);
10
- return JSON.parse(decryptedData);
11
- }),
12
- encode: (message) => encryptMessage(activeConnection.sharedSecret, JSON.stringify(message), additionalData),
13
- });
14
-
15
- export { createEncryptedMessageEncoder };
@@ -1,74 +0,0 @@
1
- 'use client'
2
- 'use strict';
3
-
4
- Object.defineProperty(exports, '__esModule', { value: true });
5
-
6
- var _tslib = require('../../../../_virtual/_tslib.cjs');
7
- var utils = require('@dynamic-labs/utils');
8
-
9
- const createPopupMessageClient = (popupWindow, targetOrigin, messageEncoder) => {
10
- const listenForMessage = (messageName, callback) => {
11
- const handleOnWindowEvent = (event) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
12
- if (event.origin !== targetOrigin)
13
- return;
14
- let parsedMessage = null;
15
- try {
16
- parsedMessage = JSON.parse(event.data);
17
- if (messageEncoder) {
18
- parsedMessage = yield messageEncoder.decode(parsedMessage);
19
- }
20
- parsedMessage =
21
- parseDataFromWindowEvent(parsedMessage);
22
- }
23
- catch (err) {
24
- return;
25
- }
26
- if (parsedMessage.name !== messageName)
27
- return;
28
- callback(...parsedMessage.args);
29
- });
30
- window.addEventListener('message', handleOnWindowEvent);
31
- return () => {
32
- window.removeEventListener('message', handleOnWindowEvent);
33
- };
34
- };
35
- const waitForMessage = (messageName, timeout) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
36
- const deferred = new utils.DeferredPromise();
37
- const timeoutId = timeout
38
- ? setTimeout(() => {
39
- deferred.reject(new Error(`Timeout waiting for message: ${messageName}`));
40
- }, timeout)
41
- : undefined;
42
- const cleanup = listenForMessage(messageName, (...args) => deferred.resolve(args));
43
- return deferred.promise.finally(() => {
44
- cleanup === null || cleanup === void 0 ? void 0 : cleanup();
45
- clearTimeout(timeoutId);
46
- });
47
- });
48
- const postMessage = (messageName,
49
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
- ...args) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
51
- var _a;
52
- const message = {
53
- args,
54
- name: messageName,
55
- };
56
- const messageToPost = (_a = (yield (messageEncoder === null || messageEncoder === void 0 ? void 0 : messageEncoder.encode(message)))) !== null && _a !== void 0 ? _a : message;
57
- popupWindow.postMessage(JSON.stringify(messageToPost), targetOrigin);
58
- });
59
- return {
60
- listenForMessage,
61
- postMessage,
62
- waitForMessage,
63
- };
64
- };
65
- const parseDataFromWindowEvent = (data) => {
66
- utils.assertDefined(data.name, 'Name is required');
67
- utils.assertDefined(data.args, 'Args is required');
68
- return {
69
- args: data.args,
70
- name: data.name,
71
- };
72
- };
73
-
74
- exports.createPopupMessageClient = createPopupMessageClient;
@@ -1,70 +0,0 @@
1
- 'use client'
2
- import { __awaiter } from '../../../../_virtual/_tslib.js';
3
- import { DeferredPromise, assertDefined } from '@dynamic-labs/utils';
4
-
5
- const createPopupMessageClient = (popupWindow, targetOrigin, messageEncoder) => {
6
- const listenForMessage = (messageName, callback) => {
7
- const handleOnWindowEvent = (event) => __awaiter(void 0, void 0, void 0, function* () {
8
- if (event.origin !== targetOrigin)
9
- return;
10
- let parsedMessage = null;
11
- try {
12
- parsedMessage = JSON.parse(event.data);
13
- if (messageEncoder) {
14
- parsedMessage = yield messageEncoder.decode(parsedMessage);
15
- }
16
- parsedMessage =
17
- parseDataFromWindowEvent(parsedMessage);
18
- }
19
- catch (err) {
20
- return;
21
- }
22
- if (parsedMessage.name !== messageName)
23
- return;
24
- callback(...parsedMessage.args);
25
- });
26
- window.addEventListener('message', handleOnWindowEvent);
27
- return () => {
28
- window.removeEventListener('message', handleOnWindowEvent);
29
- };
30
- };
31
- const waitForMessage = (messageName, timeout) => __awaiter(void 0, void 0, void 0, function* () {
32
- const deferred = new DeferredPromise();
33
- const timeoutId = timeout
34
- ? setTimeout(() => {
35
- deferred.reject(new Error(`Timeout waiting for message: ${messageName}`));
36
- }, timeout)
37
- : undefined;
38
- const cleanup = listenForMessage(messageName, (...args) => deferred.resolve(args));
39
- return deferred.promise.finally(() => {
40
- cleanup === null || cleanup === void 0 ? void 0 : cleanup();
41
- clearTimeout(timeoutId);
42
- });
43
- });
44
- const postMessage = (messageName,
45
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
46
- ...args) => __awaiter(void 0, void 0, void 0, function* () {
47
- var _a;
48
- const message = {
49
- args,
50
- name: messageName,
51
- };
52
- const messageToPost = (_a = (yield (messageEncoder === null || messageEncoder === void 0 ? void 0 : messageEncoder.encode(message)))) !== null && _a !== void 0 ? _a : message;
53
- popupWindow.postMessage(JSON.stringify(messageToPost), targetOrigin);
54
- });
55
- return {
56
- listenForMessage,
57
- postMessage,
58
- waitForMessage,
59
- };
60
- };
61
- const parseDataFromWindowEvent = (data) => {
62
- assertDefined(data.name, 'Name is required');
63
- assertDefined(data.args, 'Args is required');
64
- return {
65
- args: data.args,
66
- name: data.name,
67
- };
68
- };
69
-
70
- export { createPopupMessageClient };
@@ -1,25 +0,0 @@
1
- 'use client'
2
- 'use strict';
3
-
4
- Object.defineProperty(exports, '__esModule', { value: true });
5
-
6
- var messageTransport = require('@dynamic-labs/message-transport');
7
- var DisconnectError = require('../../../errors/DisconnectError.cjs');
8
- var UnknownError = require('../../../errors/UnknownError.cjs');
9
-
10
- const mapErrorFromPopup = (serializedError) => {
11
- if (messageTransport.isSerializedError(serializedError)) {
12
- const error = messageTransport.parseErrorFromTransport(serializedError);
13
- if (DisconnectError.DisconnectError.isDisconnectError(error)) {
14
- return new DisconnectError.DisconnectError();
15
- }
16
- else {
17
- return error;
18
- }
19
- }
20
- else {
21
- return new UnknownError.UnknownError();
22
- }
23
- };
24
-
25
- exports.mapErrorFromPopup = mapErrorFromPopup;
@@ -1,21 +0,0 @@
1
- 'use client'
2
- import { isSerializedError, parseErrorFromTransport } from '@dynamic-labs/message-transport';
3
- import { DisconnectError } from '../../../errors/DisconnectError.js';
4
- import { UnknownError } from '../../../errors/UnknownError.js';
5
-
6
- const mapErrorFromPopup = (serializedError) => {
7
- if (isSerializedError(serializedError)) {
8
- const error = parseErrorFromTransport(serializedError);
9
- if (DisconnectError.isDisconnectError(error)) {
10
- return new DisconnectError();
11
- }
12
- else {
13
- return error;
14
- }
15
- }
16
- else {
17
- return new UnknownError();
18
- }
19
- };
20
-
21
- export { mapErrorFromPopup };