@venturekit/integrations 0.0.0-dev.20260329093916
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/LICENSE +191 -0
- package/dist/auth/api-keys.d.ts +87 -0
- package/dist/auth/api-keys.d.ts.map +1 -0
- package/dist/auth/api-keys.js +177 -0
- package/dist/auth/api-keys.js.map +1 -0
- package/dist/auth/oauth2.d.ts +141 -0
- package/dist/auth/oauth2.d.ts.map +1 -0
- package/dist/auth/oauth2.js +256 -0
- package/dist/auth/oauth2.js.map +1 -0
- package/dist/http/client.d.ts +124 -0
- package/dist/http/client.d.ts.map +1 -0
- package/dist/http/client.js +239 -0
- package/dist/http/client.js.map +1 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +47 -0
- package/dist/index.js.map +1 -0
- package/package.json +66 -0
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VentureKit OAuth2 Client
|
|
3
|
+
*
|
|
4
|
+
* Handles OAuth2 token management for third-party API integrations:
|
|
5
|
+
* - Client Credentials flow (server-to-server)
|
|
6
|
+
* - Authorization Code flow (user-delegated)
|
|
7
|
+
* - Automatic token refresh before expiry
|
|
8
|
+
* - Pluggable token storage (in-memory, DynamoDB)
|
|
9
|
+
*
|
|
10
|
+
* @example Client Credentials (e.g. Stripe, Twilio)
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import { oauth2, apiClient } from '@venturekit/integrations';
|
|
13
|
+
*
|
|
14
|
+
* const auth = oauth2({
|
|
15
|
+
* flow: 'client_credentials',
|
|
16
|
+
* tokenUrl: 'https://oauth.provider.com/token',
|
|
17
|
+
* clientId: process.env.PROVIDER_CLIENT_ID!,
|
|
18
|
+
* clientSecret: process.env.PROVIDER_CLIENT_SECRET!,
|
|
19
|
+
* scopes: ['read', 'write'],
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* const client = apiClient({
|
|
23
|
+
* baseUrl: 'https://api.provider.com/v1',
|
|
24
|
+
* onRequest: [auth.interceptor()],
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* @example Authorization Code (e.g. Google, Slack)
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const auth = oauth2({
|
|
31
|
+
* flow: 'authorization_code',
|
|
32
|
+
* tokenUrl: 'https://oauth2.googleapis.com/token',
|
|
33
|
+
* authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
|
|
34
|
+
* clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
35
|
+
* clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
36
|
+
* redirectUri: 'https://myapp.com/callback',
|
|
37
|
+
* scopes: ['profile', 'email'],
|
|
38
|
+
* store: dynamoDBTokenStore({ tableName: 'oauth-tokens' }),
|
|
39
|
+
* });
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// In-memory token store
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
export function createMemoryTokenStore() {
|
|
46
|
+
const tokens = new Map();
|
|
47
|
+
return {
|
|
48
|
+
async get(key) {
|
|
49
|
+
return tokens.get(key) ?? null;
|
|
50
|
+
},
|
|
51
|
+
async save(key, token) {
|
|
52
|
+
tokens.set(key, token);
|
|
53
|
+
},
|
|
54
|
+
async delete(key) {
|
|
55
|
+
tokens.delete(key);
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Create a DynamoDB-backed token store for persisting OAuth tokens
|
|
61
|
+
* across Lambda invocations.
|
|
62
|
+
*
|
|
63
|
+
* Table schema:
|
|
64
|
+
* - Partition key: `pk` (String)
|
|
65
|
+
* - Attributes: `accessToken`, `refreshToken`, `tokenType`, `expiresAt`, `scopes`, `raw`
|
|
66
|
+
*/
|
|
67
|
+
export async function createDynamoDBTokenStore(options) {
|
|
68
|
+
const { tableName } = options;
|
|
69
|
+
const region = options.region || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || 'us-east-1';
|
|
70
|
+
const { DynamoDBClient } = await import('@aws-sdk/client-dynamodb');
|
|
71
|
+
const { DynamoDBDocumentClient, GetCommand, PutCommand, DeleteCommand } = await import('@aws-sdk/lib-dynamodb');
|
|
72
|
+
const client = DynamoDBDocumentClient.from(new DynamoDBClient({ region }));
|
|
73
|
+
return {
|
|
74
|
+
async get(key) {
|
|
75
|
+
const result = await client.send(new GetCommand({
|
|
76
|
+
TableName: tableName,
|
|
77
|
+
Key: { pk: key },
|
|
78
|
+
}));
|
|
79
|
+
if (!result.Item)
|
|
80
|
+
return null;
|
|
81
|
+
return {
|
|
82
|
+
accessToken: result.Item.accessToken,
|
|
83
|
+
refreshToken: result.Item.refreshToken,
|
|
84
|
+
tokenType: result.Item.tokenType,
|
|
85
|
+
expiresAt: result.Item.expiresAt,
|
|
86
|
+
scopes: result.Item.scopes,
|
|
87
|
+
raw: result.Item.raw,
|
|
88
|
+
};
|
|
89
|
+
},
|
|
90
|
+
async save(key, token) {
|
|
91
|
+
await client.send(new PutCommand({
|
|
92
|
+
TableName: tableName,
|
|
93
|
+
Item: {
|
|
94
|
+
pk: key,
|
|
95
|
+
...token,
|
|
96
|
+
ttl: Math.floor(token.expiresAt / 1000) + 86400, // Auto-expire 24h after token expiry
|
|
97
|
+
},
|
|
98
|
+
}));
|
|
99
|
+
},
|
|
100
|
+
async delete(key) {
|
|
101
|
+
await client.send(new DeleteCommand({
|
|
102
|
+
TableName: tableName,
|
|
103
|
+
Key: { pk: key },
|
|
104
|
+
}));
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function parseTokenResponse(data) {
|
|
109
|
+
const expiresIn = data.expires_in ?? 3600;
|
|
110
|
+
return {
|
|
111
|
+
accessToken: data.access_token,
|
|
112
|
+
refreshToken: data.refresh_token,
|
|
113
|
+
tokenType: data.token_type ?? 'Bearer',
|
|
114
|
+
expiresAt: Date.now() + expiresIn * 1000,
|
|
115
|
+
scopes: data.scope ? data.scope.split(' ') : undefined,
|
|
116
|
+
raw: data,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
async function fetchToken(tokenUrl, body) {
|
|
120
|
+
const response = await fetch(tokenUrl, {
|
|
121
|
+
method: 'POST',
|
|
122
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
123
|
+
body: new URLSearchParams(body).toString(),
|
|
124
|
+
});
|
|
125
|
+
if (!response.ok) {
|
|
126
|
+
const errorBody = await response.text();
|
|
127
|
+
throw new Error(`OAuth2 token request failed (${response.status}): ${errorBody}`);
|
|
128
|
+
}
|
|
129
|
+
const data = await response.json();
|
|
130
|
+
return parseTokenResponse(data);
|
|
131
|
+
}
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
// Factory
|
|
134
|
+
// ---------------------------------------------------------------------------
|
|
135
|
+
/**
|
|
136
|
+
* Create an OAuth2 client for a third-party API.
|
|
137
|
+
*/
|
|
138
|
+
export function oauth2(options) {
|
|
139
|
+
const { tokenUrl, clientId, clientSecret, scopes, store = createMemoryTokenStore(), storeKey = `oauth2:${clientId}`, refreshBufferSeconds = 60, extraParams = {}, } = options;
|
|
140
|
+
async function getStoredToken() {
|
|
141
|
+
return store.get(storeKey);
|
|
142
|
+
}
|
|
143
|
+
function isExpired(token) {
|
|
144
|
+
return Date.now() >= token.expiresAt - refreshBufferSeconds * 1000;
|
|
145
|
+
}
|
|
146
|
+
async function requestClientCredentials() {
|
|
147
|
+
const body = {
|
|
148
|
+
grant_type: 'client_credentials',
|
|
149
|
+
client_id: clientId,
|
|
150
|
+
client_secret: clientSecret,
|
|
151
|
+
...extraParams,
|
|
152
|
+
};
|
|
153
|
+
if (scopes?.length) {
|
|
154
|
+
body.scope = scopes.join(' ');
|
|
155
|
+
}
|
|
156
|
+
const token = await fetchToken(tokenUrl, body);
|
|
157
|
+
await store.save(storeKey, token);
|
|
158
|
+
return token;
|
|
159
|
+
}
|
|
160
|
+
async function requestRefresh(refreshToken) {
|
|
161
|
+
const body = {
|
|
162
|
+
grant_type: 'refresh_token',
|
|
163
|
+
client_id: clientId,
|
|
164
|
+
client_secret: clientSecret,
|
|
165
|
+
refresh_token: refreshToken,
|
|
166
|
+
...extraParams,
|
|
167
|
+
};
|
|
168
|
+
const token = await fetchToken(tokenUrl, body);
|
|
169
|
+
// Keep the old refresh token if the server didn't issue a new one
|
|
170
|
+
if (!token.refreshToken) {
|
|
171
|
+
token.refreshToken = refreshToken;
|
|
172
|
+
}
|
|
173
|
+
await store.save(storeKey, token);
|
|
174
|
+
return token;
|
|
175
|
+
}
|
|
176
|
+
async function exchangeCode(code) {
|
|
177
|
+
if (options.flow !== 'authorization_code') {
|
|
178
|
+
throw new Error('exchangeCode is only available for authorization_code flow');
|
|
179
|
+
}
|
|
180
|
+
const body = {
|
|
181
|
+
grant_type: 'authorization_code',
|
|
182
|
+
client_id: clientId,
|
|
183
|
+
client_secret: clientSecret,
|
|
184
|
+
code,
|
|
185
|
+
redirect_uri: options.redirectUri,
|
|
186
|
+
...extraParams,
|
|
187
|
+
};
|
|
188
|
+
const token = await fetchToken(tokenUrl, body);
|
|
189
|
+
await store.save(storeKey, token);
|
|
190
|
+
return token;
|
|
191
|
+
}
|
|
192
|
+
const client = {
|
|
193
|
+
async getToken() {
|
|
194
|
+
const existing = await getStoredToken();
|
|
195
|
+
if (existing && !isExpired(existing)) {
|
|
196
|
+
return existing;
|
|
197
|
+
}
|
|
198
|
+
// Try refresh if we have a refresh token
|
|
199
|
+
if (existing?.refreshToken) {
|
|
200
|
+
try {
|
|
201
|
+
return await requestRefresh(existing.refreshToken);
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
// Refresh failed — fall through to re-authenticate
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// Client credentials: always re-authenticate
|
|
208
|
+
if (options.flow === 'client_credentials') {
|
|
209
|
+
return requestClientCredentials();
|
|
210
|
+
}
|
|
211
|
+
// Authorization code: can't auto-authenticate, need user interaction
|
|
212
|
+
if (existing) {
|
|
213
|
+
// Return expired token — caller should handle re-authorization
|
|
214
|
+
return existing;
|
|
215
|
+
}
|
|
216
|
+
throw new Error('No token available. Use exchangeCode() to obtain an initial token via the authorization code flow.');
|
|
217
|
+
},
|
|
218
|
+
async refreshToken() {
|
|
219
|
+
const existing = await getStoredToken();
|
|
220
|
+
if (existing?.refreshToken) {
|
|
221
|
+
return requestRefresh(existing.refreshToken);
|
|
222
|
+
}
|
|
223
|
+
if (options.flow === 'client_credentials') {
|
|
224
|
+
return requestClientCredentials();
|
|
225
|
+
}
|
|
226
|
+
throw new Error('No refresh token available');
|
|
227
|
+
},
|
|
228
|
+
interceptor() {
|
|
229
|
+
return async (_url, init) => {
|
|
230
|
+
const token = await client.getToken();
|
|
231
|
+
const headers = new Headers(init.headers);
|
|
232
|
+
headers.set('Authorization', `${token.tokenType} ${token.accessToken}`);
|
|
233
|
+
return { ...init, headers };
|
|
234
|
+
};
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
// Add authorization_code specific methods
|
|
238
|
+
if (options.flow === 'authorization_code') {
|
|
239
|
+
client.exchangeCode = exchangeCode;
|
|
240
|
+
client.getAuthorizeUrl = (state) => {
|
|
241
|
+
const params = new URLSearchParams({
|
|
242
|
+
response_type: 'code',
|
|
243
|
+
client_id: clientId,
|
|
244
|
+
redirect_uri: options.redirectUri,
|
|
245
|
+
...extraParams,
|
|
246
|
+
});
|
|
247
|
+
if (scopes?.length)
|
|
248
|
+
params.set('scope', scopes.join(' '));
|
|
249
|
+
if (state)
|
|
250
|
+
params.set('state', state);
|
|
251
|
+
return `${options.authorizeUrl}?${params.toString()}`;
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
return client;
|
|
255
|
+
}
|
|
256
|
+
//# sourceMappingURL=oauth2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth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,IAAI,MAAM,CAAC,QAAQ,EAAE,EAAE,CAAC;QACxD,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VentureKit API Client
|
|
3
|
+
*
|
|
4
|
+
* A configurable HTTP client for calling third-party APIs.
|
|
5
|
+
* Built on top of the native `fetch` API with:
|
|
6
|
+
* - Automatic retry with exponential backoff
|
|
7
|
+
* - Timeout enforcement
|
|
8
|
+
* - Request/response interceptors
|
|
9
|
+
* - Structured error handling
|
|
10
|
+
* - Built-in circuit breaker support
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { apiClient } from '@venturekit/integrations';
|
|
15
|
+
*
|
|
16
|
+
* const stripe = apiClient({
|
|
17
|
+
* baseUrl: 'https://api.stripe.com/v1',
|
|
18
|
+
* headers: { Authorization: `Bearer ${STRIPE_KEY}` },
|
|
19
|
+
* retry: { maxRetries: 3 },
|
|
20
|
+
* timeout: 10_000,
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* const customer = await stripe.post<StripeCustomer>('/customers', {
|
|
24
|
+
* body: { email: 'user@example.com' },
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export interface ApiClientOptions {
|
|
29
|
+
/** Base URL for all requests (e.g. 'https://api.stripe.com/v1') */
|
|
30
|
+
baseUrl: string;
|
|
31
|
+
/** Default headers sent with every request */
|
|
32
|
+
headers?: Record<string, string>;
|
|
33
|
+
/** Default timeout in ms (default: 30000) */
|
|
34
|
+
timeout?: number;
|
|
35
|
+
/** Retry configuration */
|
|
36
|
+
retry?: RetryOptions;
|
|
37
|
+
/** Request interceptors — called before each request */
|
|
38
|
+
onRequest?: RequestInterceptor[];
|
|
39
|
+
/** Response interceptors — called after each response */
|
|
40
|
+
onResponse?: ResponseInterceptor[];
|
|
41
|
+
/** Error interceptor — called on any error before it's thrown */
|
|
42
|
+
onError?: ErrorInterceptor;
|
|
43
|
+
}
|
|
44
|
+
export interface RetryOptions {
|
|
45
|
+
/** Max number of retries (default: 0 = no retry) */
|
|
46
|
+
maxRetries?: number;
|
|
47
|
+
/** Initial delay in ms (default: 1000) */
|
|
48
|
+
initialDelayMs?: number;
|
|
49
|
+
/** Backoff multiplier (default: 2) */
|
|
50
|
+
backoffMultiplier?: number;
|
|
51
|
+
/** HTTP status codes that trigger a retry (default: [408, 429, 500, 502, 503, 504]) */
|
|
52
|
+
retryableStatuses?: number[];
|
|
53
|
+
}
|
|
54
|
+
export interface ApiRequestOptions {
|
|
55
|
+
/** Request body (automatically JSON-stringified if object) */
|
|
56
|
+
body?: unknown;
|
|
57
|
+
/** Additional headers for this request */
|
|
58
|
+
headers?: Record<string, string>;
|
|
59
|
+
/** Query parameters */
|
|
60
|
+
params?: Record<string, string | number | boolean | undefined>;
|
|
61
|
+
/** Timeout override for this request (ms) */
|
|
62
|
+
timeout?: number;
|
|
63
|
+
/** Send body as form-urlencoded instead of JSON */
|
|
64
|
+
form?: boolean;
|
|
65
|
+
/** AbortSignal for cancellation */
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
}
|
|
68
|
+
export interface ApiResponse<T = unknown> {
|
|
69
|
+
/** HTTP status code */
|
|
70
|
+
status: number;
|
|
71
|
+
/** Response headers */
|
|
72
|
+
headers: Record<string, string>;
|
|
73
|
+
/** Parsed response body */
|
|
74
|
+
data: T;
|
|
75
|
+
/** Whether the request was retried */
|
|
76
|
+
retried: boolean;
|
|
77
|
+
/** Number of retry attempts made */
|
|
78
|
+
attempts: number;
|
|
79
|
+
}
|
|
80
|
+
export declare class ApiError extends Error {
|
|
81
|
+
readonly status: number;
|
|
82
|
+
readonly headers: Record<string, string>;
|
|
83
|
+
readonly data: unknown;
|
|
84
|
+
readonly url: string;
|
|
85
|
+
readonly method: string;
|
|
86
|
+
constructor(options: {
|
|
87
|
+
message: string;
|
|
88
|
+
status: number;
|
|
89
|
+
headers: Record<string, string>;
|
|
90
|
+
data: unknown;
|
|
91
|
+
url: string;
|
|
92
|
+
method: string;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
export type RequestInterceptor = (url: string, init: RequestInit) => RequestInit | Promise<RequestInit>;
|
|
96
|
+
export type ResponseInterceptor = (response: ApiResponse<unknown>) => ApiResponse<unknown> | Promise<ApiResponse<unknown>>;
|
|
97
|
+
export type ErrorInterceptor = (error: ApiError) => void | Promise<void>;
|
|
98
|
+
export interface ApiClient {
|
|
99
|
+
get<T = unknown>(path: string, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
100
|
+
post<T = unknown>(path: string, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
101
|
+
put<T = unknown>(path: string, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
102
|
+
patch<T = unknown>(path: string, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
103
|
+
delete<T = unknown>(path: string, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
104
|
+
request<T = unknown>(method: string, path: string, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Create a configured API client for calling third-party APIs.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```typescript
|
|
111
|
+
* const github = apiClient({
|
|
112
|
+
* baseUrl: 'https://api.github.com',
|
|
113
|
+
* headers: {
|
|
114
|
+
* Authorization: `Bearer ${GITHUB_TOKEN}`,
|
|
115
|
+
* Accept: 'application/vnd.github.v3+json',
|
|
116
|
+
* },
|
|
117
|
+
* retry: { maxRetries: 2 },
|
|
118
|
+
* });
|
|
119
|
+
*
|
|
120
|
+
* const repos = await github.get<Repo[]>('/user/repos');
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
export declare function apiClient(options: ApiClientOptions): ApiClient;
|
|
124
|
+
//# sourceMappingURL=client.d.ts.map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,MAAM,WAAW,SAAS;IACxB,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IACrF,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IACtF,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IACrF,KAAK,CAAC,CAAC,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IACvF,MAAM,CAAC,CAAC,GAAG,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IACxF,OAAO,CAAC,CAAC,GAAG,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;CAC1G;AAkDD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,SAAS,CAqK9D"}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VentureKit API Client
|
|
3
|
+
*
|
|
4
|
+
* A configurable HTTP client for calling third-party APIs.
|
|
5
|
+
* Built on top of the native `fetch` API with:
|
|
6
|
+
* - Automatic retry with exponential backoff
|
|
7
|
+
* - Timeout enforcement
|
|
8
|
+
* - Request/response interceptors
|
|
9
|
+
* - Structured error handling
|
|
10
|
+
* - Built-in circuit breaker support
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* import { apiClient } from '@venturekit/integrations';
|
|
15
|
+
*
|
|
16
|
+
* const stripe = apiClient({
|
|
17
|
+
* baseUrl: 'https://api.stripe.com/v1',
|
|
18
|
+
* headers: { Authorization: `Bearer ${STRIPE_KEY}` },
|
|
19
|
+
* retry: { maxRetries: 3 },
|
|
20
|
+
* timeout: 10_000,
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* const customer = await stripe.post<StripeCustomer>('/customers', {
|
|
24
|
+
* body: { email: 'user@example.com' },
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export class ApiError extends Error {
|
|
29
|
+
status;
|
|
30
|
+
headers;
|
|
31
|
+
data;
|
|
32
|
+
url;
|
|
33
|
+
method;
|
|
34
|
+
constructor(options) {
|
|
35
|
+
super(options.message);
|
|
36
|
+
this.name = 'ApiError';
|
|
37
|
+
this.status = options.status;
|
|
38
|
+
this.headers = options.headers;
|
|
39
|
+
this.data = options.data;
|
|
40
|
+
this.url = options.url;
|
|
41
|
+
this.method = options.method;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
// Helpers
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
const DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
|
|
48
|
+
function buildUrl(baseUrl, path, params) {
|
|
49
|
+
const url = new URL(path, baseUrl.endsWith('/') ? baseUrl : baseUrl + '/');
|
|
50
|
+
if (params) {
|
|
51
|
+
for (const [key, value] of Object.entries(params)) {
|
|
52
|
+
if (value !== undefined) {
|
|
53
|
+
url.searchParams.set(key, String(value));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return url.toString();
|
|
58
|
+
}
|
|
59
|
+
function headersToRecord(headers) {
|
|
60
|
+
const result = {};
|
|
61
|
+
headers.forEach((value, key) => {
|
|
62
|
+
result[key] = value;
|
|
63
|
+
});
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
function buildBody(body, form) {
|
|
67
|
+
if (body === undefined || body === null)
|
|
68
|
+
return undefined;
|
|
69
|
+
if (form && typeof body === 'object') {
|
|
70
|
+
return new URLSearchParams(Object.entries(body).map(([k, v]) => [k, String(v)])).toString();
|
|
71
|
+
}
|
|
72
|
+
return typeof body === 'string' ? body : JSON.stringify(body);
|
|
73
|
+
}
|
|
74
|
+
async function sleep(ms) {
|
|
75
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
76
|
+
}
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// Factory
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
/**
|
|
81
|
+
* Create a configured API client for calling third-party APIs.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```typescript
|
|
85
|
+
* const github = apiClient({
|
|
86
|
+
* baseUrl: 'https://api.github.com',
|
|
87
|
+
* headers: {
|
|
88
|
+
* Authorization: `Bearer ${GITHUB_TOKEN}`,
|
|
89
|
+
* Accept: 'application/vnd.github.v3+json',
|
|
90
|
+
* },
|
|
91
|
+
* retry: { maxRetries: 2 },
|
|
92
|
+
* });
|
|
93
|
+
*
|
|
94
|
+
* const repos = await github.get<Repo[]>('/user/repos');
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export function apiClient(options) {
|
|
98
|
+
const { baseUrl, headers: defaultHeaders = {}, timeout: defaultTimeout = 30_000, retry: retryConfig = {}, onRequest = [], onResponse = [], onError, } = options;
|
|
99
|
+
const { maxRetries = 0, initialDelayMs = 1000, backoffMultiplier = 2, retryableStatuses = DEFAULT_RETRYABLE_STATUSES, } = retryConfig;
|
|
100
|
+
async function request(method, path, reqOptions = {}) {
|
|
101
|
+
const url = buildUrl(baseUrl, path, reqOptions.params);
|
|
102
|
+
const timeoutMs = reqOptions.timeout ?? defaultTimeout;
|
|
103
|
+
const contentType = reqOptions.form
|
|
104
|
+
? 'application/x-www-form-urlencoded'
|
|
105
|
+
: 'application/json';
|
|
106
|
+
const mergedHeaders = {
|
|
107
|
+
'Content-Type': contentType,
|
|
108
|
+
...defaultHeaders,
|
|
109
|
+
...reqOptions.headers,
|
|
110
|
+
};
|
|
111
|
+
// Remove Content-Type for GET/HEAD (no body)
|
|
112
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
113
|
+
delete mergedHeaders['Content-Type'];
|
|
114
|
+
}
|
|
115
|
+
let init = {
|
|
116
|
+
method,
|
|
117
|
+
headers: mergedHeaders,
|
|
118
|
+
body: buildBody(reqOptions.body, reqOptions.form ?? false),
|
|
119
|
+
signal: reqOptions.signal,
|
|
120
|
+
};
|
|
121
|
+
// Run request interceptors
|
|
122
|
+
for (const interceptor of onRequest) {
|
|
123
|
+
init = await interceptor(url, init);
|
|
124
|
+
}
|
|
125
|
+
let lastError;
|
|
126
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
127
|
+
// Timeout via AbortController
|
|
128
|
+
const controller = new AbortController();
|
|
129
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
130
|
+
// Combine user signal with timeout signal
|
|
131
|
+
const combinedSignal = reqOptions.signal
|
|
132
|
+
? anySignal([reqOptions.signal, controller.signal])
|
|
133
|
+
: controller.signal;
|
|
134
|
+
try {
|
|
135
|
+
const fetchInit = { ...init, signal: combinedSignal };
|
|
136
|
+
const response = await fetch(url, fetchInit);
|
|
137
|
+
clearTimeout(timeoutId);
|
|
138
|
+
const responseHeaders = headersToRecord(response.headers);
|
|
139
|
+
// Parse response body
|
|
140
|
+
let data;
|
|
141
|
+
const contentTypeHeader = response.headers.get('content-type') ?? '';
|
|
142
|
+
if (contentTypeHeader.includes('application/json')) {
|
|
143
|
+
data = await response.json();
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
data = await response.text();
|
|
147
|
+
}
|
|
148
|
+
// Non-success status
|
|
149
|
+
if (!response.ok) {
|
|
150
|
+
const apiError = new ApiError({
|
|
151
|
+
message: `${method} ${url} failed with status ${response.status}`,
|
|
152
|
+
status: response.status,
|
|
153
|
+
headers: responseHeaders,
|
|
154
|
+
data,
|
|
155
|
+
url,
|
|
156
|
+
method,
|
|
157
|
+
});
|
|
158
|
+
// Retry on retryable statuses
|
|
159
|
+
if (attempt < maxRetries && retryableStatuses.includes(response.status)) {
|
|
160
|
+
// Respect Retry-After header if present
|
|
161
|
+
const retryAfter = response.headers.get('retry-after');
|
|
162
|
+
const delay = retryAfter
|
|
163
|
+
? parseInt(retryAfter, 10) * 1000
|
|
164
|
+
: initialDelayMs * Math.pow(backoffMultiplier, attempt);
|
|
165
|
+
await sleep(delay);
|
|
166
|
+
lastError = apiError;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (onError)
|
|
170
|
+
await onError(apiError);
|
|
171
|
+
throw apiError;
|
|
172
|
+
}
|
|
173
|
+
let apiResponse = {
|
|
174
|
+
status: response.status,
|
|
175
|
+
headers: responseHeaders,
|
|
176
|
+
data,
|
|
177
|
+
retried: attempt > 0,
|
|
178
|
+
attempts: attempt + 1,
|
|
179
|
+
};
|
|
180
|
+
// Run response interceptors
|
|
181
|
+
for (const interceptor of onResponse) {
|
|
182
|
+
apiResponse = await interceptor(apiResponse);
|
|
183
|
+
}
|
|
184
|
+
return apiResponse;
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
clearTimeout(timeoutId);
|
|
188
|
+
if (error instanceof ApiError)
|
|
189
|
+
throw error;
|
|
190
|
+
// Network / timeout errors — retry if possible
|
|
191
|
+
const isAbort = error instanceof DOMException && error.name === 'AbortError';
|
|
192
|
+
const errMsg = isAbort
|
|
193
|
+
? `Request timeout after ${timeoutMs}ms: ${method} ${url}`
|
|
194
|
+
: `Network error: ${method} ${url} — ${error instanceof Error ? error.message : String(error)}`;
|
|
195
|
+
lastError = new ApiError({
|
|
196
|
+
message: errMsg,
|
|
197
|
+
status: 0,
|
|
198
|
+
headers: {},
|
|
199
|
+
data: null,
|
|
200
|
+
url,
|
|
201
|
+
method,
|
|
202
|
+
});
|
|
203
|
+
if (attempt < maxRetries) {
|
|
204
|
+
const delay = initialDelayMs * Math.pow(backoffMultiplier, attempt);
|
|
205
|
+
await sleep(delay);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (onError)
|
|
209
|
+
await onError(lastError);
|
|
210
|
+
throw lastError;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
// Should not reach here, but safety net
|
|
214
|
+
throw lastError ?? new Error(`Request failed: ${method} ${url}`);
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
get: (path, opts) => request('GET', path, opts),
|
|
218
|
+
post: (path, opts) => request('POST', path, opts),
|
|
219
|
+
put: (path, opts) => request('PUT', path, opts),
|
|
220
|
+
patch: (path, opts) => request('PATCH', path, opts),
|
|
221
|
+
delete: (path, opts) => request('DELETE', path, opts),
|
|
222
|
+
request,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
// ---------------------------------------------------------------------------
|
|
226
|
+
// Signal helper — combine multiple AbortSignals
|
|
227
|
+
// ---------------------------------------------------------------------------
|
|
228
|
+
function anySignal(signals) {
|
|
229
|
+
const controller = new AbortController();
|
|
230
|
+
for (const signal of signals) {
|
|
231
|
+
if (signal.aborted) {
|
|
232
|
+
controller.abort(signal.reason);
|
|
233
|
+
return controller.signal;
|
|
234
|
+
}
|
|
235
|
+
signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
|
|
236
|
+
}
|
|
237
|
+
return controller.signal;
|
|
238
|
+
}
|
|
239
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":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