Spaces:
Running
Running
File size: 5,329 Bytes
d4b85c0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
/**
* @note This API is extended by both "msw/node" and "msw/native"
* so be minding about the things you import!
*/
import type { RequiredDeep } from 'type-fest'
import { invariant } from 'outvariant'
import {
BatchInterceptor,
InterceptorReadyState,
type HttpRequestEventMap,
type Interceptor,
} from '@mswjs/interceptors'
import type { LifeCycleEventsMap, SharedOptions } from '~/core/sharedOptions'
import { SetupApi } from '~/core/SetupApi'
import { handleRequest } from '~/core/utils/handleRequest'
import type { RequestHandler } from '~/core/handlers/RequestHandler'
import type { WebSocketHandler } from '~/core/handlers/WebSocketHandler'
import { mergeRight } from '~/core/utils/internal/mergeRight'
import { InternalError, devUtils } from '~/core/utils/internal/devUtils'
import type { SetupServerCommon } from './glossary'
import { handleWebSocketEvent } from '~/core/ws/handleWebSocketEvent'
import { webSocketInterceptor } from '~/core/ws/webSocketInterceptor'
import { isHandlerKind } from '~/core/utils/internal/isHandlerKind'
export const DEFAULT_LISTEN_OPTIONS: RequiredDeep<SharedOptions> = {
onUnhandledRequest: 'warn',
}
export class SetupServerCommonApi
extends SetupApi<LifeCycleEventsMap>
implements SetupServerCommon
{
protected readonly interceptor: BatchInterceptor<
Array<Interceptor<HttpRequestEventMap>>,
HttpRequestEventMap
>
private resolvedOptions: RequiredDeep<SharedOptions>
constructor(
interceptors: Array<{ new (): Interceptor<HttpRequestEventMap> }>,
handlers: Array<RequestHandler | WebSocketHandler>,
) {
super(...handlers)
this.interceptor = new BatchInterceptor({
name: 'setup-server',
interceptors: interceptors.map((Interceptor) => new Interceptor()),
})
this.resolvedOptions = {} as RequiredDeep<SharedOptions>
}
/**
* Subscribe to all requests that are using the interceptor object
*/
private init(): void {
this.interceptor.on(
'request',
async ({ request, requestId, controller }) => {
const response = await handleRequest(
request,
requestId,
this.handlersController
.currentHandlers()
.filter(isHandlerKind('RequestHandler')),
this.resolvedOptions,
this.emitter,
{
onPassthroughResponse(request) {
const acceptHeader = request.headers.get('accept')
/**
* @note Remove the internal bypass request header.
* In the browser, this is done by the worker script.
* In Node.js, it has to be done here.
*/
if (acceptHeader) {
const nextAcceptHeader = acceptHeader.replace(
/(,\s+)?msw\/passthrough/,
'',
)
if (nextAcceptHeader) {
request.headers.set('accept', nextAcceptHeader)
} else {
request.headers.delete('accept')
}
}
},
},
)
if (response) {
controller.respondWith(response)
}
return
},
)
this.interceptor.on('unhandledException', ({ error }) => {
if (error instanceof InternalError) {
throw error
}
})
this.interceptor.on(
'response',
({ response, isMockedResponse, request, requestId }) => {
this.emitter.emit(
isMockedResponse ? 'response:mocked' : 'response:bypass',
{
response,
request,
requestId,
},
)
},
)
// Preconfigure the WebSocket interception but don't enable it just yet.
// It will be enabled when the server starts.
handleWebSocketEvent({
getUnhandledRequestStrategy: () => {
return this.resolvedOptions.onUnhandledRequest
},
getHandlers: () => {
return this.handlersController.currentHandlers()
},
onMockedConnection: () => {},
onPassthroughConnection: () => {},
})
}
public listen(options: Partial<SharedOptions> = {}): void {
this.resolvedOptions = mergeRight(
DEFAULT_LISTEN_OPTIONS,
options,
) as RequiredDeep<SharedOptions>
// Apply the interceptor when starting the server.
// Attach the event listeners to the interceptor here
// so they get re-attached whenever `.listen()` is called.
this.interceptor.apply()
this.init()
this.subscriptions.push(() => this.interceptor.dispose())
// Apply the WebSocket interception.
webSocketInterceptor.apply()
this.subscriptions.push(() => webSocketInterceptor.dispose())
// Assert that the interceptor has been applied successfully.
// Also guards us from forgetting to call "interceptor.apply()"
// as a part of the "listen" method.
invariant(
[InterceptorReadyState.APPLYING, InterceptorReadyState.APPLIED].includes(
this.interceptor.readyState,
),
devUtils.formatMessage(
'Failed to start "setupServer": the interceptor failed to apply. This is likely an issue with the library and you should report it at "%s".',
),
'https://github.com/mswjs/msw/issues/new/choose',
)
}
public close(): void {
this.dispose()
}
}
|