@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/README.md
CHANGED
|
@@ -1,3 +1,794 @@
|
|
|
1
1
|
# @kivacore/api-client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A modern, type-safe API client library for JavaScript/TypeScript applications with support for multiple backend types, streaming, error handling, and token management.
|
|
4
|
+
|
|
5
|
+
> ⚙️ **Working with Docyrus REST endpoints?** They return their payload inside a `{ success, data }` envelope (with optional `meta` for pagination). For convenience, register `envelopeUnwrapInterceptor` from [`@kivacore/app-utils`](https://github.com/Docyrus/docyrus-devkit/tree/main/packages/app-utils) so `client.get(...)` returns bare payloads — required for generated TanStack DB collections, recommended for hand-written REST calls.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- 🚀 **Multiple Client Types**: REST, Edge Functions, and Cloudflare Workers
|
|
10
|
+
- 🔐 **Built-in Token Management**: Memory, Storage, and Async token managers
|
|
11
|
+
- 🔑 **OAuth2 Authentication**: Full OAuth2 support with PKCE, Device Code, and Client Credentials flows
|
|
12
|
+
- 🌊 **Streaming Support**: SSE and chunked responses
|
|
13
|
+
- 🔄 **Request/Response Interceptors**: Transform requests and handle responses
|
|
14
|
+
- ⚡ **Retry Logic**: Automatic retry with configurable conditions
|
|
15
|
+
- 🎯 **Type-Safe**: Full TypeScript support with comprehensive type definitions
|
|
16
|
+
- 🌐 **Isomorphic**: Works in both browser and Node.js environments
|
|
17
|
+
- 🛡️ **Comprehensive Error Handling**: Typed error classes for different scenarios
|
|
18
|
+
- ⏱️ **Timeout Support**: Configurable request timeouts with AbortController
|
|
19
|
+
- 📄 **HTML to PDF**: Built-in support for HTML to PDF conversion
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @kivacore/api-client
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
yarn add @kivacore/api-client
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pnpm add @kivacore/api-client
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quick Start
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { RestApiClient, MemoryTokenManager } from '@kivacore/api-client';
|
|
39
|
+
|
|
40
|
+
// Create a client instance
|
|
41
|
+
const client = new RestApiClient({
|
|
42
|
+
baseURL: 'https://api.example.com',
|
|
43
|
+
tokenManager: new MemoryTokenManager(),
|
|
44
|
+
timeout: 5000,
|
|
45
|
+
headers: {
|
|
46
|
+
'X-API-Version': '1.0'
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// Set authentication token
|
|
51
|
+
await client.setAccessToken('your-auth-token');
|
|
52
|
+
|
|
53
|
+
// Make API calls
|
|
54
|
+
const response = await client.get('/users', {
|
|
55
|
+
params: { page: 1, limit: 10 }
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
console.log(response.data);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Client Types
|
|
62
|
+
|
|
63
|
+
### RestApiClient
|
|
64
|
+
|
|
65
|
+
Standard REST API client for traditional HTTP endpoints.
|
|
66
|
+
|
|
67
|
+
```typescript
|
|
68
|
+
import { RestApiClient } from '@kivacore/api-client';
|
|
69
|
+
|
|
70
|
+
const client = new RestApiClient({
|
|
71
|
+
baseURL: 'https://api.example.com'
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// GET request
|
|
75
|
+
const users = await client.get('/users');
|
|
76
|
+
|
|
77
|
+
// POST request with data
|
|
78
|
+
const newUser = await client.post('/users', {
|
|
79
|
+
name: 'John Doe',
|
|
80
|
+
email: 'john@example.com'
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// PUT request
|
|
84
|
+
const updatedUser = await client.put('/users/123', {
|
|
85
|
+
name: 'Jane Doe'
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// DELETE request
|
|
89
|
+
await client.delete('/users/123');
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### EdgeFunctionClient
|
|
93
|
+
|
|
94
|
+
Optimized for edge function deployments (Vercel, Netlify, etc.).
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
import { EdgeFunctionClient } from '@kivacore/api-client';
|
|
98
|
+
|
|
99
|
+
const client = new EdgeFunctionClient({
|
|
100
|
+
baseURL: 'https://edge.example.com'
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// Invoke edge function
|
|
104
|
+
const result = await client.invokeFunction('processData', {
|
|
105
|
+
input: 'data'
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// Stream from edge function
|
|
109
|
+
for await (const chunk of client.streamFunction('generateContent', { prompt: 'Hello' })) {
|
|
110
|
+
console.log(chunk);
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### CloudflareWorkerClient
|
|
115
|
+
|
|
116
|
+
Specialized client for Cloudflare Workers with dynamic function routing.
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
import { CloudflareWorkerClient } from '@kivacore/api-client';
|
|
120
|
+
|
|
121
|
+
const client = new CloudflareWorkerClient({
|
|
122
|
+
baseURL: 'https://{{function}}.example.workers.dev'
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// Automatically replaces {{function}} with the function name
|
|
126
|
+
const response = await client.post('/myfunction/endpoint', data);
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Token Management
|
|
130
|
+
|
|
131
|
+
### MemoryTokenManager
|
|
132
|
+
|
|
133
|
+
Stores tokens in memory (default).
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import { MemoryTokenManager } from '@kivacore/api-client';
|
|
137
|
+
|
|
138
|
+
const tokenManager = new MemoryTokenManager();
|
|
139
|
+
tokenManager.setToken('token');
|
|
140
|
+
const token = tokenManager.getToken();
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### StorageTokenManager
|
|
144
|
+
|
|
145
|
+
Persists tokens in browser storage.
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
import { StorageTokenManager } from '@kivacore/api-client';
|
|
149
|
+
|
|
150
|
+
// Use localStorage
|
|
151
|
+
const localManager = new StorageTokenManager(localStorage, 'auth_token');
|
|
152
|
+
|
|
153
|
+
// Use sessionStorage
|
|
154
|
+
const sessionManager = new StorageTokenManager(sessionStorage, 'auth_token');
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### AsyncTokenManager
|
|
158
|
+
|
|
159
|
+
For async token operations (e.g., secure storage, encrypted tokens).
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
import { AsyncTokenManager } from '@kivacore/api-client';
|
|
163
|
+
|
|
164
|
+
const tokenManager = new AsyncTokenManager({
|
|
165
|
+
async getToken() {
|
|
166
|
+
return await secureStorage.get('token');
|
|
167
|
+
},
|
|
168
|
+
async setToken(token: string) {
|
|
169
|
+
await secureStorage.set('token', token);
|
|
170
|
+
},
|
|
171
|
+
async clearToken() {
|
|
172
|
+
await secureStorage.remove('token');
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## OAuth2 Authentication
|
|
178
|
+
|
|
179
|
+
The library includes a complete OAuth2 client supporting all standard flows with PKCE security.
|
|
180
|
+
|
|
181
|
+
### OAuth2Client Setup
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
import { OAuth2Client, BrowserOAuth2TokenStorage } from '@kivacore/api-client';
|
|
185
|
+
|
|
186
|
+
const oauth2 = new OAuth2Client({
|
|
187
|
+
baseURL: 'https://api.docyrus.com',
|
|
188
|
+
clientId: 'your-client-id',
|
|
189
|
+
clientSecret: 'your-client-secret', // Optional for public clients using PKCE
|
|
190
|
+
redirectUri: 'http://localhost:3000/callback',
|
|
191
|
+
defaultScopes: ['openid', 'offline_access'],
|
|
192
|
+
usePKCE: true, // Enabled by default
|
|
193
|
+
tokenStorage: new BrowserOAuth2TokenStorage(localStorage)
|
|
194
|
+
});
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### Authorization Code Flow (with PKCE)
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
// Step 1: Generate authorization URL
|
|
201
|
+
const { url, state, codeVerifier } = await oauth2.getAuthorizationUrl({
|
|
202
|
+
scope: 'openid offline_access Users.Read'
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
// Step 2: Redirect user to authorization URL
|
|
206
|
+
window.location.href = url;
|
|
207
|
+
|
|
208
|
+
// Step 3: Handle callback (after redirect back)
|
|
209
|
+
const tokens = await oauth2.handleCallback(window.location.href);
|
|
210
|
+
console.log('Access Token:', tokens.accessToken);
|
|
211
|
+
console.log('Refresh Token:', tokens.refreshToken);
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Client Credentials Flow
|
|
215
|
+
|
|
216
|
+
For server-to-server authentication:
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
const tokens = await oauth2.getClientCredentialsToken({
|
|
220
|
+
scope: 'Read.All',
|
|
221
|
+
delegatedUserId: 'user-id-to-impersonate'
|
|
222
|
+
});
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### Device Code Flow (RFC 8628)
|
|
226
|
+
|
|
227
|
+
For CLI tools and devices without a browser:
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
// Step 1: Start device authorization
|
|
231
|
+
const deviceAuth = await oauth2.startDeviceAuthorization('openid offline_access');
|
|
232
|
+
|
|
233
|
+
console.log(`Go to: ${deviceAuth.verification_uri}`);
|
|
234
|
+
console.log(`Enter code: ${deviceAuth.user_code}`);
|
|
235
|
+
|
|
236
|
+
// Step 2: Poll for completion
|
|
237
|
+
const tokens = await oauth2.pollDeviceAuthorization(
|
|
238
|
+
deviceAuth.device_code,
|
|
239
|
+
deviceAuth.interval,
|
|
240
|
+
deviceAuth.expires_in,
|
|
241
|
+
{
|
|
242
|
+
onExpired: () => console.log('Code expired, please restart'),
|
|
243
|
+
signal: abortController.signal
|
|
244
|
+
}
|
|
245
|
+
);
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### Token Management
|
|
249
|
+
|
|
250
|
+
```typescript
|
|
251
|
+
// Get current tokens
|
|
252
|
+
const tokens = await oauth2.getTokens();
|
|
253
|
+
|
|
254
|
+
// Check if token is expired
|
|
255
|
+
const isExpired = await oauth2.isTokenExpired();
|
|
256
|
+
|
|
257
|
+
// Get valid access token (auto-refreshes if expired)
|
|
258
|
+
const accessToken = await oauth2.getValidAccessToken();
|
|
259
|
+
|
|
260
|
+
// Manually refresh tokens
|
|
261
|
+
const newTokens = await oauth2.refreshAccessToken();
|
|
262
|
+
|
|
263
|
+
// Revoke refresh token
|
|
264
|
+
await oauth2.revokeToken(tokens.refreshToken);
|
|
265
|
+
|
|
266
|
+
// Introspect token
|
|
267
|
+
const tokenInfo = await oauth2.introspectToken(tokens.accessToken);
|
|
268
|
+
|
|
269
|
+
// Logout (revokes token and clears storage)
|
|
270
|
+
await oauth2.logout();
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### Check Rate Limits
|
|
274
|
+
|
|
275
|
+
```typescript
|
|
276
|
+
const rateLimit = await oauth2.checkRateLimit();
|
|
277
|
+
console.log(`Remaining: ${rateLimit.remaining}/${rateLimit.limit}`);
|
|
278
|
+
console.log(`Reset in: ${rateLimit.reset} seconds`);
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
### Integration with RestApiClient
|
|
282
|
+
|
|
283
|
+
Use OAuth2 tokens with the REST client:
|
|
284
|
+
|
|
285
|
+
```typescript
|
|
286
|
+
import {
|
|
287
|
+
RestApiClient,
|
|
288
|
+
OAuth2Client,
|
|
289
|
+
OAuth2TokenManagerAdapter,
|
|
290
|
+
BrowserOAuth2TokenStorage
|
|
291
|
+
} from '@kivacore/api-client';
|
|
292
|
+
|
|
293
|
+
// Create shared token storage
|
|
294
|
+
const tokenStorage = new BrowserOAuth2TokenStorage(localStorage);
|
|
295
|
+
|
|
296
|
+
// Create OAuth2 client
|
|
297
|
+
const oauth2 = new OAuth2Client({
|
|
298
|
+
baseURL: 'https://api.docyrus.com',
|
|
299
|
+
clientId: 'your-client-id',
|
|
300
|
+
tokenStorage
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
// Create adapter for RestApiClient
|
|
304
|
+
const tokenManager = new OAuth2TokenManagerAdapter(
|
|
305
|
+
tokenStorage,
|
|
306
|
+
// Auto-refresh callback
|
|
307
|
+
async () => {
|
|
308
|
+
const tokens = await oauth2.refreshAccessToken();
|
|
309
|
+
return tokens.accessToken;
|
|
310
|
+
}
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
// Create REST client with OAuth2 token management
|
|
314
|
+
const apiClient = new RestApiClient({
|
|
315
|
+
baseURL: 'https://api.docyrus.com',
|
|
316
|
+
tokenManager
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
// Authenticate first
|
|
320
|
+
await oauth2.handleCallback(window.location.href);
|
|
321
|
+
|
|
322
|
+
// Now API calls automatically use OAuth2 tokens
|
|
323
|
+
const user = await apiClient.get('/v1/users/me');
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
### PKCE Utilities
|
|
327
|
+
|
|
328
|
+
Generate PKCE challenges manually:
|
|
329
|
+
|
|
330
|
+
```typescript
|
|
331
|
+
import {
|
|
332
|
+
generatePKCEChallenge,
|
|
333
|
+
generateCodeVerifier,
|
|
334
|
+
generateCodeChallenge,
|
|
335
|
+
generateState,
|
|
336
|
+
generateNonce
|
|
337
|
+
} from '@kivacore/api-client';
|
|
338
|
+
|
|
339
|
+
// Generate complete PKCE challenge
|
|
340
|
+
const pkce = await generatePKCEChallenge();
|
|
341
|
+
console.log(pkce.codeVerifier); // Random verifier
|
|
342
|
+
console.log(pkce.codeChallenge); // SHA-256 hash (Base64URL)
|
|
343
|
+
console.log(pkce.codeChallengeMethod); // 'S256'
|
|
344
|
+
|
|
345
|
+
// Generate individual components
|
|
346
|
+
const verifier = generateCodeVerifier(64);
|
|
347
|
+
const challenge = await generateCodeChallenge(verifier);
|
|
348
|
+
const state = generateState();
|
|
349
|
+
const nonce = generateNonce();
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
### OAuth2 Error Handling
|
|
353
|
+
|
|
354
|
+
```typescript
|
|
355
|
+
import {
|
|
356
|
+
OAuth2Error,
|
|
357
|
+
InvalidGrantError,
|
|
358
|
+
InvalidClientError,
|
|
359
|
+
AccessDeniedError,
|
|
360
|
+
AuthorizationPendingError,
|
|
361
|
+
ExpiredTokenError
|
|
362
|
+
} from '@kivacore/api-client';
|
|
363
|
+
|
|
364
|
+
try {
|
|
365
|
+
await oauth2.refreshAccessToken();
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (error instanceof InvalidGrantError) {
|
|
368
|
+
// Refresh token expired or revoked
|
|
369
|
+
console.log('Please login again');
|
|
370
|
+
} else if (error instanceof InvalidClientError) {
|
|
371
|
+
// Client authentication failed
|
|
372
|
+
console.log('Client credentials invalid');
|
|
373
|
+
} else if (error instanceof AccessDeniedError) {
|
|
374
|
+
// User denied authorization
|
|
375
|
+
console.log('Authorization denied');
|
|
376
|
+
} else if (error instanceof ExpiredTokenError) {
|
|
377
|
+
// Device code expired
|
|
378
|
+
console.log('Code expired, please restart');
|
|
379
|
+
} else if (error instanceof OAuth2Error) {
|
|
380
|
+
// Generic OAuth2 error
|
|
381
|
+
console.log(`OAuth2 error: ${error.errorCode} - ${error.errorDescription}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
### Environment Variables
|
|
387
|
+
|
|
388
|
+
Create a `.env` file based on `.env.example`:
|
|
389
|
+
|
|
390
|
+
```bash
|
|
391
|
+
# Required
|
|
392
|
+
DOCYRUS_CLIENT_ID=your-client-id
|
|
393
|
+
DOCYRUS_REDIRECT_URI=http://localhost:3000/callback
|
|
394
|
+
|
|
395
|
+
# Optional (for confidential clients)
|
|
396
|
+
DOCYRUS_CLIENT_SECRET=your-client-secret
|
|
397
|
+
|
|
398
|
+
# Optional
|
|
399
|
+
DOCYRUS_API_URL=https://api.docyrus.com
|
|
400
|
+
DOCYRUS_DEFAULT_SCOPES=openid offline_access
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
## Interceptors
|
|
404
|
+
|
|
405
|
+
Transform requests and handle responses globally.
|
|
406
|
+
|
|
407
|
+
```typescript
|
|
408
|
+
// Request interceptor
|
|
409
|
+
client.addInterceptor({
|
|
410
|
+
async request(config) {
|
|
411
|
+
// Add timestamp to all requests
|
|
412
|
+
config.headers = {
|
|
413
|
+
...config.headers,
|
|
414
|
+
'X-Request-Time': new Date().toISOString()
|
|
415
|
+
};
|
|
416
|
+
return config;
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
// Response interceptor
|
|
421
|
+
client.addInterceptor({
|
|
422
|
+
async response(response, request) {
|
|
423
|
+
console.log(`API call to ${request.url} took ${Date.now() - request.timestamp}ms`);
|
|
424
|
+
return response;
|
|
425
|
+
}
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
// Error interceptor
|
|
429
|
+
client.addInterceptor({
|
|
430
|
+
async error(error, request, response) {
|
|
431
|
+
if (error.status === 401) {
|
|
432
|
+
// Handle authentication errors
|
|
433
|
+
await refreshToken();
|
|
434
|
+
throw error;
|
|
435
|
+
}
|
|
436
|
+
return { error, request, response };
|
|
437
|
+
}
|
|
438
|
+
});
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
### Docyrus envelope unwrapping
|
|
442
|
+
|
|
443
|
+
Docyrus REST endpoints return payloads inside a `{ success, data }` envelope (optionally with `meta`/`error`/`message`). The unwrap helper lives in [`@kivacore/app-utils`](https://github.com/Docyrus/docyrus-devkit/tree/main/packages/app-utils) — `api-client` itself stays envelope-agnostic. See [`@kivacore/app-utils` → Envelope handling](https://github.com/Docyrus/docyrus-devkit/tree/main/packages/app-utils#envelope-handling) for both the global interceptor (`envelopeUnwrapInterceptor`) and the per-call helper (`unwrapEnvelope`).
|
|
444
|
+
|
|
445
|
+
## Streaming
|
|
446
|
+
|
|
447
|
+
### Server-Sent Events (SSE)
|
|
448
|
+
|
|
449
|
+
```typescript
|
|
450
|
+
const eventSource = client.sse('/events', {
|
|
451
|
+
onMessage(data) {
|
|
452
|
+
console.log('Received:', data);
|
|
453
|
+
},
|
|
454
|
+
onError(error) {
|
|
455
|
+
console.error('SSE error:', error);
|
|
456
|
+
},
|
|
457
|
+
onComplete() {
|
|
458
|
+
console.log('Stream completed');
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
// Stop the stream
|
|
463
|
+
eventSource.close();
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
### Chunked Streaming
|
|
467
|
+
|
|
468
|
+
```typescript
|
|
469
|
+
for await (const chunk of client.stream('/stream', {
|
|
470
|
+
method: 'POST',
|
|
471
|
+
body: { query: 'stream data' }
|
|
472
|
+
})) {
|
|
473
|
+
console.log('Chunk:', chunk);
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
## Error Handling
|
|
478
|
+
|
|
479
|
+
Comprehensive error types for different scenarios:
|
|
480
|
+
|
|
481
|
+
```typescript
|
|
482
|
+
import {
|
|
483
|
+
ApiError,
|
|
484
|
+
NetworkError,
|
|
485
|
+
TimeoutError,
|
|
486
|
+
AuthenticationError,
|
|
487
|
+
AuthorizationError,
|
|
488
|
+
NotFoundError,
|
|
489
|
+
RateLimitError,
|
|
490
|
+
ValidationError,
|
|
491
|
+
// OAuth2 errors
|
|
492
|
+
OAuth2Error,
|
|
493
|
+
InvalidGrantError,
|
|
494
|
+
InvalidClientError,
|
|
495
|
+
AccessDeniedError
|
|
496
|
+
} from '@kivacore/api-client';
|
|
497
|
+
|
|
498
|
+
try {
|
|
499
|
+
const data = await client.get('/protected-resource');
|
|
500
|
+
} catch (error) {
|
|
501
|
+
if (error instanceof AuthenticationError) {
|
|
502
|
+
// Handle authentication error (401)
|
|
503
|
+
console.log('Please login');
|
|
504
|
+
} else if (error instanceof AuthorizationError) {
|
|
505
|
+
// Handle authorization error (403)
|
|
506
|
+
console.log('Access denied');
|
|
507
|
+
} else if (error instanceof NotFoundError) {
|
|
508
|
+
// Handle not found error (404)
|
|
509
|
+
console.log('Resource not found');
|
|
510
|
+
} else if (error instanceof RateLimitError) {
|
|
511
|
+
// Handle rate limit error (429)
|
|
512
|
+
console.log(`Rate limited. Retry after: ${error.retryAfter}`);
|
|
513
|
+
} else if (error instanceof NetworkError) {
|
|
514
|
+
// Handle network errors
|
|
515
|
+
console.log('Network issue');
|
|
516
|
+
} else if (error instanceof TimeoutError) {
|
|
517
|
+
// Handle timeout errors
|
|
518
|
+
console.log('Request timed out');
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
## Advanced Features
|
|
524
|
+
|
|
525
|
+
### Retry Logic
|
|
526
|
+
|
|
527
|
+
```typescript
|
|
528
|
+
import { withRetry } from '@kivacore/api-client';
|
|
529
|
+
|
|
530
|
+
const response = await withRetry(
|
|
531
|
+
() => client.get('/flaky-endpoint'),
|
|
532
|
+
{
|
|
533
|
+
retries: 3,
|
|
534
|
+
retryDelay: 1000,
|
|
535
|
+
retryCondition: (error) => error.status >= 500
|
|
536
|
+
}
|
|
537
|
+
);
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
### File Upload
|
|
541
|
+
|
|
542
|
+
```typescript
|
|
543
|
+
const formData = new FormData();
|
|
544
|
+
formData.append('file', fileInput.files[0]);
|
|
545
|
+
formData.append('description', 'File description');
|
|
546
|
+
|
|
547
|
+
const response = await client.post('/upload', formData, {
|
|
548
|
+
headers: {
|
|
549
|
+
// Content-Type will be set automatically for FormData
|
|
550
|
+
}
|
|
551
|
+
});
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
### File Download
|
|
555
|
+
|
|
556
|
+
```typescript
|
|
557
|
+
const response = await client.get('/download/file.pdf', {
|
|
558
|
+
responseType: 'blob'
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
// Save the file
|
|
562
|
+
const url = URL.createObjectURL(response.data);
|
|
563
|
+
const link = document.createElement('a');
|
|
564
|
+
link.href = url;
|
|
565
|
+
link.download = 'file.pdf';
|
|
566
|
+
link.click();
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
### HTML to PDF
|
|
570
|
+
|
|
571
|
+
```typescript
|
|
572
|
+
const pdfResult = await client.html2pdf({
|
|
573
|
+
url: 'https://example.com',
|
|
574
|
+
// or
|
|
575
|
+
html: '<html><body>Content</body></html>',
|
|
576
|
+
options: {
|
|
577
|
+
format: 'A4',
|
|
578
|
+
margin: { top: 10, bottom: 10, left: 10, right: 10 },
|
|
579
|
+
landscape: false
|
|
580
|
+
}
|
|
581
|
+
});
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
### Run Custom Query
|
|
585
|
+
|
|
586
|
+
Run a custom query/report by its id.
|
|
587
|
+
|
|
588
|
+
```typescript
|
|
589
|
+
const results = await client.runCustomQuery(customQueryId, options);
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
This uses:
|
|
593
|
+
|
|
594
|
+
- `PUT reports/custom-queries/:customQueryId/run` (body = `options`)
|
|
595
|
+
|
|
596
|
+
### Filter Queries
|
|
597
|
+
|
|
598
|
+
```typescript
|
|
599
|
+
import { prepareFilterQueryForApi } from '@kivacore/api-client';
|
|
600
|
+
|
|
601
|
+
const filter = {
|
|
602
|
+
operator: 'and',
|
|
603
|
+
rules: [
|
|
604
|
+
{ field: 'status', operator: 'eq', value: 'active' },
|
|
605
|
+
{ field: 'age', operator: 'gte', value: 18 }
|
|
606
|
+
]
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
const queryString = prepareFilterQueryForApi(filter);
|
|
610
|
+
const response = await client.get(`/users?${queryString}`);
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
## Configuration Options
|
|
614
|
+
|
|
615
|
+
```typescript
|
|
616
|
+
interface ApiClientConfig {
|
|
617
|
+
// Base URL for all requests
|
|
618
|
+
baseURL?: string;
|
|
619
|
+
|
|
620
|
+
// Token manager instance
|
|
621
|
+
tokenManager?: TokenManager;
|
|
622
|
+
|
|
623
|
+
// Default headers
|
|
624
|
+
headers?: Record<string, string>;
|
|
625
|
+
|
|
626
|
+
// Request timeout in milliseconds
|
|
627
|
+
timeout?: number;
|
|
628
|
+
|
|
629
|
+
// Custom fetch implementation
|
|
630
|
+
fetch?: typeof fetch;
|
|
631
|
+
|
|
632
|
+
// Custom FormData implementation
|
|
633
|
+
FormData?: typeof FormData;
|
|
634
|
+
|
|
635
|
+
// Custom AbortController implementation
|
|
636
|
+
AbortController?: typeof AbortController;
|
|
637
|
+
|
|
638
|
+
// Storage for persistence (browser only)
|
|
639
|
+
storage?: Storage;
|
|
640
|
+
}
|
|
641
|
+
```
|
|
642
|
+
|
|
643
|
+
## Utility Functions
|
|
644
|
+
|
|
645
|
+
```typescript
|
|
646
|
+
import {
|
|
647
|
+
buildUrl,
|
|
648
|
+
isAbortError,
|
|
649
|
+
parseContentDisposition,
|
|
650
|
+
isFormData,
|
|
651
|
+
isBlob,
|
|
652
|
+
isStream,
|
|
653
|
+
createAbortSignal,
|
|
654
|
+
jsonToQueryString
|
|
655
|
+
} from '@kivacore/api-client';
|
|
656
|
+
|
|
657
|
+
// Build URL with query parameters
|
|
658
|
+
const url = buildUrl('/api/users', { page: 1, limit: 10 });
|
|
659
|
+
// Result: /api/users?page=1&limit=10
|
|
660
|
+
|
|
661
|
+
// Check if error is abort error
|
|
662
|
+
if (isAbortError(error)) {
|
|
663
|
+
console.log('Request was aborted');
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// Parse content disposition header
|
|
667
|
+
const { filename, type } = parseContentDisposition(
|
|
668
|
+
'attachment; filename="document.pdf"'
|
|
669
|
+
);
|
|
670
|
+
|
|
671
|
+
// Create abort signal with timeout
|
|
672
|
+
const signal = createAbortSignal(5000); // 5 second timeout
|
|
673
|
+
```
|
|
674
|
+
|
|
675
|
+
## TypeScript Support
|
|
676
|
+
|
|
677
|
+
Full TypeScript support with generic types:
|
|
678
|
+
|
|
679
|
+
```typescript
|
|
680
|
+
interface User {
|
|
681
|
+
id: number;
|
|
682
|
+
name: string;
|
|
683
|
+
email: string;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
interface ApiResponse<T> {
|
|
687
|
+
data: T;
|
|
688
|
+
meta: {
|
|
689
|
+
page: number;
|
|
690
|
+
total: number;
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// Typed responses
|
|
695
|
+
const response = await client.get<ApiResponse<User[]>>('/users');
|
|
696
|
+
const users: User[] = response.data.data;
|
|
697
|
+
|
|
698
|
+
// Typed request bodies
|
|
699
|
+
const newUser = await client.post<User>('/users', {
|
|
700
|
+
name: 'John Doe',
|
|
701
|
+
email: 'john@example.com'
|
|
702
|
+
} as Omit<User, 'id'>);
|
|
703
|
+
```
|
|
704
|
+
|
|
705
|
+
## React Native Support
|
|
706
|
+
|
|
707
|
+
The package provides a dedicated `./react-native` entrypoint for Expo/React Native apps.
|
|
708
|
+
|
|
709
|
+
### Installation
|
|
710
|
+
|
|
711
|
+
```bash
|
|
712
|
+
pnpm add @kivacore/api-client expo-crypto
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
### Usage
|
|
716
|
+
|
|
717
|
+
```typescript
|
|
718
|
+
import {
|
|
719
|
+
RestApiClient,
|
|
720
|
+
ReactNativeCryptoProvider,
|
|
721
|
+
createTokenStorage
|
|
722
|
+
} from '@kivacore/api-client/react-native';
|
|
723
|
+
import * as ExpoCrypto from 'expo-crypto';
|
|
724
|
+
import * as SecureStore from 'expo-secure-store';
|
|
725
|
+
|
|
726
|
+
// Create a crypto provider for PKCE
|
|
727
|
+
const cryptoProvider = new ReactNativeCryptoProvider(ExpoCrypto);
|
|
728
|
+
|
|
729
|
+
// Create token storage with any storage backend
|
|
730
|
+
const tokenStorage = createTokenStorage({
|
|
731
|
+
getItem: (key) => SecureStore.getItemAsync(key),
|
|
732
|
+
setItem: (key, value) => SecureStore.setItemAsync(key, value),
|
|
733
|
+
removeItem: (key) => SecureStore.deleteItemAsync(key),
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
// Use with OAuth2Client
|
|
737
|
+
const oauth2 = new OAuth2Client({
|
|
738
|
+
baseURL: 'https://api.docyrus.com',
|
|
739
|
+
clientId: 'your-client-id',
|
|
740
|
+
redirectUri: 'myapp://auth/callback',
|
|
741
|
+
usePKCE: true,
|
|
742
|
+
tokenStorage,
|
|
743
|
+
cryptoProvider,
|
|
744
|
+
});
|
|
745
|
+
```
|
|
746
|
+
|
|
747
|
+
### What's Different
|
|
748
|
+
|
|
749
|
+
- `ReactNativeCryptoProvider` — Replaces `btoa`/`atob`/`crypto.subtle` with `expo-crypto` and pure-JS base64
|
|
750
|
+
- `createTokenStorage(adapter)` — Factory to create `OAuth2TokenStorage` from any key-value storage (`AsyncStorage`, `SecureStore`, `MMKV`, etc.)
|
|
751
|
+
- `StorageTokenManager` and `BrowserOAuth2TokenStorage` are **not** re-exported (they depend on `localStorage`)
|
|
752
|
+
- Use `downloadHandler` in `ApiClientConfig` for file downloads (DOM-based download is not available)
|
|
753
|
+
|
|
754
|
+
## Platform Support
|
|
755
|
+
|
|
756
|
+
- Chrome/Edge: Latest 2 versions
|
|
757
|
+
- Firefox: Latest 2 versions
|
|
758
|
+
- Safari: Latest 2 versions
|
|
759
|
+
- Node.js: 18+
|
|
760
|
+
- React Native: Expo SDK 51+ (with `expo-crypto`)
|
|
761
|
+
|
|
762
|
+
## Contributing
|
|
763
|
+
|
|
764
|
+
Contributions are welcome! Please read our contributing guidelines before submitting PRs.
|
|
765
|
+
|
|
766
|
+
## License
|
|
767
|
+
|
|
768
|
+
MIT © Docyrus
|
|
769
|
+
|
|
770
|
+
## Support
|
|
771
|
+
|
|
772
|
+
For issues and feature requests, please [open an issue](https://github.com/docyrus/docyrus-ai-toolkit/issues) on GitHub.
|
|
773
|
+
|
|
774
|
+
## Development
|
|
775
|
+
|
|
776
|
+
```bash
|
|
777
|
+
# Install dependencies
|
|
778
|
+
pnpm install
|
|
779
|
+
|
|
780
|
+
# Development mode with watch
|
|
781
|
+
pnpm dev
|
|
782
|
+
|
|
783
|
+
# Build the package
|
|
784
|
+
pnpm build
|
|
785
|
+
|
|
786
|
+
# Run linting
|
|
787
|
+
pnpm lint
|
|
788
|
+
|
|
789
|
+
# Type checking
|
|
790
|
+
pnpm typecheck
|
|
791
|
+
|
|
792
|
+
# Publish package
|
|
793
|
+
pnpm publish
|
|
794
|
+
```
|