@rendomnet/apiservice 1.3.8 → 1.4.1

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,358 @@
1
+ interface OAuthToken {
2
+ access_token: string;
3
+ expires_in: number;
4
+ id_token: string;
5
+ refresh_token: string;
6
+ scope: string;
7
+ token_type: string;
8
+ }
9
+ interface Token {
10
+ accountId: string;
11
+ access_token: string;
12
+ refresh_token: string;
13
+ provider: string;
14
+ enabled?: boolean;
15
+ updatedAt?: string;
16
+ primary?: boolean;
17
+ }
18
+ interface AccountData {
19
+ lastRequestTime?: number;
20
+ lastFailed?: boolean;
21
+ token?: Token;
22
+ }
23
+ interface DelayStrategy {
24
+ calculate: (attempt: number, response?: any) => number;
25
+ }
26
+ interface ApiCallParams {
27
+ accountId: string;
28
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
29
+ route: string;
30
+ base?: string;
31
+ body?: object;
32
+ data?: object;
33
+ headers?: Record<string, string>;
34
+ queryParams?: URLSearchParams;
35
+ accessToken?: string;
36
+ useAuth?: boolean;
37
+ noContentType?: boolean;
38
+ contentType?: string;
39
+ cacheTime?: number;
40
+ files?: File[];
41
+ abortSignal?: AbortSignal;
42
+ }
43
+ interface HookSettings {
44
+ /**
45
+ * Whether to retry the API call when this hook is triggered
46
+ */
47
+ shouldRetry: boolean;
48
+ /**
49
+ * Whether to apply delay between retries
50
+ */
51
+ useRetryDelay: boolean;
52
+ /**
53
+ * The maximum number of retry attempts for this status code
54
+ */
55
+ maxRetries?: number;
56
+ /**
57
+ * Wait for an existing hook to complete before starting a new one
58
+ * Useful for avoiding duplicate refresh token calls
59
+ */
60
+ preventConcurrentCalls?: boolean;
61
+ /**
62
+ * The main handler function called when this status code is encountered
63
+ * Return an object to update the API call parameters for the retry
64
+ */
65
+ handler: (accountId: string, response: any) => Promise<any>;
66
+ /**
67
+ * Called when all retry attempts for this status code have failed
68
+ */
69
+ onMaxRetriesExceeded?: (accountId: string, error: any) => Promise<void>;
70
+ /**
71
+ * Called when the handler function throws an error
72
+ */
73
+ onHandlerError?: (accountId: string, error: any) => Promise<void>;
74
+ /**
75
+ * Custom strategy for calculating delay between retries
76
+ */
77
+ delayStrategy?: DelayStrategy;
78
+ /**
79
+ * Maximum delay in milliseconds between retries
80
+ */
81
+ maxDelay?: number;
82
+ }
83
+ type StatusCode = string | number;
84
+ interface AuthProvider {
85
+ /**
86
+ * Returns headers or other auth data for a request
87
+ */
88
+ getAuthHeaders(accountId?: string): Promise<Record<string, string>>;
89
+ /**
90
+ * Optional: refresh credentials if supported (for OAuth, etc.)
91
+ */
92
+ refresh?(refreshToken: string, accountId?: string): Promise<any>;
93
+ }
94
+ interface ApiKeyAuthProviderOptions {
95
+ apiKey: string;
96
+ headerName?: string;
97
+ queryParamName?: string;
98
+ }
99
+ interface BasicAuthProviderOptions {
100
+ username: string;
101
+ password: string;
102
+ }
103
+ type TokenService$1 = {
104
+ get: (accountId?: string) => Promise<Token>;
105
+ set: (token: Partial<Token>, accountId?: string) => Promise<void>;
106
+ refresh?: (refreshToken: string, accountId?: string) => Promise<OAuthToken>;
107
+ };
108
+
109
+ declare class FetchError extends Error {
110
+ name: string;
111
+ status: number;
112
+ code: string;
113
+ message: string;
114
+ data: any;
115
+ constructor(response: Response, data?: any, code?: string);
116
+ }
117
+
118
+ /**
119
+ * Handles caching of API responses
120
+ */
121
+ declare class CacheManager {
122
+ private cache;
123
+ private cacheTime;
124
+ /**
125
+ * Get data from cache if available and not expired
126
+ */
127
+ getFromCache(apiCallParams: ApiCallParams): any;
128
+ /**
129
+ * Save data to cache
130
+ */
131
+ saveToCache(apiCallParams: ApiCallParams, data: any): void;
132
+ /**
133
+ * Generate a unique key for caching based on request parameters
134
+ */
135
+ private getRequestKey;
136
+ /**
137
+ * Set the default cache time in milliseconds
138
+ */
139
+ setCacheTime(milliseconds: number): void;
140
+ /**
141
+ * Clear the entire cache
142
+ */
143
+ clearCache(): void;
144
+ }
145
+
146
+ /**
147
+ * Handles retry logic and delay strategies for failed API calls
148
+ */
149
+ declare class RetryManager {
150
+ private defaultMaxDelay;
151
+ private defaultMaxRetries;
152
+ /**
153
+ * Default exponential backoff strategy with full jitter
154
+ */
155
+ private defaultDelayStrategy;
156
+ /**
157
+ * Calculate and wait for appropriate delay time before retry
158
+ */
159
+ calculateAndDelay(params: {
160
+ attempt: number;
161
+ response?: any;
162
+ hook: HookSettings;
163
+ }): Promise<void>;
164
+ /**
165
+ * Extract retry-after value from response
166
+ */
167
+ private getRetryAfterValue;
168
+ /**
169
+ * Get the default maximum number of retries
170
+ */
171
+ getDefaultMaxRetries(): number;
172
+ /**
173
+ * Set the default maximum number of retries
174
+ */
175
+ setDefaultMaxRetries(maxRetries: number): void;
176
+ /**
177
+ * Set the default maximum delay between retries
178
+ */
179
+ setDefaultMaxDelay(maxDelay: number): void;
180
+ }
181
+
182
+ /**
183
+ * Manages hooks for different status codes and their processing
184
+ */
185
+ declare class HookManager {
186
+ private hooks;
187
+ private hookPromises;
188
+ /**
189
+ * Set hooks for different status codes
190
+ */
191
+ setHooks(hooks: Record<StatusCode, HookSettings>): void;
192
+ /**
193
+ * Get a hook for a specific status code
194
+ */
195
+ getHook(status: StatusCode): HookSettings | undefined;
196
+ /**
197
+ * Process a hook for a specific status code
198
+ */
199
+ processHook(accountId: string, status: StatusCode, error: any): Promise<Record<string, any> | null>;
200
+ /**
201
+ * Handle a retry failure with the appropriate hook
202
+ */
203
+ handleRetryFailure(accountId: string, status: StatusCode, error: any): Promise<void>;
204
+ /**
205
+ * Check if a hook exists and should retry for a given status
206
+ */
207
+ shouldRetry(status: StatusCode): boolean;
208
+ }
209
+
210
+ /**
211
+ * Handles HTTP requests to external APIs
212
+ */
213
+ declare class HttpClient {
214
+ /**
215
+ * Make an HTTP request
216
+ */
217
+ makeRequest(apiParams: ApiCallParams, authToken: Token | Record<string, any>): Promise<any>;
218
+ /**
219
+ * Build URL with query parameters
220
+ */
221
+ private buildUrl;
222
+ /**
223
+ * Prepare form data for file uploads
224
+ */
225
+ private prepareFormData;
226
+ /**
227
+ * Build fetch options for request
228
+ */
229
+ private buildFetchOptions;
230
+ /**
231
+ * Handle API response
232
+ */
233
+ private handleResponse;
234
+ }
235
+
236
+ /**
237
+ * Manages account data and state
238
+ */
239
+ declare class AccountManager {
240
+ private accounts;
241
+ private readonly DEFAULT_ACCOUNT;
242
+ /**
243
+ * Update account data for a specific account
244
+ */
245
+ updateAccountData(accountId: string | undefined, data: Partial<AccountData>): void;
246
+ /**
247
+ * Get account data for a specific account
248
+ */
249
+ getAccountData(accountId?: string): AccountData;
250
+ /**
251
+ * Check if an account's last request failed
252
+ */
253
+ didLastRequestFail(accountId?: string): boolean;
254
+ /**
255
+ * Set account's last request as failed
256
+ */
257
+ setLastRequestFailed(accountId?: string, failed?: boolean): void;
258
+ /**
259
+ * Update the last request time for an account
260
+ */
261
+ updateLastRequestTime(accountId?: string): void;
262
+ }
263
+
264
+ type TokenService = {
265
+ get: (accountId?: string) => Promise<Token>;
266
+ set: (token: Partial<Token>, accountId?: string) => Promise<void>;
267
+ refresh?: (refreshToken: string, accountId?: string) => Promise<OAuthToken>;
268
+ };
269
+ declare class TokenAuthProvider implements AuthProvider {
270
+ private tokenService;
271
+ constructor(tokenService: TokenService);
272
+ getAuthHeaders(accountId?: string): Promise<Record<string, string>>;
273
+ refresh(accountId: string): Promise<void>;
274
+ }
275
+
276
+ declare class ApiKeyAuthProvider implements AuthProvider {
277
+ private apiKey;
278
+ private headerName?;
279
+ private queryParamName?;
280
+ constructor(options: ApiKeyAuthProviderOptions);
281
+ getAuthHeaders(): Promise<Record<string, string>>;
282
+ }
283
+
284
+ declare class BasicAuthProvider implements AuthProvider {
285
+ private username;
286
+ private password;
287
+ constructor(options: BasicAuthProviderOptions);
288
+ getAuthHeaders(): Promise<Record<string, string>>;
289
+ }
290
+
291
+ /**
292
+ * ApiService - Core API service for making authenticated API calls
293
+ * with caching, retry, and hook support.
294
+ */
295
+ declare class ApiService {
296
+ provider: string;
297
+ private authProvider;
298
+ private baseUrl;
299
+ private cacheManager;
300
+ private retryManager;
301
+ private hookManager;
302
+ private httpClient;
303
+ private accountManager;
304
+ private maxAttempts;
305
+ constructor();
306
+ /**
307
+ * Setup the API service
308
+ */
309
+ setup({ provider, authProvider, hooks, cacheTime, baseUrl, }: {
310
+ provider: string;
311
+ authProvider: AuthProvider;
312
+ hooks?: Record<StatusCode, HookSettings | null>;
313
+ cacheTime: number;
314
+ baseUrl?: string;
315
+ }): void;
316
+ /**
317
+ * Create a default handler for 401 (Unauthorized) errors
318
+ * that implements standard credential refresh behavior
319
+ */
320
+ private createDefaultAuthRefreshHandler;
321
+ /**
322
+ * Set the maximum number of retry attempts
323
+ */
324
+ setMaxAttempts(attempts: number): void;
325
+ /**
326
+ * Update account data
327
+ */
328
+ updateAccountData(accountId: string, data: Partial<Record<string, any>>): void;
329
+ /**
330
+ * Make an API call with all features (caching, retry, hooks)
331
+ */
332
+ call(apiCallParams: Omit<ApiCallParams, 'accountId'> & {
333
+ accountId?: string;
334
+ abortSignal?: AbortSignal;
335
+ }): Promise<any>;
336
+ /**
337
+ * Legacy method for backward compatibility
338
+ * @deprecated Use call() instead
339
+ */
340
+ makeApiCall(apiCallParams: Omit<ApiCallParams, 'accountId'> & {
341
+ accountId?: string;
342
+ abortSignal?: AbortSignal;
343
+ }): Promise<any>;
344
+ /**
345
+ * Make a request with retry capability
346
+ */
347
+ private makeRequestWithRetry;
348
+ /**
349
+ * Set the cache time in milliseconds
350
+ */
351
+ setCacheTime(milliseconds: number): void;
352
+ /**
353
+ * Clear the cache
354
+ */
355
+ clearCache(): void;
356
+ }
357
+
358
+ export { type AccountData, AccountManager, type ApiCallParams, ApiKeyAuthProvider, type ApiKeyAuthProviderOptions, type AuthProvider, BasicAuthProvider, type BasicAuthProviderOptions, CacheManager, type DelayStrategy, FetchError, HookManager, type HookSettings, HttpClient, type OAuthToken, RetryManager, type StatusCode, type Token, TokenAuthProvider, type TokenService$1 as TokenService, ApiService as default };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,293 @@
1
- import { AuthProvider, ApiCallParams, HookSettings, StatusCode } from './types';
1
+ interface OAuthToken {
2
+ access_token: string;
3
+ expires_in: number;
4
+ id_token: string;
5
+ refresh_token: string;
6
+ scope: string;
7
+ token_type: string;
8
+ }
9
+ interface Token {
10
+ accountId: string;
11
+ access_token: string;
12
+ refresh_token: string;
13
+ provider: string;
14
+ enabled?: boolean;
15
+ updatedAt?: string;
16
+ primary?: boolean;
17
+ }
18
+ interface AccountData {
19
+ lastRequestTime?: number;
20
+ lastFailed?: boolean;
21
+ token?: Token;
22
+ }
23
+ interface DelayStrategy {
24
+ calculate: (attempt: number, response?: any) => number;
25
+ }
26
+ interface ApiCallParams {
27
+ accountId: string;
28
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
29
+ route: string;
30
+ base?: string;
31
+ body?: object;
32
+ data?: object;
33
+ headers?: Record<string, string>;
34
+ queryParams?: URLSearchParams;
35
+ accessToken?: string;
36
+ useAuth?: boolean;
37
+ noContentType?: boolean;
38
+ contentType?: string;
39
+ cacheTime?: number;
40
+ files?: File[];
41
+ abortSignal?: AbortSignal;
42
+ }
43
+ interface HookSettings {
44
+ /**
45
+ * Whether to retry the API call when this hook is triggered
46
+ */
47
+ shouldRetry: boolean;
48
+ /**
49
+ * Whether to apply delay between retries
50
+ */
51
+ useRetryDelay: boolean;
52
+ /**
53
+ * The maximum number of retry attempts for this status code
54
+ */
55
+ maxRetries?: number;
56
+ /**
57
+ * Wait for an existing hook to complete before starting a new one
58
+ * Useful for avoiding duplicate refresh token calls
59
+ */
60
+ preventConcurrentCalls?: boolean;
61
+ /**
62
+ * The main handler function called when this status code is encountered
63
+ * Return an object to update the API call parameters for the retry
64
+ */
65
+ handler: (accountId: string, response: any) => Promise<any>;
66
+ /**
67
+ * Called when all retry attempts for this status code have failed
68
+ */
69
+ onMaxRetriesExceeded?: (accountId: string, error: any) => Promise<void>;
70
+ /**
71
+ * Called when the handler function throws an error
72
+ */
73
+ onHandlerError?: (accountId: string, error: any) => Promise<void>;
74
+ /**
75
+ * Custom strategy for calculating delay between retries
76
+ */
77
+ delayStrategy?: DelayStrategy;
78
+ /**
79
+ * Maximum delay in milliseconds between retries
80
+ */
81
+ maxDelay?: number;
82
+ }
83
+ type StatusCode = string | number;
84
+ interface AuthProvider {
85
+ /**
86
+ * Returns headers or other auth data for a request
87
+ */
88
+ getAuthHeaders(accountId?: string): Promise<Record<string, string>>;
89
+ /**
90
+ * Optional: refresh credentials if supported (for OAuth, etc.)
91
+ */
92
+ refresh?(refreshToken: string, accountId?: string): Promise<any>;
93
+ }
94
+ interface ApiKeyAuthProviderOptions {
95
+ apiKey: string;
96
+ headerName?: string;
97
+ queryParamName?: string;
98
+ }
99
+ interface BasicAuthProviderOptions {
100
+ username: string;
101
+ password: string;
102
+ }
103
+ type TokenService$1 = {
104
+ get: (accountId?: string) => Promise<Token>;
105
+ set: (token: Partial<Token>, accountId?: string) => Promise<void>;
106
+ refresh?: (refreshToken: string, accountId?: string) => Promise<OAuthToken>;
107
+ };
108
+
109
+ declare class FetchError extends Error {
110
+ name: string;
111
+ status: number;
112
+ code: string;
113
+ message: string;
114
+ data: any;
115
+ constructor(response: Response, data?: any, code?: string);
116
+ }
117
+
118
+ /**
119
+ * Handles caching of API responses
120
+ */
121
+ declare class CacheManager {
122
+ private cache;
123
+ private cacheTime;
124
+ /**
125
+ * Get data from cache if available and not expired
126
+ */
127
+ getFromCache(apiCallParams: ApiCallParams): any;
128
+ /**
129
+ * Save data to cache
130
+ */
131
+ saveToCache(apiCallParams: ApiCallParams, data: any): void;
132
+ /**
133
+ * Generate a unique key for caching based on request parameters
134
+ */
135
+ private getRequestKey;
136
+ /**
137
+ * Set the default cache time in milliseconds
138
+ */
139
+ setCacheTime(milliseconds: number): void;
140
+ /**
141
+ * Clear the entire cache
142
+ */
143
+ clearCache(): void;
144
+ }
145
+
146
+ /**
147
+ * Handles retry logic and delay strategies for failed API calls
148
+ */
149
+ declare class RetryManager {
150
+ private defaultMaxDelay;
151
+ private defaultMaxRetries;
152
+ /**
153
+ * Default exponential backoff strategy with full jitter
154
+ */
155
+ private defaultDelayStrategy;
156
+ /**
157
+ * Calculate and wait for appropriate delay time before retry
158
+ */
159
+ calculateAndDelay(params: {
160
+ attempt: number;
161
+ response?: any;
162
+ hook: HookSettings;
163
+ }): Promise<void>;
164
+ /**
165
+ * Extract retry-after value from response
166
+ */
167
+ private getRetryAfterValue;
168
+ /**
169
+ * Get the default maximum number of retries
170
+ */
171
+ getDefaultMaxRetries(): number;
172
+ /**
173
+ * Set the default maximum number of retries
174
+ */
175
+ setDefaultMaxRetries(maxRetries: number): void;
176
+ /**
177
+ * Set the default maximum delay between retries
178
+ */
179
+ setDefaultMaxDelay(maxDelay: number): void;
180
+ }
181
+
182
+ /**
183
+ * Manages hooks for different status codes and their processing
184
+ */
185
+ declare class HookManager {
186
+ private hooks;
187
+ private hookPromises;
188
+ /**
189
+ * Set hooks for different status codes
190
+ */
191
+ setHooks(hooks: Record<StatusCode, HookSettings>): void;
192
+ /**
193
+ * Get a hook for a specific status code
194
+ */
195
+ getHook(status: StatusCode): HookSettings | undefined;
196
+ /**
197
+ * Process a hook for a specific status code
198
+ */
199
+ processHook(accountId: string, status: StatusCode, error: any): Promise<Record<string, any> | null>;
200
+ /**
201
+ * Handle a retry failure with the appropriate hook
202
+ */
203
+ handleRetryFailure(accountId: string, status: StatusCode, error: any): Promise<void>;
204
+ /**
205
+ * Check if a hook exists and should retry for a given status
206
+ */
207
+ shouldRetry(status: StatusCode): boolean;
208
+ }
209
+
210
+ /**
211
+ * Handles HTTP requests to external APIs
212
+ */
213
+ declare class HttpClient {
214
+ /**
215
+ * Make an HTTP request
216
+ */
217
+ makeRequest(apiParams: ApiCallParams, authToken: Token | Record<string, any>): Promise<any>;
218
+ /**
219
+ * Build URL with query parameters
220
+ */
221
+ private buildUrl;
222
+ /**
223
+ * Prepare form data for file uploads
224
+ */
225
+ private prepareFormData;
226
+ /**
227
+ * Build fetch options for request
228
+ */
229
+ private buildFetchOptions;
230
+ /**
231
+ * Handle API response
232
+ */
233
+ private handleResponse;
234
+ }
235
+
236
+ /**
237
+ * Manages account data and state
238
+ */
239
+ declare class AccountManager {
240
+ private accounts;
241
+ private readonly DEFAULT_ACCOUNT;
242
+ /**
243
+ * Update account data for a specific account
244
+ */
245
+ updateAccountData(accountId: string | undefined, data: Partial<AccountData>): void;
246
+ /**
247
+ * Get account data for a specific account
248
+ */
249
+ getAccountData(accountId?: string): AccountData;
250
+ /**
251
+ * Check if an account's last request failed
252
+ */
253
+ didLastRequestFail(accountId?: string): boolean;
254
+ /**
255
+ * Set account's last request as failed
256
+ */
257
+ setLastRequestFailed(accountId?: string, failed?: boolean): void;
258
+ /**
259
+ * Update the last request time for an account
260
+ */
261
+ updateLastRequestTime(accountId?: string): void;
262
+ }
263
+
264
+ type TokenService = {
265
+ get: (accountId?: string) => Promise<Token>;
266
+ set: (token: Partial<Token>, accountId?: string) => Promise<void>;
267
+ refresh?: (refreshToken: string, accountId?: string) => Promise<OAuthToken>;
268
+ };
269
+ declare class TokenAuthProvider implements AuthProvider {
270
+ private tokenService;
271
+ constructor(tokenService: TokenService);
272
+ getAuthHeaders(accountId?: string): Promise<Record<string, string>>;
273
+ refresh(accountId: string): Promise<void>;
274
+ }
275
+
276
+ declare class ApiKeyAuthProvider implements AuthProvider {
277
+ private apiKey;
278
+ private headerName?;
279
+ private queryParamName?;
280
+ constructor(options: ApiKeyAuthProviderOptions);
281
+ getAuthHeaders(): Promise<Record<string, string>>;
282
+ }
283
+
284
+ declare class BasicAuthProvider implements AuthProvider {
285
+ private username;
286
+ private password;
287
+ constructor(options: BasicAuthProviderOptions);
288
+ getAuthHeaders(): Promise<Record<string, string>>;
289
+ }
290
+
2
291
  /**
3
292
  * ApiService - Core API service for making authenticated API calls
4
293
  * with caching, retry, and hook support.
@@ -65,4 +354,5 @@ declare class ApiService {
65
354
  */
66
355
  clearCache(): void;
67
356
  }
68
- export default ApiService;
357
+
358
+ export { type AccountData, AccountManager, type ApiCallParams, ApiKeyAuthProvider, type ApiKeyAuthProviderOptions, type AuthProvider, BasicAuthProvider, type BasicAuthProviderOptions, CacheManager, type DelayStrategy, FetchError, HookManager, type HookSettings, HttpClient, type OAuthToken, RetryManager, type StatusCode, type Token, TokenAuthProvider, type TokenService$1 as TokenService, ApiService as default };