@dynamic-labs-sdk/client 0.24.0 → 0.25.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 (148) hide show
  1. package/dist/InvalidParamError-B5NwKSKU.native.esm.js +1177 -0
  2. package/dist/InvalidParamError-B5NwKSKU.native.esm.js.map +1 -0
  3. package/dist/{InvalidParamError-kLBXFKhe.esm.js → InvalidParamError-BiVmL7nM.esm.js} +4 -4
  4. package/dist/InvalidParamError-BiVmL7nM.esm.js.map +1 -0
  5. package/dist/{InvalidParamError-BgmShvv_.cjs.js → InvalidParamError-D-d-UfBL.cjs.js} +5 -5
  6. package/dist/InvalidParamError-D-d-UfBL.cjs.js.map +1 -0
  7. package/dist/{NotWaasWalletAccountError-qK9GIBpr.cjs.js → NotWaasWalletAccountError-BJaemI4V.cjs.js} +3 -3
  8. package/dist/{NotWaasWalletAccountError-qK9GIBpr.cjs.js.map → NotWaasWalletAccountError-BJaemI4V.cjs.js.map} +1 -1
  9. package/dist/NotWaasWalletAccountError-BX5lUnKT.native.esm.js +50 -0
  10. package/dist/NotWaasWalletAccountError-BX5lUnKT.native.esm.js.map +1 -0
  11. package/dist/{NotWaasWalletAccountError-VJL72OTC.esm.js → NotWaasWalletAccountError-Bo4VhW4n.esm.js} +3 -3
  12. package/dist/{NotWaasWalletAccountError-VJL72OTC.esm.js.map → NotWaasWalletAccountError-Bo4VhW4n.esm.js.map} +1 -1
  13. package/dist/client/core/createCore/createCore.d.ts.map +1 -1
  14. package/dist/client/core/types/DynamicCore.d.ts +4 -0
  15. package/dist/client/core/types/DynamicCore.d.ts.map +1 -1
  16. package/dist/client/types/DynamicClientConfig.d.ts +10 -0
  17. package/dist/client/types/DynamicClientConfig.d.ts.map +1 -1
  18. package/dist/core.cjs.js +5 -5
  19. package/dist/core.cjs.js.map +1 -1
  20. package/dist/core.esm.js +5 -5
  21. package/dist/core.esm.js.map +1 -1
  22. package/dist/core.native.esm.js +377 -0
  23. package/dist/core.native.esm.js.map +1 -0
  24. package/dist/errors/APIError/APIError.d.ts.map +1 -1
  25. package/dist/errors/InvalidParamError.d.ts.map +1 -1
  26. package/dist/errors/InvalidStorageValue.d.ts.map +1 -1
  27. package/dist/errors/InvalidWalletProviderKeyError.d.ts.map +1 -1
  28. package/dist/errors/MethodNotImplementedError.d.ts.map +1 -1
  29. package/dist/errors/MissingSocialUrlParamError.d.ts.map +1 -1
  30. package/dist/errors/NoSmartWalletAccountSignerFoundError.d.ts.map +1 -1
  31. package/dist/errors/UnavailableInServerSideError.d.ts.map +1 -1
  32. package/dist/errors/ValueMustBeDefinedError.d.ts.map +1 -1
  33. package/dist/errors/WalletAccountAlreadyVerifiedError.d.ts.map +1 -1
  34. package/dist/exports/index.d.ts +4 -4
  35. package/dist/exports/index.d.ts.map +1 -1
  36. package/dist/{getNetworkProviderFromNetworkId-RlnraKJN.esm.js → getNetworkProviderFromNetworkId-5dK99mQR.esm.js} +5 -5
  37. package/dist/getNetworkProviderFromNetworkId-5dK99mQR.esm.js.map +1 -0
  38. package/dist/{getNetworkProviderFromNetworkId-B8OjAdet.cjs.js → getNetworkProviderFromNetworkId-Cl2XDWo9.cjs.js} +5 -5
  39. package/dist/getNetworkProviderFromNetworkId-Cl2XDWo9.cjs.js.map +1 -0
  40. package/dist/getNetworkProviderFromNetworkId-DWOYr3uv.native.esm.js +1302 -0
  41. package/dist/getNetworkProviderFromNetworkId-DWOYr3uv.native.esm.js.map +1 -0
  42. package/dist/{getSignedSessionId-DBQS7lht.cjs.js → getSignedSessionId-BbhZjeRt.cjs.js} +3 -3
  43. package/dist/{getSignedSessionId-DBQS7lht.cjs.js.map → getSignedSessionId-BbhZjeRt.cjs.js.map} +1 -1
  44. package/dist/{getSignedSessionId-CvNFnwt1.esm.js → getSignedSessionId-DakTrfSz.esm.js} +3 -3
  45. package/dist/{getSignedSessionId-CvNFnwt1.esm.js.map → getSignedSessionId-DakTrfSz.esm.js.map} +1 -1
  46. package/dist/getSignedSessionId-Dk3_TQLq.native.esm.js +67 -0
  47. package/dist/getSignedSessionId-Dk3_TQLq.native.esm.js.map +1 -0
  48. package/dist/{getVerifiedCredentialForWalletAccount-CBJrrV08.cjs.js → getVerifiedCredentialForWalletAccount-BDvkZbtb.cjs.js} +3 -3
  49. package/dist/getVerifiedCredentialForWalletAccount-BDvkZbtb.cjs.js.map +1 -0
  50. package/dist/{getVerifiedCredentialForWalletAccount-8VlwTOBc.esm.js → getVerifiedCredentialForWalletAccount-ByUSFAHs.esm.js} +2 -2
  51. package/dist/getVerifiedCredentialForWalletAccount-ByUSFAHs.esm.js.map +1 -0
  52. package/dist/getVerifiedCredentialForWalletAccount-Dhqf6Tdl.native.esm.js +783 -0
  53. package/dist/getVerifiedCredentialForWalletAccount-Dhqf6Tdl.native.esm.js.map +1 -0
  54. package/dist/index.cjs.js +73 -49
  55. package/dist/index.cjs.js.map +1 -1
  56. package/dist/index.esm.js +73 -49
  57. package/dist/index.esm.js.map +1 -1
  58. package/dist/index.native.esm.js +7000 -0
  59. package/dist/index.native.esm.js.map +1 -0
  60. package/dist/{isMfaRequiredForAction-9NDyQhHS.cjs.js → isMfaRequiredForAction-CYrluCK-.cjs.js} +2 -2
  61. package/dist/{isMfaRequiredForAction-9NDyQhHS.cjs.js.map → isMfaRequiredForAction-CYrluCK-.cjs.js.map} +1 -1
  62. package/dist/{isMfaRequiredForAction-8NlpzYe6.esm.js → isMfaRequiredForAction-SFbQW5j5.esm.js} +2 -2
  63. package/dist/{isMfaRequiredForAction-8NlpzYe6.esm.js.map → isMfaRequiredForAction-SFbQW5j5.esm.js.map} +1 -1
  64. package/dist/isMfaRequiredForAction-y15A_lhP.native.esm.js +89 -0
  65. package/dist/isMfaRequiredForAction-y15A_lhP.native.esm.js.map +1 -0
  66. package/dist/modules/auth/decodeJwt/decodeJwt.d.ts.map +1 -1
  67. package/dist/modules/auth/externalAuth/signInWithExternalJwt/signInWithExternalJwt.d.ts +0 -1
  68. package/dist/modules/auth/externalAuth/signInWithExternalJwt/signInWithExternalJwt.d.ts.map +1 -1
  69. package/dist/modules/auth/extractSessionId/extractSessionId.d.ts.map +1 -1
  70. package/dist/modules/auth/initializeAuth/setLongTimeout/setLongTimeout.d.ts.map +1 -1
  71. package/dist/modules/auth/social/oauth/authenticateWithSocial/buildOAuthUrl/addOAuthUrlParams/addOAuthUrlParams.d.ts.map +1 -1
  72. package/dist/modules/auth/social/oauth/authenticateWithSocial/buildOAuthUrl/buildOAuthUrl.d.ts.map +1 -1
  73. package/dist/modules/auth/social/removeDynamicOauthParamsFromUrl/removeDynamicOauthParamsFromUrl.d.ts.map +1 -1
  74. package/dist/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/normalizeScopes/normalizeScopes.d.ts.map +1 -1
  75. package/dist/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken/parseElevatedAccessToken.d.ts.map +1 -1
  76. package/dist/modules/checkout/attachCheckoutTransactionSource/attachCheckoutTransactionSource.d.ts +34 -6
  77. package/dist/modules/checkout/attachCheckoutTransactionSource/attachCheckoutTransactionSource.d.ts.map +1 -1
  78. package/dist/modules/checkout/broadcastCheckoutTransaction/broadcastCheckoutTransaction.d.ts +11 -3
  79. package/dist/modules/checkout/broadcastCheckoutTransaction/broadcastCheckoutTransaction.d.ts.map +1 -1
  80. package/dist/modules/checkout/checkout.types.d.ts +1 -0
  81. package/dist/modules/checkout/checkout.types.d.ts.map +1 -1
  82. package/dist/modules/checkout/trackCheckoutTransaction/trackCheckoutTransaction.d.ts +7 -3
  83. package/dist/modules/checkout/trackCheckoutTransaction/trackCheckoutTransaction.d.ts.map +1 -1
  84. package/dist/modules/checkout/utils/createCheckoutSessionTokenStorageKey/createCheckoutSessionTokenStorageKey.d.ts.map +1 -1
  85. package/dist/modules/checkout/utils/subscribeToCheckoutTransaction/subscribeToCheckoutTransaction.d.ts.map +1 -1
  86. package/dist/modules/instrumentation/setInstrumentationEnabled/setInstrumentationEnabled.d.ts.map +1 -1
  87. package/dist/modules/keychainMigration/migrateSessionKeyToKeychain/KeyMigrationError.d.ts.map +1 -1
  88. package/dist/modules/legacyWalletBook/getWalletConnectCatalog/shouldFilterWallet/shouldFilterWallet.d.ts.map +1 -1
  89. package/dist/modules/otp/sendEmailOTP/sendEmailOTP.d.ts +0 -1
  90. package/dist/modules/otp/sendEmailOTP/sendEmailOTP.d.ts.map +1 -1
  91. package/dist/modules/otp/sendSmsOTP/sendSmsOTP.d.ts +0 -1
  92. package/dist/modules/otp/sendSmsOTP/sendSmsOTP.d.ts.map +1 -1
  93. package/dist/modules/user/updateUser/updateUser.d.ts +0 -1
  94. package/dist/modules/user/updateUser/updateUser.d.ts.map +1 -1
  95. package/dist/modules/waas/createWaasClient/createWaasClient.d.ts.map +1 -1
  96. package/dist/modules/waas/createWaasProvider/createWaasProvider.d.ts.map +1 -1
  97. package/dist/modules/waas/getWaasChainNameFromChain/getWaasChainNameFromChain.d.ts.map +1 -1
  98. package/dist/modules/wallets/networks/createBaseNetworkProvider/createBaseNetworkProvider.d.ts.map +1 -1
  99. package/dist/modules/wallets/networks/getSdkChainFromApiChainName/getSdkChainFromApiChainName.d.ts.map +1 -1
  100. package/dist/modules/wallets/utils/assertWalletProviderMethodDefined/assertWalletProviderMethodDefined.d.ts.map +1 -1
  101. package/dist/modules/wallets/utils/getAllProvidersFromWindow/getAllProvidersFromWindow.d.ts.map +1 -1
  102. package/dist/modules/wallets/utils/getInjectedProviderFromWindow/getInjectedProviderFromWindow.d.ts.map +1 -1
  103. package/dist/modules/wallets/utils/isSameAddress/isSameAddress.d.ts.map +1 -1
  104. package/dist/modules/wallets/utils/normalizeAddress/normalizeAddress.d.ts.map +1 -1
  105. package/dist/modules/wallets/walletProvider/splitWalletProviderKey/splitWalletProviderKey.d.ts.map +1 -1
  106. package/dist/services/instrumentation/createInstrumentation/createInstrumentation.d.ts.map +1 -1
  107. package/dist/services/instrumentation/instrumentFunction/extractParams/extractParams.d.ts.map +1 -1
  108. package/dist/services/keychain/createIndexedDBKeychainService/KeyNotFoundError.d.ts.map +1 -1
  109. package/dist/services/keychain/createIndexedDBKeychainService/createIndexedDBKeychainService.d.ts.map +1 -1
  110. package/dist/services/keychain/createIndexedDBKeychainService/utils/deleteIndexedDBItem.d.ts.map +1 -1
  111. package/dist/services/keychain/createIndexedDBKeychainService/utils/getIndexedDBItem.d.ts.map +1 -1
  112. package/dist/services/keychain/createIndexedDBKeychainService/utils/setIndexedDBItem.d.ts.map +1 -1
  113. package/dist/services/logger/createLogger/createLogger.d.ts.map +1 -1
  114. package/dist/services/realtime/createRealtimeService/createRealtimeService.d.ts.map +1 -1
  115. package/dist/services/realtime/realtime.types.d.ts +1 -0
  116. package/dist/services/realtime/realtime.types.d.ts.map +1 -1
  117. package/dist/services/runtimeServices/createRuntimeServiceAccessKey/createRuntimeServiceAccessKey.d.ts.map +1 -1
  118. package/dist/services/runtimeServices/createRuntimeServices/createRuntimeServices.d.ts.map +1 -1
  119. package/dist/services/storage/createStorage/formatForStorage/isValidDateISOString/isValidDateISOString.d.ts.map +1 -1
  120. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  121. package/dist/utils/assertDefined/assertDefined.d.ts.map +1 -1
  122. package/dist/utils/base64UrlDecode/base64UrlDecode.d.ts.map +1 -1
  123. package/dist/utils/digestSHA256/digestSHA256.d.ts.map +1 -1
  124. package/dist/utils/getChainFromVerifiedCredentialChain/getChainFromVerifiedCredentialChain.d.ts.map +1 -1
  125. package/dist/utils/isEqualShallow/isEqualShallow.d.ts.map +1 -1
  126. package/dist/utils/isErrorWithCode/isErrorWithCode.d.ts.map +1 -1
  127. package/dist/utils/isMobile/isMobile.d.ts.map +1 -1
  128. package/dist/utils/observable/createObservableState/createObservableState.d.ts.map +1 -1
  129. package/dist/utils/observable/subscribeWithSelector/subscribeWithSelector.d.ts.map +1 -1
  130. package/dist/utils/retryOnFail/InvalidRetryOnFailCallError.d.ts.map +1 -1
  131. package/dist/utils/setCookie/setCookie.d.ts.map +1 -1
  132. package/dist/waas.cjs.js +4 -4
  133. package/dist/waas.esm.js +3 -3
  134. package/dist/waas.native.esm.js +506 -0
  135. package/dist/waas.native.esm.js.map +1 -0
  136. package/dist/waasCore.cjs.js +7 -5
  137. package/dist/waasCore.cjs.js.map +1 -1
  138. package/dist/waasCore.esm.js +6 -4
  139. package/dist/waasCore.esm.js.map +1 -1
  140. package/dist/waasCore.native.esm.js +253 -0
  141. package/dist/waasCore.native.esm.js.map +1 -0
  142. package/package.json +8 -4
  143. package/dist/InvalidParamError-BgmShvv_.cjs.js.map +0 -1
  144. package/dist/InvalidParamError-kLBXFKhe.esm.js.map +0 -1
  145. package/dist/getNetworkProviderFromNetworkId-B8OjAdet.cjs.js.map +0 -1
  146. package/dist/getNetworkProviderFromNetworkId-RlnraKJN.esm.js.map +0 -1
  147. package/dist/getVerifiedCredentialForWalletAccount-8VlwTOBc.esm.js.map +0 -1
  148. package/dist/getVerifiedCredentialForWalletAccount-CBJrrV08.cjs.js.map +0 -1
@@ -0,0 +1,1177 @@
1
+ import { AuthStorageEnum, Configuration, SDKApi, isDeviceNonceSignatureRequiredForUrl } from "@dynamic-labs/sdk-api-core";
2
+
3
+ //#region package.json
4
+ var name = "@dynamic-labs-sdk/client";
5
+ var version = "0.25.0";
6
+ var dependencies = {
7
+ "@dynamic-labs-sdk/assert-package-version": "workspace:*",
8
+ "@dynamic-labs-wallet/browser-wallet-client": "0.0.325",
9
+ "@dynamic-labs/sdk-api-core": "0.0.941",
10
+ "@simplewebauthn/browser": "13.1.0",
11
+ "ably": "2.17.1",
12
+ "buffer": "6.0.3",
13
+ "eventemitter3": "5.0.1",
14
+ "zod": "4.0.5"
15
+ };
16
+
17
+ //#endregion
18
+ //#region src/client/core/getCore/getCore.ts
19
+ /** @not-instrumented */
20
+ const getCore = (client) => {
21
+ return client.__core;
22
+ };
23
+
24
+ //#endregion
25
+ //#region src/errors/base/BaseError.ts
26
+ const getDetails = ({ details, cause }) => {
27
+ if (cause instanceof BaseError) return cause.details;
28
+ if (cause?.message) return cause.message;
29
+ return details;
30
+ };
31
+ /**
32
+ * Formats the error message with all available information
33
+ */
34
+ const formatMessage = ({ shortMessage, details, docsUrl, metaMessages }) => {
35
+ return [
36
+ "[Dynamic JS SDK]",
37
+ shortMessage,
38
+ "",
39
+ ...metaMessages ? [...metaMessages, ""] : [],
40
+ ...docsUrl ? [`Docs: ${docsUrl}`] : [],
41
+ ...details ? [`Details: ${details}`] : [],
42
+ `Version: ${version}`,
43
+ `Timestamp: ${(/* @__PURE__ */ new Date()).toISOString()}`
44
+ ].join("\n");
45
+ };
46
+ /**
47
+ * Base error class that provides structured error handling with detailed information
48
+ */
49
+ var BaseError = class BaseError extends Error {
50
+ /** The error unique code */
51
+ code;
52
+ details;
53
+ formattedMessage;
54
+ name = "BaseError";
55
+ cause;
56
+ constructor(args) {
57
+ const details = getDetails(args);
58
+ const formattedMessage = formatMessage({
59
+ ...args,
60
+ details
61
+ });
62
+ super(args.shortMessage ?? formattedMessage, args.cause ? { cause: args.cause } : void 0);
63
+ this.formattedMessage = formattedMessage;
64
+ this.details = details;
65
+ this.name = args.name ?? this.name;
66
+ this.cause = args.cause ?? this.cause;
67
+ this.code = args.code;
68
+ }
69
+ /**
70
+ * Walks the cause chain of the error and returns the root error
71
+ */
72
+ walk() {
73
+ const cause = this.cause;
74
+ if (cause instanceof BaseError) return cause.walk();
75
+ return cause;
76
+ }
77
+ toString() {
78
+ return this.formattedMessage;
79
+ }
80
+ };
81
+
82
+ //#endregion
83
+ //#region src/errors/ClientNotFoundError.ts
84
+ var ClientNotFoundError = class extends BaseError {
85
+ constructor() {
86
+ super({
87
+ cause: null,
88
+ code: "client_not_found_error",
89
+ docsUrl: null,
90
+ name: "ClientNotFoundError",
91
+ shortMessage: "No Dynamic client has been created yet. Make sure you have called createDynamicClient() first."
92
+ });
93
+ }
94
+ };
95
+
96
+ //#endregion
97
+ //#region src/client/defaultClient/defaultClient.ts
98
+ let defaultClient = null;
99
+ let numOfInitializedClients = 0;
100
+ /**
101
+ * Returns the DynamicClient instance that was initialized with createDynamicClient.
102
+ *
103
+ * If more than one instance of DynamicClient was initialized, you should not use this function.
104
+ * Instead, you should pass the client instance you stored to the function that needs it.
105
+ * @not-instrumented
106
+ */
107
+ const getDefaultClient = () => {
108
+ if (!defaultClient) throw new ClientNotFoundError();
109
+ if (numOfInitializedClients > 1) getCore(defaultClient).logger.debug("Multiple instances of DynamicClient found. If you are only using one client (recommended), make sure you are not calling \"createDynamicClient\" multiple times. If you are using multiple clients, make sure you are passing which client to use as the last param of all Dynamic functions.");
110
+ return defaultClient;
111
+ };
112
+ /** @not-instrumented */
113
+ const setDefaultClient = (client) => {
114
+ defaultClient = client;
115
+ numOfInitializedClients++;
116
+ };
117
+
118
+ //#endregion
119
+ //#region src/utils/getNonce/constants.ts
120
+ const NONCE_POOL_EXPIRATION_TIME = 6e4 * 60 * 24;
121
+ const NONCE_POOL_SIZE = 5;
122
+
123
+ //#endregion
124
+ //#region src/modules/apiClient/constants.ts
125
+ const DYNAMIC_API_VERSION_HEADER = "x-dyn-api-version";
126
+ const DYNAMIC_REQUEST_ID_HEADER = "x-dyn-request-id";
127
+ const DYNAMIC_SDK_VERSION_HEADER = "x-dyn-version";
128
+ const ELEVATED_ACCESS_TOKEN_HEADER = "x-dyn-elevated-access-token";
129
+ const MFA_TOKEN_HEADER = "x-mfa-auth-token";
130
+ const SESSION_PUBLIC_KEY_HEADER = "x-dyn-session-public-key";
131
+ const DYNAMIC_SDK_API_VERSION = dependencies["@dynamic-labs/sdk-api-core"];
132
+ const DYNAMIC_SDK_SESSION_ID_HEADER = "x-dyn-session-id";
133
+ const CLIENT_SDK_NAME = "ClientSDK";
134
+
135
+ //#endregion
136
+ //#region src/utils/randomString/randomString.ts
137
+ const DEFAULT_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
138
+ /** @not-instrumented */
139
+ const randomString = ({ chars = DEFAULT_CHARS, length }) => {
140
+ const bytes = new Uint8Array(length);
141
+ crypto.getRandomValues(bytes);
142
+ let result = "";
143
+ for (let i = 0; i < length; i++) result += chars[bytes[i] % chars.length];
144
+ return result;
145
+ };
146
+
147
+ //#endregion
148
+ //#region src/errors/ValueMustBeDefinedError.ts
149
+ var ValueMustBeDefinedError = class extends BaseError {
150
+ constructor(message) {
151
+ super({
152
+ cause: null,
153
+ code: "value_must_be_defined_error",
154
+ docsUrl: null,
155
+ name: "ValueMustBeDefined",
156
+ shortMessage: message
157
+ });
158
+ }
159
+ };
160
+
161
+ //#endregion
162
+ //#region src/utils/assertDefined/assertDefined.ts
163
+ /**
164
+ * Asserts that a value is not null or undefined, throwing an error if it is.
165
+ * This function acts as a type guard, narrowing the type to exclude null and undefined.
166
+ *
167
+ * @template T - The type of the value being checked
168
+ * @param value - The value to check for null or undefined
169
+ * @param message - The error message to throw if the value is null or undefined
170
+ * @throws Throws an error with the provided message if value is null or undefined
171
+ * @example
172
+ * ```typescript
173
+ * const maybeString: string | null = getValue();
174
+ * assertDefined(maybeString, 'String value is required');
175
+ * // maybeString is now typed as string (null is excluded)
176
+ * ```
177
+ */
178
+ function assertDefined(value, message) {
179
+ if (value === null || value === void 0) throw new ValueMustBeDefinedError(message);
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/modules/projectSettings/isCookieEnabled/isCookieEnabled.ts
184
+ /**
185
+ * Returns true if the client is using Dynamic cookies or a BYO JWT cookie.
186
+ * @not-instrumented
187
+ */
188
+ const isCookieEnabled = (client) => {
189
+ assertDefined(client.projectSettings, "Project settings are not defined");
190
+ const securitySettings = client.projectSettings.security;
191
+ if (!securitySettings) return false;
192
+ const dynamicCookiesEnabled = (securitySettings.auth?.storage || []).includes(AuthStorageEnum.Cookie);
193
+ const byoJwtCookieEnabled = Boolean(securitySettings.externalAuth?.cookieName);
194
+ return dynamicCookiesEnabled || byoJwtCookieEnabled;
195
+ };
196
+
197
+ //#endregion
198
+ //#region src/modules/auth/extractSessionId/extractSessionId.ts
199
+ /**
200
+ * Extracts the session ID (`sid` claim) from a JWT token string.
201
+ *
202
+ * Decodes the base64url-encoded payload segment of the token and reads the
203
+ * `sid` field. This is used to correlate instrumentation events with the
204
+ * authenticated session, without ever forwarding the full token.
205
+ *
206
+ * Returns `null` when no token is present, when the token is malformed, or
207
+ * when the payload does not contain a `sid` claim.
208
+ * @not-instrumented
209
+ */
210
+ const extractSessionId = (token) => {
211
+ try {
212
+ const payload = token.split(".")[1];
213
+ return JSON.parse(atob(payload)).sid ?? null;
214
+ } catch {
215
+ return null;
216
+ }
217
+ };
218
+
219
+ //#endregion
220
+ //#region src/utils/getUserAgent/getUserAgent.ts
221
+ /**
222
+ * Returns the browser's `navigator.userAgent` string for inclusion in
223
+ * instrumentation events.
224
+ *
225
+ * Falls back to an empty string in environments where `navigator` is not
226
+ * available (e.g., Node.js SSR, service workers) so that callers never need
227
+ * to guard against undefined.
228
+ * @not-instrumented
229
+ */
230
+ const getUserAgent = () => {
231
+ try {
232
+ return navigator.userAgent;
233
+ } catch {
234
+ return "";
235
+ }
236
+ };
237
+
238
+ //#endregion
239
+ //#region src/services/instrumentation/constants.ts
240
+ const DEFAULT_PII_FIELDS = [
241
+ "password",
242
+ "token",
243
+ "secret",
244
+ "privateKey",
245
+ "mnemonic",
246
+ "seed",
247
+ "email",
248
+ "phone",
249
+ "ssn",
250
+ "address",
251
+ "authorization"
252
+ ];
253
+ const REDACTED_VALUE = "[REDACTED]";
254
+ const MAX_STRING_LENGTH = 500;
255
+ const TRUNCATED_SUFFIX = "...[truncated]";
256
+ /**
257
+ * Label prefix for binary data placeholders. The full placeholder includes the
258
+ * byte length, e.g. `[Binary:16 bytes]`, so consumers can gauge data size
259
+ * without the actual bytes appearing in logs.
260
+ */
261
+ const BINARY_LABEL = "Binary";
262
+ /**
263
+ * Placeholder emitted when a circular reference is detected in the value tree.
264
+ * Using a named constant makes it easy to search for or filter in downstream
265
+ * log tooling.
266
+ */
267
+ const CIRCULAR_VALUE = "[Circular]";
268
+
269
+ //#endregion
270
+ //#region src/services/instrumentation/scrubParameters/scrubParameters.ts
271
+ const scrubString = ({ key, piiFieldsLower, redactAll, value }) => {
272
+ if (piiFieldsLower.includes(key.toLowerCase())) return REDACTED_VALUE;
273
+ if (redactAll) return REDACTED_VALUE;
274
+ if (value.length > MAX_STRING_LENGTH) return value.slice(0, MAX_STRING_LENGTH) + TRUNCATED_SUFFIX;
275
+ return value;
276
+ };
277
+ const scrubArray = ({ context, value }) => {
278
+ if (context.visited.has(value)) return [CIRCULAR_VALUE];
279
+ context.visited.add(value);
280
+ const result = value.map((item, index) => scrubValue({
281
+ context,
282
+ key: String(index),
283
+ value: item
284
+ }));
285
+ context.visited.delete(value);
286
+ return result;
287
+ };
288
+ const scrubObject = ({ context, value }) => {
289
+ if (context.visited.has(value)) return { [CIRCULAR_VALUE]: true };
290
+ context.visited.add(value);
291
+ const result = Object.create(null);
292
+ for (const key of Object.keys(value)) result[key] = scrubValue({
293
+ context,
294
+ key,
295
+ value: value[key]
296
+ });
297
+ context.visited.delete(value);
298
+ return result;
299
+ };
300
+ const scrubValue = ({ context, key, value }) => {
301
+ if (value === null || value === void 0) return value;
302
+ if (value instanceof Uint8Array) return `[${BINARY_LABEL}:${value.byteLength} bytes]`;
303
+ if (context.piiFieldsLower.includes(key.toLowerCase())) return REDACTED_VALUE;
304
+ if (typeof value === "string") return scrubString({
305
+ key,
306
+ piiFieldsLower: context.piiFieldsLower,
307
+ redactAll: context.redactAll,
308
+ value
309
+ });
310
+ if (Array.isArray(value)) return scrubArray({
311
+ context,
312
+ value
313
+ });
314
+ if (value instanceof Set) {
315
+ if (context.visited.has(value)) return [CIRCULAR_VALUE];
316
+ context.visited.add(value);
317
+ const setResult = scrubArray({
318
+ context,
319
+ value: [...value]
320
+ });
321
+ context.visited.delete(value);
322
+ return setResult;
323
+ }
324
+ if (value instanceof Map) {
325
+ if (context.visited.has(value)) return { [CIRCULAR_VALUE]: true };
326
+ context.visited.add(value);
327
+ const asObject = Object.create(null);
328
+ for (const [k, v] of value.entries()) asObject[String(k)] = v;
329
+ const mapResult = scrubObject({
330
+ context,
331
+ value: asObject
332
+ });
333
+ context.visited.delete(value);
334
+ return mapResult;
335
+ }
336
+ if (value instanceof WeakMap) return "[WeakMap]";
337
+ if (value instanceof WeakSet) return "[WeakSet]";
338
+ if (value instanceof Date) return value.toISOString();
339
+ if (value instanceof Error) return `[Error: ${value.message}]`;
340
+ if (typeof value === "object") return scrubObject({
341
+ context,
342
+ value
343
+ });
344
+ return value;
345
+ };
346
+ /** @not-instrumented */
347
+ const scrubParameters = ({ piiFields, redactAll, value }) => {
348
+ return scrubObject({
349
+ context: {
350
+ piiFieldsLower: piiFields.map((field) => field.toLowerCase()),
351
+ redactAll,
352
+ visited: /* @__PURE__ */ new WeakSet()
353
+ },
354
+ value
355
+ });
356
+ };
357
+
358
+ //#endregion
359
+ //#region src/services/instrumentation/instrumentFunction/extractParams/extractParams.ts
360
+ /**
361
+ * Normalises the raw positional arguments of an instrumented function call
362
+ * into a flat `Record<string, unknown>` suitable for structured logging.
363
+ *
364
+ * ## Why this is needed
365
+ *
366
+ * Instrumented functions are wrapped with `(...args: unknown[])`, so their
367
+ * parameters arrive as an array. Logging a raw array loses the semantic names
368
+ * of each argument. This function recovers a named representation:
369
+ *
370
+ * - **No arguments** → `{}`
371
+ * - **Single plain-object argument** → that object is returned as-is, because
372
+ * SDK functions follow the single-object-parameter convention, so the object
373
+ * already carries named keys (`{ amount, to }`, etc.).
374
+ * - **Everything else** (multiple args, a single primitive, a single array) →
375
+ * each value is indexed as `arg0`, `arg1`, …
376
+ *
377
+ * ## Why arrays are NOT treated as plain objects
378
+ *
379
+ * `typeof [] === 'object'` and `[] !== null`, so without the `Array.isArray`
380
+ * guard a single-array argument would be returned as-is. That would produce
381
+ * an object with numeric string keys (`{ '0': ..., '1': ... }`), which is
382
+ * misleading and inconsistent with how multi-arg calls are handled. Instead,
383
+ * arrays fall through to the indexed `arg0` path.
384
+ * @not-instrumented
385
+ */
386
+ const extractParams = (args) => {
387
+ if (args.length === 0) return {};
388
+ if (args.length === 1 && typeof args[0] === "object" && args[0] !== null && !Array.isArray(args[0])) return args[0];
389
+ const result = {};
390
+ for (let i = 0; i < args.length; i++) result[`arg${i}`] = args[i];
391
+ return result;
392
+ };
393
+
394
+ //#endregion
395
+ //#region src/services/instrumentation/instrumentFunction/scrubResolvedValue/scrubResolvedValue.ts
396
+ /**
397
+ * Scrubs a resolved return value of any type before logging it.
398
+ * Routes through `scrubParameters` by wrapping the value so that strings,
399
+ * arrays, Dates, Errors, and all other types are handled identically to
400
+ * nested object fields.
401
+ * @not-instrumented
402
+ */
403
+ const scrubResolvedValue = ({ piiFields, redactAll, value }) => scrubParameters({
404
+ piiFields,
405
+ redactAll,
406
+ value: { result: value }
407
+ }).result;
408
+
409
+ //#endregion
410
+ //#region src/services/instrumentation/instrumentFunction/instrumentFunction.ts
411
+ const serializeError = (error) => {
412
+ if (error instanceof Error) return {
413
+ message: error.message,
414
+ name: error.name,
415
+ stack: error.stack
416
+ };
417
+ return {
418
+ message: String(error),
419
+ name: "UnknownError"
420
+ };
421
+ };
422
+ /**
423
+ * Wraps a function so that each invocation emits a structured
424
+ * `FunctionInstrumentationEvent` at three lifecycle points:
425
+ *
426
+ * - **started** — immediately before the function body executes, with the
427
+ * PII-scrubbed call parameters.
428
+ * - **resolved** — after the function (or its returned Promise) settles
429
+ * successfully, with the PII-scrubbed return value.
430
+ * - **rejected** — if the function throws synchronously or its returned
431
+ * Promise rejects.
432
+ *
433
+ * The original return value (or thrown error) is always forwarded to the
434
+ * caller unchanged — instrumentation is purely observational.
435
+ *
436
+ * ## Usage
437
+ *
438
+ * ```ts
439
+ * const transfer = instrumentFunction({
440
+ * fn: rawTransfer,
441
+ * functionName: 'transfer',
442
+ * getCore: () => core,
443
+ * });
444
+ *
445
+ * // When called, three events are emitted automatically:
446
+ * await transfer({ amount: 1, to: '0xabc' });
447
+ * ```
448
+ *
449
+ * ## How functions are wrapped
450
+ *
451
+ * `instrumentFunction` is not called manually in application code. Instead,
452
+ * the esbuild instrumentation plugin (`tools/instrumentation-plugin`) injects
453
+ * it at build time: any exported function annotated with `@instrumented` in its
454
+ * JSDoc is automatically wrapped by the plugin during the build step.
455
+ * The plugin strips the original `export`, renames the function, and re-exports
456
+ * it under the original name via `instrumentFunction(...)` — so the public API
457
+ * is unchanged and no call sites need to be updated.
458
+ *
459
+ * ## Opting out
460
+ *
461
+ * Instrumentation is skipped entirely when:
462
+ * - `getCore()` returns `undefined` (SDK not initialised), or
463
+ * - `core.instrumentation.config.enabled` is `false`.
464
+ *
465
+ * In both cases the original function is called directly with no overhead.
466
+ *
467
+ * ## PII scrubbing
468
+ *
469
+ * All string values whose key appears in `piiFields` are replaced with
470
+ * `"[redacted]"` before events are emitted. Pass `redactAll: true` to redact
471
+ * every field, regardless of key name.
472
+ * @not-instrumented
473
+ */
474
+ const instrumentFunction = ({ fn, functionName, getCore: getCore$1, redactAll }) => {
475
+ const wrapped = (...args) => {
476
+ const core = getCore$1();
477
+ if (!core) return fn(...args);
478
+ if (!core.instrumentation.config.enabled) return fn(...args);
479
+ const instrumentation = core.instrumentation;
480
+ const state = core.state.get();
481
+ const baseEvent = {
482
+ environmentId: core.environmentId,
483
+ functionName,
484
+ parameters: scrubParameters({
485
+ piiFields: instrumentation.config.piiFields,
486
+ redactAll,
487
+ value: extractParams(args)
488
+ }),
489
+ sdkSessionId: core.sdkSessionId,
490
+ sdkVersion: core.version,
491
+ status: "info",
492
+ tokenSessionId: state.token ? extractSessionId(state.token) : null,
493
+ userAgent: getUserAgent(),
494
+ userId: state.user?.id ?? null
495
+ };
496
+ instrumentation.logFunction({
497
+ ...baseEvent,
498
+ phase: "started",
499
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
500
+ });
501
+ try {
502
+ const result = fn(...args);
503
+ if (result instanceof Promise) return result.then((value) => {
504
+ instrumentation.logFunction({
505
+ ...baseEvent,
506
+ phase: "resolved",
507
+ resolvedValue: scrubResolvedValue({
508
+ piiFields: instrumentation.config.piiFields,
509
+ redactAll,
510
+ value
511
+ }),
512
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
513
+ });
514
+ return value;
515
+ }).catch((error) => {
516
+ instrumentation.logFunction({
517
+ ...baseEvent,
518
+ phase: "rejected",
519
+ rejectedError: serializeError(error),
520
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
521
+ });
522
+ throw error;
523
+ });
524
+ instrumentation.logFunction({
525
+ ...baseEvent,
526
+ phase: "resolved",
527
+ resolvedValue: scrubResolvedValue({
528
+ piiFields: instrumentation.config.piiFields,
529
+ redactAll,
530
+ value: result
531
+ }),
532
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
533
+ });
534
+ return result;
535
+ } catch (error) {
536
+ instrumentation.logFunction({
537
+ ...baseEvent,
538
+ phase: "rejected",
539
+ rejectedError: serializeError(error),
540
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
541
+ });
542
+ throw error;
543
+ }
544
+ };
545
+ return wrapped;
546
+ };
547
+
548
+ //#endregion
549
+ //#region src/modules/sessionKeys/getSessionKeys/getSessionKeys.ts
550
+ /** @instrumented */
551
+ const getSessionKeys = (client) => {
552
+ const publicKey = getCore(client).state.get().sessionKeys;
553
+ if (!publicKey) return;
554
+ return { publicKey };
555
+ };
556
+ const __getSessionKeys_impl = getSessionKeys;
557
+ const __getSessionKeys_wrapped = instrumentFunction({
558
+ fn: __getSessionKeys_impl,
559
+ functionName: "getSessionKeys",
560
+ getCore: () => {
561
+ try {
562
+ return getCore(getDefaultClient());
563
+ } catch {
564
+ return;
565
+ }
566
+ }
567
+ });
568
+
569
+ //#endregion
570
+ //#region src/modules/auth/getElevatedAccessToken/getElevatedAccessToken.ts
571
+ /**
572
+ * Gets an elevated access token by scope.
573
+ *
574
+ * This function retrieves an elevated access token that contains the specified scope.
575
+ * Expired tokens are automatically filtered out.
576
+ *
577
+ * By default, if the token has `singleUse: true`, it will be automatically
578
+ * consumed (removed from state) after retrieval. Pass `consume: false` to
579
+ * check for token existence without consuming it.
580
+ *
581
+ * @param params - The parameters object.
582
+ * @param params.scope - The scope to match (e.g., 'wallet:export').
583
+ * @param params.consume - Whether to consume single-use tokens (default: true).
584
+ * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
585
+ * @returns The elevated access token if found and not expired, or undefined if not found or expired.
586
+ *
587
+ * @example
588
+ * ```typescript
589
+ * // Retrieve and consume (default)
590
+ * const token = getElevatedAccessToken({ scope: 'wallet:export' });
591
+ *
592
+ * // Check existence without consuming
593
+ * const token = getElevatedAccessToken({ scope: 'credential:unlink', consume: false });
594
+ * ```
595
+ * @not-instrumented
596
+ */
597
+ const getElevatedAccessToken = ({ consume = true, scope }, client = getDefaultClient()) => {
598
+ const core = getCore(client);
599
+ const now = /* @__PURE__ */ new Date();
600
+ const elevatedAccessTokens = core.state.get().elevatedAccessTokens || [];
601
+ const validTokens = elevatedAccessTokens.filter((token$1) => !token$1.expiresAt || token$1.expiresAt > now);
602
+ if (validTokens.length !== elevatedAccessTokens.length) core.state.set({ elevatedAccessTokens: validTokens });
603
+ const token = validTokens.find((token$1) => token$1.scopes.includes(scope));
604
+ if (!token) return;
605
+ if (consume && token.singleUse) {
606
+ const updatedTokens = validTokens.filter((t) => t !== token);
607
+ core.state.set({ elevatedAccessTokens: updatedTokens });
608
+ }
609
+ return token.token;
610
+ };
611
+ const __getElevatedAccessToken_impl = getElevatedAccessToken;
612
+ const __getElevatedAccessToken_wrapped = instrumentFunction({
613
+ fn: __getElevatedAccessToken_impl,
614
+ functionName: "getElevatedAccessToken",
615
+ getCore: () => {
616
+ try {
617
+ return getCore(getDefaultClient());
618
+ } catch {
619
+ return;
620
+ }
621
+ }
622
+ });
623
+
624
+ //#endregion
625
+ //#region src/errors/APIError/APIError.ts
626
+ var APIError = class APIError extends BaseError {
627
+ status;
628
+ constructor(message, code, status) {
629
+ super({
630
+ cause: null,
631
+ code,
632
+ docsUrl: null,
633
+ name: "APIError",
634
+ shortMessage: message
635
+ });
636
+ this.status = status;
637
+ }
638
+ static async fromResponse(response) {
639
+ try {
640
+ const errorBody = await response.clone().json();
641
+ if (errorBody && "error" in errorBody && typeof errorBody.error === "string") {
642
+ const errorCode = "code" in errorBody && typeof errorBody.code === "string" ? errorBody.code : "unknown_error";
643
+ return new APIError(errorBody.error, errorCode, response.status);
644
+ }
645
+ return null;
646
+ } catch {
647
+ return null;
648
+ }
649
+ }
650
+ };
651
+
652
+ //#endregion
653
+ //#region src/errors/InvalidExternalAuthError.ts
654
+ var InvalidExternalAuthError = class extends BaseError {
655
+ constructor({ cause }) {
656
+ super({
657
+ cause,
658
+ code: "invalid_external_auth_error",
659
+ docsUrl: "https://www.dynamic.xyz/docs/external-auth/third-party-auth-overview",
660
+ name: "InvalidExternalAuthError",
661
+ shortMessage: "Error authenticating with external JWT"
662
+ });
663
+ }
664
+ };
665
+
666
+ //#endregion
667
+ //#region src/errors/LinkCredentialError.ts
668
+ var LinkCredentialError = class extends BaseError {
669
+ constructor({ cause }) {
670
+ super({
671
+ cause,
672
+ code: "link_credential_error",
673
+ docsUrl: null,
674
+ name: "LinkCredentialError",
675
+ shortMessage: "The credential you are trying to link is associated with another account and cannot be reassigned."
676
+ });
677
+ }
678
+ };
679
+
680
+ //#endregion
681
+ //#region src/errors/MfaInvalidOtpError.ts
682
+ var MfaInvalidOtpError = class extends BaseError {
683
+ constructor({ cause }) {
684
+ super({
685
+ cause,
686
+ code: "mfa_invalid_otp_error",
687
+ docsUrl: null,
688
+ name: "MfaInvalidOtpError",
689
+ shortMessage: "Invalid OTP"
690
+ });
691
+ }
692
+ };
693
+
694
+ //#endregion
695
+ //#region src/errors/MfaRateLimitedError.ts
696
+ var MfaRateLimitedError = class extends BaseError {
697
+ constructor({ cause }) {
698
+ super({
699
+ cause,
700
+ code: "mfa_rate_limited_error",
701
+ docsUrl: null,
702
+ name: "MfaRateLimitedError",
703
+ shortMessage: "Rate limited"
704
+ });
705
+ }
706
+ };
707
+
708
+ //#endregion
709
+ //#region src/errors/SandboxMaximumThresholdReachedError.ts
710
+ var SandboxMaximumThresholdReachedError = class extends BaseError {
711
+ constructor({ cause }) {
712
+ super({
713
+ cause,
714
+ code: "sandbox_maximum_threshold_reached_error",
715
+ docsUrl: "https://www.dynamic.xyz/docs/developer-dashboard/sandbox-vs-live#sandbox-vs-live",
716
+ name: "SandboxMaximumThresholdReachedError",
717
+ shortMessage: "Your sandbox environment has reached the maximum MAU. Please use a live environment for production traffic."
718
+ });
719
+ }
720
+ };
721
+
722
+ //#endregion
723
+ //#region src/modules/apiClient/utils/clientErrorMapper/clientErrorMapper.ts
724
+ /**
725
+ * Default error mapper for the client that handles common API error codes.
726
+ *
727
+ * This mapper transforms specific API error codes into more specific error types:
728
+ * - `mfa_invalid_code` → `MfaInvalidOtpError`
729
+ * - `mfa_rate_limited` → `MfaRateLimitedError`
730
+ *
731
+ * @param error - The error to be mapped
732
+ * @returns A transformed error if the error code matches a known pattern, or null if no transformation is needed
733
+ *
734
+ * @example
735
+ * ```typescript
736
+ * // This will be automatically applied to all API errors
737
+ * const apiClient = createApiClient({}, client);
738
+ *
739
+ * // The clientErrorMapper will automatically convert mfa_invalid_code errors
740
+ * // to MfaInvalidOtpError instances
741
+ * ```
742
+ * @not-instrumented
743
+ */
744
+ const clientErrorMapper = (error) => {
745
+ if (error instanceof APIError) {
746
+ if (error.code === "mfa_invalid_code") return new MfaInvalidOtpError({ cause: error });
747
+ if (error.code === "mfa_rate_limited") return new MfaRateLimitedError({ cause: error });
748
+ if (error.code === "invalid_external_auth") return new InvalidExternalAuthError({ cause: error });
749
+ if (error.code === "sandbox_maximum_threshold_reached") return new SandboxMaximumThresholdReachedError({ cause: error });
750
+ if (error.code === "merge_accounts_invalid" || error.code === "reassign_wallet_error") return new LinkCredentialError({ cause: error });
751
+ }
752
+ return null;
753
+ };
754
+
755
+ //#endregion
756
+ //#region src/modules/apiClient/utils/convertToApiErrorMiddleware/convertToApiErrorMiddleware.ts
757
+ /**
758
+ * Creates middleware that converts HTTP error responses to APIError instances
759
+ * and optionally applies custom error mappers to transform them into specific error types.
760
+ *
761
+ * @param options.errorMappers - Array of error mappers to apply to API errors
762
+ * @returns A middleware function that handles error conversion and mapping
763
+ * @not-instrumented
764
+ */
765
+ const createConvertToApiErrorMiddleware = ({ errorMappers = [] }) => ({ post: async (context) => {
766
+ if (context.response.status >= 400) {
767
+ const apiError = await APIError.fromResponse(context.response);
768
+ if (apiError) {
769
+ let errorToThrow = apiError;
770
+ for (const mapper of errorMappers) {
771
+ const newError = mapper(apiError);
772
+ if (newError) {
773
+ errorToThrow = newError;
774
+ break;
775
+ }
776
+ }
777
+ throw errorToThrow;
778
+ }
779
+ }
780
+ return context.response;
781
+ } });
782
+
783
+ //#endregion
784
+ //#region src/utils/getNonce/getNonce.ts
785
+ /**
786
+ * Returns a nonce for wallet ownership verification.
787
+ *
788
+ * Pops the first nonce from the prefetched pool. When the pool is running low
789
+ * (≤1 remaining after pop) a background refetch is triggered. If the pool is
790
+ * empty, nonces are fetched on-demand before returning.
791
+ * @instrumented
792
+ */
793
+ const getNonce = async (client) => {
794
+ const core = getCore(client);
795
+ const pool = core.state.get().prefetchedNonces;
796
+ if (pool.length > 0) {
797
+ const [nonce, ...remaining] = pool;
798
+ core.state.set({ prefetchedNonces: remaining });
799
+ if (remaining.length <= 1) fetchAndStoreNonces(client);
800
+ return nonce;
801
+ }
802
+ await fetchAndStoreNonces(client);
803
+ return getNonce(client);
804
+ };
805
+ const __getNonce_impl = getNonce;
806
+ const __getNonce_wrapped = instrumentFunction({
807
+ fn: __getNonce_impl,
808
+ functionName: "getNonce",
809
+ getCore: () => {
810
+ try {
811
+ return getCore(getDefaultClient());
812
+ } catch {
813
+ return;
814
+ }
815
+ }
816
+ });
817
+
818
+ //#endregion
819
+ //#region src/modules/deviceRegistration/getDeviceSigner/getDeviceSigner.ts
820
+ /** @instrumented */
821
+ const getDeviceSigner = async (client) => {
822
+ const { deviceSigner, keychain } = getCore(client);
823
+ /**
824
+ * If the device signer is available, it should handle the device signing.
825
+ * This is used for mobile devices with secure enclave.
826
+ */
827
+ if (deviceSigner) return deviceSigner;
828
+ const keyName = "device";
829
+ if (!await keychain.getPublicKey(keyName)) await keychain.generateKey(keyName);
830
+ return {
831
+ getPublicKey: () => keychain.getPublicKey(keyName),
832
+ sign: (payload) => keychain.sign(keyName, payload)
833
+ };
834
+ };
835
+ const __getDeviceSigner_impl = getDeviceSigner;
836
+ const __getDeviceSigner_wrapped = instrumentFunction({
837
+ fn: __getDeviceSigner_impl,
838
+ functionName: "getDeviceSigner",
839
+ getCore: () => {
840
+ try {
841
+ return getCore(getDefaultClient());
842
+ } catch {
843
+ return;
844
+ }
845
+ }
846
+ });
847
+
848
+ //#endregion
849
+ //#region src/modules/deviceRegistration/getHeadersForNonceSignedByDeviceSigners/getHeadersForNonceSignedByDeviceSigners.ts
850
+ /** @instrumented */
851
+ const getHeadersForNonceSignedByDeviceSigners = async (client) => {
852
+ const { projectSettings } = client;
853
+ assertDefined(projectSettings, "Project settings not found");
854
+ /**
855
+ * For cookie based environments, the device registration is handled
856
+ * by settings the cookie in the browser.
857
+ * Then we dont need to provide the headers
858
+ */
859
+ if (isCookieEnabled(client)) return {};
860
+ const deviceSigner = await __getDeviceSigner_wrapped(client);
861
+ const nonce = await __getNonce_wrapped(client);
862
+ const signedNonce = await deviceSigner.sign(nonce);
863
+ const publicKey = await deviceSigner.getPublicKey();
864
+ return {
865
+ "x-dynamic-device-nonce": nonce,
866
+ "x-dynamic-device-publickey": publicKey,
867
+ "x-dynamic-device-signed-nonce": signedNonce
868
+ };
869
+ };
870
+ const __getHeadersForNonceSignedByDeviceSigners_impl = getHeadersForNonceSignedByDeviceSigners;
871
+ const __getHeadersForNonceSignedByDeviceSigners_wrapped = instrumentFunction({
872
+ fn: __getHeadersForNonceSignedByDeviceSigners_impl,
873
+ functionName: "getHeadersForNonceSignedByDeviceSigners",
874
+ getCore: () => {
875
+ try {
876
+ return getCore(getDefaultClient());
877
+ } catch {
878
+ return;
879
+ }
880
+ }
881
+ });
882
+
883
+ //#endregion
884
+ //#region src/modules/apiClient/utils/deviceSignatureHeadersMiddleware/createDeviceSignatureHeadersMiddleware.ts
885
+ /** @instrumented */
886
+ const createDeviceSignatureHeadersMiddleware = (client) => {
887
+ return { pre: async (context) => {
888
+ /**
889
+ * The signed nonce is not required for cookie based environments.
890
+ */
891
+ if (isDeviceNonceSignatureRequiredForUrl(context.url) && !isCookieEnabled(client)) {
892
+ const deviceSignerHeaders = await __getHeadersForNonceSignedByDeviceSigners_wrapped(client);
893
+ return {
894
+ init: {
895
+ ...context.init,
896
+ headers: {
897
+ ...context.init.headers,
898
+ ...deviceSignerHeaders
899
+ }
900
+ },
901
+ url: context.url
902
+ };
903
+ }
904
+ } };
905
+ };
906
+ const __createDeviceSignatureHeadersMiddleware_impl = createDeviceSignatureHeadersMiddleware;
907
+ const __createDeviceSignatureHeadersMiddleware_wrapped = instrumentFunction({
908
+ fn: __createDeviceSignatureHeadersMiddleware_impl,
909
+ functionName: "createDeviceSignatureHeadersMiddleware",
910
+ getCore: () => {
911
+ try {
912
+ return getCore(getDefaultClient());
913
+ } catch {
914
+ return;
915
+ }
916
+ }
917
+ });
918
+
919
+ //#endregion
920
+ //#region src/errors/UnauthorizedError.ts
921
+ var UnauthorizedError = class extends BaseError {
922
+ constructor({ cause }) {
923
+ super({
924
+ cause,
925
+ code: "unauthorized_error",
926
+ docsUrl: null,
927
+ name: "UnauthorizedError",
928
+ shortMessage: "Unauthorized"
929
+ });
930
+ }
931
+ };
932
+
933
+ //#endregion
934
+ //#region src/modules/apiClient/utils/unauthorizedMiddleware/createUnauthorizedMiddleware.ts
935
+ /** @not-instrumented */
936
+ const createUnauthorizedMiddleware = () => ({ post: async (context) => {
937
+ if (context.response.status === 401) {
938
+ let cause = null;
939
+ try {
940
+ const errorBody = await context.response.clone().json();
941
+ if (errorBody && "error" in errorBody && typeof errorBody.error === "string") cause = new Error(errorBody.error);
942
+ } catch {}
943
+ throw new UnauthorizedError({ cause });
944
+ }
945
+ return context.response;
946
+ } });
947
+
948
+ //#endregion
949
+ //#region src/modules/apiClient/createApiClient.ts
950
+ /**
951
+ * Returns a new instance of the SDK API client.
952
+ *
953
+ * This is not meant for storing, as it is very light we can create it whenever needed.
954
+ * @instrumented
955
+ */
956
+ const createApiClient = (options = {}, client) => {
957
+ const core = getCore(client);
958
+ const coreState = core.state.get();
959
+ const settings = {
960
+ basePath: core.apiBaseUrl,
961
+ headers: {
962
+ "Content-Type": "application/json",
963
+ [DYNAMIC_API_VERSION_HEADER]: `API/${DYNAMIC_SDK_API_VERSION}`,
964
+ [DYNAMIC_REQUEST_ID_HEADER]: randomString({ length: 50 }),
965
+ [DYNAMIC_SDK_SESSION_ID_HEADER]: core.sdkSessionId,
966
+ [DYNAMIC_SDK_VERSION_HEADER]: `${CLIENT_SDK_NAME}/${version}`,
967
+ ...core.getApiHeaders(),
968
+ ...options.headers
969
+ }
970
+ };
971
+ if (client.token) settings.headers.Authorization = `Bearer ${client.token}`;
972
+ if (client.projectSettings && isCookieEnabled(client)) settings.credentials = "include";
973
+ if (options.includeMfaToken && coreState.mfaToken) settings.headers[MFA_TOKEN_HEADER] = coreState.mfaToken;
974
+ if (options.elevatedAccessTokenScope) {
975
+ const elevatedToken = __getElevatedAccessToken_wrapped({ scope: options.elevatedAccessTokenScope }, client);
976
+ if (elevatedToken) settings.headers[ELEVATED_ACCESS_TOKEN_HEADER] = elevatedToken;
977
+ }
978
+ const sessionPublicKey = __getSessionKeys_wrapped(client)?.publicKey;
979
+ const isSessionPublicKeyHeaderPresent = settings.headers[SESSION_PUBLIC_KEY_HEADER] !== void 0;
980
+ if (sessionPublicKey && !isSessionPublicKeyHeaderPresent) settings.headers[SESSION_PUBLIC_KEY_HEADER] = sessionPublicKey;
981
+ return new SDKApi(new Configuration({
982
+ ...settings,
983
+ fetchApi: core.fetch,
984
+ middleware: [
985
+ __createDeviceSignatureHeadersMiddleware_wrapped(client),
986
+ createConvertToApiErrorMiddleware({ errorMappers: [...options.errorMappers || [], clientErrorMapper] }),
987
+ createUnauthorizedMiddleware()
988
+ ]
989
+ }));
990
+ };
991
+ const __createApiClient_impl = createApiClient;
992
+ const __createApiClient_wrapped = instrumentFunction({
993
+ fn: __createApiClient_impl,
994
+ functionName: "createApiClient",
995
+ getCore: () => {
996
+ try {
997
+ return getCore(getDefaultClient());
998
+ } catch {
999
+ return;
1000
+ }
1001
+ }
1002
+ });
1003
+
1004
+ //#endregion
1005
+ //#region src/utils/getNonce/fetchAndStoreNonces/fetchAndStoreNonces.ts
1006
+ /**
1007
+ * Fetches a batch of nonces from the API.
1008
+ *
1009
+ * Prefetching is critical for iOS deep link wallet providers (e.g. Phantom
1010
+ * redirect). On iOS, a network request (like fetching a nonce) between a user
1011
+ * action and a deeplink call will break the gesture chain, causing iOS to
1012
+ * silently ignore the deeplink. By prefetching nonces ahead of time,
1013
+ * `getNonce` can return synchronously from cache and the deeplink fires
1014
+ * without an interrupting network round-trip.
1015
+ *
1016
+ * New nonces are **appended** to the existing pool so that unconsumed entries
1017
+ * are not discarded by a background refetch.
1018
+ * @not-instrumented
1019
+ */
1020
+ const fetchAndStoreNonces = async (client) => {
1021
+ const core = getCore(client);
1022
+ const { environmentId } = core;
1023
+ const { nonces } = await __createApiClient_wrapped({}, client).getNonces({
1024
+ count: NONCE_POOL_SIZE,
1025
+ environmentId
1026
+ });
1027
+ const existing = core.state.get().prefetchedNonces;
1028
+ core.state.set({
1029
+ prefetchedNonces: [...existing, ...nonces],
1030
+ prefetchedNoncesExpiration: Date.now() + NONCE_POOL_EXPIRATION_TIME
1031
+ });
1032
+ };
1033
+
1034
+ //#endregion
1035
+ //#region src/modules/wallets/constants.ts
1036
+ const CHAINS_INFO_MAP = {
1037
+ ALEO: {
1038
+ apiChainName: "aleo",
1039
+ blockchainName: "Aleo",
1040
+ verifiedCredentialChainName: "aleo"
1041
+ },
1042
+ ALGO: {
1043
+ apiChainName: "algo",
1044
+ blockchainName: "Algorand",
1045
+ verifiedCredentialChainName: "algorand"
1046
+ },
1047
+ APTOS: {
1048
+ apiChainName: "aptos",
1049
+ blockchainName: "Aptos",
1050
+ verifiedCredentialChainName: "aptos"
1051
+ },
1052
+ BTC: {
1053
+ apiChainName: "bitcoin",
1054
+ blockchainName: "Bitcoin",
1055
+ verifiedCredentialChainName: "bip122"
1056
+ },
1057
+ COSMOS: {
1058
+ apiChainName: "cosmos",
1059
+ blockchainName: "Cosmos",
1060
+ verifiedCredentialChainName: "cosmos"
1061
+ },
1062
+ ECLIPSE: {
1063
+ apiChainName: "eclipse",
1064
+ blockchainName: "Eclipse",
1065
+ verifiedCredentialChainName: "eclipse"
1066
+ },
1067
+ EVM: {
1068
+ apiChainName: "evm",
1069
+ blockchainName: "Ethereum",
1070
+ verifiedCredentialChainName: "eip155"
1071
+ },
1072
+ FLOW: {
1073
+ apiChainName: "flow",
1074
+ blockchainName: "Flow",
1075
+ verifiedCredentialChainName: "flow"
1076
+ },
1077
+ MIDNIGHT: {
1078
+ apiChainName: "midnight",
1079
+ blockchainName: "Midnight",
1080
+ verifiedCredentialChainName: "midnight"
1081
+ },
1082
+ SOL: {
1083
+ apiChainName: "solana",
1084
+ blockchainName: "Solana",
1085
+ verifiedCredentialChainName: "solana",
1086
+ waasChainNameOverride: "SVM"
1087
+ },
1088
+ SPARK: {
1089
+ apiChainName: "spark",
1090
+ blockchainName: "Spark",
1091
+ verifiedCredentialChainName: "spark"
1092
+ },
1093
+ STARK: {
1094
+ apiChainName: "starknet",
1095
+ blockchainName: "Starknet",
1096
+ verifiedCredentialChainName: "starknet"
1097
+ },
1098
+ STELLAR: {
1099
+ apiChainName: "stellar",
1100
+ blockchainName: "Stellar",
1101
+ verifiedCredentialChainName: "stellar"
1102
+ },
1103
+ SUI: {
1104
+ apiChainName: "sui",
1105
+ blockchainName: "Sui",
1106
+ verifiedCredentialChainName: "sui"
1107
+ },
1108
+ TEMPO: {
1109
+ apiChainName: "tempo",
1110
+ blockchainName: "Tempo",
1111
+ verifiedCredentialChainName: "tempo"
1112
+ },
1113
+ TON: {
1114
+ apiChainName: "ton",
1115
+ blockchainName: "TON",
1116
+ verifiedCredentialChainName: "ton"
1117
+ },
1118
+ TRON: {
1119
+ apiChainName: "tron",
1120
+ blockchainName: "Tron",
1121
+ verifiedCredentialChainName: "tron"
1122
+ }
1123
+ };
1124
+
1125
+ //#endregion
1126
+ //#region src/utils/getChainFromVerifiedCredentialChain/getChainFromVerifiedCredentialChain.ts
1127
+ /** @instrumented */
1128
+ const getChainFromVerifiedCredentialChain = (verifiedCredentialChain) => {
1129
+ const chain = Object.keys(CHAINS_INFO_MAP).find((chain$1) => CHAINS_INFO_MAP[chain$1].verifiedCredentialChainName === verifiedCredentialChain);
1130
+ assertDefined(chain, `Unknown chain: ${verifiedCredentialChain}`);
1131
+ return chain;
1132
+ };
1133
+ const __getChainFromVerifiedCredentialChain_impl = getChainFromVerifiedCredentialChain;
1134
+ const __getChainFromVerifiedCredentialChain_wrapped = instrumentFunction({
1135
+ fn: __getChainFromVerifiedCredentialChain_impl,
1136
+ functionName: "getChainFromVerifiedCredentialChain",
1137
+ getCore: () => {
1138
+ try {
1139
+ return getCore(getDefaultClient());
1140
+ } catch {
1141
+ return;
1142
+ }
1143
+ }
1144
+ });
1145
+
1146
+ //#endregion
1147
+ //#region src/constants.ts
1148
+ const SDK_API_CORE_VERSION = dependencies["@dynamic-labs/sdk-api-core"];
1149
+ const DYNAMIC_ICONIC_SPRITE_URL = "https://iconic.dynamic-static-assets.com/icons/sprite.svg";
1150
+
1151
+ //#endregion
1152
+ //#region src/modules/waas/constants.ts
1153
+ const DEFAULT_WAAS_BASE_API_URL = "https://app.dynamicauth.com";
1154
+ const DEFAULT_WAAS_BASE_MPC_RELAY_API_URL = "https://relay.dynamicauth.com";
1155
+ const DYNAMIC_WAAS_METADATA = {
1156
+ displayName: "Dynamic WaaS",
1157
+ icon: `${DYNAMIC_ICONIC_SPRITE_URL}#dynamicwaas`,
1158
+ normalizedWalletName: "dynamicwaas"
1159
+ };
1160
+
1161
+ //#endregion
1162
+ //#region src/errors/InvalidParamError.ts
1163
+ var InvalidParamError = class extends BaseError {
1164
+ constructor(message) {
1165
+ super({
1166
+ cause: null,
1167
+ code: "invalid_param_error",
1168
+ docsUrl: null,
1169
+ name: "InvalidParamError",
1170
+ shortMessage: message
1171
+ });
1172
+ }
1173
+ };
1174
+
1175
+ //#endregion
1176
+ export { ValueMustBeDefinedError as A, name as B, __getSessionKeys_wrapped as C, extractSessionId as D, getUserAgent as E, getDefaultClient as F, setDefaultClient as I, ClientNotFoundError as L, CLIENT_SDK_NAME as M, DYNAMIC_SDK_API_VERSION as N, isCookieEnabled as O, NONCE_POOL_SIZE as P, BaseError as R, __getElevatedAccessToken_wrapped as S, DEFAULT_PII_FIELDS as T, version as V, MfaRateLimitedError as _, DYNAMIC_ICONIC_SPRITE_URL as a, InvalidExternalAuthError as b, CHAINS_INFO_MAP as c, UnauthorizedError as d, __createDeviceSignatureHeadersMiddleware_wrapped as f, SandboxMaximumThresholdReachedError as g, __getNonce_wrapped as h, DYNAMIC_WAAS_METADATA as i, randomString as j, assertDefined as k, fetchAndStoreNonces as l, __getDeviceSigner_wrapped as m, DEFAULT_WAAS_BASE_API_URL as n, SDK_API_CORE_VERSION as o, __getHeadersForNonceSignedByDeviceSigners_wrapped as p, DEFAULT_WAAS_BASE_MPC_RELAY_API_URL as r, __getChainFromVerifiedCredentialChain_wrapped as s, InvalidParamError as t, __createApiClient_wrapped as u, MfaInvalidOtpError as v, instrumentFunction as w, APIError as x, LinkCredentialError as y, getCore as z };
1177
+ //# sourceMappingURL=InvalidParamError-B5NwKSKU.native.esm.js.map