fetchguard 2.2.0 → 2.2.2

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 CHANGED
@@ -524,8 +524,12 @@ For complex auth flows with custom parsers or strategies, use `workerFactory` to
524
524
 
525
525
  ```ts
526
526
  // my-worker.ts
527
- import { registerProvider, createProvider } from 'fetchguard'
528
- import { createIndexedDBStorage } from 'fetchguard'
527
+ // IMPORTANT: Import from 'fetchguard/worker' to ensure same registry instance!
528
+ import {
529
+ registerProvider,
530
+ createProvider,
531
+ createIndexedDBStorage
532
+ } from 'fetchguard/worker'
529
533
 
530
534
  // Register custom provider INSIDE the worker
531
535
  registerProvider('my-custom-auth', createProvider({
@@ -577,9 +581,6 @@ registerProvider('my-custom-auth', createProvider({
577
581
  }
578
582
  }
579
583
  }))
580
-
581
- // Re-export worker entry point (required!)
582
- export * from 'fetchguard/worker'
583
584
  ```
584
585
 
585
586
  **Step 2: Use workerFactory in main thread**
package/dist/index.d.ts CHANGED
@@ -1,493 +1,8 @@
1
+ import { F as FetchGuardOptions, a as FetchGuardRequestInit, b as FetchEnvelope, A as AuthResult, W as WorkerConfig, P as ProviderPresetConfig, R as RefreshReason, T as TokenProvider, S as SerializedFormDataResult, c as SerializedFormData } from './worker-DBL8XAZJ.js';
2
+ export { f as AuthStrategy, D as DebugHooks, n as DedupeConfig, E as ExchangeTokenOptions, I as IndexedDBStorageOptions, N as NetworkErrorDetail, w as ProviderConfig, d as RefreshTokenStorage, o as RequestMetrics, m as RetryConfig, h as SerializedFile, i as SerializedFormDataEntry, l as StorageErrorCallback, k as StorageErrorContext, g as TokenInfo, e as TokenParser, j as TransportResult, y as bodyParser, G as bodyStrategy, t as clearProviders, z as cookieParser, B as cookieStrategy, H as createBodyStrategy, C as createCookieStrategy, x as createIndexedDBStorage, v as createProvider, p as getProvider, q as hasProvider, s as listProviders, r as registerProvider, u as unregisterProvider } from './worker-DBL8XAZJ.js';
1
3
  import * as ts_micro_result from 'ts-micro-result';
2
4
  import { Result, ErrorDetail, ResultMeta } from 'ts-micro-result';
3
5
 
4
- /**
5
- * FetchGuard Business Types
6
- *
7
- * Contains domain logic types: Provider, Config, API Response, etc.
8
- * For message protocol types, see messages.ts
9
- */
10
- /**
11
- * Token info returned from provider
12
- *
13
- * All fields are optional to support various custom auth methods:
14
- * - Standard login/refresh: returns token + optional fields
15
- * - Update user info: may only return user (no token update)
16
- * - Verify OTP: may return nothing (just validation)
17
- * - Custom auth flows: flexible field combinations
18
- */
19
- interface TokenInfo {
20
- token?: string | null;
21
- expiresAt?: number | null;
22
- refreshToken?: string | null;
23
- user?: unknown;
24
- }
25
- /**
26
- * Options for token exchange operation
27
- *
28
- * Used when switching tenant, changing scope, or any operation
29
- * that exchanges current token for a new one with different claims
30
- */
31
- interface ExchangeTokenOptions {
32
- /** HTTP method to use. Default: 'POST' */
33
- method?: 'POST' | 'PUT';
34
- /** Payload to send with the request (e.g., tenantId, scope) */
35
- payload?: Record<string, unknown>;
36
- /** Custom headers for this request. Overrides defaultHeaders if same key. */
37
- headers?: Record<string, string>;
38
- }
39
- /**
40
- * Auth result returned from auth operations and auth state changes
41
- * Used by: login(), logout(), refreshToken(), onAuthStateChanged()
42
- */
43
- interface AuthResult {
44
- /** Whether user is authenticated (has valid non-expired token) */
45
- authenticated: boolean;
46
- /** User info from token (if available) */
47
- user?: unknown;
48
- /** Token expiry timestamp in milliseconds (if available) */
49
- expiresAt?: number | null;
50
- }
51
- /**
52
- * Interface for token provider
53
- *
54
- * Provider has 3 required methods:
55
- * - refreshToken: Refresh access token when expired
56
- * - login: Login with credentials
57
- * - logout: Logout (clear tokens)
58
- *
59
- * User can add custom auth methods (loginWithPhone, loginWithGoogle, etc.)
60
- * All custom methods must return Result<TokenInfo> for token retrieval
61
- */
62
- interface TokenProvider {
63
- /**
64
- * Refresh tokens (required)
65
- * @param refreshToken - Current refresh token (from worker memory, null if not available)
66
- * @returns Result<TokenInfo> with new tokens
67
- */
68
- refreshToken(refreshToken: string | null): Promise<Result<TokenInfo>>;
69
- /**
70
- * Login with credentials (required)
71
- * @param payload - Login credentials (email/password, etc.)
72
- * @param url - Optional URL override (if not provided, uses configured loginUrl)
73
- * @returns Result<TokenInfo> with tokens
74
- */
75
- login(payload: unknown, url?: string): Promise<Result<TokenInfo>>;
76
- /**
77
- * Logout - clear tokens (required)
78
- * @param payload - Optional logout payload
79
- * @returns Result<TokenInfo> with all fields reset (token = '', refreshToken = undefined, user = undefined)
80
- */
81
- logout(payload?: unknown): Promise<Result<TokenInfo>>;
82
- /**
83
- * Exchange current token for a new one with different context
84
- *
85
- * Useful for switching tenants, changing scopes, or any operation
86
- * that requires exchanging the current token for a new one.
87
- *
88
- * @param accessToken - Current access token (injected by worker)
89
- * @param url - URL to call for token exchange
90
- * @param options - Exchange options (method, payload)
91
- * @returns Result<TokenInfo> with new tokens
92
- */
93
- exchangeToken(accessToken: string, url: string, options?: ExchangeTokenOptions): Promise<Result<TokenInfo>>;
94
- /**
95
- * Custom auth methods (optional)
96
- * Examples: loginWithPhone, loginWithGoogle, loginWithFacebook, etc.
97
- * All must return Result<TokenInfo> for token retrieval
98
- *
99
- * Note: Using any[] for args to allow flexible custom auth methods
100
- * while maintaining type compatibility with specific method signatures above
101
- */
102
- [key: string]: (...args: any[]) => Promise<Result<TokenInfo>>;
103
- }
104
- /**
105
- * Storage error context for debugging
106
- */
107
- type StorageErrorContext = 'get' | 'set' | 'delete' | 'open';
108
- /**
109
- * Storage error callback type
110
- * Called when IndexedDB operations fail (quota exceeded, permission denied, etc.)
111
- * Storage still fails closed (returns null), but this allows logging/debugging.
112
- */
113
- type StorageErrorCallback = (error: Error, context: StorageErrorContext) => void;
114
- /**
115
- * Interface for refresh token storage - only stores refresh token
116
- *
117
- * Access token is always stored in worker memory.
118
- * Refresh token storage is OPTIONAL:
119
- * - If available (IndexedDB): persist refresh token for reuse after reload
120
- * - If not (undefined): cookie-based auth (httpOnly cookie)
121
- */
122
- interface RefreshTokenStorage {
123
- get(): Promise<string | null>;
124
- set(token: string | null): Promise<void>;
125
- }
126
- /**
127
- * Interface for token parser - parse token from backend response
128
- * Parser returns complete TokenInfo (including user data)
129
- */
130
- interface TokenParser {
131
- parse(response: Response): Promise<TokenInfo>;
132
- }
133
- /**
134
- * Interface for auth strategy - defines how to call auth APIs
135
- *
136
- * Strategy focuses only on API calls, returns Response
137
- * Provider handles parsing and storage
138
- *
139
- * All methods are required
140
- */
141
- interface AuthStrategy {
142
- /** Refresh access token */
143
- refresh(refreshToken: string | null): Promise<Response>;
144
- /**
145
- * Login with credentials
146
- * @param payload - Login credentials
147
- * @param url - Optional URL override (if not provided, uses configured loginUrl)
148
- */
149
- login(payload: unknown, url?: string): Promise<Response>;
150
- /** Logout */
151
- logout(payload?: unknown): Promise<Response>;
152
- /**
153
- * Exchange current token for a new one with different context
154
- * @param accessToken - Current access token
155
- * @param url - URL to call for token exchange
156
- * @param options - Exchange options (method, payload)
157
- */
158
- exchangeToken(accessToken: string, url: string, options?: ExchangeTokenOptions): Promise<Response>;
159
- }
160
- /**
161
- * Provider preset configuration for built-in auth strategies
162
- */
163
- interface ProviderPresetConfig {
164
- type: 'cookie-auth' | 'body-auth';
165
- refreshUrl: string;
166
- loginUrl: string;
167
- logoutUrl: string;
168
- refreshTokenKey?: string;
169
- /** Custom headers to include in all auth requests (login, logout, refresh) */
170
- headers?: Record<string, string>;
171
- }
172
- /**
173
- * Configuration for FetchGuard client
174
- */
175
- interface FetchGuardOptions {
176
- /**
177
- * Token provider - 3 options:
178
- * 1. TokenProvider instance (for custom providers)
179
- * 2. ProviderPresetConfig object (for built-in presets)
180
- * 3. string (for registry lookup - advanced usage)
181
- */
182
- provider: TokenProvider | ProviderPresetConfig | string;
183
- /** List of allowed domains (wildcard supported) */
184
- allowedDomains?: string[];
185
- /** Early refresh time for tokens (ms) */
186
- refreshEarlyMs?: number;
187
- /** Default headers to include in all requests */
188
- defaultHeaders?: Record<string, string>;
189
- /**
190
- * Maximum concurrent requests to worker (default: 6)
191
- * Controls how many requests can be in-flight simultaneously.
192
- * Set to 1 for strictly sequential processing.
193
- * Higher values increase throughput but may cause worker congestion.
194
- */
195
- maxConcurrent?: number;
196
- /**
197
- * Maximum queue size for pending requests (default: 1000)
198
- * When queue is full, new requests will immediately fail with QUEUE_FULL error.
199
- * Prevents memory leak if worker is unresponsive.
200
- */
201
- maxQueueSize?: number;
202
- /**
203
- * Worker setup timeout in milliseconds (default: 10000)
204
- * How long to wait for worker to be ready before failing.
205
- */
206
- setupTimeout?: number;
207
- /**
208
- * Default request timeout in milliseconds (default: 30000)
209
- * How long to wait for a request to complete before timing out.
210
- * Can be overridden per-request via fetch options.
211
- */
212
- requestTimeout?: number;
213
- /**
214
- * Debug hooks for observing operations (logging, monitoring)
215
- * All hooks are observe-only - they cannot modify requests/responses.
216
- */
217
- debug?: DebugHooks;
218
- /**
219
- * Retry configuration for network errors
220
- * Only retries on transport failures, NOT on HTTP errors (4xx/5xx)
221
- */
222
- retry?: RetryConfig;
223
- /**
224
- * Request deduplication configuration
225
- * When enabled, duplicate requests to the same URL within a time window
226
- * will share the same response instead of making multiple requests.
227
- */
228
- dedupe?: DedupeConfig;
229
- /**
230
- * Custom worker factory function
231
- *
232
- * Use this when you need a custom provider with parser/strategy functions.
233
- * Create a custom worker file that imports 'fetchguard/worker' and registers
234
- * your provider, then pass a factory function that creates that worker.
235
- *
236
- * @example
237
- * ```ts
238
- * // my-worker.ts
239
- * import 'fetchguard/worker'
240
- * import { registerProvider, createProvider, ... } from 'fetchguard'
241
- * const myProvider = createProvider({ parser: myParser, strategy: myStrategy, ... })
242
- * registerProvider('my-auth', myProvider)
243
- *
244
- * // main.ts
245
- * import MyWorker from './my-worker?worker'
246
- * const api = createClient({
247
- * provider: 'my-auth',
248
- * workerFactory: () => new MyWorker()
249
- * })
250
- * ```
251
- */
252
- workerFactory?: () => Worker;
253
- }
254
- /**
255
- * Internal worker configuration
256
- */
257
- interface WorkerConfig {
258
- allowedDomains: string[];
259
- refreshEarlyMs: number;
260
- defaultHeaders: Record<string, string>;
261
- }
262
- /**
263
- * Extended RequestInit with FetchGuard-specific options
264
- */
265
- interface FetchGuardRequestInit extends RequestInit {
266
- /** Whether this request requires authentication. Default: true */
267
- requiresAuth?: boolean;
268
- /** Include response headers in result metadata and FETCH_RESULT payload */
269
- includeHeaders?: boolean;
270
- }
271
- /**
272
- * Fetch envelope - raw HTTP response from worker
273
- *
274
- * Worker only fetches and returns raw data, does NOT judge HTTP status.
275
- * Client receives envelope and decides ok/err based on business logic.
276
- *
277
- * - status: HTTP status code (2xx, 3xx, 4xx, 5xx)
278
- * - body: string (text/JSON) or base64 (binary)
279
- * - contentType: always present, indicates how to decode body
280
- * - headers: empty object if includeHeaders: false
281
- */
282
- interface FetchEnvelope {
283
- status: number;
284
- body: string;
285
- contentType: string;
286
- headers: Record<string, string>;
287
- }
288
- /**
289
- * Serialized file data for transfer over postMessage
290
- * Uses ArrayBuffer for zero-copy transfer via Transferable
291
- */
292
- interface SerializedFile {
293
- name: string;
294
- type: string;
295
- /** ArrayBuffer - transferred via postMessage Transferable for zero-copy */
296
- buffer: ArrayBuffer;
297
- }
298
- /**
299
- * Serialized FormData entry - can be string or file
300
- */
301
- type SerializedFormDataEntry = string | SerializedFile;
302
- /**
303
- * Serialized FormData for transfer over postMessage
304
- */
305
- interface SerializedFormData {
306
- _type: 'FormData';
307
- entries: Array<[string, SerializedFormDataEntry]>;
308
- }
309
- /**
310
- * Result of FormData serialization with transferables
311
- * Used for zero-copy transfer via postMessage
312
- */
313
- interface SerializedFormDataResult {
314
- data: SerializedFormData;
315
- /** ArrayBuffers to transfer - pass to postMessage as second argument */
316
- transferables: ArrayBuffer[];
317
- }
318
- /**
319
- * Network error detail for transport failures
320
- * Used when no HTTP response is received (connection failed, timeout, cancelled)
321
- */
322
- interface NetworkErrorDetail {
323
- code: 'NETWORK_ERROR' | 'REQUEST_CANCELLED' | 'RESPONSE_PARSE_FAILED';
324
- message: string;
325
- }
326
- /**
327
- * Reason for token refresh
328
- */
329
- type RefreshReason = 'expired' | 'proactive' | 'manual';
330
- /**
331
- * Request timing metrics for performance monitoring
332
- *
333
- * All times are in milliseconds.
334
- */
335
- interface RequestMetrics {
336
- /** When request was initiated (Date.now()) */
337
- startTime: number;
338
- /** When response was received (Date.now()) */
339
- endTime: number;
340
- /** Total duration (endTime - startTime) */
341
- duration: number;
342
- /** Time spent waiting in queue before processing */
343
- queueTime: number;
344
- /** Time spent in IPC (postMessage round-trip overhead) */
345
- ipcTime: number;
346
- }
347
- /**
348
- * Debug hooks for observing FetchGuard operations
349
- *
350
- * All hooks are observe-only - they cannot modify requests/responses.
351
- * Useful for logging, debugging, and monitoring.
352
- *
353
- * Note: Hooks run synchronously and should not perform heavy operations.
354
- */
355
- interface DebugHooks {
356
- /**
357
- * Called before each request is sent to worker
358
- * @param url - Request URL
359
- * @param options - Request options (method, headers, etc.)
360
- */
361
- onRequest?: (url: string, options: FetchGuardRequestInit) => void;
362
- /**
363
- * Called when response is received from worker
364
- * @param url - Request URL
365
- * @param envelope - Response envelope (status, body, headers)
366
- * @param metrics - Request timing metrics (optional, for performance monitoring)
367
- */
368
- onResponse?: (url: string, envelope: FetchEnvelope, metrics?: RequestMetrics) => void;
369
- /**
370
- * Called when token refresh occurs
371
- * @param reason - Why refresh happened: 'expired', 'proactive', or 'manual'
372
- */
373
- onRefresh?: (reason: RefreshReason) => void;
374
- /**
375
- * Called when transport error occurs (network failure, timeout, cancelled)
376
- * @param url - Request URL
377
- * @param error - Error detail with code and message
378
- * @param metrics - Request timing metrics (optional)
379
- */
380
- onError?: (url: string, error: NetworkErrorDetail, metrics?: RequestMetrics) => void;
381
- /**
382
- * Called when worker is ready after initialization
383
- */
384
- onWorkerReady?: () => void;
385
- /**
386
- * Called when worker encounters a fatal error
387
- * @param error - Error event from worker
388
- */
389
- onWorkerError?: (error: ErrorEvent) => void;
390
- }
391
- /**
392
- * Retry configuration for network errors
393
- *
394
- * Only retries on transport failures (network error, timeout).
395
- * Does NOT retry on HTTP errors (4xx/5xx) - those are valid responses.
396
- * Does NOT retry cancelled requests.
397
- */
398
- interface RetryConfig {
399
- /**
400
- * Maximum number of retry attempts (default: 0 = no retry)
401
- */
402
- maxAttempts?: number;
403
- /**
404
- * Delay between retries in milliseconds (default: 1000)
405
- */
406
- delay?: number;
407
- /**
408
- * Exponential backoff multiplier (default: 1 = no backoff)
409
- * Example: delay=1000, backoff=2 => 1s, 2s, 4s, 8s...
410
- */
411
- backoff?: number;
412
- /**
413
- * Maximum delay in milliseconds (default: 30000)
414
- * Caps the delay when using exponential backoff
415
- */
416
- maxDelay?: number;
417
- /**
418
- * Jitter factor to add randomness to retry delays (default: 0 = no jitter)
419
- * Range: 0 to 1 (e.g., 0.5 = ±50% randomness)
420
- * Helps prevent thundering herd when many clients retry simultaneously.
421
- *
422
- * Note: Jitter is only applied when shouldRetry returns true.
423
- * If request fails permanently, no jitter delay occurs.
424
- *
425
- * Example: delay=1000, jitter=0.5 => delay between 500ms and 1500ms
426
- */
427
- jitter?: number;
428
- /**
429
- * Custom condition to determine if error should be retried
430
- * Default: retry on NETWORK_ERROR only
431
- * @param error - The error that occurred
432
- * @returns true to retry, false to fail immediately
433
- */
434
- shouldRetry?: (error: NetworkErrorDetail) => boolean;
435
- }
436
- /**
437
- * Request deduplication configuration
438
- *
439
- * When enabled, identical GET requests (same URL) within a time window
440
- * will share the same in-flight request instead of making duplicates.
441
- *
442
- * IMPORTANT:
443
- * - Only applies to GET requests (POST/PUT/DELETE are never deduplicated)
444
- * - Only deduplicates in-flight requests (not caching)
445
- * - Safe for most read operations
446
- */
447
- interface DedupeConfig {
448
- /**
449
- * Enable deduplication (default: false)
450
- */
451
- enabled?: boolean;
452
- /**
453
- * Time window in milliseconds to consider requests as duplicates (default: 0)
454
- * 0 = only dedupe concurrent/in-flight requests
455
- * >0 = also dedupe requests within this time window after completion
456
- */
457
- window?: number;
458
- /**
459
- * Custom key generator for deduplication
460
- * Default: uses URL only for GET requests
461
- * @param url - Request URL
462
- * @param options - Request options
463
- * @returns Key string, or null to skip deduplication for this request
464
- */
465
- keyGenerator?: (url: string, options: FetchGuardRequestInit) => string | null;
466
- }
467
- /**
468
- * Transport result - represents the outcome of a network request
469
- *
470
- * IMPORTANT: This is a TRANSPORT result, not a business result.
471
- * - ok = HTTP response received (check envelope.status for 2xx/4xx/5xx)
472
- * - err = Network failure (no response received)
473
- *
474
- * Example:
475
- * ```typescript
476
- * const result = await api.get('/users')
477
- * if (result.ok) {
478
- * // Transport succeeded - got HTTP response
479
- * if (result.data.status >= 200 && result.data.status < 400) {
480
- * // Business success
481
- * } else {
482
- * // Business error (4xx/5xx) - still has response body
483
- * }
484
- * } else {
485
- * // Transport failed - no response (network error, timeout, cancelled)
486
- * }
487
- * ```
488
- */
489
- type TransportResult = Result<FetchEnvelope>;
490
-
491
6
  /**
492
7
  * FetchGuard Client - main interface cho việc gọi API thông qua Web Worker
493
8
  */
@@ -919,159 +434,6 @@ type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];
919
434
  */
920
435
  type ErrorCodeKey = keyof typeof ERROR_CODES;
921
436
 
922
- /**
923
- * Register a token provider with name
924
- */
925
- declare function registerProvider(name: string, provider: TokenProvider): void;
926
- /**
927
- * Get provider by name
928
- */
929
- declare function getProvider(name: string): TokenProvider;
930
- /**
931
- * Check if provider exists
932
- */
933
- declare function hasProvider(name: string): boolean;
934
- /**
935
- * Get list of all provider names
936
- */
937
- declare function listProviders(): string[];
938
- /**
939
- * Remove provider
940
- */
941
- declare function unregisterProvider(name: string): boolean;
942
- /**
943
- * Remove all providers
944
- */
945
- declare function clearProviders(): void;
946
-
947
- /**
948
- * Custom auth method type
949
- */
950
- type CustomAuthMethod = (...args: unknown[]) => Promise<Result<TokenInfo>>;
951
- /**
952
- * Configuration for creating provider
953
- *
954
- * refreshStorage: OPTIONAL - to load refresh token initially when worker starts
955
- * - undefined: cookie-based auth (httpOnly cookie, no need to load)
956
- * - RefreshTokenStorage: body-based auth (load from IndexedDB on startup)
957
- *
958
- * strategy: AuthStrategy with refresh (required), login/logout (required)
959
- *
960
- * customMethods: OPTIONAL - custom auth methods (loginWithPhone, loginWithGoogle, etc.)
961
- */
962
- interface ProviderConfig {
963
- refreshStorage?: RefreshTokenStorage;
964
- parser: TokenParser;
965
- strategy: AuthStrategy;
966
- customMethods?: Record<string, CustomAuthMethod>;
967
- }
968
- /**
969
- * Factory function to create TokenProvider from modular components
970
- *
971
- * Provider automatically handles refresh token:
972
- * - If refreshToken is null and storage exists → load from storage initially
973
- * - If refreshToken exists → use token from worker memory
974
- * - Cookie-based (no storage) → always null
975
- *
976
- * Custom methods:
977
- * - User can add custom auth methods (loginWithPhone, loginWithGoogle, etc.)
978
- * - Custom methods will be spread into provider object
979
- */
980
- declare function createProvider(config: ProviderConfig): TokenProvider;
981
-
982
- /**
983
- * IndexedDB storage options
984
- */
985
- interface IndexedDBStorageOptions {
986
- /** Database name (default: 'FetchGuardDB') */
987
- dbName?: string;
988
- /** Key for refresh token (default: 'refreshToken') */
989
- refreshTokenKey?: string;
990
- /**
991
- * Error callback for debugging storage failures
992
- * Called when IndexedDB operations fail (quota exceeded, permission denied, etc.)
993
- * Storage still fails closed (returns null), but this allows logging/debugging.
994
- */
995
- onError?: StorageErrorCallback;
996
- }
997
- /**
998
- * IndexedDB storage - only stores refresh token in IndexedDB
999
- * Suitable for body-based refresh strategy
1000
- * Persists refresh token for reuse after reload
1001
- *
1002
- * @param options - Storage options or legacy dbName string
1003
- * @param legacyRefreshTokenKey - Legacy refreshTokenKey (for backward compatibility)
1004
- */
1005
- declare function createIndexedDBStorage(options?: IndexedDBStorageOptions | string, legacyRefreshTokenKey?: string): RefreshTokenStorage;
1006
-
1007
- /**
1008
- * Body parser - parse token from response body (JSON)
1009
- * Expects response format: { data: { accessToken, refreshToken, expiresAt?, user? } }
1010
- */
1011
- declare const bodyParser: TokenParser;
1012
-
1013
- /**
1014
- * Cookie parser - parse access token from response body
1015
- * Expects response format: { data: { accessToken, expiresAt?, user? } }
1016
- * Refresh token is automatically set by backend into httpOnly cookie
1017
- */
1018
- declare const cookieParser: TokenParser;
1019
-
1020
- /**
1021
- * Cookie auth strategy - all auth operations via httpOnly cookies
1022
- * Suitable for SSR and cross-domain authentication
1023
- *
1024
- * Refresh token is sent automatically via httpOnly cookie
1025
- * Credentials are sent in request body
1026
- *
1027
- * Login URL can be:
1028
- * - Configured once: loginUrl: 'https://api.example.com/auth/login'
1029
- * - Passed per call: login(payload, 'https://...')
1030
- *
1031
- * Header priority (lowest to highest):
1032
- * - defaultHeaders (from FetchGuardOptions)
1033
- * - headers (from ProviderPresetConfig)
1034
- * - Content-Type: application/json
1035
- */
1036
- declare function createCookieStrategy(config: {
1037
- refreshUrl: string;
1038
- loginUrl: string;
1039
- logoutUrl: string;
1040
- headers?: Record<string, string>;
1041
- defaultHeaders?: Record<string, string>;
1042
- }): AuthStrategy;
1043
- /**
1044
- * Standard cookie strategy
1045
- */
1046
- declare const cookieStrategy: AuthStrategy;
1047
-
1048
- /**
1049
- * Body auth strategy - all auth operations via request body
1050
- * Suitable for SPA applications
1051
- *
1052
- * All tokens/credentials are sent in request body
1053
- *
1054
- * Login URL can be:
1055
- * - Configured once: loginUrl: 'https://api.example.com/auth/login'
1056
- * - Passed per call: login(payload, 'https://...')
1057
- *
1058
- * Header priority (lowest to highest):
1059
- * - defaultHeaders (from FetchGuardOptions)
1060
- * - headers (from ProviderPresetConfig)
1061
- * - Content-Type: application/json
1062
- */
1063
- declare function createBodyStrategy(config: {
1064
- refreshUrl: string;
1065
- loginUrl: string;
1066
- logoutUrl: string;
1067
- headers?: Record<string, string>;
1068
- defaultHeaders?: Record<string, string>;
1069
- }): AuthStrategy;
1070
- /**
1071
- * Standard body strategy
1072
- */
1073
- declare const bodyStrategy: AuthStrategy;
1074
-
1075
437
  /**
1076
438
  * Cookie Provider - uses httpOnly cookies
1077
439
  * Suitable for SSR and cross-domain authentication
@@ -1272,4 +634,4 @@ declare function matchResult<T>(result: Result<FetchEnvelope>, handlers: {
1272
634
  }[]) => T;
1273
635
  }): T | undefined;
1274
636
 
1275
- export { AuthErrors, type AuthResult, type AuthStrategy, type DebugHooks, type DedupeConfig, DomainErrors, ERROR_CODES, type ErrorCode, type ErrorCodeKey, type ExchangeTokenOptions, type FetchEnvelope, FetchGuardClient, type FetchGuardOptions, type FetchGuardRequestInit, GeneralErrors, type IndexedDBStorageOptions, InitErrors, MSG, type MainToWorkerMessage, type MessageType, type NetworkErrorDetail, type ProviderConfig, type ProviderPresetConfig, type RefreshReason, type RefreshTokenStorage, RequestErrors, type RequestMetrics, type RetryConfig, type SerializedFile, type SerializedFormData, type SerializedFormDataEntry, type StorageErrorCallback, type StorageErrorContext, type TokenInfo, type TokenParser, type TokenProvider, type TransportResult, type WorkerConfig, type WorkerToMainMessage, base64ToArrayBuffer, bodyParser, bodyStrategy, clearProviders, cookieParser, cookieStrategy, createBodyProvider, createBodyStrategy, createClient, createCookieProvider, createCookieStrategy, createIndexedDBStorage, createProvider, deserializeFormData, getErrorBody, getErrorMessage, getProvider, getStatus, hasProvider, hasStatus, isBinaryContentType, isClientError, isFormData, isNetworkError, isSerializedFormData, isServerError, isSuccess, listProviders, matchResult, parseJson, registerProvider, serializeFormData, unregisterProvider };
637
+ export { AuthErrors, AuthResult, DomainErrors, ERROR_CODES, type ErrorCode, type ErrorCodeKey, FetchEnvelope, FetchGuardClient, FetchGuardOptions, FetchGuardRequestInit, GeneralErrors, InitErrors, MSG, type MainToWorkerMessage, type MessageType, ProviderPresetConfig, RefreshReason, RequestErrors, SerializedFormData, TokenProvider, WorkerConfig, type WorkerToMainMessage, base64ToArrayBuffer, createBodyProvider, createClient, createCookieProvider, deserializeFormData, getErrorBody, getErrorMessage, getStatus, hasStatus, isBinaryContentType, isClientError, isFormData, isNetworkError, isSerializedFormData, isServerError, isSuccess, matchResult, parseJson, serializeFormData };