@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/README.md +792 -1
- package/REVIEW.md +292 -0
- package/dist/index.d.ts +597 -0
- package/dist/index.js +1486 -0
- package/dist/index.js.map +1 -0
- package/dist/react-native/index.d.ts +75 -0
- package/dist/react-native/index.js +1534 -0
- package/dist/react-native/index.js.map +1 -0
- package/docyrus-api-query-guide.md +2057 -0
- package/package.json +40 -3
- package/src/clients/base-client.ts +570 -0
- package/src/clients/cf-client.ts +82 -0
- package/src/clients/edge-client.ts +34 -0
- package/src/clients/rest-client.ts +58 -0
- package/src/core/crypto.ts +63 -0
- package/src/core/errors.ts +183 -0
- package/src/core/token-manager.ts +59 -0
- package/src/core/types.ts +96 -0
- package/src/core/utils.ts +138 -0
- package/src/index.ts +112 -0
- package/src/oauth2/index.ts +37 -0
- package/src/oauth2/oauth2-client.ts +668 -0
- package/src/oauth2/oauth2-token-manager.ts +128 -0
- package/src/oauth2/oauth2-types.ts +234 -0
- package/src/oauth2/pkce.ts +121 -0
- package/src/react-native/index.ts +112 -0
- package/src/react-native/rn-crypto.ts +115 -0
- package/src/react-native/rn-helpers.ts +89 -0
- package/tsconfig.json +9 -0
- package/tsup.config.ts +13 -0
- package/vitest.config.mts +13 -0
package/REVIEW.md
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
# API Client Library Review & Modernization Recommendations
|
|
2
|
+
|
|
3
|
+
## Current Issues & Bad Practices
|
|
4
|
+
|
|
5
|
+
### 1. **Redundant Promise Wrapping**
|
|
6
|
+
The HTTP methods (`get`, `post`, `put`, etc.) unnecessarily wrap promises:
|
|
7
|
+
```typescript
|
|
8
|
+
// Current (anti-pattern)
|
|
9
|
+
const get = async <T>(endpoint: string, data = {}, headers = {}): Promise<T> => {
|
|
10
|
+
return new Promise((resolve, reject) => {
|
|
11
|
+
doRequest('GET', endpoint, data, headers)
|
|
12
|
+
.then(resolve)
|
|
13
|
+
.catch(reject);
|
|
14
|
+
});
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// Should be
|
|
18
|
+
const get = async <T>(endpoint: string, data = {}, headers = {}): Promise<T> => {
|
|
19
|
+
return doRequest('GET', endpoint, data, headers) as Promise<T>;
|
|
20
|
+
};
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### 2. **Mixed Async/Await and Promise Chain**
|
|
24
|
+
The `doRequest` function mixes patterns inconsistently. Should use async/await throughout.
|
|
25
|
+
|
|
26
|
+
### 3. **Type Safety Issues**
|
|
27
|
+
- Excessive use of `unknown` and type assertions
|
|
28
|
+
- JSDoc comments alongside TypeScript (redundant)
|
|
29
|
+
- Loose typing for error handling
|
|
30
|
+
|
|
31
|
+
### 4. **Error Handling**
|
|
32
|
+
- Console.error/warn in library code (should let consumers handle)
|
|
33
|
+
- Inconsistent error structures
|
|
34
|
+
- Missing error recovery mechanisms
|
|
35
|
+
|
|
36
|
+
### 5. **Security Concerns**
|
|
37
|
+
- Access token stored in mutable closure variable
|
|
38
|
+
- No token refresh mechanism
|
|
39
|
+
- Hardcoded URL in `html2pdf`
|
|
40
|
+
|
|
41
|
+
### 6. **Stream API Issues**
|
|
42
|
+
- EventSource doesn't support POST/headers natively
|
|
43
|
+
- `stream` method exposes auth token in URL query params (security risk)
|
|
44
|
+
- No cleanup/abort mechanism for streams
|
|
45
|
+
|
|
46
|
+
### 7. **Browser-Specific Code**
|
|
47
|
+
- Direct DOM manipulation (`document.createElement`)
|
|
48
|
+
- Browser globals (`sessionStorage`, `window`)
|
|
49
|
+
- No isomorphic support
|
|
50
|
+
|
|
51
|
+
## Modernization Recommendations
|
|
52
|
+
|
|
53
|
+
### 1. **Use Modern Fetch Patterns**
|
|
54
|
+
```typescript
|
|
55
|
+
interface RequestConfig extends RequestInit {
|
|
56
|
+
params?: Record<string, unknown>;
|
|
57
|
+
responseType?: 'json' | 'blob' | 'text';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
class ApiClient {
|
|
61
|
+
private async request<T>(url: string, config: RequestConfig): Promise<T> {
|
|
62
|
+
const { params, responseType = 'json', ...fetchConfig } = config;
|
|
63
|
+
|
|
64
|
+
if (params) {
|
|
65
|
+
url += '?' + new URLSearchParams(params as any);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const response = await fetch(url, fetchConfig);
|
|
69
|
+
|
|
70
|
+
if (!response.ok) {
|
|
71
|
+
throw await this.handleError(response);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return response[responseType]();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 2. **Implement Interceptors**
|
|
80
|
+
```typescript
|
|
81
|
+
interface Interceptor {
|
|
82
|
+
request?: (config: RequestConfig) => RequestConfig | Promise<RequestConfig>;
|
|
83
|
+
response?: (response: Response) => Response | Promise<Response>;
|
|
84
|
+
error?: (error: Error) => Error | Promise<Error>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
class ApiClient {
|
|
88
|
+
private interceptors: Interceptor[] = [];
|
|
89
|
+
|
|
90
|
+
addInterceptor(interceptor: Interceptor) {
|
|
91
|
+
this.interceptors.push(interceptor);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 3. **Add Abort Controller Support**
|
|
97
|
+
```typescript
|
|
98
|
+
interface RequestConfig {
|
|
99
|
+
signal?: AbortSignal;
|
|
100
|
+
timeout?: number;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async request<T>(url: string, config: RequestConfig): Promise<T> {
|
|
104
|
+
const controller = new AbortController();
|
|
105
|
+
const timeoutId = config.timeout
|
|
106
|
+
? setTimeout(() => controller.abort(), config.timeout)
|
|
107
|
+
: null;
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
const response = await fetch(url, {
|
|
111
|
+
...config,
|
|
112
|
+
signal: config.signal || controller.signal
|
|
113
|
+
});
|
|
114
|
+
// ...
|
|
115
|
+
} finally {
|
|
116
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 4. **Proper TypeScript Types**
|
|
122
|
+
```typescript
|
|
123
|
+
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
124
|
+
|
|
125
|
+
interface ApiResponse<T = unknown> {
|
|
126
|
+
data: T;
|
|
127
|
+
headers: Headers;
|
|
128
|
+
status: number;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
interface ApiError {
|
|
132
|
+
message: string;
|
|
133
|
+
code?: string;
|
|
134
|
+
details?: Record<string, unknown>;
|
|
135
|
+
status?: number;
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### 5. **SSE with Proper Error Handling**
|
|
140
|
+
```typescript
|
|
141
|
+
interface SSEOptions {
|
|
142
|
+
onMessage: (data: unknown) => void;
|
|
143
|
+
onError?: (error: Error) => void;
|
|
144
|
+
onComplete?: () => void;
|
|
145
|
+
signal?: AbortSignal;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async *streamSSE(url: string, options: SSEOptions) {
|
|
149
|
+
const response = await fetch(url, {
|
|
150
|
+
headers: { 'Accept': 'text/event-stream' },
|
|
151
|
+
signal: options.signal
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
const reader = response.body?.getReader();
|
|
155
|
+
const decoder = new TextDecoder();
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
while (true) {
|
|
159
|
+
const { done, value } = await reader!.read();
|
|
160
|
+
if (done) break;
|
|
161
|
+
|
|
162
|
+
const chunk = decoder.decode(value);
|
|
163
|
+
yield chunk;
|
|
164
|
+
}
|
|
165
|
+
} finally {
|
|
166
|
+
reader?.releaseLock();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### 6. **Environment Agnostic**
|
|
172
|
+
```typescript
|
|
173
|
+
interface ClientConfig {
|
|
174
|
+
storage?: Storage;
|
|
175
|
+
fetch?: typeof fetch;
|
|
176
|
+
FormData?: typeof FormData;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
class ApiClient {
|
|
180
|
+
constructor(private config: ClientConfig) {
|
|
181
|
+
this.fetch = config.fetch || globalThis.fetch;
|
|
182
|
+
this.FormData = config.FormData || globalThis.FormData;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### 7. **Token Management**
|
|
188
|
+
```typescript
|
|
189
|
+
interface TokenManager {
|
|
190
|
+
getToken(): Promise<string | null>;
|
|
191
|
+
setToken(token: string): Promise<void>;
|
|
192
|
+
refreshToken?(): Promise<string>;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
class ApiClient {
|
|
196
|
+
constructor(private tokenManager: TokenManager) {}
|
|
197
|
+
|
|
198
|
+
private async getAuthHeader(): Promise<string | undefined> {
|
|
199
|
+
const token = await this.tokenManager.getToken();
|
|
200
|
+
return token ? `Bearer ${token}` : undefined;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
### 8. **Export Separate Clients**
|
|
206
|
+
```typescript
|
|
207
|
+
// Main export
|
|
208
|
+
export class ApiClient { /* ... */ }
|
|
209
|
+
|
|
210
|
+
// Backend-specific exports
|
|
211
|
+
export class RestApiClient extends ApiClient { /* ... */ }
|
|
212
|
+
export class EdgeFunctionClient extends ApiClient { /* ... */ }
|
|
213
|
+
export class CloudflareWorkerClient extends ApiClient { /* ... */ }
|
|
214
|
+
|
|
215
|
+
// Factory function for backwards compatibility
|
|
216
|
+
export function createApiClient(options: ApiClientOptions) {
|
|
217
|
+
switch (options.backend) {
|
|
218
|
+
case 'edge': return new EdgeFunctionClient(options);
|
|
219
|
+
case 'cf': return new CloudflareWorkerClient(options);
|
|
220
|
+
default: return new RestApiClient(options);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### 9. **Better Error Classes**
|
|
226
|
+
```typescript
|
|
227
|
+
export class ApiError extends Error {
|
|
228
|
+
constructor(
|
|
229
|
+
message: string,
|
|
230
|
+
public status?: number,
|
|
231
|
+
public code?: string,
|
|
232
|
+
public details?: Record<string, unknown>
|
|
233
|
+
) {
|
|
234
|
+
super(message);
|
|
235
|
+
this.name = 'ApiError';
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export class NetworkError extends ApiError {
|
|
240
|
+
name = 'NetworkError';
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export class TimeoutError extends ApiError {
|
|
244
|
+
name = 'TimeoutError';
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### 10. **Add Retry Logic**
|
|
249
|
+
```typescript
|
|
250
|
+
interface RetryConfig {
|
|
251
|
+
retries?: number;
|
|
252
|
+
retryDelay?: number;
|
|
253
|
+
retryCondition?: (error: Error) => boolean;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function withRetry<T>(
|
|
257
|
+
fn: () => Promise<T>,
|
|
258
|
+
config: RetryConfig
|
|
259
|
+
): Promise<T> {
|
|
260
|
+
let lastError: Error;
|
|
261
|
+
|
|
262
|
+
for (let i = 0; i <= (config.retries ?? 3); i++) {
|
|
263
|
+
try {
|
|
264
|
+
return await fn();
|
|
265
|
+
} catch (error) {
|
|
266
|
+
lastError = error as Error;
|
|
267
|
+
|
|
268
|
+
if (i === config.retries || !config.retryCondition?.(lastError)) {
|
|
269
|
+
throw lastError;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
await new Promise(r => setTimeout(r, config.retryDelay ?? 1000));
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
throw lastError!;
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
## Summary
|
|
281
|
+
|
|
282
|
+
The library needs significant modernization to align with current best practices:
|
|
283
|
+
1. Adopt consistent async/await patterns
|
|
284
|
+
2. Improve type safety
|
|
285
|
+
3. Remove browser-specific code for isomorphic support
|
|
286
|
+
4. Implement proper error handling
|
|
287
|
+
5. Add request cancellation support
|
|
288
|
+
6. Use interceptors for cross-cutting concerns
|
|
289
|
+
7. Separate concerns into focused classes
|
|
290
|
+
8. Add retry and timeout mechanisms
|
|
291
|
+
9. Remove security vulnerabilities (auth in URLs)
|
|
292
|
+
10. Support modern streaming APIs properly
|