astro-tokenkit 1.0.2 → 1.0.3

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.
Files changed (2) hide show
  1. package/dist/index.d.ts +347 -6
  2. package/package.json +2 -2
package/dist/index.d.ts CHANGED
@@ -1,6 +1,347 @@
1
- export { createClient, APIClient } from './client/client';
2
- export { tokenKit, defineMiddleware } from './integration';
3
- export { createMiddleware } from './middleware';
4
- export type { ClientConfig, AuthConfig, RefreshPolicy, CookieConfig, RetryConfig, RequestOptions, RequestConfig, APIResponse, Session, TokenBundle, FieldMapping, RequestInterceptor, ResponseInterceptor, ErrorInterceptor, TokenKitContext } from './types';
5
- export { APIError, AuthError, NetworkError, TimeoutError, } from './types';
6
- export { parseTime, formatTime } from './utils/time';
1
+ import * as astro from 'astro';
2
+ import { AstroCookies, AstroIntegration, MiddlewareHandler } from 'astro';
3
+ import { AsyncLocalStorage } from 'node:async_hooks';
4
+
5
+ /**
6
+ * Token bundle returned from auth endpoints
7
+ */
8
+ interface TokenBundle {
9
+ accessToken: string;
10
+ refreshToken: string;
11
+ accessExpiresAt: number;
12
+ refreshExpiresAt?: number;
13
+ sessionPayload?: Record<string, any>;
14
+ }
15
+ /**
16
+ * Minimal context required by TokenKit
17
+ */
18
+ interface TokenKitContext {
19
+ cookies: AstroCookies;
20
+ [key: string]: any;
21
+ }
22
+ /**
23
+ * Session information
24
+ */
25
+ interface Session {
26
+ accessToken: string;
27
+ expiresAt: number;
28
+ payload?: Record<string, any>;
29
+ }
30
+ /**
31
+ * Request options
32
+ */
33
+ interface RequestOptions {
34
+ /** Astro context (optional if middleware binds it) */
35
+ ctx?: TokenKitContext;
36
+ /** Additional headers */
37
+ headers?: Record<string, string>;
38
+ /** Request timeout in ms */
39
+ timeout?: number;
40
+ /** Query parameters */
41
+ params?: Record<string, any>;
42
+ /** Skip authentication for this request */
43
+ skipAuth?: boolean;
44
+ /** Custom signal for cancellation */
45
+ signal?: AbortSignal;
46
+ }
47
+ /**
48
+ * Request configuration
49
+ */
50
+ interface RequestConfig extends RequestOptions {
51
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
52
+ url: string;
53
+ data?: any;
54
+ }
55
+ /**
56
+ * HTTP response
57
+ */
58
+ interface APIResponse<T = any> {
59
+ data: T;
60
+ status: number;
61
+ statusText: string;
62
+ headers: Headers;
63
+ url: string;
64
+ }
65
+ /**
66
+ * Field mapping for auto-detection
67
+ */
68
+ interface FieldMapping {
69
+ accessToken?: string;
70
+ refreshToken?: string;
71
+ expiresAt?: string;
72
+ expiresIn?: string;
73
+ sessionPayload?: string;
74
+ }
75
+ /**
76
+ * Auth configuration
77
+ */
78
+ interface AuthConfig {
79
+ /** Login endpoint (relative to baseURL) */
80
+ login: string;
81
+ /** Refresh endpoint (relative to baseURL) */
82
+ refresh: string;
83
+ /** Logout endpoint (optional, relative to baseURL) */
84
+ logout?: string;
85
+ /** Field mapping (auto-detected if not provided) */
86
+ fields?: FieldMapping;
87
+ /** Custom login response parser */
88
+ parseLogin?: (body: any) => TokenBundle;
89
+ /** Custom refresh response parser */
90
+ parseRefresh?: (body: any) => TokenBundle;
91
+ /** Custom token injection function (default: Bearer) */
92
+ injectToken?: (token: string) => string;
93
+ /** Refresh policy */
94
+ policy?: RefreshPolicy;
95
+ /** Cookie configuration */
96
+ cookies?: CookieConfig;
97
+ }
98
+ /**
99
+ * Refresh policy
100
+ */
101
+ interface RefreshPolicy {
102
+ /** Refresh before expiry (e.g., '5m' or 300) */
103
+ refreshBefore?: string | number;
104
+ /** Clock skew tolerance (e.g., '1m' or 60) */
105
+ clockSkew?: string | number;
106
+ /** Minimum interval between refreshes (e.g., '30s' or 30) */
107
+ minInterval?: string | number;
108
+ }
109
+ /**
110
+ * Cookie configuration
111
+ */
112
+ interface CookieConfig {
113
+ /** Secure flag (auto-detected from NODE_ENV if not set) */
114
+ secure?: boolean;
115
+ /** SameSite policy */
116
+ sameSite?: 'strict' | 'lax' | 'none';
117
+ /** Cookie domain */
118
+ domain?: string;
119
+ /** Cookie names prefix */
120
+ prefix?: string;
121
+ }
122
+ /**
123
+ * Retry configuration
124
+ */
125
+ interface RetryConfig {
126
+ /** Number of retry attempts */
127
+ attempts?: number;
128
+ /** Status codes to retry */
129
+ statusCodes?: number[];
130
+ /** Backoff strategy */
131
+ backoff?: 'linear' | 'exponential';
132
+ /** Initial delay in ms */
133
+ delay?: number;
134
+ }
135
+ /**
136
+ * Request interceptor
137
+ */
138
+ type RequestInterceptor = (config: RequestConfig, ctx?: TokenKitContext) => RequestConfig | Promise<RequestConfig>;
139
+ /**
140
+ * Response interceptor
141
+ */
142
+ type ResponseInterceptor = <T = any>(response: APIResponse<T>, ctx?: TokenKitContext) => APIResponse<T> | Promise<APIResponse<T>>;
143
+ /**
144
+ * Error interceptor
145
+ */
146
+ type ErrorInterceptor = (error: APIError, ctx?: TokenKitContext) => never | Promise<never>;
147
+ /**
148
+ * Interceptors configuration
149
+ */
150
+ interface InterceptorsConfig {
151
+ request?: RequestInterceptor[];
152
+ response?: ResponseInterceptor[];
153
+ error?: ErrorInterceptor[];
154
+ }
155
+ /**
156
+ * Client configuration
157
+ */
158
+ interface ClientConfig {
159
+ /** Base URL for all requests */
160
+ baseURL: string;
161
+ /** Auth configuration (optional for non-auth clients) */
162
+ auth?: AuthConfig;
163
+ /** Default headers for all requests */
164
+ headers?: Record<string, string>;
165
+ /** Default timeout in ms */
166
+ timeout?: number;
167
+ /** Retry configuration */
168
+ retry?: RetryConfig;
169
+ /** Interceptors */
170
+ interceptors?: InterceptorsConfig;
171
+ /** External AsyncLocalStorage instance (optional) */
172
+ context?: AsyncLocalStorage<any>;
173
+ /** Method to get the context store (optional) */
174
+ getContextStore?: () => TokenKitContext | undefined | null;
175
+ }
176
+ /**
177
+ * API Error
178
+ */
179
+ declare class APIError extends Error {
180
+ status?: number | undefined;
181
+ response?: any | undefined;
182
+ request?: RequestConfig | undefined;
183
+ constructor(message: string, status?: number | undefined, response?: any | undefined, request?: RequestConfig | undefined);
184
+ }
185
+ /**
186
+ * Authentication Error
187
+ */
188
+ declare class AuthError extends APIError {
189
+ constructor(message: string, status?: number, response?: any, request?: RequestConfig);
190
+ }
191
+ /**
192
+ * Network Error
193
+ */
194
+ declare class NetworkError extends APIError {
195
+ constructor(message: string, request?: RequestConfig);
196
+ }
197
+ /**
198
+ * Timeout Error
199
+ */
200
+ declare class TimeoutError extends APIError {
201
+ constructor(message: string, request?: RequestConfig);
202
+ }
203
+
204
+ /**
205
+ * Token Manager handles all token operations
206
+ */
207
+ declare class TokenManager {
208
+ private config;
209
+ private singleFlight;
210
+ private baseURL;
211
+ constructor(config: AuthConfig, baseURL: string);
212
+ /**
213
+ * Perform login
214
+ */
215
+ login(ctx: TokenKitContext, credentials: any): Promise<TokenBundle>;
216
+ /**
217
+ * Perform token refresh
218
+ */
219
+ refresh(ctx: TokenKitContext, refreshToken: string): Promise<TokenBundle | null>;
220
+ /**
221
+ * Ensure valid tokens (with automatic refresh)
222
+ */
223
+ ensure(ctx: TokenKitContext): Promise<Session | null>;
224
+ /**
225
+ * Logout (clear tokens)
226
+ */
227
+ logout(ctx: TokenKitContext): Promise<void>;
228
+ /**
229
+ * Get current session (no refresh)
230
+ */
231
+ getSession(ctx: TokenKitContext): Session | null;
232
+ /**
233
+ * Check if authenticated
234
+ */
235
+ isAuthenticated(ctx: TokenKitContext): boolean;
236
+ /**
237
+ * Create flight key for single-flight deduplication
238
+ */
239
+ private createFlightKey;
240
+ }
241
+
242
+ /**
243
+ * Configuration for context handling
244
+ */
245
+ interface ContextOptions {
246
+ context?: AsyncLocalStorage<any>;
247
+ getContextStore?: () => TokenKitContext | undefined | null;
248
+ }
249
+
250
+ /**
251
+ * API Client
252
+ */
253
+ declare class APIClient {
254
+ tokenManager?: TokenManager;
255
+ private config;
256
+ contextOptions: ContextOptions;
257
+ constructor(config: ClientConfig);
258
+ /**
259
+ * GET request
260
+ */
261
+ get<T = any>(url: string, options?: RequestOptions): Promise<T>;
262
+ /**
263
+ * POST request
264
+ */
265
+ post<T = any>(url: string, data?: any, options?: RequestOptions): Promise<T>;
266
+ /**
267
+ * PUT request
268
+ */
269
+ put<T = any>(url: string, data?: any, options?: RequestOptions): Promise<T>;
270
+ /**
271
+ * PATCH request
272
+ */
273
+ patch<T = any>(url: string, data?: any, options?: RequestOptions): Promise<T>;
274
+ /**
275
+ * DELETE request
276
+ */
277
+ delete<T = any>(url: string, options?: RequestOptions): Promise<T>;
278
+ /**
279
+ * Generic request method
280
+ */
281
+ request<T = any>(config: RequestConfig): Promise<T>;
282
+ /**
283
+ * Execute single request
284
+ */
285
+ private executeRequest;
286
+ /**
287
+ * Parse response
288
+ */
289
+ private parseResponse;
290
+ /**
291
+ * Build full URL with query params
292
+ */
293
+ private buildURL;
294
+ /**
295
+ * Build request headers
296
+ */
297
+ private buildHeaders;
298
+ /**
299
+ * Login
300
+ */
301
+ login(credentials: any, ctx?: TokenKitContext): Promise<void>;
302
+ /**
303
+ * Logout
304
+ */
305
+ logout(ctx?: TokenKitContext): Promise<void>;
306
+ /**
307
+ * Check if authenticated
308
+ */
309
+ isAuthenticated(ctx?: TokenKitContext): boolean;
310
+ /**
311
+ * Get current session
312
+ */
313
+ getSession(ctx?: TokenKitContext): Session | null;
314
+ }
315
+ /**
316
+ * Create API client
317
+ */
318
+ declare function createClient(config: ClientConfig): APIClient;
319
+
320
+ /**
321
+ * Astro integration for TokenKit
322
+ *
323
+ * This integration facilitates the setup of TokenKit in an Astro project.
324
+ */
325
+ declare function tokenKit(client?: APIClient): AstroIntegration;
326
+ /**
327
+ * Helper to define middleware in a separate file if needed
328
+ */
329
+ declare const defineMiddleware: (client: APIClient) => astro.MiddlewareHandler;
330
+
331
+ /**
332
+ * Create middleware for context binding and automatic token rotation
333
+ */
334
+ declare function createMiddleware(client: APIClient): MiddlewareHandler;
335
+
336
+ /**
337
+ * Parse time string to seconds
338
+ * Supports: '5m', '30s', '1h', '2d'
339
+ */
340
+ declare function parseTime(input: string | number): number;
341
+ /**
342
+ * Format seconds to human-readable string
343
+ */
344
+ declare function formatTime(seconds: number): string;
345
+
346
+ export { APIClient, APIError, AuthError, NetworkError, TimeoutError, createClient, createMiddleware, defineMiddleware, formatTime, parseTime, tokenKit };
347
+ export type { APIResponse, AuthConfig, ClientConfig, CookieConfig, ErrorInterceptor, FieldMapping, RefreshPolicy, RequestConfig, RequestInterceptor, RequestOptions, ResponseInterceptor, RetryConfig, Session, TokenBundle, TokenKitContext };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro-tokenkit",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "A powerful API client for Astro with automatic token rotation, session management, and seamless context integration.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -25,7 +25,6 @@
25
25
  "refresh-token",
26
26
  "middleware"
27
27
  ],
28
- "dependencies": {},
29
28
  "peerDependencies": {
30
29
  "astro": "^4.0.0 || ^5.0.0"
31
30
  },
@@ -35,6 +34,7 @@
35
34
  "@types/node": "^20.11.0",
36
35
  "rimraf": "^6.0.1",
37
36
  "rollup": "^4.56.0",
37
+ "rollup-plugin-dts": "^6.3.0",
38
38
  "tslib": "^2.8.1",
39
39
  "typescript": "^5.3.3",
40
40
  "vitest": "^1.2.1"