@gatewayfm/ups-sdk 0.1.14 → 0.1.16
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.
- package/dist/account/index.d.mts +1 -1
- package/dist/account/index.d.ts +1 -1
- package/dist/account/index.js +2 -2
- package/dist/account/index.mjs +1 -1
- package/dist/{chunk-2S2KS5ZI.js → chunk-6S7HWY3Z.js} +17 -11
- package/dist/chunk-6S7HWY3Z.js.map +1 -0
- package/dist/{chunk-PMX24TXY.js → chunk-7M4ZN7F3.js} +50 -4
- package/dist/chunk-7M4ZN7F3.js.map +1 -0
- package/dist/{chunk-BUSFZFJS.mjs → chunk-EONLKSST.mjs} +11 -10
- package/dist/chunk-EONLKSST.mjs.map +1 -0
- package/dist/{chunk-VORGSH76.mjs → chunk-ULP4VMHK.mjs} +50 -5
- package/dist/chunk-ULP4VMHK.mjs.map +1 -0
- package/dist/{chunk-XKQI2VMJ.js → chunk-XFJ6SPQN.js} +11 -10
- package/dist/chunk-XFJ6SPQN.js.map +1 -0
- package/dist/{chunk-S65V52WZ.mjs → chunk-ZVB256ZP.mjs} +17 -11
- package/dist/chunk-ZVB256ZP.mjs.map +1 -0
- package/dist/{index-D_ytPgEV.d.ts → index-0emNrQ4Y.d.ts} +1 -1
- package/dist/{index-Csrh5-dl.d.mts → index-BEjQJc66.d.mts} +35 -4
- package/dist/{index-Csrh5-dl.d.ts → index-BEjQJc66.d.ts} +35 -4
- package/dist/{index-1p5DSytk.d.mts → index-bErQcXnC.d.mts} +1 -1
- package/dist/index.d.mts +35 -4
- package/dist/index.d.ts +35 -4
- package/dist/index.js +77 -33
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +70 -30
- package/dist/index.mjs.map +1 -1
- package/dist/payment/index.d.mts +14 -2
- package/dist/payment/index.d.ts +14 -2
- package/dist/payment/index.js +2 -2
- package/dist/payment/index.mjs +1 -1
- package/dist/wallet/index.d.mts +2 -2
- package/dist/wallet/index.d.ts +2 -2
- package/dist/wallet/index.js +2 -2
- package/dist/wallet/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-2S2KS5ZI.js.map +0 -1
- package/dist/chunk-BUSFZFJS.mjs.map +0 -1
- package/dist/chunk-PMX24TXY.js.map +0 -1
- package/dist/chunk-S65V52WZ.mjs.map +0 -1
- package/dist/chunk-VORGSH76.mjs.map +0 -1
- package/dist/chunk-XKQI2VMJ.js.map +0 -1
|
@@ -33,8 +33,8 @@ type EIP1193Provider = {
|
|
|
33
33
|
method: string;
|
|
34
34
|
params?: unknown[];
|
|
35
35
|
}) => Promise<unknown>;
|
|
36
|
-
on?: (event: string, handler: (...args:
|
|
37
|
-
removeListener?: (event: string, handler: (...args:
|
|
36
|
+
on?: (event: string, handler: (...args: unknown[]) => void) => void;
|
|
37
|
+
removeListener?: (event: string, handler: (...args: unknown[]) => void) => void;
|
|
38
38
|
};
|
|
39
39
|
interface WalletState {
|
|
40
40
|
isConnected: boolean;
|
|
@@ -81,7 +81,8 @@ interface PaymentRequirements {
|
|
|
81
81
|
declare enum PaymentType {
|
|
82
82
|
UNSPECIFIED = "UNSPECIFIED",
|
|
83
83
|
DIRECT = "DIRECT",
|
|
84
|
-
ESCROW = "ESCROW"
|
|
84
|
+
ESCROW = "ESCROW",
|
|
85
|
+
INVOICE = "INVOICE"
|
|
85
86
|
}
|
|
86
87
|
interface PaymentExtra {
|
|
87
88
|
name?: string;
|
|
@@ -90,6 +91,8 @@ interface PaymentExtra {
|
|
|
90
91
|
arbiter?: string;
|
|
91
92
|
release_time?: number;
|
|
92
93
|
payee?: string;
|
|
94
|
+
invoice_id?: string;
|
|
95
|
+
invoice_payment_type?: 'DIRECT' | 'ESCROW';
|
|
93
96
|
}
|
|
94
97
|
interface PaymentAuthorization {
|
|
95
98
|
from: string;
|
|
@@ -156,5 +159,33 @@ interface EscrowActionResponse {
|
|
|
156
159
|
transaction?: string;
|
|
157
160
|
network?: string;
|
|
158
161
|
}
|
|
162
|
+
type InvoiceStatus = 'UNSPECIFIED' | 'PENDING' | 'PARTIALLY_PAID' | 'PAID' | 'CANCELLED' | 'EXPIRED';
|
|
163
|
+
interface Invoice {
|
|
164
|
+
invoice_id: string;
|
|
165
|
+
merchant: string;
|
|
166
|
+
payer: string;
|
|
167
|
+
amount: string;
|
|
168
|
+
paid_amount: string;
|
|
169
|
+
due_date: number;
|
|
170
|
+
created_at: number;
|
|
171
|
+
payment_type: 'DIRECT' | 'ESCROW';
|
|
172
|
+
status: InvoiceStatus;
|
|
173
|
+
metadata_uri: string;
|
|
174
|
+
}
|
|
175
|
+
interface CreateInvoiceRequest {
|
|
176
|
+
merchant?: string;
|
|
177
|
+
amount: string;
|
|
178
|
+
payer?: string;
|
|
179
|
+
due_date: number;
|
|
180
|
+
payment_type: 'DIRECT' | 'ESCROW';
|
|
181
|
+
metadata_uri: string;
|
|
182
|
+
}
|
|
183
|
+
interface InvoiceResponse {
|
|
184
|
+
invoice: Invoice;
|
|
185
|
+
}
|
|
186
|
+
interface InvoiceListResponse {
|
|
187
|
+
invoices: Invoice[];
|
|
188
|
+
next_page_token: string;
|
|
189
|
+
}
|
|
159
190
|
|
|
160
|
-
export { type AuthState as A, type ConnectResult as C, type Escrow as E, type PaymentAuthorization as P, type SettleResponse as S, type User as U, type VerifyResponse as V, type WalletState as W, type AuthResult as a, type EscrowActionResponse as b, type
|
|
191
|
+
export { type AuthState as A, type ConnectResult as C, type Escrow as E, type InvoiceResponse as I, type PaymentAuthorization as P, type SettleResponse as S, type User as U, type VerifyResponse as V, type WalletState as W, type AuthResult as a, type EscrowActionResponse as b, type CreateInvoiceRequest as c, type InvoiceListResponse as d, type UPSConfig as e, type EIP1193Provider as f, type ConnectedWallet as g, type Account as h, type AccountStatus as i, type CreateAccountParams as j, type CreateAccountResponse as k, type EIP712Domain as l, type EIP712Type as m, type EIP712TypedData as n, type EscrowStatus as o, type Invoice as p, type InvoiceStatus as q, type PaymentExtra as r, type PaymentRequirements as s, PaymentType as t, type SignedAuthorization as u, type SupportedScheme as v, type SupportedSchemesResponse as w };
|
|
@@ -33,8 +33,8 @@ type EIP1193Provider = {
|
|
|
33
33
|
method: string;
|
|
34
34
|
params?: unknown[];
|
|
35
35
|
}) => Promise<unknown>;
|
|
36
|
-
on?: (event: string, handler: (...args:
|
|
37
|
-
removeListener?: (event: string, handler: (...args:
|
|
36
|
+
on?: (event: string, handler: (...args: unknown[]) => void) => void;
|
|
37
|
+
removeListener?: (event: string, handler: (...args: unknown[]) => void) => void;
|
|
38
38
|
};
|
|
39
39
|
interface WalletState {
|
|
40
40
|
isConnected: boolean;
|
|
@@ -81,7 +81,8 @@ interface PaymentRequirements {
|
|
|
81
81
|
declare enum PaymentType {
|
|
82
82
|
UNSPECIFIED = "UNSPECIFIED",
|
|
83
83
|
DIRECT = "DIRECT",
|
|
84
|
-
ESCROW = "ESCROW"
|
|
84
|
+
ESCROW = "ESCROW",
|
|
85
|
+
INVOICE = "INVOICE"
|
|
85
86
|
}
|
|
86
87
|
interface PaymentExtra {
|
|
87
88
|
name?: string;
|
|
@@ -90,6 +91,8 @@ interface PaymentExtra {
|
|
|
90
91
|
arbiter?: string;
|
|
91
92
|
release_time?: number;
|
|
92
93
|
payee?: string;
|
|
94
|
+
invoice_id?: string;
|
|
95
|
+
invoice_payment_type?: 'DIRECT' | 'ESCROW';
|
|
93
96
|
}
|
|
94
97
|
interface PaymentAuthorization {
|
|
95
98
|
from: string;
|
|
@@ -156,5 +159,33 @@ interface EscrowActionResponse {
|
|
|
156
159
|
transaction?: string;
|
|
157
160
|
network?: string;
|
|
158
161
|
}
|
|
162
|
+
type InvoiceStatus = 'UNSPECIFIED' | 'PENDING' | 'PARTIALLY_PAID' | 'PAID' | 'CANCELLED' | 'EXPIRED';
|
|
163
|
+
interface Invoice {
|
|
164
|
+
invoice_id: string;
|
|
165
|
+
merchant: string;
|
|
166
|
+
payer: string;
|
|
167
|
+
amount: string;
|
|
168
|
+
paid_amount: string;
|
|
169
|
+
due_date: number;
|
|
170
|
+
created_at: number;
|
|
171
|
+
payment_type: 'DIRECT' | 'ESCROW';
|
|
172
|
+
status: InvoiceStatus;
|
|
173
|
+
metadata_uri: string;
|
|
174
|
+
}
|
|
175
|
+
interface CreateInvoiceRequest {
|
|
176
|
+
merchant?: string;
|
|
177
|
+
amount: string;
|
|
178
|
+
payer?: string;
|
|
179
|
+
due_date: number;
|
|
180
|
+
payment_type: 'DIRECT' | 'ESCROW';
|
|
181
|
+
metadata_uri: string;
|
|
182
|
+
}
|
|
183
|
+
interface InvoiceResponse {
|
|
184
|
+
invoice: Invoice;
|
|
185
|
+
}
|
|
186
|
+
interface InvoiceListResponse {
|
|
187
|
+
invoices: Invoice[];
|
|
188
|
+
next_page_token: string;
|
|
189
|
+
}
|
|
159
190
|
|
|
160
|
-
export { type AuthState as A, type ConnectResult as C, type Escrow as E, type PaymentAuthorization as P, type SettleResponse as S, type User as U, type VerifyResponse as V, type WalletState as W, type AuthResult as a, type EscrowActionResponse as b, type
|
|
191
|
+
export { type AuthState as A, type ConnectResult as C, type Escrow as E, type InvoiceResponse as I, type PaymentAuthorization as P, type SettleResponse as S, type User as U, type VerifyResponse as V, type WalletState as W, type AuthResult as a, type EscrowActionResponse as b, type CreateInvoiceRequest as c, type InvoiceListResponse as d, type UPSConfig as e, type EIP1193Provider as f, type ConnectedWallet as g, type Account as h, type AccountStatus as i, type CreateAccountParams as j, type CreateAccountResponse as k, type EIP712Domain as l, type EIP712Type as m, type EIP712TypedData as n, type EscrowStatus as o, type Invoice as p, type InvoiceStatus as q, type PaymentExtra as r, type PaymentRequirements as s, PaymentType as t, type SignedAuthorization as u, type SupportedScheme as v, type SupportedSchemesResponse as w };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { W as WalletState,
|
|
1
|
+
import { W as WalletState, f as EIP1193Provider, g as ConnectedWallet, n as EIP712TypedData } from './index-BEjQJc66.mjs';
|
|
2
2
|
|
|
3
3
|
type Callback<T = any> = (payload: T) => void;
|
|
4
4
|
type Unsubscribe = () => void;
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as AuthState, C as ConnectResult, a as AuthResult, E as Escrow, b as EscrowActionResponse, U as User,
|
|
2
|
-
export {
|
|
1
|
+
import { A as AuthState, C as ConnectResult, a as AuthResult, E as Escrow, b as EscrowActionResponse, c as CreateInvoiceRequest, I as InvoiceResponse, d as InvoiceListResponse, U as User, e as UPSConfig, f as EIP1193Provider, g as ConnectedWallet } from './index-BEjQJc66.mjs';
|
|
2
|
+
export { h as Account, i as AccountStatus, j as CreateAccountParams, k as CreateAccountResponse, l as EIP712Domain, m as EIP712Type, n as EIP712TypedData, o as EscrowStatus, p as Invoice, q as InvoiceStatus, P as PaymentAuthorization, r as PaymentExtra, s as PaymentRequirements, t as PaymentType, S as SettleResponse, u as SignedAuthorization, v as SupportedScheme, w as SupportedSchemesResponse, V as VerifyResponse, W as WalletState } from './index-BEjQJc66.mjs';
|
|
3
3
|
import { H as HttpClient } from './http-client-D9JtkvUx.mjs';
|
|
4
|
-
import { E as EventBus, W as WalletModule } from './index-
|
|
4
|
+
import { E as EventBus, W as WalletModule } from './index-bErQcXnC.mjs';
|
|
5
5
|
import { AccountModule } from './account/index.mjs';
|
|
6
6
|
import { PaymentModule } from './payment/index.mjs';
|
|
7
7
|
|
|
@@ -79,6 +79,36 @@ declare class EscrowModule {
|
|
|
79
79
|
refund(escrowId: string, network: string): Promise<EscrowActionResponse>;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
declare class InvoiceModule {
|
|
83
|
+
private http;
|
|
84
|
+
constructor(http: HttpClient);
|
|
85
|
+
/**
|
|
86
|
+
* Create a new invoice
|
|
87
|
+
* @param request Invoice creation details
|
|
88
|
+
*/
|
|
89
|
+
create(request: CreateInvoiceRequest): Promise<InvoiceResponse>;
|
|
90
|
+
/**
|
|
91
|
+
* Get invoice by ID
|
|
92
|
+
* @param id Invoice ID
|
|
93
|
+
*/
|
|
94
|
+
get(id: string): Promise<InvoiceResponse>;
|
|
95
|
+
/**
|
|
96
|
+
* List invoices
|
|
97
|
+
* @param params Filter parameters
|
|
98
|
+
*/
|
|
99
|
+
list(params?: {
|
|
100
|
+
merchant?: string;
|
|
101
|
+
payer?: string;
|
|
102
|
+
page_size?: number;
|
|
103
|
+
page_token?: string;
|
|
104
|
+
}): Promise<InvoiceListResponse>;
|
|
105
|
+
/**
|
|
106
|
+
* Cancel invoice
|
|
107
|
+
* @param id Invoice ID
|
|
108
|
+
*/
|
|
109
|
+
cancel(id: string): Promise<InvoiceResponse>;
|
|
110
|
+
}
|
|
111
|
+
|
|
82
112
|
/**
|
|
83
113
|
* UserModule provides access to user profile operations.
|
|
84
114
|
*
|
|
@@ -106,6 +136,7 @@ declare class UPSClient {
|
|
|
106
136
|
readonly account: AccountModule;
|
|
107
137
|
readonly payment: PaymentModule;
|
|
108
138
|
readonly escrow: EscrowModule;
|
|
139
|
+
readonly invoice: InvoiceModule;
|
|
109
140
|
readonly user: UserModule;
|
|
110
141
|
private http;
|
|
111
142
|
private eventBus;
|
|
@@ -127,4 +158,4 @@ declare class UPSClient {
|
|
|
127
158
|
destroy(): void;
|
|
128
159
|
}
|
|
129
160
|
|
|
130
|
-
export { AccountModule, AuthError, AuthManager, AuthResult, AuthState, ConnectResult, ConnectedWallet, EIP1193Provider, Escrow, EscrowActionResponse, EscrowModule, EventBus, HttpClient, NetworkError, PaymentError, PaymentModule, RateLimitError, UPSClient, UPSConfig, UPSError, User, UserModule, WalletError, WalletModule };
|
|
161
|
+
export { AccountModule, AuthError, AuthManager, AuthResult, AuthState, ConnectResult, ConnectedWallet, CreateInvoiceRequest, EIP1193Provider, Escrow, EscrowActionResponse, EscrowModule, EventBus, HttpClient, InvoiceListResponse, InvoiceModule, InvoiceResponse, NetworkError, PaymentError, PaymentModule, RateLimitError, UPSClient, UPSConfig, UPSError, User, UserModule, WalletError, WalletModule };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { A as AuthState, C as ConnectResult, a as AuthResult, E as Escrow, b as EscrowActionResponse, U as User,
|
|
2
|
-
export {
|
|
1
|
+
import { A as AuthState, C as ConnectResult, a as AuthResult, E as Escrow, b as EscrowActionResponse, c as CreateInvoiceRequest, I as InvoiceResponse, d as InvoiceListResponse, U as User, e as UPSConfig, f as EIP1193Provider, g as ConnectedWallet } from './index-BEjQJc66.js';
|
|
2
|
+
export { h as Account, i as AccountStatus, j as CreateAccountParams, k as CreateAccountResponse, l as EIP712Domain, m as EIP712Type, n as EIP712TypedData, o as EscrowStatus, p as Invoice, q as InvoiceStatus, P as PaymentAuthorization, r as PaymentExtra, s as PaymentRequirements, t as PaymentType, S as SettleResponse, u as SignedAuthorization, v as SupportedScheme, w as SupportedSchemesResponse, V as VerifyResponse, W as WalletState } from './index-BEjQJc66.js';
|
|
3
3
|
import { H as HttpClient } from './http-client-D9JtkvUx.js';
|
|
4
|
-
import { E as EventBus, W as WalletModule } from './index-
|
|
4
|
+
import { E as EventBus, W as WalletModule } from './index-0emNrQ4Y.js';
|
|
5
5
|
import { AccountModule } from './account/index.js';
|
|
6
6
|
import { PaymentModule } from './payment/index.js';
|
|
7
7
|
|
|
@@ -79,6 +79,36 @@ declare class EscrowModule {
|
|
|
79
79
|
refund(escrowId: string, network: string): Promise<EscrowActionResponse>;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
declare class InvoiceModule {
|
|
83
|
+
private http;
|
|
84
|
+
constructor(http: HttpClient);
|
|
85
|
+
/**
|
|
86
|
+
* Create a new invoice
|
|
87
|
+
* @param request Invoice creation details
|
|
88
|
+
*/
|
|
89
|
+
create(request: CreateInvoiceRequest): Promise<InvoiceResponse>;
|
|
90
|
+
/**
|
|
91
|
+
* Get invoice by ID
|
|
92
|
+
* @param id Invoice ID
|
|
93
|
+
*/
|
|
94
|
+
get(id: string): Promise<InvoiceResponse>;
|
|
95
|
+
/**
|
|
96
|
+
* List invoices
|
|
97
|
+
* @param params Filter parameters
|
|
98
|
+
*/
|
|
99
|
+
list(params?: {
|
|
100
|
+
merchant?: string;
|
|
101
|
+
payer?: string;
|
|
102
|
+
page_size?: number;
|
|
103
|
+
page_token?: string;
|
|
104
|
+
}): Promise<InvoiceListResponse>;
|
|
105
|
+
/**
|
|
106
|
+
* Cancel invoice
|
|
107
|
+
* @param id Invoice ID
|
|
108
|
+
*/
|
|
109
|
+
cancel(id: string): Promise<InvoiceResponse>;
|
|
110
|
+
}
|
|
111
|
+
|
|
82
112
|
/**
|
|
83
113
|
* UserModule provides access to user profile operations.
|
|
84
114
|
*
|
|
@@ -106,6 +136,7 @@ declare class UPSClient {
|
|
|
106
136
|
readonly account: AccountModule;
|
|
107
137
|
readonly payment: PaymentModule;
|
|
108
138
|
readonly escrow: EscrowModule;
|
|
139
|
+
readonly invoice: InvoiceModule;
|
|
109
140
|
readonly user: UserModule;
|
|
110
141
|
private http;
|
|
111
142
|
private eventBus;
|
|
@@ -127,4 +158,4 @@ declare class UPSClient {
|
|
|
127
158
|
destroy(): void;
|
|
128
159
|
}
|
|
129
160
|
|
|
130
|
-
export { AccountModule, AuthError, AuthManager, AuthResult, AuthState, ConnectResult, ConnectedWallet, EIP1193Provider, Escrow, EscrowActionResponse, EscrowModule, EventBus, HttpClient, NetworkError, PaymentError, PaymentModule, RateLimitError, UPSClient, UPSConfig, UPSError, User, UserModule, WalletError, WalletModule };
|
|
161
|
+
export { AccountModule, AuthError, AuthManager, AuthResult, AuthState, ConnectResult, ConnectedWallet, CreateInvoiceRequest, EIP1193Provider, Escrow, EscrowActionResponse, EscrowModule, EventBus, HttpClient, InvoiceListResponse, InvoiceModule, InvoiceResponse, NetworkError, PaymentError, PaymentModule, RateLimitError, UPSClient, UPSConfig, UPSError, User, UserModule, WalletError, WalletModule };
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
5
|
-
var
|
|
3
|
+
var chunkXFJ6SPQN_js = require('./chunk-XFJ6SPQN.js');
|
|
4
|
+
var chunk7M4ZN7F3_js = require('./chunk-7M4ZN7F3.js');
|
|
5
|
+
var chunk6S7HWY3Z_js = require('./chunk-6S7HWY3Z.js');
|
|
6
6
|
var chunkG525R6AV_js = require('./chunk-G525R6AV.js');
|
|
7
7
|
|
|
8
|
-
// src/types/index.ts
|
|
9
|
-
var PaymentType = /* @__PURE__ */ ((PaymentType2) => {
|
|
10
|
-
PaymentType2["UNSPECIFIED"] = "UNSPECIFIED";
|
|
11
|
-
PaymentType2["DIRECT"] = "DIRECT";
|
|
12
|
-
PaymentType2["ESCROW"] = "ESCROW";
|
|
13
|
-
return PaymentType2;
|
|
14
|
-
})(PaymentType || {});
|
|
15
|
-
|
|
16
8
|
// src/core/http-client.ts
|
|
17
9
|
var HttpClient = class {
|
|
18
10
|
baseUrl;
|
|
@@ -22,7 +14,7 @@ var HttpClient = class {
|
|
|
22
14
|
constructor(config) {
|
|
23
15
|
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
24
16
|
this.timeout = config.timeout || 3e4;
|
|
25
|
-
this.retryAttempts = config.retryAttempts
|
|
17
|
+
this.retryAttempts = config.retryAttempts ?? 3;
|
|
26
18
|
this.getToken = config.getToken;
|
|
27
19
|
}
|
|
28
20
|
async request(path, options = {}) {
|
|
@@ -83,10 +75,11 @@ var HttpClient = class {
|
|
|
83
75
|
if (error instanceof chunkG525R6AV_js.AuthError) {
|
|
84
76
|
throw error;
|
|
85
77
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
78
|
+
const e = error;
|
|
79
|
+
if (e.name === "AbortError") {
|
|
80
|
+
lastError = new chunkG525R6AV_js.NetworkError("Request timed out", e);
|
|
81
|
+
} else if (!(e instanceof chunkG525R6AV_js.NetworkError) && !(e instanceof chunkG525R6AV_js.UPSError)) {
|
|
82
|
+
lastError = new chunkG525R6AV_js.NetworkError(e.message || "Unknown error", e);
|
|
90
83
|
}
|
|
91
84
|
if (attempt < this.retryAttempts) {
|
|
92
85
|
const waitTime = Math.pow(2, attempt) * 1e3;
|
|
@@ -203,7 +196,7 @@ var AuthManager = class {
|
|
|
203
196
|
}, { skipAuth: true });
|
|
204
197
|
const authResult = {
|
|
205
198
|
token: result.token,
|
|
206
|
-
expiresAt: result.expires_at || result.expiresAt
|
|
199
|
+
expiresAt: result.expires_at || result.expiresAt || new Date(Date.now() + 24 * 60 * 60 * 1e3).toISOString()
|
|
207
200
|
};
|
|
208
201
|
this.handleAuthSuccess(authResult, walletAddress);
|
|
209
202
|
return authResult;
|
|
@@ -249,11 +242,12 @@ var AuthManager = class {
|
|
|
249
242
|
}
|
|
250
243
|
}
|
|
251
244
|
mapUser(data) {
|
|
245
|
+
const d = data;
|
|
252
246
|
return {
|
|
253
|
-
id:
|
|
254
|
-
walletAddress:
|
|
255
|
-
status:
|
|
256
|
-
createdAt:
|
|
247
|
+
id: d.id,
|
|
248
|
+
walletAddress: d.wallet_address,
|
|
249
|
+
status: d.status,
|
|
250
|
+
createdAt: d.created_at
|
|
257
251
|
};
|
|
258
252
|
}
|
|
259
253
|
logout() {
|
|
@@ -331,6 +325,48 @@ var EscrowModule = class {
|
|
|
331
325
|
}
|
|
332
326
|
};
|
|
333
327
|
|
|
328
|
+
// src/invoice/index.ts
|
|
329
|
+
var InvoiceModule = class {
|
|
330
|
+
constructor(http) {
|
|
331
|
+
this.http = http;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Create a new invoice
|
|
335
|
+
* @param request Invoice creation details
|
|
336
|
+
*/
|
|
337
|
+
async create(request) {
|
|
338
|
+
return this.http.post("/invoices", request);
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Get invoice by ID
|
|
342
|
+
* @param id Invoice ID
|
|
343
|
+
*/
|
|
344
|
+
async get(id) {
|
|
345
|
+
return this.http.get(`/invoices/${id}`);
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* List invoices
|
|
349
|
+
* @param params Filter parameters
|
|
350
|
+
*/
|
|
351
|
+
async list(params) {
|
|
352
|
+
const query = new URLSearchParams();
|
|
353
|
+
if (params?.merchant) query.append("merchant", params.merchant);
|
|
354
|
+
if (params?.payer) query.append("payer", params.payer);
|
|
355
|
+
if (params?.page_size) query.append("page_size", params.page_size.toString());
|
|
356
|
+
if (params?.page_token) query.append("page_token", params.page_token);
|
|
357
|
+
const queryString = query.toString();
|
|
358
|
+
const path = queryString ? `/invoices?${queryString}` : "/invoices";
|
|
359
|
+
return this.http.get(path);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Cancel invoice
|
|
363
|
+
* @param id Invoice ID
|
|
364
|
+
*/
|
|
365
|
+
async cancel(id) {
|
|
366
|
+
return this.http.post(`/invoices/${id}/cancel`, {});
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
|
|
334
370
|
// src/user/index.ts
|
|
335
371
|
var UserModule = class {
|
|
336
372
|
constructor(http) {
|
|
@@ -345,11 +381,12 @@ var UserModule = class {
|
|
|
345
381
|
return this.mapUser(response.user);
|
|
346
382
|
}
|
|
347
383
|
mapUser(data) {
|
|
384
|
+
const d = data;
|
|
348
385
|
return {
|
|
349
|
-
id:
|
|
350
|
-
walletAddress:
|
|
351
|
-
status:
|
|
352
|
-
createdAt:
|
|
386
|
+
id: d.id,
|
|
387
|
+
walletAddress: d.wallet_address,
|
|
388
|
+
status: d.status,
|
|
389
|
+
createdAt: d.created_at
|
|
353
390
|
};
|
|
354
391
|
}
|
|
355
392
|
};
|
|
@@ -362,6 +399,7 @@ var UPSClient = class {
|
|
|
362
399
|
account;
|
|
363
400
|
payment;
|
|
364
401
|
escrow;
|
|
402
|
+
invoice;
|
|
365
403
|
user;
|
|
366
404
|
http;
|
|
367
405
|
eventBus;
|
|
@@ -378,10 +416,11 @@ var UPSClient = class {
|
|
|
378
416
|
getToken: () => this.auth.getToken()
|
|
379
417
|
});
|
|
380
418
|
this.auth = new AuthManager(this.http, this.eventBus, config.refreshInterval);
|
|
381
|
-
this.wallet = new
|
|
382
|
-
this.account = new
|
|
383
|
-
this.payment = new
|
|
419
|
+
this.wallet = new chunk6S7HWY3Z_js.WalletModule(this.eventBus);
|
|
420
|
+
this.account = new chunkXFJ6SPQN_js.AccountModule(this.http);
|
|
421
|
+
this.payment = new chunk7M4ZN7F3_js.PaymentModule(this.http, this.wallet);
|
|
384
422
|
this.escrow = new EscrowModule(this.http);
|
|
423
|
+
this.invoice = new InvoiceModule(this.http);
|
|
385
424
|
this.user = new UserModule(this.http);
|
|
386
425
|
}
|
|
387
426
|
async connect(provider) {
|
|
@@ -418,7 +457,8 @@ var UPSClient = class {
|
|
|
418
457
|
const signature = await this.wallet.signMessage(loginMessage);
|
|
419
458
|
await this.auth.login(address, loginMessage, signature);
|
|
420
459
|
} catch (error) {
|
|
421
|
-
const
|
|
460
|
+
const e = error;
|
|
461
|
+
const isAuthError = e.status === 404 || e.status === 401 || e.status === 400 || e.message?.includes?.("not found") || e.details?.message?.includes?.("not found");
|
|
422
462
|
if (isAuthError) {
|
|
423
463
|
const registerMessage = `Register for UPSx402`;
|
|
424
464
|
const signature = await this.wallet.signMessage(registerMessage);
|
|
@@ -440,15 +480,19 @@ var UPSClient = class {
|
|
|
440
480
|
|
|
441
481
|
Object.defineProperty(exports, "AccountModule", {
|
|
442
482
|
enumerable: true,
|
|
443
|
-
get: function () { return
|
|
483
|
+
get: function () { return chunkXFJ6SPQN_js.AccountModule; }
|
|
444
484
|
});
|
|
445
485
|
Object.defineProperty(exports, "PaymentModule", {
|
|
446
486
|
enumerable: true,
|
|
447
|
-
get: function () { return
|
|
487
|
+
get: function () { return chunk7M4ZN7F3_js.PaymentModule; }
|
|
488
|
+
});
|
|
489
|
+
Object.defineProperty(exports, "PaymentType", {
|
|
490
|
+
enumerable: true,
|
|
491
|
+
get: function () { return chunk7M4ZN7F3_js.PaymentType; }
|
|
448
492
|
});
|
|
449
493
|
Object.defineProperty(exports, "WalletModule", {
|
|
450
494
|
enumerable: true,
|
|
451
|
-
get: function () { return
|
|
495
|
+
get: function () { return chunk6S7HWY3Z_js.WalletModule; }
|
|
452
496
|
});
|
|
453
497
|
Object.defineProperty(exports, "AuthError", {
|
|
454
498
|
enumerable: true,
|
|
@@ -478,7 +522,7 @@ exports.AuthManager = AuthManager;
|
|
|
478
522
|
exports.EscrowModule = EscrowModule;
|
|
479
523
|
exports.EventBus = EventBus;
|
|
480
524
|
exports.HttpClient = HttpClient;
|
|
481
|
-
exports.
|
|
525
|
+
exports.InvoiceModule = InvoiceModule;
|
|
482
526
|
exports.UPSClient = UPSClient;
|
|
483
527
|
exports.UserModule = UserModule;
|
|
484
528
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/index.ts","../src/core/http-client.ts","../src/core/event-bus.ts","../src/core/auth-manager.ts","../src/escrow/index.ts","../src/user/index.ts","../src/client.ts"],"names":["PaymentType","AuthError","NetworkError","UPSError","WalletModule","AccountModule","PaymentModule","WalletError"],"mappings":";;;;;;;;AAiGO,IAAK,WAAA,qBAAAA,YAAAA,KAAL;AACH,EAAAA,aAAA,aAAA,CAAA,GAAc,aAAA;AACd,EAAAA,aAAA,QAAA,CAAA,GAAS,QAAA;AACT,EAAAA,aAAA,QAAA,CAAA,GAAS,QAAA;AAHD,EAAA,OAAAA,YAAAA;AAAA,CAAA,EAAA,WAAA,IAAA,EAAA;;;ACpFL,IAAM,aAAN,MAAiB;AAAA,EACZ,OAAA;AAAA,EACA,OAAA;AAAA,EACA,aAAA;AAAA,EACA,QAAA;AAAA,EAER,YAAY,MAAA,EAA0B;AAClC,IAAA,IAAA,CAAK,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/C,IAAA,IAAA,CAAK,OAAA,GAAU,OAAO,OAAA,IAAW,GAAA;AACjC,IAAA,IAAA,CAAK,a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AA,IACJ;AAAA,EACJ;AAAA,EAEA,MAAM,UAAA,GAA4B;AAC9B,IAAA,MAAM,IAAA,CAAK,OAAO,UAAA,EAAW;AAC7B,IAAA,IAAA,CAAK,KAAK,MAAA,EAAO;AAAA,EACrB;AAAA,EAEA,OAAA,GAAgB;AACZ,IAAA,IAAA,CAAK,KAAK,MAAA,EAAO;AACjB,IAAA,IAAA,CAAK,SAAS,KAAA,EAAM;AAAA,EACxB;AACJ","file":"index.js","sourcesContent":["export interface UPSConfig {\n baseUrl: string; // API base URL\n network: string; // CAIP-2 format: \"eip155:737998412\"\n chainId?: number; // Optional, parsed from network if not provided\n timeout?: number; // Request timeout (default: 30000)\n retryAttempts?: number; // Retry count (default: 3)\n refreshInterval?: number; // Token refresh interval in ms (default: 60000 = 1 min)\n}\n\n// Authentication\nexport interface AuthState {\n isAuthenticated: boolean;\n token: string | null;\n expiresAt: Date | null;\n address: string | null;\n}\n\nexport interface AuthResult {\n token: string;\n expiresAt: string;\n}\n\n// User (from /auth/connect and /users/me)\nexport interface User {\n id: string;\n walletAddress: string;\n status: string;\n createdAt: string;\n}\n\n// Connect auth result (unified auth flow)\nexport interface ConnectResult {\n user: User;\n token: string;\n expiresAt: string;\n isNewUser: boolean;\n}\n\n// Wallet\nexport type EIP1193Provider = {\n request: (args: { method: string; params?: unknown[] }) => Promise<unknown>;\n on?: (event: string, handler: (...args: any[]) => void) => void;\n removeListener?: (event: string, handler: (...args: any[]) => void) => void;\n};\n\nexport interface WalletState {\n isConnected: boolean;\n address: string | null;\n chainId: number | null;\n provider: EIP1193Provider | null;\n}\n\nexport interface ConnectedWallet {\n address: string;\n chainId: number;\n provider: EIP1193Provider;\n}\n\n// Account\nexport type AccountStatus = 'pending' | 'kyc_in_progress' | 'active' | 'frozen' | 'closed';\n\nexport interface Account {\n id: string;\n ownerAddress: string;\n walletAddress: string;\n status: AccountStatus;\n kycLevel: number;\n userId?: string;\n createdAt: string;\n updatedAt?: string;\n}\n\nexport interface CreateAccountParams {\n ownerAddress: string;\n salt: string; // 0x-prefixed 32-byte hex\n}\n\nexport interface CreateAccountResponse {\n account: Account;\n txHash: string;\n}\n\n// Payment (x402)\nexport interface PaymentRequirements {\n scheme: string;\n network: string;\n maxAmountRequired: string;\n asset: string;\n payTo: string;\n maxTimeoutSeconds: number;\n resource?: string;\n description?: string;\n\n extra?: PaymentExtra;\n from?: string;\n}\n\nexport enum PaymentType {\n UNSPECIFIED = 'UNSPECIFIED',\n DIRECT = 'DIRECT',\n ESCROW = 'ESCROW'\n}\n\nexport interface PaymentExtra {\n name?: string;\n version?: string;\n payment_type?: PaymentType; // snake_case from API\n arbiter?: string;\n release_time?: number; // snake_case from API\n payee?: string; // intended recipient for escrow\n}\n\nexport interface PaymentAuthorization {\n from: string;\n to: string;\n value: string;\n validAfter: number;\n validBefore: number;\n nonce: string; // bytes32 hex\n}\n\nexport interface SignedAuthorization extends PaymentAuthorization {\n signature: string;\n}\n\nexport interface VerifyResponse {\n isValid: boolean;\n invalidReason?: string;\n payer?: string;\n}\n\nexport interface SettleResponse {\n success: boolean;\n errorReason?: string;\n transaction?: string;\n network?: string;\n payer?: string;\n}\n\n// x402 Supported Schemes\nexport interface SupportedScheme {\n x402Version: number;\n scheme: string;\n network: string;\n}\n\nexport interface SupportedSchemesResponse {\n kinds: SupportedScheme[];\n extensions?: string[];\n signers?: Record<string, string[]>;\n}\n\n// EIP-712 Typed Data\nexport interface EIP712Domain {\n name: string;\n version: string;\n chainId: number;\n verifyingContract: string;\n}\n\nexport interface EIP712Type {\n name: string;\n type: string;\n}\n\nexport interface EIP712TypedData {\n domain: EIP712Domain;\n types: Record<string, EIP712Type[]>;\n primaryType: string;\n message: Record<string, unknown>;\n}\n\n// Escrow\nexport interface Escrow {\n escrowId: string;\n payer: string;\n payee: string;\n amount: string;\n arbiter: string;\n releaseTime: number;\n status: EscrowStatus;\n}\n\nexport type EscrowStatus = 'ACTIVE' | 'RELEASED' | 'REFUNDED';\n\nexport interface EscrowActionResponse {\n success: boolean;\n errorReason?: string;\n transaction?: string;\n network?: string;\n}\n\n\n","import { NetworkError, AuthError, UPSError } from './errors';\n\ninterface HttpClientConfig {\n baseUrl: string;\n timeout?: number;\n retryAttempts?: number;\n getToken?: () => string | null;\n}\n\ninterface RequestOptions extends RequestInit {\n skipAuth?: boolean;\n}\n\nexport class HttpClient {\n private baseUrl: string;\n private timeout: number;\n private retryAttempts: number;\n private getToken?: () => string | null;\n\n constructor(config: HttpClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, '');\n this.timeout = config.timeout || 30000;\n this.retryAttempts = config.retryAttempts || 3;\n this.getToken = config.getToken;\n }\n\n async request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n const url = `${this.baseUrl}${path.startsWith('/') ? path : '/' + path}`;\n const headers = new Headers(options.headers);\n\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (!options.skipAuth && this.getToken) {\n const token = this.getToken();\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n }\n\n const config: RequestInit = {\n ...options,\n headers,\n };\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt <= this.retryAttempts; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n ...config,\n signal: controller.signal,\n });\n\n if (response.status === 429) {\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter ? parseInt(retryAfter, 10) * 1000 : Math.pow(2, attempt) * 1000;\n await this.delay(waitTime);\n continue;\n }\n\n if (response.status === 401) {\n throw new AuthError('Authentication failed');\n }\n\n if (!response.ok) {\n let errorDetails;\n const text = await response.text();\n try {\n errorDetails = JSON.parse(text);\n } catch {\n errorDetails = text;\n }\n const detailsStr = typeof errorDetails === 'string' ? errorDetails : JSON.stringify(errorDetails);\n throw new NetworkError(`Request failed with status ${response.status}: ${detailsStr}`, errorDetails, response.status);\n }\n\n // Handle 204 No Content\n if (response.status === 204) {\n return undefined as unknown as T;\n }\n\n return await response.json();\n } finally {\n clearTimeout(timeoutId);\n }\n } catch (error: any) {\n lastError = error;\n\n if (error instanceof AuthError) {\n throw error;\n }\n\n if (error.name === 'AbortError') {\n lastError = new NetworkError('Request timed out', error);\n } else if (!(error instanceof NetworkError) && !(error instanceof UPSError)) {\n // Wrap unknown errors\n lastError = new NetworkError(error.message || 'Unknown error', error);\n }\n\n if (attempt < this.retryAttempts) {\n const waitTime = Math.pow(2, attempt) * 1000;\n await this.delay(waitTime);\n continue;\n }\n }\n }\n\n throw lastError || new NetworkError('Request failed after retries');\n }\n\n async get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(path, { ...options, method: 'GET' });\n }\n\n async post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(path, {\n ...options,\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","type Callback<T = any> = (payload: T) => void;\ntype Unsubscribe = () => void;\n\nexport class EventBus {\n private listeners: Map<string, Set<Callback>> = new Map();\n\n emit<T>(event: string, payload: T): void {\n const callbacks = this.listeners.get(event);\n if (callbacks) {\n callbacks.forEach((callback) => {\n try {\n callback(payload);\n } catch (error) {\n console.error(`Error in event handler for ${event}:`, error);\n }\n });\n }\n }\n\n on<T>(event: string, callback: Callback<T>): Unsubscribe {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(callback);\n\n return () => this.off(event, callback);\n }\n\n once<T>(event: string, callback: Callback<T>): Unsubscribe {\n const unsubscribe = this.on<T>(event, (payload) => {\n unsubscribe();\n callback(payload);\n });\n return unsubscribe;\n }\n\n off(event: string, callback: Callback): void {\n const callbacks = this.listeners.get(event);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.listeners.delete(event);\n }\n }\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n","import { HttpClient } from './http-client';\nimport { EventBus } from './event-bus';\nimport { AuthState, AuthResult, ConnectResult, User } from '../types';\n\nexport class AuthManager {\n private _state: AuthState = {\n isAuthenticated: false,\n token: null,\n expiresAt: null,\n address: null,\n };\n private refreshTimer: NodeJS.Timeout | null = null;\n private refreshInterval: number;\n\n constructor(\n private http: HttpClient,\n private eventBus: EventBus,\n refreshInterval: number = 60000 // Default 1 minute\n ) {\n this.refreshInterval = refreshInterval;\n }\n\n get state(): AuthState {\n return { ...this._state };\n }\n\n /**\n * Unified connect method - creates user if new, authenticates if existing\n * This is the preferred authentication method.\n */\n async connect(walletAddress: string, message: string, signature: string): Promise<ConnectResult> {\n const result = await this.http.post<any>('/auth/connect', {\n wallet_address: walletAddress,\n message,\n signature,\n }, { skipAuth: true });\n\n const connectResult: ConnectResult = {\n user: this.mapUser(result.user),\n token: result.token,\n expiresAt: result.expires_at,\n isNewUser: result.is_new_user ?? false,\n };\n\n this.handleAuthSuccess({ token: result.token, expiresAt: result.expires_at }, walletAddress);\n return connectResult;\n }\n\n /**\n * @deprecated Use connect() instead\n */\n async login(walletAddress: string, message: string, signature: string): Promise<AuthResult> {\n const result = await this.http.post<any>('/auth/login', {\n wallet_address: walletAddress,\n message,\n signature,\n }, { skipAuth: true });\n\n const authResult: AuthResult = {\n token: result.token,\n expiresAt: result.expires_at || result.expiresAt,\n };\n\n this.handleAuthSuccess(authResult, walletAddress);\n return authResult;\n }\n\n /**\n * @deprecated Use connect() instead\n */\n async register(walletAddress: string, message: string, signature: string): Promise<AuthResult> {\n const result = await this.http.post<any>('/auth/register', {\n wallet_address: walletAddress,\n message,\n signature,\n }, { skipAuth: true });\n\n const authResult: AuthResult = {\n token: result.token,\n expiresAt: result.expires_at || result.expiresAt || new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),\n };\n\n this.handleAuthSuccess(authResult, walletAddress);\n return authResult;\n }\n\n private handleAuthSuccess(result: AuthResult, walletAddress: string) {\n this.updateState({\n isAuthenticated: true,\n token: result.token,\n expiresAt: new Date(result.expiresAt),\n address: walletAddress,\n });\n this.scheduleRefresh();\n }\n\n async refresh(): Promise<void> {\n if (!this._state.token) return;\n\n try {\n const result = await this.http.post<{ token: string; expires_at: string }>('/auth/refresh');\n\n this.updateState({\n ...this._state,\n token: result.token,\n expiresAt: new Date(result.expires_at),\n });\n\n this.scheduleRefresh();\n } catch (error) {\n console.error('Token refresh failed:', error);\n this.logout();\n }\n }\n\n private mapUser(data: any): User {\n return {\n id: data.id,\n walletAddress: data.wallet_address,\n status: data.status,\n createdAt: data.created_at,\n };\n }\n\n logout(): void {\n if (this.refreshTimer) {\n clearTimeout(this.refreshTimer);\n this.refreshTimer = null;\n }\n\n this.updateState({\n isAuthenticated: false,\n token: null,\n expiresAt: null,\n address: null,\n });\n }\n\n getToken(): string | null {\n return this._state.token;\n }\n\n isAuthenticated(): boolean {\n return this._state.isAuthenticated;\n }\n\n onStateChange(callback: (state: AuthState) => void): () => void {\n return this.eventBus.on('auth:changed', callback);\n }\n\n private updateState(newState: AuthState) {\n this._state = newState;\n this.eventBus.emit('auth:changed', this._state);\n }\n\n private scheduleRefresh() {\n if (this.refreshTimer) {\n clearTimeout(this.refreshTimer);\n }\n\n if (!this._state.expiresAt) return;\n\n const expiresAt = this._state.expiresAt.getTime();\n const now = Date.now();\n\n // If token is already expired, don't schedule refresh\n if (expiresAt <= now) {\n return;\n }\n\n // Schedule refresh at the configured interval (e.g., 1 hour)\n // But ensure we refresh before the token expires\n const timeUntilExpiry = expiresAt - now;\n const refreshTime = Math.min(this.refreshInterval, timeUntilExpiry - 60000); // At least 1 min buffer\n\n if (refreshTime > 0) {\n this.refreshTimer = setTimeout(() => this.refresh(), refreshTime);\n }\n }\n}\n","import { HttpClient } from '../core/http-client';\nimport { Escrow, EscrowActionResponse } from '../types';\n\nexport class EscrowModule {\n constructor(private http: HttpClient) { }\n\n /**\n * Get escrow details by ID\n * @param escrowId Escrow ID\n */\n async get(escrowId: string): Promise<Escrow> {\n return this.http.get<Escrow>(`/x402/escrow/${escrowId}`, { skipAuth: false });\n }\n\n /**\n * Release escrow funds (Payer or Arbiter only)\n * @param escrowId Escrow ID\n */\n async release(escrowId: string, network: string): Promise<EscrowActionResponse> {\n return this.http.post<EscrowActionResponse>(`/x402/escrow/${escrowId}/release`, {\n network\n });\n }\n\n /**\n * Refund escrow funds (Arbiter only)\n * @param escrowId Escrow ID\n */\n async refund(escrowId: string, network: string): Promise<EscrowActionResponse> {\n return this.http.post<EscrowActionResponse>(`/x402/escrow/${escrowId}/refund`, {\n network\n });\n }\n}\n","import { HttpClient } from '../core/http-client';\nimport { User } from '../types';\n\n/**\n * UserModule provides access to user profile operations.\n * \n * @example\n * ```typescript\n * const user = await client.user.getCurrentUser();\n * console.log(user.id, user.walletAddress);\n * ```\n */\nexport class UserModule {\n constructor(private http: HttpClient) { }\n\n /**\n * Get the current authenticated user's profile.\n * Requires authentication.\n */\n async getCurrentUser(): Promise<User> {\n const response = await this.http.get<{ user: any }>('/users/me');\n return this.mapUser(response.user);\n }\n\n private mapUser(data: any): User {\n return {\n id: data.id,\n walletAddress: data.wallet_address,\n status: data.status,\n createdAt: data.created_at,\n };\n }\n}\n","import { HttpClient } from './core/http-client';\nimport { EventBus } from './core/event-bus';\nimport { AuthManager } from './core/auth-manager';\nimport { WalletModule } from './wallet';\nimport { AccountModule } from './account';\nimport { PaymentModule } from './payment';\nimport { EscrowModule } from './escrow';\nimport { UserModule } from './user';\nimport { UPSConfig, ConnectedWallet, EIP1193Provider, ConnectResult } from './types';\nimport { WalletError } from './core/errors';\n\nexport class UPSClient {\n readonly config: UPSConfig;\n readonly wallet: WalletModule;\n readonly auth: AuthManager;\n readonly account: AccountModule;\n readonly payment: PaymentModule;\n readonly escrow: EscrowModule;\n readonly user: UserModule;\n\n private http: HttpClient;\n private eventBus: EventBus;\n\n constructor(config: UPSConfig) {\n this.config = config;\n\n // Parse chainId if not provided but network is \"eip155:123\"\n if (!this.config.chainId && this.config.network.startsWith('eip155:')) {\n this.config.chainId = parseInt(this.config.network.split(':')[1], 10);\n }\n\n this.eventBus = new EventBus();\n\n this.http = new HttpClient({\n baseUrl: config.baseUrl,\n timeout: config.timeout,\n retryAttempts: config.retryAttempts,\n getToken: () => this.auth.getToken(),\n });\n\n this.auth = new AuthManager(this.http, this.eventBus, config.refreshInterval);\n this.wallet = new WalletModule(this.eventBus);\n this.account = new AccountModule(this.http);\n this.payment = new PaymentModule(this.http, this.wallet);\n this.escrow = new EscrowModule(this.http);\n this.user = new UserModule(this.http);\n }\n\n async connect(provider: EIP1193Provider): Promise<ConnectedWallet> {\n return this.wallet.connect(provider);\n }\n\n /**\n * Authenticate with the UPS backend using the unified /auth/connect endpoint.\n * This will create a new user if one doesn't exist, or authenticate an existing user.\n * \n * @returns ConnectResult containing user info and whether this is a new user\n */\n async authenticate(): Promise<ConnectResult> {\n if (!this.wallet.isConnected()) {\n throw new WalletError('Wallet must be connected to authenticate');\n }\n\n const address = this.wallet.getAddress();\n if (!address) throw new WalletError('No wallet address available');\n\n const message = `Connect to UPSx402`;\n const signature = await this.wallet.signMessage(message);\n\n return this.auth.connect(address, message, signature);\n }\n\n /**\n * @deprecated Use authenticate() instead which uses the unified /auth/connect endpoint.\n * This method uses the legacy login/register flow.\n */\n async authenticateLegacy(): Promise<void> {\n if (!this.wallet.isConnected()) {\n throw new WalletError('Wallet must be connected to authenticate');\n }\n\n const address = this.wallet.getAddress();\n if (!address) throw new WalletError('No wallet address available');\n\n // Try Login\n const loginMessage = `Login to UPSx402`;\n try {\n const signature = await this.wallet.signMessage(loginMessage);\n await this.auth.login(address, loginMessage, signature);\n } catch (error: any) {\n // If related to \"User not found\" or 404/401/400, try Register\n const isAuthError = error.status === 404 || error.status === 401 || error.status === 400 || error.message?.includes('not found') || error.details?.message?.includes('not found');\n\n if (isAuthError) {\n const registerMessage = `Register for UPSx402`;\n const signature = await this.wallet.signMessage(registerMessage);\n await this.auth.register(address, registerMessage, signature);\n } else {\n throw error;\n }\n }\n }\n\n async disconnect(): Promise<void> {\n await this.wallet.disconnect();\n this.auth.logout();\n }\n\n destroy(): void {\n this.auth.logout(); // Clears refresh timer\n this.eventBus.clear();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/http-client.ts","../src/core/event-bus.ts","../src/core/auth-manager.ts","../src/escrow/index.ts","../src/invoice/index.ts","../src/user/index.ts","../src/client.ts"],"names":["AuthError","NetworkError","UPSError","WalletModule","AccountModule","PaymentModule","WalletError"],"mappings":";;;;;;;;AAaO,IAAM,aAAN,MAAiB;AAAA,EACZ,OAAA;AAAA,EACA,OAAA;AAAA,EACA,aAAA;AAAA,EACA,QAAA;AAAA,EAER,YAAY,MAAA,EAA0B;AAClC,IAAA,IAAA,CAAK,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/C,IAAA,IAAA,CAAK,OAAA,GAAU,OAAO,OAAA,IAAW,GAAA;AACjC,IAAA,IAAA,CAAK,aAAA,GAAgB,OAAO,aAAA,IAAiB,CAAA;AAC7C,IAAA,IAAA,CAAK,WAAW,MAAA,CAAO,QAAA;AAAA,EAC3B;AAAA,EAEA,MAAM,OAAA,CAAW,IAAA,EAAc,OAAA,GAA0B,EAAC,EAAe;AACrE,IAAA,MAAM,GAAA,GAAM,CAAA,EAAG,IAAA,CAAK,OAAO,CAAA,EAAG,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,GAAI,IAAA,GAAO,GAAA,GAAM,IAAI,CAAA,CAAA;AACtE,IAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA;AAE3C,IAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,cAAc,CAAA,EAAG;AAC9B,MAAA,OAAA,CAAQ,GAAA,CAAI,gBAAgB,kBAAkB,CAAA;AAAA,IAClD;AAEA,IAAA,IAAI,CAAC,OAAA,CAAQ,QAAA,IAAY,IAAA,CAAK,QAAA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;AAAA,EAEA,OAAA,GAAgB;AACZ,IAAA,IAAA,CAAK,KAAK,MAAA,EAAO;AACjB,IAAA,IAAA,CAAK,SAAS,KAAA,EAAM;AAAA,EACxB;AACJ","file":"index.js","sourcesContent":["import { NetworkError, AuthError, UPSError } from './errors';\n\ninterface HttpClientConfig {\n baseUrl: string;\n timeout?: number;\n retryAttempts?: number;\n getToken?: () => string | null;\n}\n\ninterface RequestOptions extends RequestInit {\n skipAuth?: boolean;\n}\n\nexport class HttpClient {\n private baseUrl: string;\n private timeout: number;\n private retryAttempts: number;\n private getToken?: () => string | null;\n\n constructor(config: HttpClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, '');\n this.timeout = config.timeout || 30000;\n this.retryAttempts = config.retryAttempts ?? 3;\n this.getToken = config.getToken;\n }\n\n async request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n const url = `${this.baseUrl}${path.startsWith('/') ? path : '/' + path}`;\n const headers = new Headers(options.headers);\n\n if (!headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (!options.skipAuth && this.getToken) {\n const token = this.getToken();\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n }\n\n const config: RequestInit = {\n ...options,\n headers,\n };\n\n let lastError: Error | null = null;\n for (let attempt = 0; attempt <= this.retryAttempts; attempt++) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(url, {\n ...config,\n signal: controller.signal,\n });\n\n if (response.status === 429) {\n const retryAfter = response.headers.get('Retry-After');\n const waitTime = retryAfter ? parseInt(retryAfter, 10) * 1000 : Math.pow(2, attempt) * 1000;\n await this.delay(waitTime);\n continue;\n }\n\n if (response.status === 401) {\n throw new AuthError('Authentication failed');\n }\n\n if (!response.ok) {\n let errorDetails;\n const text = await response.text();\n try {\n errorDetails = JSON.parse(text);\n } catch {\n errorDetails = text;\n }\n const detailsStr = typeof errorDetails === 'string' ? errorDetails : JSON.stringify(errorDetails);\n throw new NetworkError(`Request failed with status ${response.status}: ${detailsStr}`, errorDetails, response.status);\n }\n\n // Handle 204 No Content\n if (response.status === 204) {\n return undefined as unknown as T;\n }\n\n return await response.json();\n } finally {\n clearTimeout(timeoutId);\n }\n } catch (error: unknown) {\n lastError = error as Error;\n\n if (error instanceof AuthError) {\n throw error;\n }\n\n const e = error as Error;\n\n if (e.name === 'AbortError') {\n lastError = new NetworkError('Request timed out', e);\n } else if (!(e instanceof NetworkError) && !(e instanceof UPSError)) {\n // Wrap unknown errors\n lastError = new NetworkError(e.message || 'Unknown error', e);\n }\n\n if (attempt < this.retryAttempts) {\n const waitTime = Math.pow(2, attempt) * 1000;\n await this.delay(waitTime);\n continue;\n }\n }\n }\n\n throw lastError || new NetworkError('Request failed after retries');\n }\n\n async get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(path, { ...options, method: 'GET' });\n }\n\n async post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {\n return this.request<T>(path, {\n ...options,\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","type Callback<T = any> = (payload: T) => void;\ntype Unsubscribe = () => void;\n\nexport class EventBus {\n private listeners: Map<string, Set<Callback>> = new Map();\n\n emit<T>(event: string, payload: T): void {\n const callbacks = this.listeners.get(event);\n if (callbacks) {\n callbacks.forEach((callback) => {\n try {\n callback(payload);\n } catch (error) {\n console.error(`Error in event handler for ${event}:`, error);\n }\n });\n }\n }\n\n on<T>(event: string, callback: Callback<T>): Unsubscribe {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(callback);\n\n return () => this.off(event, callback);\n }\n\n once<T>(event: string, callback: Callback<T>): Unsubscribe {\n const unsubscribe = this.on<T>(event, (payload) => {\n unsubscribe();\n callback(payload);\n });\n return unsubscribe;\n }\n\n off(event: string, callback: Callback): void {\n const callbacks = this.listeners.get(event);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.listeners.delete(event);\n }\n }\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n","import { HttpClient } from './http-client';\nimport { EventBus } from './event-bus';\nimport { AuthState, AuthResult, ConnectResult, User } from '../types';\n\nexport class AuthManager {\n private _state: AuthState = {\n isAuthenticated: false,\n token: null,\n expiresAt: null,\n address: null,\n };\n private refreshTimer: NodeJS.Timeout | null = null;\n private refreshInterval: number;\n\n constructor(\n private http: HttpClient,\n private eventBus: EventBus,\n refreshInterval: number = 60000 // Default 1 minute\n ) {\n this.refreshInterval = refreshInterval;\n }\n\n get state(): AuthState {\n return { ...this._state };\n }\n\n /**\n * Unified connect method - creates user if new, authenticates if existing\n * This is the preferred authentication method.\n */\n async connect(walletAddress: string, message: string, signature: string): Promise<ConnectResult> {\n const result = await this.http.post<{ user: unknown; token: string; expires_at: string; is_new_user?: boolean }>('/auth/connect', {\n wallet_address: walletAddress,\n message,\n signature,\n }, { skipAuth: true });\n\n const connectResult: ConnectResult = {\n user: this.mapUser(result.user),\n token: result.token,\n expiresAt: result.expires_at,\n isNewUser: result.is_new_user ?? false,\n };\n\n this.handleAuthSuccess({ token: result.token, expiresAt: result.expires_at }, walletAddress);\n return connectResult;\n }\n\n /**\n * @deprecated Use connect() instead\n */\n async login(walletAddress: string, message: string, signature: string): Promise<AuthResult> {\n const result = await this.http.post<{ token: string; expires_at?: string; expiresAt?: string }>('/auth/login', {\n wallet_address: walletAddress,\n message,\n signature,\n }, { skipAuth: true });\n\n const authResult: AuthResult = {\n token: result.token,\n expiresAt: result.expires_at || result.expiresAt || new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),\n };\n\n this.handleAuthSuccess(authResult, walletAddress);\n return authResult;\n }\n\n /**\n * @deprecated Use connect() instead\n */\n async register(walletAddress: string, message: string, signature: string): Promise<AuthResult> {\n const result = await this.http.post<{ token: string; expires_at?: string; expiresAt?: string }>('/auth/register', {\n wallet_address: walletAddress,\n message,\n signature,\n }, { skipAuth: true });\n\n const authResult: AuthResult = {\n token: result.token,\n expiresAt: result.expires_at || result.expiresAt || new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),\n };\n\n this.handleAuthSuccess(authResult, walletAddress);\n return authResult;\n }\n\n private handleAuthSuccess(result: AuthResult, walletAddress: string) {\n this.updateState({\n isAuthenticated: true,\n token: result.token,\n expiresAt: new Date(result.expiresAt),\n address: walletAddress,\n });\n this.scheduleRefresh();\n }\n\n async refresh(): Promise<void> {\n if (!this._state.token) return;\n\n try {\n const result = await this.http.post<{ token: string; expires_at: string }>('/auth/refresh');\n\n this.updateState({\n ...this._state,\n token: result.token,\n expiresAt: new Date(result.expires_at),\n });\n\n this.scheduleRefresh();\n } catch (error) {\n console.error('Token refresh failed:', error);\n this.logout();\n }\n }\n\n private mapUser(data: any): User {\n const d = data as any;\n return {\n id: d.id,\n walletAddress: d.wallet_address,\n status: d.status,\n createdAt: d.created_at,\n };\n }\n\n logout(): void {\n if (this.refreshTimer) {\n clearTimeout(this.refreshTimer);\n this.refreshTimer = null;\n }\n\n this.updateState({\n isAuthenticated: false,\n token: null,\n expiresAt: null,\n address: null,\n });\n }\n\n getToken(): string | null {\n return this._state.token;\n }\n\n isAuthenticated(): boolean {\n return this._state.isAuthenticated;\n }\n\n onStateChange(callback: (state: AuthState) => void): () => void {\n return this.eventBus.on('auth:changed', callback);\n }\n\n private updateState(newState: AuthState) {\n this._state = newState;\n this.eventBus.emit('auth:changed', this._state);\n }\n\n private scheduleRefresh() {\n if (this.refreshTimer) {\n clearTimeout(this.refreshTimer);\n }\n\n if (!this._state.expiresAt) return;\n\n const expiresAt = this._state.expiresAt.getTime();\n const now = Date.now();\n\n // If token is already expired, don't schedule refresh\n if (expiresAt <= now) {\n return;\n }\n\n // Schedule refresh at the configured interval (e.g., 1 hour)\n // But ensure we refresh before the token expires\n const timeUntilExpiry = expiresAt - now;\n const refreshTime = Math.min(this.refreshInterval, timeUntilExpiry - 60000); // At least 1 min buffer\n\n if (refreshTime > 0) {\n this.refreshTimer = setTimeout(() => this.refresh(), refreshTime);\n }\n }\n}\n","import { HttpClient } from '../core/http-client';\nimport { Escrow, EscrowActionResponse } from '../types';\n\nexport class EscrowModule {\n constructor(private http: HttpClient) { }\n\n /**\n * Get escrow details by ID\n * @param escrowId Escrow ID\n */\n async get(escrowId: string): Promise<Escrow> {\n return this.http.get<Escrow>(`/x402/escrow/${escrowId}`, { skipAuth: false });\n }\n\n /**\n * Release escrow funds (Payer or Arbiter only)\n * @param escrowId Escrow ID\n */\n async release(escrowId: string, network: string): Promise<EscrowActionResponse> {\n return this.http.post<EscrowActionResponse>(`/x402/escrow/${escrowId}/release`, {\n network\n });\n }\n\n /**\n * Refund escrow funds (Arbiter only)\n * @param escrowId Escrow ID\n */\n async refund(escrowId: string, network: string): Promise<EscrowActionResponse> {\n return this.http.post<EscrowActionResponse>(`/x402/escrow/${escrowId}/refund`, {\n network\n });\n }\n}\n","import { HttpClient } from '../core/http-client';\nimport {\n CreateInvoiceRequest,\n InvoiceResponse,\n InvoiceListResponse\n} from '../types';\n\nexport class InvoiceModule {\n constructor(private http: HttpClient) { }\n\n /**\n * Create a new invoice\n * @param request Invoice creation details\n */\n async create(request: CreateInvoiceRequest): Promise<InvoiceResponse> {\n return this.http.post<InvoiceResponse>('/invoices', request);\n }\n\n /**\n * Get invoice by ID\n * @param id Invoice ID\n */\n async get(id: string): Promise<InvoiceResponse> {\n return this.http.get<InvoiceResponse>(`/invoices/${id}`);\n }\n\n /**\n * List invoices\n * @param params Filter parameters\n */\n async list(params?: { merchant?: string; payer?: string; page_size?: number; page_token?: string }): Promise<InvoiceListResponse> {\n const query = new URLSearchParams();\n if (params?.merchant) query.append('merchant', params.merchant);\n if (params?.payer) query.append('payer', params.payer);\n if (params?.page_size) query.append('page_size', params.page_size.toString());\n if (params?.page_token) query.append('page_token', params.page_token);\n\n const queryString = query.toString();\n const path = queryString ? `/invoices?${queryString}` : '/invoices';\n\n return this.http.get<InvoiceListResponse>(path);\n }\n\n /**\n * Cancel invoice\n * @param id Invoice ID\n */\n async cancel(id: string): Promise<InvoiceResponse> {\n return this.http.post<InvoiceResponse>(`/invoices/${id}/cancel`, {});\n }\n}\n","import { HttpClient } from '../core/http-client';\nimport { User } from '../types';\n\n/**\n * UserModule provides access to user profile operations.\n * \n * @example\n * ```typescript\n * const user = await client.user.getCurrentUser();\n * console.log(user.id, user.walletAddress);\n * ```\n */\nexport class UserModule {\n constructor(private http: HttpClient) { }\n\n /**\n * Get the current authenticated user's profile.\n * Requires authentication.\n */\n async getCurrentUser(): Promise<User> {\n const response = await this.http.get<{ user: unknown }>('/users/me');\n return this.mapUser(response.user);\n }\n\n private mapUser(data: any): User {\n const d = data as any;\n return {\n id: d.id,\n walletAddress: d.wallet_address,\n status: d.status,\n createdAt: d.created_at,\n };\n }\n}\n","import { HttpClient } from './core/http-client';\nimport { EventBus } from './core/event-bus';\nimport { AuthManager } from './core/auth-manager';\nimport { WalletModule } from './wallet';\nimport { AccountModule } from './account';\nimport { PaymentModule } from './payment';\nimport { EscrowModule } from './escrow';\nimport { InvoiceModule } from './invoice';\nimport { UserModule } from './user';\nimport { UPSConfig, ConnectedWallet, EIP1193Provider, ConnectResult } from './types';\nimport { WalletError } from './core/errors';\n\nexport class UPSClient {\n readonly config: UPSConfig;\n readonly wallet: WalletModule;\n readonly auth: AuthManager;\n readonly account: AccountModule;\n readonly payment: PaymentModule;\n readonly escrow: EscrowModule;\n readonly invoice: InvoiceModule;\n readonly user: UserModule;\n\n private http: HttpClient;\n private eventBus: EventBus;\n\n constructor(config: UPSConfig) {\n this.config = config;\n\n // Parse chainId if not provided but network is \"eip155:123\"\n if (!this.config.chainId && this.config.network.startsWith('eip155:')) {\n this.config.chainId = parseInt(this.config.network.split(':')[1], 10);\n }\n\n this.eventBus = new EventBus();\n\n this.http = new HttpClient({\n baseUrl: config.baseUrl,\n timeout: config.timeout,\n retryAttempts: config.retryAttempts,\n getToken: () => this.auth.getToken(),\n });\n\n this.auth = new AuthManager(this.http, this.eventBus, config.refreshInterval);\n this.wallet = new WalletModule(this.eventBus);\n this.account = new AccountModule(this.http);\n this.payment = new PaymentModule(this.http, this.wallet);\n this.escrow = new EscrowModule(this.http);\n this.invoice = new InvoiceModule(this.http);\n this.user = new UserModule(this.http);\n }\n\n async connect(provider: EIP1193Provider): Promise<ConnectedWallet> {\n return this.wallet.connect(provider);\n }\n\n /**\n * Authenticate with the UPS backend using the unified /auth/connect endpoint.\n * This will create a new user if one doesn't exist, or authenticate an existing user.\n * \n * @returns ConnectResult containing user info and whether this is a new user\n */\n async authenticate(): Promise<ConnectResult> {\n if (!this.wallet.isConnected()) {\n throw new WalletError('Wallet must be connected to authenticate');\n }\n\n const address = this.wallet.getAddress();\n if (!address) throw new WalletError('No wallet address available');\n\n const message = `Connect to UPSx402`;\n const signature = await this.wallet.signMessage(message);\n\n return this.auth.connect(address, message, signature);\n }\n\n /**\n * @deprecated Use authenticate() instead which uses the unified /auth/connect endpoint.\n * This method uses the legacy login/register flow.\n */\n async authenticateLegacy(): Promise<void> {\n if (!this.wallet.isConnected()) {\n throw new WalletError('Wallet must be connected to authenticate');\n }\n\n const address = this.wallet.getAddress();\n if (!address) throw new WalletError('No wallet address available');\n\n // Try Login\n const loginMessage = `Login to UPSx402`;\n try {\n const signature = await this.wallet.signMessage(loginMessage);\n await this.auth.login(address, loginMessage, signature);\n } catch (error: unknown) {\n // If related to \"User not found\" or 404/401/400, try Register\n const e = error as any; // Cast to any to check specific properties safely\n const isAuthError = e.status === 404 || e.status === 401 || e.status === 400 ||\n e.message?.includes?.('not found') ||\n e.details?.message?.includes?.('not found');\n\n if (isAuthError) {\n const registerMessage = `Register for UPSx402`;\n const signature = await this.wallet.signMessage(registerMessage);\n await this.auth.register(address, registerMessage, signature);\n } else {\n throw error;\n }\n }\n }\n\n async disconnect(): Promise<void> {\n await this.wallet.disconnect();\n this.auth.logout();\n }\n\n destroy(): void {\n this.auth.logout(); // Clears refresh timer\n this.eventBus.clear();\n }\n}\n"]}
|