@portal-hq/utils 4.8.0 → 5.0.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.
@@ -0,0 +1,260 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var _a;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.staticApiKeyOf = exports.failFromMpcError = exports.reportUnauthorized = exports.onCredentialsInvalidated = exports.invalidateCredentials = exports.resolveCredentialToken = exports.resolveCredentials = exports.StaticCredentials = void 0;
14
+ const errors_1 = require("../errors");
15
+ const logger_1 = require("../logger");
16
+ /**
17
+ * Cross-copy brand. The key and the branded shape (a string `value`) are a
18
+ * compatibility contract across versions — see `PortalCredentialError`.
19
+ */
20
+ const BRAND = Symbol.for('@portal-hq/utils/StaticCredentials');
21
+ class StaticCredentials {
22
+ constructor(apiKey) {
23
+ /** @internal Cross-copy brand. Read it through {@link StaticCredentials.is}. */
24
+ this[_a] = true;
25
+ this.value = apiKey;
26
+ }
27
+ /**
28
+ * Brand check, not `instanceof` — an instance from another copy of this
29
+ * package must still match. Reports the brand only: callers reading a member
30
+ * must re-check it, as {@link staticApiKeyOf} does.
31
+ */
32
+ static is(credentials) {
33
+ return (typeof credentials === 'object' &&
34
+ credentials !== null &&
35
+ credentials[BRAND] === true);
36
+ }
37
+ getToken() {
38
+ return Promise.resolve(this.value);
39
+ }
40
+ /** No-op: a Client API Key is custodian-owned and holds no local state to drop. */
41
+ invalidate() {
42
+ return Promise.resolve();
43
+ }
44
+ }
45
+ exports.StaticCredentials = StaticCredentials;
46
+ _a = BRAND;
47
+ /**
48
+ * Resolves the single credential source a component was constructed with.
49
+ *
50
+ * Throws `InvalidApiKeyError` when neither source is given — callers depend on
51
+ * that type.
52
+ */
53
+ function resolveCredentials({ apiKey, credentials, }) {
54
+ if (credentials && apiKey) {
55
+ throw new Error('[Portal] Provide either `apiKey` or `credentials`, not both.');
56
+ }
57
+ if (credentials) {
58
+ return credentials;
59
+ }
60
+ if (!apiKey) {
61
+ throw new errors_1.InvalidApiKeyError();
62
+ }
63
+ return new StaticCredentials(apiKey);
64
+ }
65
+ exports.resolveCredentials = resolveCredentials;
66
+ /**
67
+ * The SDK's credential boundary: normalizes every failure to
68
+ * `PortalCredentialError`, since a host-supplied `PortalCredentials` can throw
69
+ * anything. A `PortalCredentialError` from the provider passes through
70
+ * untouched so its `reason` is never downgraded.
71
+ */
72
+ function resolveCredentialToken(credentials) {
73
+ return __awaiter(this, void 0, void 0, function* () {
74
+ let token;
75
+ try {
76
+ token = yield credentials.getToken();
77
+ }
78
+ catch (error) {
79
+ if (errors_1.PortalCredentialError.is(error)) {
80
+ throw error;
81
+ }
82
+ throw new errors_1.PortalCredentialError({
83
+ reason: errors_1.PortalCredentialErrorReason.ProviderFailure,
84
+ cause: error,
85
+ });
86
+ }
87
+ if (!token) {
88
+ throw new errors_1.PortalCredentialError({
89
+ reason: errors_1.PortalCredentialErrorReason.Unavailable,
90
+ });
91
+ }
92
+ return token;
93
+ });
94
+ }
95
+ exports.resolveCredentialToken = resolveCredentialToken;
96
+ /**
97
+ * Keyed by the credential, not by subsystem, so several requesters 401-ing at
98
+ * once — all of which arrive here through `reportUnauthorized` — share one
99
+ * invalidation instead of each issuing a keychain delete.
100
+ */
101
+ const invalidations = new WeakMap();
102
+ function invalidateCredentials(credentials) {
103
+ const inFlight = invalidations.get(credentials);
104
+ if (inFlight) {
105
+ return inFlight;
106
+ }
107
+ // A host-supplied `invalidate()` may throw synchronously or return something
108
+ // that is not a native Promise. Starting from `Promise.resolve()` turns both
109
+ // into a rejection here rather than a throw that escapes before the guard
110
+ // below is registered, which would silently disable deduplication.
111
+ const invalidation = Promise.resolve()
112
+ .then(() => credentials.invalidate())
113
+ .finally(() => {
114
+ invalidations.delete(credentials);
115
+ });
116
+ invalidations.set(credentials, invalidation);
117
+ return invalidation;
118
+ }
119
+ exports.invalidateCredentials = invalidateCredentials;
120
+ /**
121
+ * Host listeners, keyed by the credential rather than by the `Portal` holding
122
+ * it, so they are reachable from the 401 call sites — which see a credential
123
+ * and nothing else — and so a credential that is dropped takes its listeners
124
+ * with it.
125
+ *
126
+ * One entry is one subscription, never one callback: two subscribers may hand
127
+ * in the same function, and an entry keyed on the function itself would
128
+ * collapse them into one that either unsubscribe removes — silently
129
+ * deregistering a subscriber that never asked to be.
130
+ */
131
+ const invalidationListeners = new WeakMap();
132
+ /** Credentials already announced to the host, so each is reported once. */
133
+ const reported = new WeakSet();
134
+ /**
135
+ * Subscribes to the backend invalidating `credentials`. Returns an
136
+ * unsubscribe; see `Portal.onSessionInvalidated` for the host-facing contract.
137
+ *
138
+ * A credential can already have been reported before the host gets to
139
+ * subscribe — validity is discovered by making a request, so a host that
140
+ * awaits one before mounting its subscriber would otherwise never hear that
141
+ * the session is over, and nothing else exposes that state.
142
+ */
143
+ function onCredentialsInvalidated(credentials, listener) {
144
+ var _b;
145
+ const listeners = (_b = invalidationListeners.get(credentials)) !== null && _b !== void 0 ? _b : new Set();
146
+ // This subscription's identity in `listeners`, distinct from every other
147
+ // subscription of the same `listener` — see the note on that map.
148
+ const subscription = () => listener();
149
+ listeners.add(subscription);
150
+ invalidationListeners.set(credentials, listeners);
151
+ // `notifyInvalidated` will not run again for this credential, so catch this
152
+ // subscription up itself. Deferred so the caller holds its unsubscribe
153
+ // before the callback can run, and re-checked then so a subscription
154
+ // dropped straight away stays silent — which is also what keeps a React
155
+ // effect that tears down and remounts within one commit to a single call.
156
+ // A Client API Key never reaches here: it is never recorded as reported.
157
+ if (reported.has(credentials)) {
158
+ void Promise.resolve().then(() => {
159
+ if (!listeners.has(subscription)) {
160
+ return;
161
+ }
162
+ try {
163
+ subscription();
164
+ }
165
+ catch (_b) {
166
+ // As in `notifyInvalidated`: a host callback failing is not this
167
+ // module's problem to propagate.
168
+ }
169
+ });
170
+ }
171
+ return () => {
172
+ listeners.delete(subscription);
173
+ };
174
+ }
175
+ exports.onCredentialsInvalidated = onCredentialsInvalidated;
176
+ /**
177
+ * At most once per credential, and never for a Client API Key: that credential
178
+ * is custodian-owned, its `invalidate()` is a no-op, and there is no local
179
+ * session for a 401 to have ended.
180
+ */
181
+ function notifyInvalidated(credentials) {
182
+ var _b;
183
+ if (StaticCredentials.is(credentials) || reported.has(credentials)) {
184
+ return;
185
+ }
186
+ reported.add(credentials);
187
+ // Snapshot: a listener is free to unsubscribe itself, or subscribe another,
188
+ // from inside the callback.
189
+ for (const listener of Array.from((_b = invalidationListeners.get(credentials)) !== null && _b !== void 0 ? _b : [])) {
190
+ try {
191
+ listener();
192
+ }
193
+ catch (_c) {
194
+ // A host callback failing must not take the other listeners, the
195
+ // invalidation, or this bookkeeping down with it.
196
+ }
197
+ }
198
+ }
199
+ /**
200
+ * The 401 path every Portal-authenticated requester routes through: invalidate
201
+ * the credential, then tell the host its session ended.
202
+ *
203
+ * Kept separate from {@link invalidateCredentials}, which stays the plain
204
+ * operation a host-initiated sign-out uses — only a backend rejection is news
205
+ * to the host.
206
+ *
207
+ * Notifies even when the invalidation rejects: the token is dropped in memory
208
+ * first, so the session is over either way. The rejection still propagates,
209
+ * and every call site already treats it as bookkeeping that must not replace
210
+ * the original failure.
211
+ */
212
+ function reportUnauthorized(credentials) {
213
+ return __awaiter(this, void 0, void 0, function* () {
214
+ try {
215
+ yield invalidateCredentials(credentials);
216
+ }
217
+ finally {
218
+ notifyInvalidated(credentials);
219
+ }
220
+ });
221
+ }
222
+ exports.reportUnauthorized = reportUnauthorized;
223
+ /**
224
+ * The MPC equivalent of the 401 path above: the binary issues its own
225
+ * authenticated requests, so a rejected credential arrives as an `AUTH_FAILED`
226
+ * envelope rather than a status code any requester here can see.
227
+ *
228
+ * The binary's error is rethrown unchanged either way — the invalidation is
229
+ * bookkeeping, and callers keep branching on `PortalMpcError` and its `id`.
230
+ */
231
+ function failFromMpcError(credentials, error) {
232
+ return __awaiter(this, void 0, void 0, function* () {
233
+ if ((0, errors_1.isMpcAuthFailure)(error)) {
234
+ try {
235
+ yield reportUnauthorized(credentials);
236
+ }
237
+ catch (bookkeeping) {
238
+ logger_1.sdkLogger.error('[Portal] Failed to invalidate a credential the MPC binary rejected', bookkeeping);
239
+ }
240
+ }
241
+ throw new errors_1.PortalMpcError(error);
242
+ });
243
+ }
244
+ exports.failFromMpcError = failFromMpcError;
245
+ /**
246
+ * The raw Client API Key behind a credential, or `''` when it is not a static
247
+ * key — never a wrong or stale token. Temporary bridge for subsystems that
248
+ * need a synchronous `apiKey`.
249
+ */
250
+ function staticApiKeyOf(credentials) {
251
+ if (!StaticCredentials.is(credentials)) {
252
+ return '';
253
+ }
254
+ // The brand identifies the shape, it does not prove it: an instance from
255
+ // another copy of this package is only structurally compatible, so re-check
256
+ // the type.
257
+ const { value } = credentials;
258
+ return typeof value === 'string' ? value : '';
259
+ }
260
+ exports.staticApiKeyOf = staticApiKeyOf;
@@ -5,6 +5,7 @@ class HttpError extends Error {
5
5
  super(`${status} - ${statusText}: ${message}`);
6
6
  // Set the prototype explicitly.
7
7
  Object.setPrototypeOf(this, HttpError.prototype);
8
+ this.status = status;
8
9
  }
9
10
  }
10
11
  exports.default = HttpError;
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.RpcErrorCodes = exports.ProviderRpcError = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = void 0;
20
+ exports.RpcErrorCodes = exports.ProviderRpcError = exports.PortalCredentialErrorReason = exports.PortalCredentialError = exports.PortalAuthErrorReason = exports.PortalAuthError = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = void 0;
21
21
  var cloud_storage_read_error_1 = require("./cloud-storage-read-error");
22
22
  Object.defineProperty(exports, "CloudStorageReadError", { enumerable: true, get: function () { return __importDefault(cloud_storage_read_error_1).default; } });
23
23
  var http_error_1 = require("./http-error");
@@ -34,6 +34,12 @@ var mpc_signing_error_1 = require("./mpc-signing-error");
34
34
  Object.defineProperty(exports, "MpcSigningError", { enumerable: true, get: function () { return __importDefault(mpc_signing_error_1).default; } });
35
35
  var no_address_error_1 = require("./no-address-error");
36
36
  Object.defineProperty(exports, "NoAddressError", { enumerable: true, get: function () { return __importDefault(no_address_error_1).default; } });
37
+ var portal_auth_error_1 = require("./portal-auth-error");
38
+ Object.defineProperty(exports, "PortalAuthError", { enumerable: true, get: function () { return __importDefault(portal_auth_error_1).default; } });
39
+ Object.defineProperty(exports, "PortalAuthErrorReason", { enumerable: true, get: function () { return portal_auth_error_1.PortalAuthErrorReason; } });
40
+ var portal_credential_error_1 = require("./portal-credential-error");
41
+ Object.defineProperty(exports, "PortalCredentialError", { enumerable: true, get: function () { return __importDefault(portal_credential_error_1).default; } });
42
+ Object.defineProperty(exports, "PortalCredentialErrorReason", { enumerable: true, get: function () { return portal_credential_error_1.PortalCredentialErrorReason; } });
37
43
  __exportStar(require("./portal-error"), exports);
38
44
  var provider_rpc_error_1 = require("./provider-rpc-error");
39
45
  Object.defineProperty(exports, "ProviderRpcError", { enumerable: true, get: function () { return __importDefault(provider_rpc_error_1).default; } });
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.PortalAuthErrorReason = void 0;
5
+ /**
6
+ * Why a Client Auth login could not be completed.
7
+ *
8
+ * The backend answers every unusable grant with the same undifferentiated 401
9
+ * — replayed, expired, forged, wrong auth environment, and disabled or invalid
10
+ * auth method are deliberately indistinguishable — so these reasons describe
11
+ * what the SDK actually knows and the action the host should take, not what
12
+ * went wrong server-side.
13
+ */
14
+ var PortalAuthErrorReason;
15
+ (function (PortalAuthErrorReason) {
16
+ /**
17
+ * The backend refused to exchange the grant. Whatever the cause, the grant
18
+ * is spent and cannot be retried: start a new sign-in.
19
+ */
20
+ PortalAuthErrorReason["GrantRejected"] = "GRANT_REJECTED";
21
+ /**
22
+ * The authentication provider sent the user back with an error instead of a
23
+ * grant. The user never completed the provider's flow.
24
+ */
25
+ PortalAuthErrorReason["ProviderRejected"] = "PROVIDER_REJECTED";
26
+ })(PortalAuthErrorReason = exports.PortalAuthErrorReason || (exports.PortalAuthErrorReason = {}));
27
+ const authErrors = {
28
+ [PortalAuthErrorReason.GrantRejected]: 'The authentication grant was rejected. It may already have been used, expired, or been issued for a different auth environment. Start a new sign-in.',
29
+ [PortalAuthErrorReason.ProviderRejected]: 'The authentication provider rejected the sign-in.',
30
+ };
31
+ /**
32
+ * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
33
+ * when a consumer's tree resolves two `@portal-hq/utils`.
34
+ *
35
+ * This key and the members {@link PortalAuthError.is} implies are a
36
+ * compatibility contract: changing either breaks recognition between copies.
37
+ */
38
+ const BRAND = Symbol.for('@portal-hq/utils/PortalAuthError');
39
+ /**
40
+ * The single error every Client Auth completion failure is normalized to;
41
+ * branch on `reason`.
42
+ */
43
+ class PortalAuthError extends Error {
44
+ constructor({ reason, detail, cause }) {
45
+ super(`[PortalAuth] ${authErrors[reason]}${detail ? ` (${detail})` : ''}`);
46
+ /** @internal Cross-copy brand. Read it through {@link PortalAuthError.is}. */
47
+ this[_a] = true;
48
+ Object.setPrototypeOf(this, PortalAuthError.prototype);
49
+ this.reason = reason;
50
+ this.cause = cause;
51
+ }
52
+ /**
53
+ * Brand check — see BRAND. Narrowing a branded error from another copy to
54
+ * this class is intentional.
55
+ */
56
+ static is(error) {
57
+ return (typeof error === 'object' &&
58
+ error !== null &&
59
+ error[BRAND] === true);
60
+ }
61
+ }
62
+ _a = BRAND;
63
+ exports.default = PortalAuthError;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.PortalCredentialErrorReason = void 0;
5
+ /** Why a credential could not be turned into a usable token. */
6
+ var PortalCredentialErrorReason;
7
+ (function (PortalCredentialErrorReason) {
8
+ /** Resolution succeeded but produced nothing usable. */
9
+ PortalCredentialErrorReason["Unavailable"] = "CREDENTIAL_UNAVAILABLE";
10
+ /** The credential provider itself failed — a storage read, a custom
11
+ * `PortalCredentials` implementation throwing, and so on. */
12
+ PortalCredentialErrorReason["ProviderFailure"] = "CREDENTIAL_PROVIDER_FAILURE";
13
+ /** The credential is known to be dead: the session was invalidated. */
14
+ PortalCredentialErrorReason["SessionInvalidated"] = "SESSION_INVALIDATED";
15
+ })(PortalCredentialErrorReason = exports.PortalCredentialErrorReason || (exports.PortalCredentialErrorReason = {}));
16
+ const credentialErrors = {
17
+ [PortalCredentialErrorReason.Unavailable]: 'No credential was available. Provide an apiKey or credentials when constructing Portal.',
18
+ [PortalCredentialErrorReason.ProviderFailure]: 'The credential provider failed to supply a credential.',
19
+ [PortalCredentialErrorReason.SessionInvalidated]: 'The session is no longer valid. Authenticate again to obtain a new one.',
20
+ };
21
+ /**
22
+ * Cross-copy brand. `instanceof` compares prototypes, so it returns `false`
23
+ * when a consumer's tree resolves two `@portal-hq/utils` — a real
24
+ * `SessionInvalidated` then silently degrades to a provider failure.
25
+ *
26
+ * This key and the members {@link PortalCredentialError.is} implies are a
27
+ * compatibility contract: changing either breaks recognition between copies.
28
+ */
29
+ const BRAND = Symbol.for('@portal-hq/utils/PortalCredentialError');
30
+ /**
31
+ * The single error every credential resolution failure is normalized to; branch
32
+ * on `reason`.
33
+ */
34
+ class PortalCredentialError extends Error {
35
+ constructor({ reason, cause }) {
36
+ super(`[Portal] ${credentialErrors[reason]}`);
37
+ /** @internal Cross-copy brand. Read it through {@link PortalCredentialError.is}. */
38
+ this[_a] = true;
39
+ Object.setPrototypeOf(this, PortalCredentialError.prototype);
40
+ this.reason = reason;
41
+ this.cause = cause;
42
+ }
43
+ /**
44
+ * Brand check — see BRAND. Narrowing a branded error from another copy to
45
+ * this class is intentional.
46
+ */
47
+ static is(error) {
48
+ return (typeof error === 'object' &&
49
+ error !== null &&
50
+ error[BRAND] === true);
51
+ }
52
+ /** True when re-authentication is the only way forward. */
53
+ get requiresReauthentication() {
54
+ return this.reason === PortalCredentialErrorReason.SessionInvalidated;
55
+ }
56
+ }
57
+ _a = BRAND;
58
+ exports.default = PortalCredentialError;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PortalMpcError = exports.PortalErrorCodeTypes = exports.PortalErrorCodes = void 0;
3
+ exports.isMpcAuthFailure = exports.MPC_AUTH_FAILED_ERROR_ID = exports.PortalMpcError = exports.PortalErrorCodeTypes = exports.PortalErrorCodes = void 0;
4
4
  var PortalErrorCodes;
5
5
  (function (PortalErrorCodes) {
6
6
  PortalErrorCodes[PortalErrorCodes["InvalidRankAndThreshold"] = 100] = "InvalidRankAndThreshold";
@@ -77,3 +77,15 @@ class PortalMpcError extends Error {
77
77
  }
78
78
  }
79
79
  exports.PortalMpcError = PortalMpcError;
80
+ /**
81
+ * The MPC binary issues its own authenticated requests, so the SDK never sees
82
+ * the HTTP 401 behind a rejected credential — this ID is the only form it
83
+ * reaches us in. Matched on the ID, never the companion `code`, which exists
84
+ * only for clients predating these IDs.
85
+ */
86
+ exports.MPC_AUTH_FAILED_ERROR_ID = 'AUTH_FAILED';
87
+ /** Accepts a raw error envelope or a thrown {@link PortalMpcError}. */
88
+ const isMpcAuthFailure = (error) => typeof error === 'object' &&
89
+ error !== null &&
90
+ error.id === exports.MPC_AUTH_FAILED_ERROR_ID;
91
+ exports.isMpcAuthFailure = isMpcAuthFailure;
@@ -15,9 +15,7 @@ var Events;
15
15
  Events["GetEnabledDapps"] = "Get Enabled Dapps";
16
16
  Events["GetNFTs"] = "Get NFTs";
17
17
  Events["GetNetworks"] = "Get Networks";
18
- Events["GetQuote"] = "Get Quote";
19
18
  Events["GetSigningShareMetadata"] = "Get Signing Share Metadata";
20
- Events["GetSources"] = "Get Sources";
21
19
  Events["GetTransactions"] = "Get Transactions";
22
20
  Events["GetTransactionHistory"] = "Get Transaction History";
23
21
  Events["PrepareClientEject"] = "Prepare Client Eject";
@@ -64,6 +62,8 @@ var Events;
64
62
  Events["EvmAccountType7702BuildAuthorizationList"] = "Evm Account Type 7702 BuildAuthorizationList";
65
63
  Events["EvmAccountType7702BuildUpgradeTx"] = "Evm Account Type 7702 BuildUpgradeTx";
66
64
  Events["EvmAccountType7702Upgrade"] = "Evm Account Type 7702 Upgrade";
65
+ Events["UserOperationsBuildBatched"] = "UserOperations BuildBatched";
66
+ Events["UserOperationsBroadcastBatched"] = "UserOperations BroadcastBatched";
67
67
  Events["NoahInitiateKyc"] = "Noah Initiate KYC";
68
68
  Events["NoahInitiatePayin"] = "Noah Initiate Payin";
69
69
  Events["NoahSimulatePayin"] = "Noah Simulate Payin";
@@ -3,8 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.TRACE_ID_HEADER = exports.createExecutionContext = exports.generateTraceId = exports.EvaluateTransactionOperationType = exports.HttpRequester = exports.PortalRequests = exports.HttpRequest = exports.parseRequest = exports.numberToHexString = exports.getClientPlatformVersion = exports.Events = exports.RpcErrorCodes = exports.ProviderRpcError = exports.PortalMpcError = exports.PortalErrorCodeTypes = exports.PortalErrorCodes = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = exports.Storage = exports.PortalRequestMethod = exports.PasswordStorage = exports.MpcStatuses = exports.KeychainAdapter = exports.convert = exports.convertCryptoToLocal = exports.convertLocalToCrypto = exports.DEFAULT_HOSTS = exports.buildDefaultGatewayConfig = exports.NAMESPACE_TO_CURVE = exports.ALL_CHAIN_IDS = exports.BITCOIN_CHAIN_IDS = exports.TRON_CHAIN_IDS = exports.SOLANA_CHAIN_IDS = exports.EVM_CHAIN_IDS = exports.DEFAULT_CHAIN_ID_CAIP2 = exports.DEFAULT_CHAIN_ID_NUMERIC = exports.CAIP2_CHAIN_ID_REGEX = exports.FRIENDLY_CHAIN_NAME_TO_CAIP2 = exports.SUPPORTED_BITCOIN_P2WPKH_CHAINS = exports.CHAIN_NAMESPACES = exports.getChainNameForId = exports.getChainIdForName = exports.chainNameToId = exports.chainIdToName = void 0;
7
- exports.sdkLogger = exports.UUID_V4_REGEX = void 0;
6
+ exports.PortalMpcError = exports.PortalErrorCodeTypes = exports.PortalErrorCodes = exports.MPC_AUTH_FAILED_ERROR_ID = exports.PortalCredentialErrorReason = exports.PortalCredentialError = exports.PortalAuthErrorReason = exports.PortalAuthError = exports.NoAddressError = exports.MpcSigningError = exports.MissingOptionError = exports.InvalidGatewayConfigError = exports.InvalidChainIdError = exports.InvalidApiKeyError = exports.HttpError = exports.CloudStorageReadError = exports.Storage = exports.PortalRequestMethod = exports.PasswordStorage = exports.MpcStatuses = exports.KeychainAdapter = exports.convert = exports.convertCryptoToLocal = exports.convertLocalToCrypto = exports.staticApiKeyOf = exports.resolveCredentialToken = exports.resolveCredentials = exports.reportUnauthorized = exports.onCredentialsInvalidated = exports.invalidateCredentials = exports.failFromMpcError = exports.StaticCredentials = exports.DEFAULT_HOSTS = exports.buildDefaultGatewayConfig = exports.NAMESPACE_TO_CURVE = exports.ALL_CHAIN_IDS = exports.BITCOIN_CHAIN_IDS = exports.TRON_CHAIN_IDS = exports.SOLANA_CHAIN_IDS = exports.EVM_CHAIN_IDS = exports.DEFAULT_CHAIN_ID_CAIP2 = exports.DEFAULT_CHAIN_ID_NUMERIC = exports.CAIP2_CHAIN_ID_REGEX = exports.FRIENDLY_CHAIN_NAME_TO_CAIP2 = exports.SUPPORTED_BITCOIN_P2WPKH_CHAINS = exports.CHAIN_NAMESPACES = exports.getChainNameForId = exports.getChainIdForName = exports.chainNameToId = exports.chainIdToName = void 0;
7
+ exports.sdkLogger = exports.UUID_V4_REGEX = exports.TRACE_ID_HEADER = exports.createExecutionContext = exports.generateTraceId = exports.EvaluateTransactionOperationType = exports.HttpRequester = exports.PortalRequests = exports.HttpRequest = exports.parseRequest = exports.numberToHexString = exports.getClientPlatformVersion = exports.Events = exports.RpcErrorCodes = exports.ProviderRpcError = exports.isMpcAuthFailure = void 0;
8
8
  var chains_1 = require("./chains");
9
9
  Object.defineProperty(exports, "chainIdToName", { enumerable: true, get: function () { return chains_1.chainIdToName; } });
10
10
  Object.defineProperty(exports, "chainNameToId", { enumerable: true, get: function () { return chains_1.chainNameToId; } });
@@ -25,6 +25,15 @@ Object.defineProperty(exports, "NAMESPACE_TO_CURVE", { enumerable: true, get: fu
25
25
  var config_1 = require("./config");
26
26
  Object.defineProperty(exports, "buildDefaultGatewayConfig", { enumerable: true, get: function () { return config_1.buildDefaultGatewayConfig; } });
27
27
  Object.defineProperty(exports, "DEFAULT_HOSTS", { enumerable: true, get: function () { return config_1.DEFAULT_HOSTS; } });
28
+ var credentials_1 = require("./credentials");
29
+ Object.defineProperty(exports, "StaticCredentials", { enumerable: true, get: function () { return credentials_1.StaticCredentials; } });
30
+ Object.defineProperty(exports, "failFromMpcError", { enumerable: true, get: function () { return credentials_1.failFromMpcError; } });
31
+ Object.defineProperty(exports, "invalidateCredentials", { enumerable: true, get: function () { return credentials_1.invalidateCredentials; } });
32
+ Object.defineProperty(exports, "onCredentialsInvalidated", { enumerable: true, get: function () { return credentials_1.onCredentialsInvalidated; } });
33
+ Object.defineProperty(exports, "reportUnauthorized", { enumerable: true, get: function () { return credentials_1.reportUnauthorized; } });
34
+ Object.defineProperty(exports, "resolveCredentials", { enumerable: true, get: function () { return credentials_1.resolveCredentials; } });
35
+ Object.defineProperty(exports, "resolveCredentialToken", { enumerable: true, get: function () { return credentials_1.resolveCredentialToken; } });
36
+ Object.defineProperty(exports, "staticApiKeyOf", { enumerable: true, get: function () { return credentials_1.staticApiKeyOf; } });
28
37
  var currency_1 = require("./currency");
29
38
  Object.defineProperty(exports, "convertLocalToCrypto", { enumerable: true, get: function () { return currency_1.convertLocalToCrypto; } });
30
39
  Object.defineProperty(exports, "convertCryptoToLocal", { enumerable: true, get: function () { return currency_1.convertCryptoToLocal; } });
@@ -44,9 +53,15 @@ Object.defineProperty(exports, "InvalidGatewayConfigError", { enumerable: true,
44
53
  Object.defineProperty(exports, "MissingOptionError", { enumerable: true, get: function () { return errors_1.MissingOptionError; } });
45
54
  Object.defineProperty(exports, "MpcSigningError", { enumerable: true, get: function () { return errors_1.MpcSigningError; } });
46
55
  Object.defineProperty(exports, "NoAddressError", { enumerable: true, get: function () { return errors_1.NoAddressError; } });
56
+ Object.defineProperty(exports, "PortalAuthError", { enumerable: true, get: function () { return errors_1.PortalAuthError; } });
57
+ Object.defineProperty(exports, "PortalAuthErrorReason", { enumerable: true, get: function () { return errors_1.PortalAuthErrorReason; } });
58
+ Object.defineProperty(exports, "PortalCredentialError", { enumerable: true, get: function () { return errors_1.PortalCredentialError; } });
59
+ Object.defineProperty(exports, "PortalCredentialErrorReason", { enumerable: true, get: function () { return errors_1.PortalCredentialErrorReason; } });
60
+ Object.defineProperty(exports, "MPC_AUTH_FAILED_ERROR_ID", { enumerable: true, get: function () { return errors_1.MPC_AUTH_FAILED_ERROR_ID; } });
47
61
  Object.defineProperty(exports, "PortalErrorCodes", { enumerable: true, get: function () { return errors_1.PortalErrorCodes; } });
48
62
  Object.defineProperty(exports, "PortalErrorCodeTypes", { enumerable: true, get: function () { return errors_1.PortalErrorCodeTypes; } });
49
63
  Object.defineProperty(exports, "PortalMpcError", { enumerable: true, get: function () { return errors_1.PortalMpcError; } });
64
+ Object.defineProperty(exports, "isMpcAuthFailure", { enumerable: true, get: function () { return errors_1.isMpcAuthFailure; } });
50
65
  Object.defineProperty(exports, "ProviderRpcError", { enumerable: true, get: function () { return errors_1.ProviderRpcError; } });
51
66
  Object.defineProperty(exports, "RpcErrorCodes", { enumerable: true, get: function () { return errors_1.RpcErrorCodes; } });
52
67
  var events_1 = require("./events");
@@ -9,11 +9,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ const errors_1 = require("../errors");
12
13
  const index_1 = require("../index");
13
14
  const tracing_1 = require("../tracing");
14
15
  class HttpRequester {
15
- constructor({ baseUrl }) {
16
+ constructor({ baseUrl, onUnauthorized }) {
16
17
  this.baseUrl = baseUrl;
18
+ this.onUnauthorized = onUnauthorized;
19
+ }
20
+ /**
21
+ * Sends a request, notifying `onUnauthorized` on 401. Observational only:
22
+ * the hook's own failure is swallowed and the original `HttpError` is always
23
+ * what the caller sees.
24
+ */
25
+ send(requestOptions) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ try {
28
+ return (yield new index_1.HttpRequest(requestOptions).send());
29
+ }
30
+ catch (error) {
31
+ if (this.onUnauthorized &&
32
+ error instanceof errors_1.HttpError &&
33
+ error.status === 401) {
34
+ try {
35
+ yield this.onUnauthorized();
36
+ }
37
+ catch (_a) {
38
+ // Never let credential bookkeeping replace the original failure.
39
+ }
40
+ }
41
+ throw error;
42
+ }
43
+ });
17
44
  }
18
45
  buildHeaders(headers = {}, traceId) {
19
46
  return Object.assign(Object.assign({ 'Content-Type': 'application/json' }, headers), (traceId ? { [tracing_1.TRACE_ID_HEADER]: traceId } : {}));
@@ -26,9 +53,7 @@ class HttpRequester {
26
53
  url: `${this.baseUrl}${path}`,
27
54
  };
28
55
  requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
29
- const request = new index_1.HttpRequest(requestOptions);
30
- const response = (yield request.send());
31
- return response;
56
+ return this.send(requestOptions);
32
57
  });
33
58
  }
34
59
  get(path, options) {
@@ -39,9 +64,7 @@ class HttpRequester {
39
64
  url: `${this.baseUrl}${path}`,
40
65
  };
41
66
  requestOptions.headers = this.buildHeaders(((_a = options === null || options === void 0 ? void 0 : options.headers) !== null && _a !== void 0 ? _a : {}), options === null || options === void 0 ? void 0 : options.traceId);
42
- const request = new index_1.HttpRequest(requestOptions);
43
- const response = (yield request.send());
44
- return response;
67
+ return this.send(requestOptions);
45
68
  });
46
69
  }
47
70
  post(path, options) {
@@ -55,9 +78,7 @@ class HttpRequester {
55
78
  if (options === null || options === void 0 ? void 0 : options.body) {
56
79
  requestOptions.body = options.body;
57
80
  }
58
- const request = new index_1.HttpRequest(requestOptions);
59
- const response = (yield request.send());
60
- return response;
81
+ return this.send(requestOptions);
61
82
  });
62
83
  }
63
84
  put(path, options) {
@@ -71,9 +92,7 @@ class HttpRequester {
71
92
  if (options === null || options === void 0 ? void 0 : options.body) {
72
93
  requestOptions.body = options.body;
73
94
  }
74
- const request = new index_1.HttpRequest(requestOptions);
75
- const response = (yield request.send());
76
- return response;
95
+ return this.send(requestOptions);
77
96
  });
78
97
  }
79
98
  patch(path, options) {
@@ -87,9 +106,7 @@ class HttpRequester {
87
106
  if (options === null || options === void 0 ? void 0 : options.body) {
88
107
  requestOptions.body = options.body;
89
108
  }
90
- const request = new index_1.HttpRequest(requestOptions);
91
- const response = (yield request.send());
92
- return response;
109
+ return this.send(requestOptions);
93
110
  });
94
111
  }
95
112
  }
@@ -1 +1 @@
1
- { "version": "4.8.0" }
1
+ { "version": "5.0.0" }