@dynamic-labs/utils 3.0.0-alpha.2 → 3.0.0-alpha.21

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 (53) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/_virtual/_tslib.cjs +15 -0
  3. package/_virtual/_tslib.js +14 -1
  4. package/package.json +7 -8
  5. package/src/eip6963/eip6963Provider.cjs +40 -0
  6. package/src/eip6963/eip6963Provider.d.ts +34 -0
  7. package/src/eip6963/eip6963Provider.js +35 -0
  8. package/src/eip6963/index.d.ts +1 -0
  9. package/src/errors/ExternalAuthError.cjs +14 -0
  10. package/src/errors/ExternalAuthError.d.ts +4 -0
  11. package/src/errors/ExternalAuthError.js +10 -0
  12. package/src/errors/WalletAddressMismatchError.cjs +17 -0
  13. package/src/errors/WalletAddressMismatchError.d.ts +11 -0
  14. package/src/errors/WalletAddressMismatchError.js +13 -0
  15. package/src/errors/index.d.ts +2 -0
  16. package/src/handleMobileWalletRedirect/handleMobileWalletRedirect.cjs +5 -1
  17. package/src/handleMobileWalletRedirect/handleMobileWalletRedirect.js +5 -1
  18. package/src/hexToString/hexToString.cjs +32 -0
  19. package/src/hexToString/hexToString.d.ts +12 -0
  20. package/src/hexToString/hexToString.js +28 -0
  21. package/src/hexToString/index.d.ts +1 -0
  22. package/src/index.cjs +17 -4
  23. package/src/index.d.ts +5 -1
  24. package/src/index.js +8 -1
  25. package/src/isHex/index.d.ts +1 -0
  26. package/src/isHex/isHex.cjs +20 -0
  27. package/src/isHex/isHex.d.ts +6 -0
  28. package/src/isHex/isHex.js +16 -0
  29. package/src/nativeMobileOauthStateParam.cjs +13 -0
  30. package/src/nativeMobileOauthStateParam.d.ts +14 -0
  31. package/src/nativeMobileOauthStateParam.js +9 -0
  32. package/src/retryableFn.cjs +5 -1
  33. package/src/retryableFn.js +5 -1
  34. package/src/services/FetchService/FetchService.cjs +10 -5
  35. package/src/services/FetchService/FetchService.d.ts +2 -2
  36. package/src/services/FetchService/FetchService.js +10 -5
  37. package/src/services/Oauth2Service/Oauth2Service.cjs +38 -0
  38. package/src/services/Oauth2Service/Oauth2Service.d.ts +30 -0
  39. package/src/services/Oauth2Service/Oauth2Service.js +34 -0
  40. package/src/services/Oauth2Service/createWindowOauth2Service/createWindowOauth2Service.cjs +170 -0
  41. package/src/services/Oauth2Service/createWindowOauth2Service/createWindowOauth2Service.d.ts +2 -0
  42. package/src/services/Oauth2Service/createWindowOauth2Service/createWindowOauth2Service.js +166 -0
  43. package/src/services/Oauth2Service/createWindowOauth2Service/index.d.ts +1 -0
  44. package/src/services/Oauth2Service/index.d.ts +2 -0
  45. package/src/services/PlatformService/PlatformService.cjs +13 -12
  46. package/src/services/PlatformService/PlatformService.d.ts +2 -3
  47. package/src/services/PlatformService/PlatformService.js +13 -12
  48. package/src/services/PlatformService/createBrowserPlatformService/createBrowserPlatformService.cjs +0 -3
  49. package/src/services/PlatformService/createBrowserPlatformService/createBrowserPlatformService.js +0 -3
  50. package/src/services/PlatformService/types.d.ts +0 -4
  51. package/src/getOrMapViemChain.cjs +0 -77
  52. package/src/getOrMapViemChain.d.ts +0 -11
  53. package/src/getOrMapViemChain.js +0 -51
package/src/index.cjs CHANGED
@@ -35,6 +35,8 @@ var CookieInvalidError = require('./errors/CookieInvalidError.cjs');
35
35
  var AccessBlockedError = require('./errors/AccessBlockedError.cjs');
36
36
  var EmbeddedWalletException = require('./errors/EmbeddedWalletException.cjs');
37
37
  var MfaInvalidOtpError = require('./errors/MfaInvalidOtpError.cjs');
38
+ var ExternalAuthError = require('./errors/ExternalAuthError.cjs');
39
+ var WalletAddressMismatchError = require('./errors/WalletAddressMismatchError.cjs');
38
40
  var CancellablePromise = require('./CancellablePromise/CancellablePromise.cjs');
39
41
  var isFunction = require('./isFunction/isFunction.cjs');
40
42
  var isMobile = require('./isMobile.cjs');
@@ -43,7 +45,6 @@ var bufferToBase64 = require('./bufferToBase64.cjs');
43
45
  var last = require('./last.cjs');
44
46
  var getProvidersFromWindow = require('./getProvidersFromWindow.cjs');
45
47
  var sleep = require('./sleep/sleep.cjs');
46
- var getOrMapViemChain = require('./getOrMapViemChain.cjs');
47
48
  var retryableFn = require('./retryableFn.cjs');
48
49
  var wrapMethodWithCallback = require('./wrapMethodWithCallback/wrapMethodWithCallback.cjs');
49
50
  var DeferredPromise = require('./DeferredPromise/DeferredPromise.cjs');
@@ -55,12 +56,18 @@ var formatNumberText = require('./formatNumberText/formatNumberText.cjs');
55
56
  var ceil = require('./ceil/ceil.cjs');
56
57
  var trimEnd = require('./trimEnd/trimEnd.cjs');
57
58
  var isLedgerAddressViaVerifiedCredentials = require('./isLedgerAddressViaVerifiedCredentials.cjs');
59
+ var nativeMobileOauthStateParam = require('./nativeMobileOauthStateParam.cjs');
60
+ var eip6963Provider = require('./eip6963/eip6963Provider.cjs');
58
61
  var runSafe = require('./runSafe/runSafe.cjs');
59
62
  var PlatformService = require('./services/PlatformService/PlatformService.cjs');
60
63
  var createBrowserPlatformService = require('./services/PlatformService/createBrowserPlatformService/createBrowserPlatformService.cjs');
61
64
  var FetchService = require('./services/FetchService/FetchService.cjs');
65
+ var Oauth2Service = require('./services/Oauth2Service/Oauth2Service.cjs');
66
+ var createWindowOauth2Service = require('./services/Oauth2Service/createWindowOauth2Service/createWindowOauth2Service.cjs');
62
67
  var template = require('./template/template.cjs');
63
68
  var get = require('./get/get.cjs');
69
+ var hexToString = require('./hexToString/hexToString.cjs');
70
+ var isHex = require('./isHex/isHex.cjs');
64
71
 
65
72
 
66
73
 
@@ -96,6 +103,8 @@ exports.CookieInvalidError = CookieInvalidError.CookieInvalidError;
96
103
  exports.AccessBlockedError = AccessBlockedError.AccessBlockedError;
97
104
  exports.EmbeddedWalletException = EmbeddedWalletException.EmbeddedWalletException;
98
105
  exports.MfaInvalidOtpError = MfaInvalidOtpError.MfaInvalidOtpError;
106
+ exports.ExternalAuthError = ExternalAuthError.ExternalAuthError;
107
+ exports.WalletAddressMismatchError = WalletAddressMismatchError.WalletAddressMismatchError;
99
108
  exports.CancellablePromise = CancellablePromise.CancellablePromise;
100
109
  exports.isFunction = isFunction.isFunction;
101
110
  exports.getAndroidVersion = isMobile.getAndroidVersion;
@@ -115,9 +124,6 @@ exports.bufferToBase64 = bufferToBase64.bufferToBase64;
115
124
  exports.last = last.last;
116
125
  exports.getProvidersFromWindow = getProvidersFromWindow.getProvidersFromWindow;
117
126
  exports.sleep = sleep.sleep;
118
- exports.getChain = getOrMapViemChain.getChain;
119
- exports.getOrMapViemChain = getOrMapViemChain.getOrMapViemChain;
120
- exports.mapChain = getOrMapViemChain.mapChain;
121
127
  exports.FALLBACK_UNDEFINED = retryableFn.FALLBACK_UNDEFINED;
122
128
  exports.retryableFn = retryableFn.retryableFn;
123
129
  exports.wrapMethodWithCallback = wrapMethodWithCallback.wrapMethodWithCallback;
@@ -130,9 +136,16 @@ exports.formatNumberText = formatNumberText.formatNumberText;
130
136
  exports.ceil = ceil.ceil;
131
137
  exports.trimEnd = trimEnd.trimEnd;
132
138
  exports.isLedgerAddressViaVerifiedCredentials = isLedgerAddressViaVerifiedCredentials.isLedgerAddressViaVerifiedCredentials;
139
+ exports.nativeMobileOauthStateParam = nativeMobileOauthStateParam.nativeMobileOauthStateParam;
140
+ exports.Eip6963Provider = eip6963Provider.Eip6963Provider;
141
+ exports.Eip6963ProviderSingleton = eip6963Provider.Eip6963ProviderSingleton;
133
142
  exports.runSafe = runSafe.runSafe;
134
143
  exports.PlatformService = PlatformService.PlatformService;
135
144
  exports.createBrowserPlatformService = createBrowserPlatformService.createBrowserPlatformService;
136
145
  exports.FetchService = FetchService.FetchService;
146
+ exports.Oauth2Service = Oauth2Service.Oauth2Service;
147
+ exports.createWindowOauth2Service = createWindowOauth2Service.createWindowOauth2Service;
137
148
  exports.template = template.template;
138
149
  exports.get = get.get;
150
+ exports.hexToString = hexToString.hexToString;
151
+ exports.isHex = isHex.isHex;
package/src/index.d.ts CHANGED
@@ -9,7 +9,6 @@ export * from './bufferToBase64';
9
9
  export * from './last';
10
10
  export * from './getProvidersFromWindow';
11
11
  export * from './sleep';
12
- export * from './getOrMapViemChain';
13
12
  export * from './retryableFn';
14
13
  export * from './wrapMethodWithCallback';
15
14
  export * from './DeferredPromise';
@@ -21,8 +20,13 @@ export * from './formatNumberText';
21
20
  export * from './ceil';
22
21
  export * from './trimEnd';
23
22
  export * from './isLedgerAddressViaVerifiedCredentials';
23
+ export * from './nativeMobileOauthStateParam';
24
+ export * from './eip6963';
24
25
  export { runSafe } from './runSafe';
25
26
  export { PlatformService, createBrowserPlatformService, type IPlatformService, } from './services/PlatformService';
26
27
  export { FetchService } from './services/FetchService';
28
+ export { Oauth2Service, type GetOauthCodeError, type GetOauthCodeProps, type IOauth2Service, createWindowOauth2Service, } from './services/Oauth2Service';
27
29
  export { template } from './template';
28
30
  export { get } from './get';
31
+ export { hexToString } from './hexToString';
32
+ export { isHex } from './isHex';
package/src/index.js CHANGED
@@ -31,6 +31,8 @@ export { CookieInvalidError } from './errors/CookieInvalidError.js';
31
31
  export { AccessBlockedError } from './errors/AccessBlockedError.js';
32
32
  export { EmbeddedWalletException } from './errors/EmbeddedWalletException.js';
33
33
  export { MfaInvalidOtpError } from './errors/MfaInvalidOtpError.js';
34
+ export { ExternalAuthError } from './errors/ExternalAuthError.js';
35
+ export { WalletAddressMismatchError } from './errors/WalletAddressMismatchError.js';
34
36
  export { CancellablePromise } from './CancellablePromise/CancellablePromise.js';
35
37
  export { isFunction } from './isFunction/isFunction.js';
36
38
  export { getAndroidVersion, isAndroid, isIOS, isIPad, isIPhone, isIPhone8OrEarlier, isLegacySafari, isMobile, isSamsungBrowser, isWindows } from './isMobile.js';
@@ -39,7 +41,6 @@ export { bufferToBase64 } from './bufferToBase64.js';
39
41
  export { last } from './last.js';
40
42
  export { getProvidersFromWindow } from './getProvidersFromWindow.js';
41
43
  export { sleep } from './sleep/sleep.js';
42
- export { getChain, getOrMapViemChain, mapChain } from './getOrMapViemChain.js';
43
44
  export { FALLBACK_UNDEFINED, retryableFn } from './retryableFn.js';
44
45
  export { wrapMethodWithCallback } from './wrapMethodWithCallback/wrapMethodWithCallback.js';
45
46
  export { DeferredPromise } from './DeferredPromise/DeferredPromise.js';
@@ -51,9 +52,15 @@ export { formatNumberText } from './formatNumberText/formatNumberText.js';
51
52
  export { ceil } from './ceil/ceil.js';
52
53
  export { trimEnd } from './trimEnd/trimEnd.js';
53
54
  export { isLedgerAddressViaVerifiedCredentials } from './isLedgerAddressViaVerifiedCredentials.js';
55
+ export { nativeMobileOauthStateParam } from './nativeMobileOauthStateParam.js';
56
+ export { Eip6963Provider, Eip6963ProviderSingleton } from './eip6963/eip6963Provider.js';
54
57
  export { runSafe } from './runSafe/runSafe.js';
55
58
  export { PlatformService } from './services/PlatformService/PlatformService.js';
56
59
  export { createBrowserPlatformService } from './services/PlatformService/createBrowserPlatformService/createBrowserPlatformService.js';
57
60
  export { FetchService } from './services/FetchService/FetchService.js';
61
+ export { Oauth2Service } from './services/Oauth2Service/Oauth2Service.js';
62
+ export { createWindowOauth2Service } from './services/Oauth2Service/createWindowOauth2Service/createWindowOauth2Service.js';
58
63
  export { template } from './template/template.js';
59
64
  export { get } from './get/get.js';
65
+ export { hexToString } from './hexToString/hexToString.js';
66
+ export { isHex } from './isHex/isHex.js';
@@ -0,0 +1 @@
1
+ export { isHex } from './isHex';
@@ -0,0 +1,20 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ /**
7
+ * Checks if the provided string is a valid hexadecimal string.
8
+ * @param str The string to check.
9
+ * @returns `true` if the string is a valid hexadecimal string, `false` otherwise.
10
+ */
11
+ const isHex = (str) => {
12
+ if (typeof str !== 'string') {
13
+ throw new Error('Input must be a string');
14
+ }
15
+ const normalizedStr = str.startsWith('0x') ? str.substring(2) : str;
16
+ const regex = /^[0-9a-fA-F]+$/;
17
+ return regex.test(normalizedStr);
18
+ };
19
+
20
+ exports.isHex = isHex;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Checks if the provided string is a valid hexadecimal string.
3
+ * @param str The string to check.
4
+ * @returns `true` if the string is a valid hexadecimal string, `false` otherwise.
5
+ */
6
+ export declare const isHex: (str: string) => boolean;
@@ -0,0 +1,16 @@
1
+ 'use client'
2
+ /**
3
+ * Checks if the provided string is a valid hexadecimal string.
4
+ * @param str The string to check.
5
+ * @returns `true` if the string is a valid hexadecimal string, `false` otherwise.
6
+ */
7
+ const isHex = (str) => {
8
+ if (typeof str !== 'string') {
9
+ throw new Error('Input must be a string');
10
+ }
11
+ const normalizedStr = str.startsWith('0x') ? str.substring(2) : str;
12
+ const regex = /^[0-9a-fA-F]+$/;
13
+ return regex.test(normalizedStr);
14
+ };
15
+
16
+ export { isHex };
@@ -0,0 +1,13 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ /**
7
+ * Represents the value that separates the random string from the
8
+ * mobile deeplink URL in the state param from the oauth messages
9
+ * emitted from native mobile apps.
10
+ */
11
+ const nativeMobileOauthStateParam = '_client-redirect:';
12
+
13
+ exports.nativeMobileOauthStateParam = nativeMobileOauthStateParam;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Represents the value that separates the random string from the
3
+ * mobile deeplink URL in the state param from the oauth messages
4
+ * emitted from native mobile apps.
5
+ */
6
+ export declare const nativeMobileOauthStateParam = "_client-redirect:";
7
+ /**
8
+ * Represents the format of the state variable exchanged in oauth2 messages
9
+ * by native mobile devices.
10
+ *
11
+ * It has a random state string followed byt the client redirect URL as configured
12
+ * in the Client.
13
+ */
14
+ export type NativeMobileOauthState = `${string}${typeof nativeMobileOauthStateParam}${string}`;
@@ -0,0 +1,9 @@
1
+ 'use client'
2
+ /**
3
+ * Represents the value that separates the random string from the
4
+ * mobile deeplink URL in the state param from the oauth messages
5
+ * emitted from native mobile apps.
6
+ */
7
+ const nativeMobileOauthStateParam = '_client-redirect:';
8
+
9
+ export { nativeMobileOauthStateParam };
@@ -9,8 +9,12 @@ require('./errors/TransactionGasCannotBeSponsoredError.cjs');
9
9
  require('./logger/logger.cjs');
10
10
  require('./bufferPolyfill.cjs');
11
11
  var sleep = require('./sleep/sleep.cjs');
12
- require('viem/chains');
12
+ require('./services/PlatformService/PlatformService.cjs');
13
13
  require('tldts');
14
+ require('./services/FetchService/FetchService.cjs');
15
+ require('./services/Oauth2Service/Oauth2Service.cjs');
16
+ require('@dynamic-labs/types');
17
+ require('@dynamic-labs/sdk-api-core');
14
18
 
15
19
  const FALLBACK_UNDEFINED = 'FALLBACK_UNDEFINED';
16
20
  const retryableFn = (fn_1, ...args_1) => _tslib.__awaiter(void 0, [fn_1, ...args_1], void 0, function* (fn, options = {}) {
@@ -5,8 +5,12 @@ import './errors/TransactionGasCannotBeSponsoredError.js';
5
5
  import './logger/logger.js';
6
6
  import './bufferPolyfill.js';
7
7
  import { sleep } from './sleep/sleep.js';
8
- import 'viem/chains';
8
+ import './services/PlatformService/PlatformService.js';
9
9
  import 'tldts';
10
+ import './services/FetchService/FetchService.js';
11
+ import './services/Oauth2Service/Oauth2Service.js';
12
+ import '@dynamic-labs/types';
13
+ import '@dynamic-labs/sdk-api-core';
10
14
 
11
15
  const FALLBACK_UNDEFINED = 'FALLBACK_UNDEFINED';
12
16
  const retryableFn = (fn_1, ...args_1) => __awaiter(void 0, [fn_1, ...args_1], void 0, function* (fn, options = {}) {
@@ -3,22 +3,27 @@
3
3
 
4
4
  Object.defineProperty(exports, '__esModule', { value: true });
5
5
 
6
+ var _tslib = require('../../../_virtual/_tslib.cjs');
7
+
8
+ var _a, _FetchService_implementation;
6
9
  /**
7
10
  * Class implementing the fetch service with a configurable fetch implementation.
8
11
  */
9
12
  class FetchService {
10
13
  static get implementation() {
11
- if (!FetchService._implementation) {
14
+ if (!_tslib.__classPrivateFieldGet(_a, _a, "f", _FetchService_implementation)) {
12
15
  return { fetch: window.fetch.bind(window) };
13
16
  }
14
- return FetchService._implementation;
17
+ return _tslib.__classPrivateFieldGet(_a, _a, "f", _FetchService_implementation);
15
18
  }
16
- static setImplementation(implementation) {
17
- FetchService._implementation = implementation;
19
+ static set implementation(implementation) {
20
+ _tslib.__classPrivateFieldSet(_a, _a, implementation, "f", _FetchService_implementation);
18
21
  }
19
22
  static get fetch() {
20
- return FetchService.implementation.fetch;
23
+ return _a.implementation.fetch;
21
24
  }
22
25
  }
26
+ _a = FetchService;
27
+ _FetchService_implementation = { value: void 0 };
23
28
 
24
29
  exports.FetchService = FetchService;
@@ -3,8 +3,8 @@ import { IFetchService } from './types';
3
3
  * Class implementing the fetch service with a configurable fetch implementation.
4
4
  */
5
5
  export declare class FetchService {
6
- static _implementation: IFetchService;
6
+ #private;
7
7
  static get implementation(): IFetchService;
8
- static setImplementation(implementation: IFetchService): void;
8
+ static set implementation(implementation: IFetchService);
9
9
  static get fetch(): (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;
10
10
  }
@@ -1,20 +1,25 @@
1
1
  'use client'
2
+ import { __classPrivateFieldGet, __classPrivateFieldSet } from '../../../_virtual/_tslib.js';
3
+
4
+ var _a, _FetchService_implementation;
2
5
  /**
3
6
  * Class implementing the fetch service with a configurable fetch implementation.
4
7
  */
5
8
  class FetchService {
6
9
  static get implementation() {
7
- if (!FetchService._implementation) {
10
+ if (!__classPrivateFieldGet(_a, _a, "f", _FetchService_implementation)) {
8
11
  return { fetch: window.fetch.bind(window) };
9
12
  }
10
- return FetchService._implementation;
13
+ return __classPrivateFieldGet(_a, _a, "f", _FetchService_implementation);
11
14
  }
12
- static setImplementation(implementation) {
13
- FetchService._implementation = implementation;
15
+ static set implementation(implementation) {
16
+ __classPrivateFieldSet(_a, _a, implementation, "f", _FetchService_implementation);
14
17
  }
15
18
  static get fetch() {
16
- return FetchService.implementation.fetch;
19
+ return _a.implementation.fetch;
17
20
  }
18
21
  }
22
+ _a = FetchService;
23
+ _FetchService_implementation = { value: void 0 };
19
24
 
20
25
  export { FetchService };
@@ -0,0 +1,38 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var _tslib = require('../../../_virtual/_tslib.cjs');
7
+ var types = require('@dynamic-labs/types');
8
+ var createWindowOauth2Service = require('./createWindowOauth2Service/createWindowOauth2Service.cjs');
9
+
10
+ var _a, _Oauth2Service_implementation;
11
+ /**
12
+ * Class implementing the fetch service with a configurable fetch implementation.
13
+ */
14
+ class Oauth2Service {
15
+ static get implementation() {
16
+ if (!_tslib.__classPrivateFieldGet(_a, _a, "f", _Oauth2Service_implementation)) {
17
+ return createWindowOauth2Service.createWindowOauth2Service();
18
+ }
19
+ return _tslib.__classPrivateFieldGet(_a, _a, "f", _Oauth2Service_implementation);
20
+ }
21
+ static set implementation(implementation) {
22
+ _tslib.__classPrivateFieldSet(_a, _a, implementation, "f", _Oauth2Service_implementation);
23
+ }
24
+ static get getOauthCode() {
25
+ return _a.implementation.getOauthCode;
26
+ }
27
+ }
28
+ _a = Oauth2Service;
29
+ _Oauth2Service_implementation = { value: void 0 };
30
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
+ Oauth2Service.isGetOauthCodeError = (error) => error === 'user-cancelled' ||
32
+ (typeof error === 'object' &&
33
+ 'code' in error &&
34
+ Object.values(types.SocialOAuthErrorCode).includes(error.code) &&
35
+ 'message' in error &&
36
+ typeof error.message === 'string');
37
+
38
+ exports.Oauth2Service = Oauth2Service;
@@ -0,0 +1,30 @@
1
+ import { OauthResultResponse, Provider, ProviderEnum } from '@dynamic-labs/sdk-api-core';
2
+ import { SocialOAuthErrorCode } from '@dynamic-labs/types';
3
+ export type GetOauthCodeProps = {
4
+ provider: ProviderEnum;
5
+ apiProvider: Provider | undefined;
6
+ setIsProcessing: (value: boolean) => void;
7
+ onSettled?: VoidFunction;
8
+ getOAuthResultFromApi: () => Promise<OauthResultResponse | undefined>;
9
+ state: string;
10
+ oauthLoginUrl: URL;
11
+ sessionTimeout: number;
12
+ isMobile?: boolean;
13
+ };
14
+ export type IOauth2Service = {
15
+ getOauthCode: (props: GetOauthCodeProps) => Promise<string>;
16
+ };
17
+ export type GetOauthCodeError = 'user-cancelled' | {
18
+ code: SocialOAuthErrorCode;
19
+ message: string;
20
+ };
21
+ /**
22
+ * Class implementing the fetch service with a configurable fetch implementation.
23
+ */
24
+ export declare class Oauth2Service {
25
+ #private;
26
+ static get implementation(): IOauth2Service;
27
+ static set implementation(implementation: IOauth2Service);
28
+ static get getOauthCode(): (props: GetOauthCodeProps) => Promise<string>;
29
+ static isGetOauthCodeError: (error: any) => error is GetOauthCodeError;
30
+ }
@@ -0,0 +1,34 @@
1
+ 'use client'
2
+ import { __classPrivateFieldGet, __classPrivateFieldSet } from '../../../_virtual/_tslib.js';
3
+ import { SocialOAuthErrorCode } from '@dynamic-labs/types';
4
+ import { createWindowOauth2Service } from './createWindowOauth2Service/createWindowOauth2Service.js';
5
+
6
+ var _a, _Oauth2Service_implementation;
7
+ /**
8
+ * Class implementing the fetch service with a configurable fetch implementation.
9
+ */
10
+ class Oauth2Service {
11
+ static get implementation() {
12
+ if (!__classPrivateFieldGet(_a, _a, "f", _Oauth2Service_implementation)) {
13
+ return createWindowOauth2Service();
14
+ }
15
+ return __classPrivateFieldGet(_a, _a, "f", _Oauth2Service_implementation);
16
+ }
17
+ static set implementation(implementation) {
18
+ __classPrivateFieldSet(_a, _a, implementation, "f", _Oauth2Service_implementation);
19
+ }
20
+ static get getOauthCode() {
21
+ return _a.implementation.getOauthCode;
22
+ }
23
+ }
24
+ _a = Oauth2Service;
25
+ _Oauth2Service_implementation = { value: void 0 };
26
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
+ Oauth2Service.isGetOauthCodeError = (error) => error === 'user-cancelled' ||
28
+ (typeof error === 'object' &&
29
+ 'code' in error &&
30
+ Object.values(SocialOAuthErrorCode).includes(error.code) &&
31
+ 'message' in error &&
32
+ typeof error.message === 'string');
33
+
34
+ export { Oauth2Service };
@@ -0,0 +1,170 @@
1
+ 'use client'
2
+ 'use strict';
3
+
4
+ Object.defineProperty(exports, '__esModule', { value: true });
5
+
6
+ var _tslib = require('../../../../_virtual/_tslib.cjs');
7
+ var types = require('@dynamic-labs/types');
8
+ var sdkApiCore = require('@dynamic-labs/sdk-api-core');
9
+ var logger = require('../../../logger/logger.cjs');
10
+
11
+ const providersWithoutWindowOpenerReference = ['twitter'];
12
+ let authWindowInterval;
13
+ const createWindowOauth2Service = () => ({
14
+ getOauthCode: ({ apiProvider, provider, setIsProcessing, state, oauthLoginUrl, getOAuthResultFromApi, sessionTimeout, isMobile, onSettled, }) => new Promise((resolve, _reject) => {
15
+ // When we catch this error we assume it follows this type, so we must enforce it
16
+ // here to ensure the assumption is correct
17
+ const typedReject = (params) => _reject(params);
18
+ // Clear any potential pending timeouts and intervals
19
+ clearInterval(authWindowInterval);
20
+ const providersWaitingOauthMessage = {};
21
+ let shouldPool = false;
22
+ const authWindow = window.open('', '_blank', 'width=500,height=600');
23
+ const clearListeners = () => {
24
+ window.removeEventListener('message', handleWindowMessage);
25
+ providersWaitingOauthMessage[provider] = false;
26
+ };
27
+ const handleWindowMessage = (event) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
28
+ const message = event.data;
29
+ if (!(apiProvider === null || apiProvider === void 0 ? void 0 : apiProvider.redirectUrl)) {
30
+ return;
31
+ }
32
+ let expectedOrigin = window.location.origin;
33
+ if (!providersWithoutWindowOpenerReference.includes(provider)) {
34
+ try {
35
+ const redirectUri = new URL(apiProvider.redirectUrl);
36
+ expectedOrigin = redirectUri.origin;
37
+ }
38
+ catch (e) {
39
+ logger.logger.error('Failed to parse social provider redirect url', {
40
+ error: e,
41
+ });
42
+ return;
43
+ }
44
+ }
45
+ if ((message === null || message === void 0 ? void 0 : message.type) === 'origin_check' && authWindow) {
46
+ logger.logger.debug('Origin check message received. Sending response now.', {
47
+ data: message,
48
+ expectedOrigin,
49
+ });
50
+ authWindow.postMessage('origin_check_response', expectedOrigin);
51
+ return;
52
+ }
53
+ const isAuthorizationMessage = (message === null || message === void 0 ? void 0 : message.type) === 'authorization_response';
54
+ if (isAuthorizationMessage) {
55
+ logger.logger.debug('Message received', { data: message });
56
+ }
57
+ const isExpectedOrigin = event.origin === expectedOrigin;
58
+ const isValidMessage = isAuthorizationMessage &&
59
+ (message === null || message === void 0 ? void 0 : message.provider) === provider &&
60
+ isExpectedOrigin;
61
+ // don't process invalid messages for provider
62
+ if (!isValidMessage) {
63
+ return;
64
+ }
65
+ setIsProcessing(true);
66
+ if (!providersWaitingOauthMessage[provider]) {
67
+ typedReject({
68
+ code: types.SocialOAuthErrorCode.SESSION_TIMEOUT,
69
+ message: `Connecting ${provider} account session timeout.`,
70
+ });
71
+ return;
72
+ }
73
+ clearListeners();
74
+ const { code, error, state: authState } = message;
75
+ if (error && error !== 'undefined') {
76
+ typedReject({
77
+ code: types.SocialOAuthErrorCode.OAUTH_ERROR,
78
+ message: `Failed to connect ${provider} social account: ${error}`,
79
+ });
80
+ return;
81
+ }
82
+ // check that the state we receive from message is the same state we calculated earlier
83
+ // this could be an attack
84
+ // this state check is used only by providers with an open window opener reference (eg, not twitter)
85
+ if (!providersWithoutWindowOpenerReference.includes(provider) &&
86
+ state !== authState) {
87
+ typedReject({
88
+ code: types.SocialOAuthErrorCode.OAUTH_ERROR,
89
+ message: `Failed to connect ${provider} social account: Invalid random state`,
90
+ });
91
+ return;
92
+ }
93
+ if (!code) {
94
+ typedReject({
95
+ code: types.SocialOAuthErrorCode.NO_AUTH_CODE,
96
+ message: `Failed to connect ${provider} social account: no authorization code`,
97
+ });
98
+ return;
99
+ }
100
+ resolve(code);
101
+ setIsProcessing(false);
102
+ });
103
+ if (!providersWaitingOauthMessage[provider]) {
104
+ window.addEventListener('message', handleWindowMessage);
105
+ providersWaitingOauthMessage[provider] = true;
106
+ }
107
+ authWindow === null || authWindow === void 0 ? void 0 : authWindow.location.assign(oauthLoginUrl);
108
+ if (!providersWithoutWindowOpenerReference.includes(provider)) {
109
+ // For provider that support window.opener, we need to clear all states/listeners when the window is closed
110
+ authWindowInterval = setInterval(() => {
111
+ if (!(authWindow === null || authWindow === void 0 ? void 0 : authWindow.closed))
112
+ return;
113
+ clearInterval(authWindowInterval);
114
+ setIsProcessing(false);
115
+ // user didn't complete oauth
116
+ if (providersWaitingOauthMessage[provider])
117
+ typedReject('user-cancelled');
118
+ }, 2000);
119
+ }
120
+ else {
121
+ // For provider that don't support window.opener, we need to use a timeout to pool the oauth result
122
+ // If we don't get a valid result in {async sessionTimeout} ms, we'll assume the user closed the window
123
+ // and we'll clear all states/listeners
124
+ const poolOauthResult = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
125
+ if (!shouldPool)
126
+ return;
127
+ const result = yield getOAuthResultFromApi();
128
+ if (!shouldPool)
129
+ return;
130
+ if ((result === null || result === void 0 ? void 0 : result.status) !== sdkApiCore.OauthResultStatus.Completed) {
131
+ authWindowInterval = setTimeout(() => {
132
+ poolOauthResult();
133
+ }, 1000);
134
+ return;
135
+ }
136
+ shouldPool = false;
137
+ const authMessage = {
138
+ code: result === null || result === void 0 ? void 0 : result.code,
139
+ error: result === null || result === void 0 ? void 0 : result.error,
140
+ provider,
141
+ type: 'authorization_response',
142
+ };
143
+ window.postMessage(authMessage, '*');
144
+ });
145
+ // start pooling oauth result
146
+ shouldPool = true;
147
+ poolOauthResult();
148
+ // if this is mobile, set a longer timeout to allow the user to login to the provider in the browser
149
+ let authWindowTimeout = sessionTimeout;
150
+ if (isMobile) {
151
+ authWindowTimeout = authWindowTimeout * 3;
152
+ }
153
+ authWindowInterval = setTimeout(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
154
+ shouldPool = false;
155
+ // clear all states/listeners, assuming user closed the window before completing oauth
156
+ if (providersWaitingOauthMessage[provider]) {
157
+ clearListeners();
158
+ typedReject({
159
+ code: types.SocialOAuthErrorCode.OAUTH_WINDOW_TIMEOUT,
160
+ message: `Connecting ${provider} account window timeout.`,
161
+ });
162
+ }
163
+ setIsProcessing(false);
164
+ onSettled === null || onSettled === void 0 ? void 0 : onSettled();
165
+ }), authWindowTimeout);
166
+ }
167
+ }),
168
+ });
169
+
170
+ exports.createWindowOauth2Service = createWindowOauth2Service;
@@ -0,0 +1,2 @@
1
+ import { IOauth2Service } from '../Oauth2Service';
2
+ export declare const createWindowOauth2Service: () => IOauth2Service;