@kivacore/api-client 0.0.0 → 0.3.8

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/package.json CHANGED
@@ -1,10 +1,47 @@
1
1
  {
2
2
  "name": "@kivacore/api-client",
3
- "version": "0.0.0",
4
- "description": "Placeholder that lets CI publish this package with npm trusted publishing. Install the latest version.",
3
+ "version": "0.3.8",
5
4
  "repository": {
6
5
  "type": "git",
7
6
  "url": "https://github.com/Docyrus/docyrus-devkit.git",
8
7
  "directory": "packages/api-client"
8
+ },
9
+ "type": "module",
10
+ "main": "./dist/index.js",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "import": "./dist/index.js",
16
+ "types": "./dist/index.d.ts"
17
+ },
18
+ "./react-native": {
19
+ "import": "./dist/react-native/index.js",
20
+ "types": "./dist/react-native/index.d.ts"
21
+ }
22
+ },
23
+ "peerDependencies": {
24
+ "expo-crypto": ">=14.0.0"
25
+ },
26
+ "peerDependenciesMeta": {
27
+ "expo-crypto": {
28
+ "optional": true
29
+ }
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "26.6.6",
33
+ "tsup": "9.0.0",
34
+ "typescript": "7.0.2",
35
+ "vitest": "5.1.0"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "dev": "tsup --watch",
40
+ "lint": "eslint src",
41
+ "format": "eslint src --fix",
42
+ "typecheck": "eslint src && tsc --noEmit",
43
+ "test": "vitest run --passWithNoTests",
44
+ "test:watch": "vitest",
45
+ "deploy": "pnpm run build && pnpm publish --access public"
9
46
  }
10
- }
47
+ }
@@ -0,0 +1,570 @@
1
+ import {
2
+ type ApiClientConfig,
3
+ type RequestConfig,
4
+ type ApiResponse,
5
+ type Interceptor,
6
+ type TokenManager,
7
+ type HttpMethod,
8
+ type QueryParamValue,
9
+ type StreamOptions
10
+ } from '../core/types';
11
+
12
+ import {
13
+ ApiError,
14
+ NetworkError,
15
+ AbortError,
16
+ AuthenticationError,
17
+ AuthorizationError,
18
+ NotFoundError,
19
+ RateLimitError,
20
+ ServerError,
21
+ ValidationError,
22
+ ConflictError
23
+ } from '../core/errors';
24
+ import {
25
+ buildUrl,
26
+ createAbortSignal,
27
+ isAbortError,
28
+ withRetry,
29
+ isFormData,
30
+ isBlob,
31
+ isStream
32
+ } from '../core/utils';
33
+ import { MemoryTokenManager } from '../core/token-manager';
34
+
35
+ export abstract class BaseApiClient {
36
+ protected baseURL: string;
37
+ protected tokenManager: TokenManager;
38
+ protected interceptors: Interceptor[] = [];
39
+ protected defaultHeaders: Record<string, string> = {};
40
+ protected fetchImpl: typeof fetch;
41
+ protected FormDataImpl: typeof FormData;
42
+ protected AbortControllerImpl: typeof AbortController;
43
+ protected storage?: Storage;
44
+ protected defaultTimeout?: number;
45
+ protected downloadHandler?: (blob: Blob, filename: string) => Promise<void> | void;
46
+ constructor(config: ApiClientConfig = {}) {
47
+ this.baseURL = config.baseURL || '';
48
+ this.tokenManager = config.tokenManager || new MemoryTokenManager();
49
+ this.defaultHeaders = config.headers || {};
50
+ this.defaultTimeout = config.timeout;
51
+ this.downloadHandler = config.downloadHandler;
52
+
53
+ /*
54
+ * Use provided implementations or global ones
55
+ * Important: bind fetch to the global object to avoid
56
+ * "Illegal invocation" when called as a method (this.fetchImpl(...)) in browsers
57
+ */
58
+ const rawFetch = (config.fetch || globalThis.fetch) as typeof fetch | undefined;
59
+
60
+ if (!rawFetch) {
61
+ throw new Error('Fetch API is not available. Please provide a fetch implementation.');
62
+ }
63
+ this.fetchImpl = rawFetch.bind(globalThis);
64
+ this.FormDataImpl = config.FormData || globalThis.FormData;
65
+ this.AbortControllerImpl = config.AbortController || globalThis.AbortController;
66
+ this.storage = config.storage;
67
+
68
+ if (!this.fetchImpl) {
69
+ throw new Error('Fetch API is not available. Please provide a fetch implementation.');
70
+ }
71
+ }
72
+ addInterceptor(interceptor: Interceptor): void {
73
+ this.interceptors.push(interceptor);
74
+ }
75
+ removeInterceptor(interceptor: Interceptor): void {
76
+ const index = this.interceptors.indexOf(interceptor);
77
+
78
+ if (index !== -1) {
79
+ this.interceptors.splice(index, 1);
80
+ }
81
+ }
82
+ async setAccessToken(token: string): Promise<void> {
83
+ const result = this.tokenManager.setToken(token);
84
+
85
+ if (result instanceof Promise) {
86
+ await result;
87
+ }
88
+ }
89
+ async getAccessToken(): Promise<string | null> {
90
+ const result = this.tokenManager.getToken();
91
+
92
+ return result instanceof Promise ? await result : result;
93
+ }
94
+ async clearAccessToken(): Promise<void> {
95
+ const result = this.tokenManager.clearToken();
96
+
97
+ if (result instanceof Promise) {
98
+ await result;
99
+ }
100
+ }
101
+ protected async applyRequestInterceptors(config: RequestConfig): Promise<RequestConfig> {
102
+ let currentConfig = config;
103
+
104
+ for (const interceptor of this.interceptors) {
105
+ if (interceptor.request) {
106
+ currentConfig = await interceptor.request(currentConfig);
107
+ }
108
+ }
109
+
110
+ return currentConfig;
111
+ }
112
+ protected async applyResponseInterceptors<T>(response: ApiResponse<T>): Promise<ApiResponse<T>> {
113
+ let currentResponse = response;
114
+
115
+ for (const interceptor of this.interceptors) {
116
+ if (interceptor.response) {
117
+ currentResponse = await interceptor.response(currentResponse);
118
+ }
119
+ }
120
+
121
+ return currentResponse;
122
+ }
123
+ protected async applyErrorInterceptors(error: Error): Promise<never> {
124
+ let currentError = error;
125
+
126
+ for (const interceptor of this.interceptors) {
127
+ if (interceptor.error) {
128
+ try {
129
+ const result = await interceptor.error(currentError);
130
+
131
+ if (result instanceof Error) {
132
+ currentError = result;
133
+ }
134
+ } catch (e) {
135
+ // If interceptor throws, use that error
136
+ currentError = e as Error;
137
+ }
138
+ }
139
+ }
140
+
141
+ throw currentError;
142
+ }
143
+ protected async prepareHeaders(config: RequestConfig): Promise<Headers> {
144
+ const headers = new Headers(this.defaultHeaders);
145
+
146
+ // Add auth header if token exists
147
+ const token = await this.getAccessToken();
148
+
149
+ if (token) {
150
+ headers.set('Authorization', `Bearer ${token}`);
151
+ }
152
+
153
+ // Add custom headers from config
154
+ if (config.headers) {
155
+ const configHeaders = config.headers instanceof Headers ? config.headers : new Headers(config.headers);
156
+
157
+ configHeaders.forEach((value, key) => {
158
+ headers.set(key, value);
159
+ });
160
+ }
161
+
162
+ // Add session tracking if available (guarded for non-browser environments)
163
+ if (this.storage && typeof globalThis.sessionStorage !== 'undefined') {
164
+ try {
165
+ const tid = globalThis.sessionStorage.getItem('tid');
166
+
167
+ if (tid) {
168
+ headers.set('X-Tid', tid);
169
+ }
170
+ } catch {
171
+ // sessionStorage may throw in some environments (e.g., React Native)
172
+ }
173
+ }
174
+
175
+ return headers;
176
+ }
177
+ protected prepareBody(data: unknown, headers: Headers): BodyInit | undefined {
178
+ if (!data) return undefined;
179
+
180
+ if (isFormData(data) || isBlob(data) || isStream(data)) {
181
+ // Don't set Content-Type for FormData, let browser set it with boundary
182
+ return data as BodyInit;
183
+ }
184
+
185
+ if (typeof data === 'string') {
186
+ headers.set('Content-Type', 'text/plain');
187
+
188
+ return data;
189
+ }
190
+
191
+ // Default to JSON
192
+ headers.set('Content-Type', 'application/json');
193
+
194
+ return JSON.stringify(data);
195
+ }
196
+ protected createApiError(response: Response, errorData?: any): ApiError {
197
+ const { status } = response;
198
+ let message = errorData?.message || errorData?.error || response.statusText;
199
+ const details = errorData?.details || errorData;
200
+
201
+ // Extract error message from various response formats
202
+ if (errorData && typeof errorData === 'object') {
203
+ if (errorData.error && typeof errorData.error === 'object') {
204
+ message = errorData.error.message || JSON.stringify(errorData.error);
205
+ } else if (errorData.message) {
206
+ ({ message } = errorData);
207
+ }
208
+ }
209
+
210
+ // Return specific error types based on status
211
+ switch (status) {
212
+ case 400:
213
+ return new ValidationError(message, details);
214
+
215
+ case 401:
216
+ return new AuthenticationError(message);
217
+
218
+ case 403:
219
+ return new AuthorizationError(message);
220
+
221
+ case 404:
222
+ return new NotFoundError(response.url);
223
+
224
+ case 409:
225
+ return new ConflictError(message, details);
226
+
227
+ case 429:
228
+ return new RateLimitError(details?.retryAfter);
229
+
230
+ default:
231
+ if (status >= 500) {
232
+ return new ServerError(message, status, details);
233
+ }
234
+
235
+ return new ApiError(message, status, undefined, details);
236
+ }
237
+ }
238
+ protected async request<T = unknown>(
239
+ method: HttpMethod,
240
+ endpoint: string,
241
+ data?: unknown,
242
+ config: RequestConfig = {}
243
+ ): Promise<ApiResponse<T>> {
244
+ // Apply request interceptors
245
+ config = await this.applyRequestInterceptors(config);
246
+
247
+ // Build URL with params
248
+ const url = buildUrl(this.baseURL, endpoint, config.params);
249
+
250
+ // Prepare headers
251
+ const headers = await this.prepareHeaders(config);
252
+
253
+ // Prepare body
254
+ const body = ['GET', 'HEAD'].includes(method) ? undefined : this.prepareBody(data, headers);
255
+
256
+ // Create abort signal with timeout
257
+ const { signal, cleanup } = createAbortSignal(
258
+ config.timeout || this.defaultTimeout,
259
+ config.signal || undefined
260
+ );
261
+
262
+ // Build fetch options
263
+ const fetchOptions: RequestInit = {
264
+ ...config,
265
+ method,
266
+ headers,
267
+ body,
268
+ signal
269
+ };
270
+
271
+ const executeRequest = async () => {
272
+ const response = await this.fetchImpl(url, fetchOptions);
273
+
274
+ if (!response.ok) {
275
+ let errorData;
276
+
277
+ try {
278
+ const contentType = response.headers.get('Content-Type') || '';
279
+
280
+ if (contentType.includes('application/json')) {
281
+ errorData = await response.json();
282
+ } else {
283
+ errorData = await response.text();
284
+ }
285
+ } catch {
286
+ // Ignore JSON parse errors
287
+ }
288
+
289
+ throw this.createApiError(response, errorData);
290
+ }
291
+
292
+ // Parse response based on type
293
+ const responseType = config.responseType || 'json';
294
+ let responseData: T;
295
+
296
+ switch (responseType) {
297
+ case 'blob':
298
+ responseData = await response.blob() as T;
299
+ break;
300
+
301
+ case 'text':
302
+ responseData = await response.text() as T;
303
+ break;
304
+
305
+ case 'arrayBuffer':
306
+ responseData = await response.arrayBuffer() as T;
307
+ break;
308
+
309
+ case 'formData':
310
+ responseData = await response.formData() as T;
311
+ break;
312
+
313
+ default:
314
+ try {
315
+ responseData = await response.json() as T;
316
+ } catch {
317
+ responseData = null as T;
318
+ }
319
+ }
320
+
321
+ const apiResponse: ApiResponse<T> = {
322
+ data: responseData,
323
+ headers: response.headers,
324
+ status: response.status,
325
+ statusText: response.statusText
326
+ };
327
+
328
+ // Apply response interceptors
329
+ return await this.applyResponseInterceptors(apiResponse);
330
+ };
331
+
332
+ try {
333
+ // Execute with retry if configured
334
+ if (config.retries !== undefined && config.retries > 0) {
335
+ return await withRetry(
336
+ executeRequest,
337
+ config.retries,
338
+ config.retryDelay,
339
+ config.retryCondition
340
+ );
341
+ }
342
+
343
+ return await executeRequest();
344
+ } catch (error) {
345
+ cleanup();
346
+
347
+ // Handle specific error types
348
+ if (isAbortError(error)) {
349
+ throw new AbortError();
350
+ }
351
+
352
+ if (error instanceof TypeError && error.message === 'Failed to fetch') {
353
+ throw new NetworkError('Network request failed');
354
+ }
355
+
356
+ /*
357
+ * Reactive 401: refresh token and retry once.
358
+ * Only swallow the error if the refresh itself fails; a successful
359
+ * refresh followed by a different failure (403, 429, 5xx…) must
360
+ * surface that new error rather than the original 401.
361
+ */
362
+ if (error instanceof AuthenticationError && this.tokenManager.refreshToken) {
363
+ let refreshSucceeded = false;
364
+
365
+ try {
366
+ const newToken = await this.tokenManager.refreshToken();
367
+
368
+ headers.set('Authorization', `Bearer ${newToken}`);
369
+ refreshSucceeded = true;
370
+ } catch {
371
+ // Refresh failed — fall through to surface the original 401
372
+ }
373
+
374
+ if (refreshSucceeded) {
375
+ return await executeRequest();
376
+ }
377
+ }
378
+
379
+ if (error instanceof ApiError) {
380
+ return this.applyErrorInterceptors(error);
381
+ }
382
+
383
+ // Unknown error
384
+ throw new ApiError(
385
+ error instanceof Error ? error.message : 'Unknown error occurred',
386
+ undefined,
387
+ 'UNKNOWN_ERROR'
388
+ );
389
+ } finally {
390
+ cleanup();
391
+ }
392
+ }
393
+ async get<T = unknown>(endpoint: string, params?: Record<string, QueryParamValue>, config?: RequestConfig): Promise<T> {
394
+ const response = await this.request<T>('GET', endpoint, undefined, { ...config, params });
395
+
396
+ return response.data;
397
+ }
398
+ async post<T = unknown>(endpoint: string, data?: unknown, config?: RequestConfig): Promise<T> {
399
+ const response = await this.request<T>('POST', endpoint, data, config);
400
+
401
+ return response.data;
402
+ }
403
+ async put<T = unknown>(endpoint: string, data?: unknown, config?: RequestConfig): Promise<T> {
404
+ const response = await this.request<T>('PUT', endpoint, data, config);
405
+
406
+ return response.data;
407
+ }
408
+ async runCustomQuery<T = { [key: string]: any }[]>(
409
+ customQueryId: string,
410
+ options?: Record<string, any>,
411
+ config?: RequestConfig
412
+ ): Promise<T> {
413
+ return this.put<T>(`reports/custom-queries/${customQueryId}/run`, options, config);
414
+ }
415
+ async patch<T = unknown>(endpoint: string, data?: unknown, config?: RequestConfig): Promise<T> {
416
+ const response = await this.request<T>('PATCH', endpoint, data, config);
417
+
418
+ return response.data;
419
+ }
420
+ async delete<T = unknown>(endpoint: string, data?: unknown, config?: RequestConfig): Promise<T> {
421
+ const response = await this.request<T>('DELETE', endpoint, data, config);
422
+
423
+ return response.data;
424
+ }
425
+ async download(endpoint: string, data?: unknown, config?: RequestConfig): Promise<void> {
426
+ const response = await this.request<Blob>('POST', endpoint, data, {
427
+ ...config,
428
+ responseType: 'blob'
429
+ });
430
+
431
+ const contentDisposition = response.headers.get('content-disposition');
432
+ let filename = 'download';
433
+
434
+ if (contentDisposition) {
435
+ const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
436
+
437
+ if (match && match[1]) {
438
+ filename = match[1].replace(/['"]/g, '');
439
+ }
440
+ }
441
+
442
+ // Use custom download handler if provided (e.g., React Native)
443
+ if (this.downloadHandler) {
444
+ await this.downloadHandler(response.data, filename);
445
+
446
+ return;
447
+ }
448
+
449
+ // Default: browser DOM download
450
+ if (typeof document === 'undefined' || typeof URL.createObjectURL !== 'function') {
451
+ throw new Error('File download requires a browser environment or a custom downloadHandler');
452
+ }
453
+
454
+ const url = URL.createObjectURL(response.data);
455
+ const link = document.createElement('a');
456
+
457
+ link.href = url;
458
+ link.download = filename;
459
+ document.body.appendChild(link);
460
+ link.click();
461
+ document.body.removeChild(link);
462
+
463
+ // Cleanup
464
+ setTimeout(() => URL.revokeObjectURL(url), 100);
465
+ }
466
+ async* stream(endpoint: string, options: Partial<StreamOptions>): AsyncGenerator<string, void, unknown> {
467
+ const {
468
+ method = 'POST', body, headers = {}, signal, onError
469
+ } = options;
470
+
471
+ try {
472
+ const authHeader = await this.getAccessToken();
473
+ const response = await this.fetchImpl(buildUrl(this.baseURL, endpoint, {}), {
474
+ method,
475
+ headers: {
476
+ ...headers,
477
+ Accept: 'text/event-stream',
478
+ 'Cache-Control': 'no-cache',
479
+ ...(authHeader ? { Authorization: `Bearer ${authHeader}` } : {}),
480
+ ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {})
481
+ },
482
+ body: method === 'POST' && body ? JSON.stringify(body) : undefined,
483
+ signal
484
+ });
485
+
486
+ if (!response.ok) {
487
+ throw this.createApiError(response);
488
+ }
489
+
490
+ if (!response.body) {
491
+ throw new ApiError('Response body is empty');
492
+ }
493
+
494
+ const reader = response.body.getReader();
495
+ const decoder = new TextDecoder();
496
+ let buffer = '';
497
+
498
+ try {
499
+ while (true) {
500
+ const { done, value } = await reader.read();
501
+
502
+ if (done) break;
503
+
504
+ buffer += decoder.decode(value, { stream: true });
505
+
506
+ // Process SSE messages
507
+ const lines = buffer.split('\n');
508
+
509
+ buffer = lines.pop() || '';
510
+
511
+ for (const line of lines) {
512
+ if (line.startsWith('data: ')) {
513
+ const data = line.slice(6);
514
+
515
+ if (data === '[DONE]') {
516
+ return;
517
+ }
518
+
519
+ yield data;
520
+ }
521
+ }
522
+ }
523
+ } finally {
524
+ reader.releaseLock();
525
+ }
526
+ } catch (error) {
527
+ if (onError) {
528
+ onError(error as Error);
529
+ }
530
+ throw error;
531
+ }
532
+ }
533
+ async postStream(
534
+ endpoint: string,
535
+ data?: unknown,
536
+ onMessage?: (chunk: string) => void,
537
+ onError?: (error: Error) => void,
538
+ onComplete?: () => void
539
+ ): Promise<void> {
540
+ try {
541
+ const generator = this.stream(endpoint, {
542
+ method: 'POST',
543
+ body: data,
544
+ onMessage: (onMessage as (data: unknown) => void) || (() => {}),
545
+ onError
546
+ });
547
+
548
+ for await (const chunk of generator) {
549
+ if (onMessage) {
550
+ try {
551
+ const parsed = JSON.parse(chunk);
552
+
553
+ onMessage(parsed);
554
+ } catch {
555
+ onMessage(chunk);
556
+ }
557
+ }
558
+ }
559
+
560
+ if (onComplete) {
561
+ onComplete();
562
+ }
563
+ } catch (error) {
564
+ if (onError) {
565
+ onError(error as Error);
566
+ }
567
+ throw error;
568
+ }
569
+ }
570
+ }
@@ -0,0 +1,82 @@
1
+ import { type ApiClientConfig, type RequestConfig, type ApiResponse } from '../core/types';
2
+
3
+ import { BaseApiClient } from './base-client';
4
+
5
+ export class CloudflareWorkerClient extends BaseApiClient {
6
+ constructor(config: ApiClientConfig = {}) {
7
+ if (!config.baseURL) {
8
+ throw new Error('CloudflareWorkerClient requires a baseURL in the configuration');
9
+ }
10
+
11
+ super(config);
12
+ }
13
+ protected override async request<T = unknown>(
14
+ method: any,
15
+ endpoint: string,
16
+ data?: unknown,
17
+ config: RequestConfig = {}
18
+ ): Promise<ApiResponse<T>> {
19
+ /*
20
+ * For Cloudflare Workers, extract function name from endpoint
21
+ * and replace {{function}} placeholder in baseURL
22
+ */
23
+ const functionName = endpoint.split('/')[1] || endpoint;
24
+ const remainingPath = endpoint.includes('/') ? endpoint.substring(endpoint.indexOf('/', 1)) : '';
25
+
26
+ // Replace {{function}} in baseURL with actual function name
27
+ const originalBaseURL = this.baseURL;
28
+
29
+ if (this.baseURL.includes('{{function}}')) {
30
+ this.baseURL = this.baseURL.replace('{{function}}', functionName);
31
+ }
32
+
33
+ try {
34
+ // Call parent request with modified endpoint
35
+ return await super.request<T>(method, remainingPath, data, config);
36
+ } finally {
37
+ // Restore original baseURL
38
+ this.baseURL = originalBaseURL;
39
+ }
40
+ }
41
+ // Worker-specific method to invoke functions
42
+ async invokeWorker<T = unknown>(
43
+ workerName: string,
44
+ route: string = '',
45
+ data?: unknown,
46
+ config?: RequestConfig
47
+ ): Promise<T> {
48
+ const endpoint = route ? `${workerName}/${route}` : workerName;
49
+
50
+ return this.post<T>(endpoint, data, config);
51
+ }
52
+ // Durable Object binding support
53
+ async durableObject<T = unknown>(
54
+ namespace: string,
55
+ id: string,
56
+ method: string,
57
+ data?: unknown
58
+ ): Promise<T> {
59
+ return this.post<T>(`durable/${namespace}/${id}/${method}`, data);
60
+ }
61
+ // KV namespace support
62
+ async kvGet<T = unknown>(namespace: string, key: string): Promise<T> {
63
+ return this.get<T>(`kv/${namespace}/${key}`);
64
+ }
65
+ async kvPut<T = unknown>(
66
+ namespace: string,
67
+ key: string,
68
+ value: T,
69
+ metadata?: Record<string, unknown>
70
+ ): Promise<void> {
71
+ await this.put(`kv/${namespace}/${key}`, { value, metadata });
72
+ }
73
+ async kvDelete(namespace: string, key: string): Promise<void> {
74
+ await this.delete(`kv/${namespace}/${key}`);
75
+ }
76
+ async kvList(
77
+ namespace: string,
78
+ options?: { prefix?: string; limit?: number; cursor?: string }
79
+ ): Promise<{ keys: string[]; cursor?: string }> {
80
+ return this.get(`kv/${namespace}`, options as any);
81
+ }
82
+ }