(...handlers: Array<AnyHandler>)
| 31 | * @see {@link https://mswjs.io/docs/api/setup-worker `setupWorker()` API reference} |
| 32 | */ |
| 33 | export function setupWorker(...handlers: Array<AnyHandler>): SetupWorker { |
| 34 | invariant( |
| 35 | !isNodeProcess(), |
| 36 | devUtils.formatMessage( |
| 37 | 'Failed to execute `setupWorker` in a non-browser environment', |
| 38 | ), |
| 39 | ) |
| 40 | |
| 41 | const network = defineNetwork< |
| 42 | Array<ServiceWorkerSource | FallbackHttpSource | InterceptorSource> |
| 43 | >({ |
| 44 | sources: [], |
| 45 | handlers, |
| 46 | }) |
| 47 | |
| 48 | return { |
| 49 | async start(options) { |
| 50 | if (options?.waitUntilReady != null) { |
| 51 | devUtils.warn( |
| 52 | `The "waitUntilReady" option has been deprecated. Please remove it from this "worker.start()" call. Follow the recommended Browser integration (https://mswjs.io/docs/integrations/browser) to eliminate any race conditions between the Service Worker registration and any requests made by your application on initial render.`, |
| 53 | ) |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * @todo @fixme |
| 58 | * This is kept for backward-compatibility reasons. We don't really need this check anymore. |
| 59 | */ |
| 60 | if (network.readyState === NetworkReadyState.ENABLED) { |
| 61 | devUtils.warn( |
| 62 | 'Found a redundant "worker.start()" call. Note that starting the worker while mocking is already enabled will have no effect. Consider removing this "worker.start()" call.', |
| 63 | ) |
| 64 | return |
| 65 | } |
| 66 | |
| 67 | const httpSource = supportsServiceWorker() |
| 68 | ? await ServiceWorkerSource.from({ |
| 69 | serviceWorker: { |
| 70 | url: |
| 71 | options?.serviceWorker?.url?.toString() || DEFAULT_WORKER_URL, |
| 72 | options: options?.serviceWorker?.options, |
| 73 | }, |
| 74 | findWorker: options?.findWorker, |
| 75 | quiet: options?.quiet, |
| 76 | }) |
| 77 | : new FallbackHttpSource({ |
| 78 | quiet: options?.quiet, |
| 79 | }) |
| 80 | |
| 81 | network.configure({ |
| 82 | sources: [ |
| 83 | httpSource, |
| 84 | new InterceptorSource({ |
| 85 | interceptors: [new WebSocketInterceptor() as any], |
| 86 | }), |
| 87 | ], |
| 88 | onUnhandledFrame: fromLegacyOnUnhandledRequest(() => { |
| 89 | return options?.onUnhandledRequest || 'warn' |
| 90 | }), |
searching dependent graphs…