fetchguard 2.1.2 → 2.2.1

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/dist/index.d.ts CHANGED
@@ -1,469 +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
- /**
231
- * Internal worker configuration
232
- */
233
- interface WorkerConfig {
234
- allowedDomains: string[];
235
- refreshEarlyMs: number;
236
- defaultHeaders: Record<string, string>;
237
- }
238
- /**
239
- * Extended RequestInit with FetchGuard-specific options
240
- */
241
- interface FetchGuardRequestInit extends RequestInit {
242
- /** Whether this request requires authentication. Default: true */
243
- requiresAuth?: boolean;
244
- /** Include response headers in result metadata and FETCH_RESULT payload */
245
- includeHeaders?: boolean;
246
- }
247
- /**
248
- * Fetch envelope - raw HTTP response from worker
249
- *
250
- * Worker only fetches and returns raw data, does NOT judge HTTP status.
251
- * Client receives envelope and decides ok/err based on business logic.
252
- *
253
- * - status: HTTP status code (2xx, 3xx, 4xx, 5xx)
254
- * - body: string (text/JSON) or base64 (binary)
255
- * - contentType: always present, indicates how to decode body
256
- * - headers: empty object if includeHeaders: false
257
- */
258
- interface FetchEnvelope {
259
- status: number;
260
- body: string;
261
- contentType: string;
262
- headers: Record<string, string>;
263
- }
264
- /**
265
- * Serialized file data for transfer over postMessage
266
- * Uses ArrayBuffer for zero-copy transfer via Transferable
267
- */
268
- interface SerializedFile {
269
- name: string;
270
- type: string;
271
- /** ArrayBuffer - transferred via postMessage Transferable for zero-copy */
272
- buffer: ArrayBuffer;
273
- }
274
- /**
275
- * Serialized FormData entry - can be string or file
276
- */
277
- type SerializedFormDataEntry = string | SerializedFile;
278
- /**
279
- * Serialized FormData for transfer over postMessage
280
- */
281
- interface SerializedFormData {
282
- _type: 'FormData';
283
- entries: Array<[string, SerializedFormDataEntry]>;
284
- }
285
- /**
286
- * Result of FormData serialization with transferables
287
- * Used for zero-copy transfer via postMessage
288
- */
289
- interface SerializedFormDataResult {
290
- data: SerializedFormData;
291
- /** ArrayBuffers to transfer - pass to postMessage as second argument */
292
- transferables: ArrayBuffer[];
293
- }
294
- /**
295
- * Network error detail for transport failures
296
- * Used when no HTTP response is received (connection failed, timeout, cancelled)
297
- */
298
- interface NetworkErrorDetail {
299
- code: 'NETWORK_ERROR' | 'REQUEST_CANCELLED' | 'RESPONSE_PARSE_FAILED';
300
- message: string;
301
- }
302
- /**
303
- * Reason for token refresh
304
- */
305
- type RefreshReason = 'expired' | 'proactive' | 'manual';
306
- /**
307
- * Request timing metrics for performance monitoring
308
- *
309
- * All times are in milliseconds.
310
- */
311
- interface RequestMetrics {
312
- /** When request was initiated (Date.now()) */
313
- startTime: number;
314
- /** When response was received (Date.now()) */
315
- endTime: number;
316
- /** Total duration (endTime - startTime) */
317
- duration: number;
318
- /** Time spent waiting in queue before processing */
319
- queueTime: number;
320
- /** Time spent in IPC (postMessage round-trip overhead) */
321
- ipcTime: number;
322
- }
323
- /**
324
- * Debug hooks for observing FetchGuard operations
325
- *
326
- * All hooks are observe-only - they cannot modify requests/responses.
327
- * Useful for logging, debugging, and monitoring.
328
- *
329
- * Note: Hooks run synchronously and should not perform heavy operations.
330
- */
331
- interface DebugHooks {
332
- /**
333
- * Called before each request is sent to worker
334
- * @param url - Request URL
335
- * @param options - Request options (method, headers, etc.)
336
- */
337
- onRequest?: (url: string, options: FetchGuardRequestInit) => void;
338
- /**
339
- * Called when response is received from worker
340
- * @param url - Request URL
341
- * @param envelope - Response envelope (status, body, headers)
342
- * @param metrics - Request timing metrics (optional, for performance monitoring)
343
- */
344
- onResponse?: (url: string, envelope: FetchEnvelope, metrics?: RequestMetrics) => void;
345
- /**
346
- * Called when token refresh occurs
347
- * @param reason - Why refresh happened: 'expired', 'proactive', or 'manual'
348
- */
349
- onRefresh?: (reason: RefreshReason) => void;
350
- /**
351
- * Called when transport error occurs (network failure, timeout, cancelled)
352
- * @param url - Request URL
353
- * @param error - Error detail with code and message
354
- * @param metrics - Request timing metrics (optional)
355
- */
356
- onError?: (url: string, error: NetworkErrorDetail, metrics?: RequestMetrics) => void;
357
- /**
358
- * Called when worker is ready after initialization
359
- */
360
- onWorkerReady?: () => void;
361
- /**
362
- * Called when worker encounters a fatal error
363
- * @param error - Error event from worker
364
- */
365
- onWorkerError?: (error: ErrorEvent) => void;
366
- }
367
- /**
368
- * Retry configuration for network errors
369
- *
370
- * Only retries on transport failures (network error, timeout).
371
- * Does NOT retry on HTTP errors (4xx/5xx) - those are valid responses.
372
- * Does NOT retry cancelled requests.
373
- */
374
- interface RetryConfig {
375
- /**
376
- * Maximum number of retry attempts (default: 0 = no retry)
377
- */
378
- maxAttempts?: number;
379
- /**
380
- * Delay between retries in milliseconds (default: 1000)
381
- */
382
- delay?: number;
383
- /**
384
- * Exponential backoff multiplier (default: 1 = no backoff)
385
- * Example: delay=1000, backoff=2 => 1s, 2s, 4s, 8s...
386
- */
387
- backoff?: number;
388
- /**
389
- * Maximum delay in milliseconds (default: 30000)
390
- * Caps the delay when using exponential backoff
391
- */
392
- maxDelay?: number;
393
- /**
394
- * Jitter factor to add randomness to retry delays (default: 0 = no jitter)
395
- * Range: 0 to 1 (e.g., 0.5 = ±50% randomness)
396
- * Helps prevent thundering herd when many clients retry simultaneously.
397
- *
398
- * Note: Jitter is only applied when shouldRetry returns true.
399
- * If request fails permanently, no jitter delay occurs.
400
- *
401
- * Example: delay=1000, jitter=0.5 => delay between 500ms and 1500ms
402
- */
403
- jitter?: number;
404
- /**
405
- * Custom condition to determine if error should be retried
406
- * Default: retry on NETWORK_ERROR only
407
- * @param error - The error that occurred
408
- * @returns true to retry, false to fail immediately
409
- */
410
- shouldRetry?: (error: NetworkErrorDetail) => boolean;
411
- }
412
- /**
413
- * Request deduplication configuration
414
- *
415
- * When enabled, identical GET requests (same URL) within a time window
416
- * will share the same in-flight request instead of making duplicates.
417
- *
418
- * IMPORTANT:
419
- * - Only applies to GET requests (POST/PUT/DELETE are never deduplicated)
420
- * - Only deduplicates in-flight requests (not caching)
421
- * - Safe for most read operations
422
- */
423
- interface DedupeConfig {
424
- /**
425
- * Enable deduplication (default: false)
426
- */
427
- enabled?: boolean;
428
- /**
429
- * Time window in milliseconds to consider requests as duplicates (default: 0)
430
- * 0 = only dedupe concurrent/in-flight requests
431
- * >0 = also dedupe requests within this time window after completion
432
- */
433
- window?: number;
434
- /**
435
- * Custom key generator for deduplication
436
- * Default: uses URL only for GET requests
437
- * @param url - Request URL
438
- * @param options - Request options
439
- * @returns Key string, or null to skip deduplication for this request
440
- */
441
- keyGenerator?: (url: string, options: FetchGuardRequestInit) => string | null;
442
- }
443
- /**
444
- * Transport result - represents the outcome of a network request
445
- *
446
- * IMPORTANT: This is a TRANSPORT result, not a business result.
447
- * - ok = HTTP response received (check envelope.status for 2xx/4xx/5xx)
448
- * - err = Network failure (no response received)
449
- *
450
- * Example:
451
- * ```typescript
452
- * const result = await api.get('/users')
453
- * if (result.ok) {
454
- * // Transport succeeded - got HTTP response
455
- * if (result.data.status >= 200 && result.data.status < 400) {
456
- * // Business success
457
- * } else {
458
- * // Business error (4xx/5xx) - still has response body
459
- * }
460
- * } else {
461
- * // Transport failed - no response (network error, timeout, cancelled)
462
- * }
463
- * ```
464
- */
465
- type TransportResult = Result<FetchEnvelope>;
466
-
467
6
  /**
468
7
  * FetchGuard Client - main interface cho việc gọi API thông qua Web Worker
469
8
  */
@@ -895,159 +434,6 @@ type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];
895
434
  */
896
435
  type ErrorCodeKey = keyof typeof ERROR_CODES;
897
436
 
898
- /**
899
- * Register a token provider with name
900
- */
901
- declare function registerProvider(name: string, provider: TokenProvider): void;
902
- /**
903
- * Get provider by name
904
- */
905
- declare function getProvider(name: string): TokenProvider;
906
- /**
907
- * Check if provider exists
908
- */
909
- declare function hasProvider(name: string): boolean;
910
- /**
911
- * Get list of all provider names
912
- */
913
- declare function listProviders(): string[];
914
- /**
915
- * Remove provider
916
- */
917
- declare function unregisterProvider(name: string): boolean;
918
- /**
919
- * Remove all providers
920
- */
921
- declare function clearProviders(): void;
922
-
923
- /**
924
- * Custom auth method type
925
- */
926
- type CustomAuthMethod = (...args: unknown[]) => Promise<Result<TokenInfo>>;
927
- /**
928
- * Configuration for creating provider
929
- *
930
- * refreshStorage: OPTIONAL - to load refresh token initially when worker starts
931
- * - undefined: cookie-based auth (httpOnly cookie, no need to load)
932
- * - RefreshTokenStorage: body-based auth (load from IndexedDB on startup)
933
- *
934
- * strategy: AuthStrategy with refresh (required), login/logout (required)
935
- *
936
- * customMethods: OPTIONAL - custom auth methods (loginWithPhone, loginWithGoogle, etc.)
937
- */
938
- interface ProviderConfig {
939
- refreshStorage?: RefreshTokenStorage;
940
- parser: TokenParser;
941
- strategy: AuthStrategy;
942
- customMethods?: Record<string, CustomAuthMethod>;
943
- }
944
- /**
945
- * Factory function to create TokenProvider from modular components
946
- *
947
- * Provider automatically handles refresh token:
948
- * - If refreshToken is null and storage exists → load from storage initially
949
- * - If refreshToken exists → use token from worker memory
950
- * - Cookie-based (no storage) → always null
951
- *
952
- * Custom methods:
953
- * - User can add custom auth methods (loginWithPhone, loginWithGoogle, etc.)
954
- * - Custom methods will be spread into provider object
955
- */
956
- declare function createProvider(config: ProviderConfig): TokenProvider;
957
-
958
- /**
959
- * IndexedDB storage options
960
- */
961
- interface IndexedDBStorageOptions {
962
- /** Database name (default: 'FetchGuardDB') */
963
- dbName?: string;
964
- /** Key for refresh token (default: 'refreshToken') */
965
- refreshTokenKey?: string;
966
- /**
967
- * Error callback for debugging storage failures
968
- * Called when IndexedDB operations fail (quota exceeded, permission denied, etc.)
969
- * Storage still fails closed (returns null), but this allows logging/debugging.
970
- */
971
- onError?: StorageErrorCallback;
972
- }
973
- /**
974
- * IndexedDB storage - only stores refresh token in IndexedDB
975
- * Suitable for body-based refresh strategy
976
- * Persists refresh token for reuse after reload
977
- *
978
- * @param options - Storage options or legacy dbName string
979
- * @param legacyRefreshTokenKey - Legacy refreshTokenKey (for backward compatibility)
980
- */
981
- declare function createIndexedDBStorage(options?: IndexedDBStorageOptions | string, legacyRefreshTokenKey?: string): RefreshTokenStorage;
982
-
983
- /**
984
- * Body parser - parse token from response body (JSON)
985
- * Expects response format: { data: { accessToken, refreshToken, expiresAt?, user? } }
986
- */
987
- declare const bodyParser: TokenParser;
988
-
989
- /**
990
- * Cookie parser - parse access token from response body
991
- * Expects response format: { data: { accessToken, expiresAt?, user? } }
992
- * Refresh token is automatically set by backend into httpOnly cookie
993
- */
994
- declare const cookieParser: TokenParser;
995
-
996
- /**
997
- * Cookie auth strategy - all auth operations via httpOnly cookies
998
- * Suitable for SSR and cross-domain authentication
999
- *
1000
- * Refresh token is sent automatically via httpOnly cookie
1001
- * Credentials are sent in request body
1002
- *
1003
- * Login URL can be:
1004
- * - Configured once: loginUrl: 'https://api.example.com/auth/login'
1005
- * - Passed per call: login(payload, 'https://...')
1006
- *
1007
- * Header priority (lowest to highest):
1008
- * - defaultHeaders (from FetchGuardOptions)
1009
- * - headers (from ProviderPresetConfig)
1010
- * - Content-Type: application/json
1011
- */
1012
- declare function createCookieStrategy(config: {
1013
- refreshUrl: string;
1014
- loginUrl: string;
1015
- logoutUrl: string;
1016
- headers?: Record<string, string>;
1017
- defaultHeaders?: Record<string, string>;
1018
- }): AuthStrategy;
1019
- /**
1020
- * Standard cookie strategy
1021
- */
1022
- declare const cookieStrategy: AuthStrategy;
1023
-
1024
- /**
1025
- * Body auth strategy - all auth operations via request body
1026
- * Suitable for SPA applications
1027
- *
1028
- * All tokens/credentials are sent in request body
1029
- *
1030
- * Login URL can be:
1031
- * - Configured once: loginUrl: 'https://api.example.com/auth/login'
1032
- * - Passed per call: login(payload, 'https://...')
1033
- *
1034
- * Header priority (lowest to highest):
1035
- * - defaultHeaders (from FetchGuardOptions)
1036
- * - headers (from ProviderPresetConfig)
1037
- * - Content-Type: application/json
1038
- */
1039
- declare function createBodyStrategy(config: {
1040
- refreshUrl: string;
1041
- loginUrl: string;
1042
- logoutUrl: string;
1043
- headers?: Record<string, string>;
1044
- defaultHeaders?: Record<string, string>;
1045
- }): AuthStrategy;
1046
- /**
1047
- * Standard body strategy
1048
- */
1049
- declare const bodyStrategy: AuthStrategy;
1050
-
1051
437
  /**
1052
438
  * Cookie Provider - uses httpOnly cookies
1053
439
  * Suitable for SSR and cross-domain authentication
@@ -1248,4 +634,4 @@ declare function matchResult<T>(result: Result<FetchEnvelope>, handlers: {
1248
634
  }[]) => T;
1249
635
  }): T | undefined;
1250
636
 
1251
- 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 };
package/dist/index.js CHANGED
@@ -184,9 +184,13 @@ var FetchGuardClient = class {
184
184
  this.debug = options.debug;
185
185
  this.retry = options.retry;
186
186
  this.dedupe = options.dedupe;
187
- this.worker = new Worker(new URL("./worker.js", import.meta.url), {
188
- type: "module"
189
- });
187
+ if (options.workerFactory) {
188
+ this.worker = options.workerFactory();
189
+ } else {
190
+ this.worker = new Worker(new URL("./worker.js", import.meta.url), {
191
+ type: "module"
192
+ });
193
+ }
190
194
  this.worker.onmessage = this.handleWorkerMessage.bind(this);
191
195
  this.worker.onerror = this.handleWorkerError.bind(this);
192
196
  this.initializeWorker(options);