@coinbase/cdp-api-client 0.0.110 → 0.0.111

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.
@@ -1,262 +1,76 @@
1
- import { Analytics as o } from "./index2.js";
2
- import "./index3.js";
3
- import c from "axios";
4
- import { ERROR_DOCS_PAGE_URL as h } from "./index9.js";
5
- import { UnknownApiError as R, HttpErrorType as u, isOpenAPIError as A, APIError as d, UnknownError as k } from "./index8.js";
6
- const w = () => typeof window < "u" && typeof document < "u";
7
- let a = c.create({
8
- baseURL: "https://api.cdp.coinbase.com/platform"
9
- }), i = null;
10
- const O = (t) => {
11
- if (a = c.create({
12
- baseURL: t.basePath || "https://api.cdp.coinbase.com/platform",
13
- // Only enable cookies in browser environments where they're supported
14
- withCredentials: w()
15
- }), a.interceptors.request.use(async (r) => {
16
- const e = U(r), s = f(r);
17
- if (!i || v(s.pathname) || _(s.pathname) && !await i.isSignedIn() || !I(s.pathname))
18
- return r;
19
- const n = await i.getXWalletAuth({
20
- requestMethod: e,
21
- requestHost: s.host,
22
- requestPath: s.pathname,
23
- requestData: r.data
24
- });
25
- return n && (r.headers["X-Wallet-Auth"] = n), r;
26
- }), a.interceptors.request.use(async (r) => {
27
- const e = f(r);
28
- if (!i || v(e.pathname) || _(e.pathname) && !await i.isSignedIn())
29
- return r;
30
- const s = await i.getToken();
31
- return s && s !== "" && (r.headers.Authorization = `Bearer ${s}`), r;
32
- }), !w()) {
33
- const r = t.platform ? `CDP/reactnative/${t.platform}` : "CDP/reactnative";
34
- a.interceptors.request.use(async (e) => {
35
- let s = e.headers["User-Agent"];
36
- return s = s ? `${s} ${r}` : r, e.headers["User-Agent"] = s, e;
37
- });
1
+ const u = {
2
+ unexpected_error: "unexpected_error",
3
+ unauthorized: "unauthorized",
4
+ not_found: "not_found",
5
+ bad_gateway: "bad_gateway",
6
+ service_unavailable: "service_unavailable",
7
+ unknown: "unknown"
8
+ };
9
+ class a extends Error {
10
+ statusCode;
11
+ errorType;
12
+ errorMessage;
13
+ correlationId;
14
+ errorLink;
15
+ /**
16
+ * Constructor for the APIError class
17
+ *
18
+ * @param statusCode - The HTTP status code
19
+ * @param errorType - The type of error
20
+ * @param errorMessage - The error message
21
+ * @param correlationId - The correlation ID
22
+ * @param errorLink - URL to documentation about this error
23
+ * @param cause - The cause of the error
24
+ */
25
+ constructor(e, o, t, n, s, i) {
26
+ super(t, { cause: i }), this.name = "APIError", this.statusCode = e, this.errorType = o, this.errorMessage = t, n !== void 0 && (this.correlationId = n), s !== void 0 && (this.errorLink = s);
27
+ }
28
+ /**
29
+ * Convert the error to a JSON object, excluding undefined properties
30
+ *
31
+ * @returns The error as a JSON object
32
+ */
33
+ toJSON() {
34
+ return {
35
+ name: this.name,
36
+ statusCode: this.statusCode,
37
+ errorType: this.errorType,
38
+ errorMessage: this.errorMessage,
39
+ ...this.correlationId && { correlationId: this.correlationId },
40
+ ...this.errorLink && { errorLink: this.errorLink }
41
+ };
38
42
  }
39
- t.refreshTokenStorage && P(t.refreshTokenStorage), t.appAttestation && y(t.appAttestation, t.platform), t.debugging && (a.interceptors.request.use((r) => (console.log("Request:", r), r)), a.interceptors.response.use((r) => (console.log("Response:", r), r)));
40
- }, D = (t) => {
41
- i = t;
42
- }, y = (t, r) => {
43
- a.interceptors.request.use(async (e) => {
44
- const s = f(e);
45
- if (!q(s.pathname) || !t.isEnabled())
46
- return e;
47
- try {
48
- if (r === "ios") {
49
- const n = s.pathname.match(/\/projects\/([^/]+)\//);
50
- if (!n || !n[1])
51
- return e;
52
- const g = `/v2/embedded-wallet-api/projects/${n[1]}/attestation/challenge`, l = (await a.post(g)).data.challenge;
53
- if (!l)
54
- return console.warn("Failed to fetch assertion challenge"), e;
55
- const p = await t.generateAssertion(l);
56
- if (!p)
57
- return e;
58
- e.headers["X-App-Attestation-Assertion"] = p.assertion, e.headers["X-App-Attestation-Key-ID"] = p.keyId, e.headers["X-App-Attestation-Challenge"] = l;
59
- } else {
60
- const n = await t.generateAssertion(JSON.stringify(e.data));
61
- if (!n)
62
- return e;
63
- e.headers["X-Integrity-Token"] = n.assertion, e.headers["X-Package-Name"] = t.appIdentifier;
64
- }
65
- return e;
66
- } catch (n) {
67
- throw new Error(
68
- `App attestation required but assertion generation failed: ${n instanceof Error ? n.message : String(n)}`
69
- );
70
- }
71
- });
72
- }, E = (t, r) => ({
73
- ...t,
74
- headers: {
75
- ...t.headers || {},
76
- "X-Idempotency-Key": r
43
+ }
44
+ class d extends a {
45
+ /**
46
+ * Constructor for the UnknownApiError class
47
+ *
48
+ * @param errorType - The type of error
49
+ * @param errorMessage - The error message
50
+ * @param cause - The cause of the error
51
+ */
52
+ constructor(e, o, t) {
53
+ super(0, e, o, void 0, void 0, t), this.name = "UnknownApiError";
77
54
  }
78
- }), z = async (t, r) => {
79
- $(t), r && r !== "" && (t = E(t, r));
80
- try {
81
- return (await a(t)).data;
82
- } catch (e) {
83
- if (c.isAxiosError(e) && !e.response)
84
- throw new R(
85
- u.unknown,
86
- e.cause instanceof Error ? e.cause.message : e.message,
87
- e.cause
88
- );
89
- if (c.isAxiosError(e) && e.response) {
90
- if (A(e.response.data))
91
- throw new d(
92
- e.response.status,
93
- e.response.data.errorType,
94
- e.response.data.errorMessage,
95
- e.response.data.correlationId,
96
- e.response.data.errorLink,
97
- e.cause
98
- );
99
- {
100
- const s = e.response.status;
101
- switch (s) {
102
- case 401:
103
- throw new d(
104
- s,
105
- u.unauthorized,
106
- "Unauthorized.",
107
- void 0,
108
- `${h}#unauthorized`,
109
- e.cause
110
- );
111
- case 404:
112
- throw new d(
113
- s,
114
- u.not_found,
115
- "API not found.",
116
- void 0,
117
- `${h}#not_found`,
118
- e.cause
119
- );
120
- case 502:
121
- throw new d(
122
- s,
123
- u.bad_gateway,
124
- "Bad gateway.",
125
- void 0,
126
- `${h}`,
127
- e.cause
128
- );
129
- case 503:
130
- throw new d(
131
- s,
132
- u.service_unavailable,
133
- "Service unavailable. Please try again later.",
134
- void 0,
135
- `${h}`,
136
- e.cause
137
- );
138
- default: {
139
- let n = "";
140
- if (e.response.data)
141
- try {
142
- n = JSON.stringify(e.response.data);
143
- } catch {
144
- n = String(e.response.data);
145
- }
146
- const m = n ? `An unexpected error occurred: ${n}` : "An unexpected error occurred.";
147
- throw new d(
148
- s,
149
- u.unexpected_error,
150
- m,
151
- void 0,
152
- `${h}`,
153
- e.cause
154
- );
155
- }
156
- }
157
- }
158
- }
159
- throw new k("Something went wrong.", e instanceof Error ? e : void 0);
55
+ }
56
+ class c extends Error {
57
+ /**
58
+ * Constructor for the UnknownError class
59
+ *
60
+ * @param message - The error message
61
+ * @param cause - The cause of the error
62
+ */
63
+ constructor(e, o) {
64
+ super(e, { cause: o }), this.name = "UnknownError";
160
65
  }
161
- }, P = (t) => {
162
- a.interceptors.response.use(
163
- async (r) => {
164
- try {
165
- if (b(r)) {
166
- o.sendSessionRefreshEvent({
167
- name: "refresh_token_response"
168
- });
169
- const e = r.data?.refreshToken;
170
- e && (o.sendSessionRefreshEvent({
171
- name: "refresh_token_received"
172
- }), await Promise.race([
173
- t.setRefreshToken(e),
174
- new Promise(
175
- (s, n) => setTimeout(() => n(new Error("setRefreshToken timed out after 5000ms")), 5e3)
176
- )
177
- ]), o.sendSessionRefreshEvent({
178
- name: "refresh_token_stored"
179
- }));
180
- }
181
- } catch (e) {
182
- const s = e instanceof Error ? e.message : String(e);
183
- o.sendSessionRefreshEvent({
184
- name: "refresh_token_store_failed",
185
- error_message: s
186
- }), console.warn("Failed to store refresh token:", e);
187
- }
188
- return r;
189
- },
190
- (r) => Promise.reject(r)
191
- ), a.interceptors.request.use(async (r) => {
192
- try {
193
- if (T(r.url)) {
194
- const e = await t.getRefreshToken();
195
- e || setTimeout(() => {
196
- t.getRefreshToken().then((s) => {
197
- s && o.sendSessionRefreshEvent({
198
- name: "refresh_token_received_after_missing"
199
- });
200
- }).catch((s) => {
201
- const n = s instanceof Error ? s.message : String(s);
202
- o.sendSessionRefreshEvent({
203
- name: "refresh_token_retrieve_failed_after_missing",
204
- error_message: n
205
- });
206
- });
207
- }, 10), e ? (o.sendSessionRefreshEvent({
208
- name: "refresh_token_retrieved"
209
- }), r.data = {
210
- ...r.data,
211
- refreshToken: e
212
- }) : o.sendSessionRefreshEvent({
213
- name: "refresh_token_missing"
214
- });
215
- }
216
- S(r.url) && (o.sendSessionRefreshEvent({
217
- name: "refresh_token_removing_token"
218
- }), await t.removeRefreshToken());
219
- } catch (e) {
220
- const s = e instanceof Error ? e.message : String(e);
221
- o.sendSessionRefreshEvent({
222
- name: "refresh_token_retrieve_failed",
223
- error_message: s
224
- }), console.warn("Failed to retrieve refresh token:", e);
225
- }
226
- return r;
227
- });
228
- }, S = (t) => t ? /^\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/logout$/.test(t) : !1, T = (t) => t ? /^\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/(refresh|logout)$/.test(t) : !1, b = (t) => {
229
- const r = t.config.url;
230
- return r ? /^\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/(verify\/(email|sms|siwe|oauth\/.*)|refresh)$/.test(
231
- r
232
- ) : !1;
233
- }, $ = (t) => {
234
- if (!a.getUri() || a.getUri() === "")
235
- throw new Error("CDP client URI not configured. Call configure() first.");
236
- if (!t.url || t.url === "")
237
- throw new Error("AxiosRequestConfig URL is empty. This should never happen.");
238
- if (!t.method || t.method === "")
239
- throw new Error("AxiosRequestConfig method is empty. This should never happen.");
240
- }, U = (t) => t.method?.toString().toUpperCase() || "GET", f = (t) => {
241
- if (!t.url)
242
- throw new Error("URL is required for authentication");
243
- const r = a.getUri() + t.url;
244
- return new URL(r);
245
- }, v = (t) => {
246
- const r = /^\/platform\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/(refresh|logout)$/, e = /^\/platform\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/(mfa)$/, s = /^\/platform\/v2\/embedded-wallet-api\/projects\/[^/]+\/config$/, n = /^\/platform\/v2\/embedded-wallet-api\/projects\/[^/]+\/attestation\/(challenge|register)$/;
247
- return r.test(t) || e.test(t) || s.test(t) || n.test(t);
248
- }, I = (t) => !/^\/platform\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/custom\/authenticate$/.test(t), _ = (t) => {
249
- const r = /^\/platform\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/(init)$/, e = /^\/platform\/v2\/embedded-wallet-api\/projects\/[^/]+\/auth\/verify\//;
250
- return r.test(t) || e.test(t);
251
- }, q = (t) => [
252
- // Auth flows: prevent account takeover on mobile clients
253
- /\/auth\/verify\//,
254
- // VerifyEmailAuthentication, VerifySmsAuthentication, VerifyOAuthCode, VerifyOAuthEndUserIdentity
255
- /\/auth\/refresh$/
256
- // RefreshAccessToken
257
- ].some((e) => e.test(t));
66
+ }
67
+ function p(r) {
68
+ return r !== null && typeof r == "object" && "errorType" in r && typeof r.errorType == "string" && "errorMessage" in r && typeof r.errorMessage == "string";
69
+ }
258
70
  export {
259
- z as cdpApiClient,
260
- O as configureCdpApiClient,
261
- D as setAuthManager
71
+ a as APIError,
72
+ u as HttpErrorType,
73
+ d as UnknownApiError,
74
+ c as UnknownError,
75
+ p as isOpenAPIError
262
76
  };