mockServiceWorker.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /**
  2. * Mock Service Worker.
  3. * @see https://github.com/mswjs/msw
  4. * - Please do NOT modify this file.
  5. * - Please do NOT serve this file on production.
  6. */
  7. /* eslint-disable */
  8. /* tslint:disable */
  9. const INTEGRITY_CHECKSUM = 'f7d0ed371e596d181f62c6f68c4b7baf'
  10. const bypassHeaderName = 'x-msw-bypass'
  11. const activeClientIds = new Set()
  12. self.addEventListener('install', function () {
  13. return self.skipWaiting()
  14. })
  15. self.addEventListener('activate', async function (event) {
  16. return self.clients.claim()
  17. })
  18. self.addEventListener('message', async function (event) {
  19. const clientId = event.source.id
  20. if (!clientId || !self.clients) {
  21. return
  22. }
  23. const client = await self.clients.get(clientId)
  24. if (!client) {
  25. return
  26. }
  27. const allClients = await self.clients.matchAll()
  28. switch (event.data) {
  29. case 'KEEPALIVE_REQUEST': {
  30. sendToClient(client, {
  31. type: 'KEEPALIVE_RESPONSE',
  32. })
  33. break
  34. }
  35. case 'INTEGRITY_CHECK_REQUEST': {
  36. sendToClient(client, {
  37. type: 'INTEGRITY_CHECK_RESPONSE',
  38. payload: INTEGRITY_CHECKSUM,
  39. })
  40. break
  41. }
  42. case 'MOCK_ACTIVATE': {
  43. activeClientIds.add(clientId)
  44. sendToClient(client, {
  45. type: 'MOCKING_ENABLED',
  46. payload: true,
  47. })
  48. break
  49. }
  50. case 'MOCK_DEACTIVATE': {
  51. activeClientIds.delete(clientId)
  52. break
  53. }
  54. case 'CLIENT_CLOSED': {
  55. activeClientIds.delete(clientId)
  56. const remainingClients = allClients.filter((client) => {
  57. return client.id !== clientId
  58. })
  59. // Unregister itself when there are no more clients
  60. if (remainingClients.length === 0) {
  61. self.registration.unregister()
  62. }
  63. break
  64. }
  65. }
  66. })
  67. // Resolve the "master" client for the given event.
  68. // Client that issues a request doesn't necessarily equal the client
  69. // that registered the worker. It's with the latter the worker should
  70. // communicate with during the response resolving phase.
  71. async function resolveMasterClient(event) {
  72. const client = await self.clients.get(event.clientId)
  73. if (client.frameType === 'top-level') {
  74. return client
  75. }
  76. const allClients = await self.clients.matchAll()
  77. return allClients
  78. .filter((client) => {
  79. // Get only those clients that are currently visible.
  80. return client.visibilityState === 'visible'
  81. })
  82. .find((client) => {
  83. // Find the client ID that's recorded in the
  84. // set of clients that have registered the worker.
  85. return activeClientIds.has(client.id)
  86. })
  87. }
  88. async function handleRequest(event, requestId) {
  89. const client = await resolveMasterClient(event)
  90. const response = await getResponse(event, client, requestId)
  91. // Send back the response clone for the "response:*" life-cycle events.
  92. // Ensure MSW is active and ready to handle the message, otherwise
  93. // this message will pend indefinitely.
  94. if (activeClientIds.has(client.id)) {
  95. const clonedResponse = response.clone()
  96. sendToClient(client, {
  97. type: 'RESPONSE',
  98. payload: {
  99. requestId,
  100. type: clonedResponse.type,
  101. ok: clonedResponse.ok,
  102. status: clonedResponse.status,
  103. statusText: clonedResponse.statusText,
  104. body: clonedResponse.body === null ? null : await clonedResponse.text(),
  105. headers: serializeHeaders(clonedResponse.headers),
  106. redirected: clonedResponse.redirected,
  107. },
  108. })
  109. }
  110. return response
  111. }
  112. async function getResponse(event, client, requestId) {
  113. const { request } = event
  114. const requestClone = request.clone()
  115. const getOriginalResponse = () => fetch(requestClone)
  116. // Bypass mocking when the request client is not active.
  117. if (!client) {
  118. return getOriginalResponse()
  119. }
  120. // Bypass initial page load requests (i.e. static assets).
  121. // The absence of the immediate/parent client in the map of the active clients
  122. // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
  123. // and is not ready to handle requests.
  124. if (!activeClientIds.has(client.id)) {
  125. return await getOriginalResponse()
  126. }
  127. // Bypass requests with the explicit bypass header
  128. if (requestClone.headers.get(bypassHeaderName) === 'true') {
  129. const cleanRequestHeaders = serializeHeaders(requestClone.headers)
  130. // Remove the bypass header to comply with the CORS preflight check.
  131. delete cleanRequestHeaders[bypassHeaderName]
  132. const originalRequest = new Request(requestClone, {
  133. headers: new Headers(cleanRequestHeaders),
  134. })
  135. return fetch(originalRequest)
  136. }
  137. // Send the request to the client-side MSW.
  138. const reqHeaders = serializeHeaders(request.headers)
  139. const body = await request.text()
  140. const clientMessage = await sendToClient(client, {
  141. type: 'REQUEST',
  142. payload: {
  143. id: requestId,
  144. url: request.url,
  145. method: request.method,
  146. headers: reqHeaders,
  147. cache: request.cache,
  148. mode: request.mode,
  149. credentials: request.credentials,
  150. destination: request.destination,
  151. integrity: request.integrity,
  152. redirect: request.redirect,
  153. referrer: request.referrer,
  154. referrerPolicy: request.referrerPolicy,
  155. body,
  156. bodyUsed: request.bodyUsed,
  157. keepalive: request.keepalive,
  158. },
  159. })
  160. switch (clientMessage.type) {
  161. case 'MOCK_SUCCESS': {
  162. return delayPromise(
  163. () => respondWithMock(clientMessage),
  164. clientMessage.payload.delay,
  165. )
  166. }
  167. case 'MOCK_NOT_FOUND': {
  168. return getOriginalResponse()
  169. }
  170. case 'NETWORK_ERROR': {
  171. const { name, message } = clientMessage.payload
  172. const networkError = new Error(message)
  173. networkError.name = name
  174. // Rejecting a request Promise emulates a network error.
  175. throw networkError
  176. }
  177. case 'INTERNAL_ERROR': {
  178. const parsedBody = JSON.parse(clientMessage.payload.body)
  179. console.error(
  180. `\
  181. [MSW] Request handler function for "%s %s" has thrown the following exception:
  182. ${parsedBody.errorType}: ${parsedBody.message}
  183. (see more detailed error stack trace in the mocked response body)
  184. This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.
  185. If you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
  186. `,
  187. request.method,
  188. request.url,
  189. )
  190. return respondWithMock(clientMessage)
  191. }
  192. }
  193. return getOriginalResponse()
  194. }
  195. self.addEventListener('fetch', function (event) {
  196. const { request } = event
  197. // Bypass navigation requests.
  198. if (request.mode === 'navigate') {
  199. return
  200. }
  201. // Opening the DevTools triggers the "only-if-cached" request
  202. // that cannot be handled by the worker. Bypass such requests.
  203. if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
  204. return
  205. }
  206. // Bypass all requests when there are no active clients.
  207. // Prevents the self-unregistered worked from handling requests
  208. // after it's been deleted (still remains active until the next reload).
  209. if (activeClientIds.size === 0) {
  210. return
  211. }
  212. const requestId = uuidv4()
  213. return event.respondWith(
  214. handleRequest(event, requestId).catch((error) => {
  215. console.error(
  216. '[MSW] Failed to mock a "%s" request to "%s": %s',
  217. request.method,
  218. request.url,
  219. error,
  220. )
  221. }),
  222. )
  223. })
  224. function serializeHeaders(headers) {
  225. const reqHeaders = {}
  226. headers.forEach((value, name) => {
  227. reqHeaders[name] = reqHeaders[name]
  228. ? [].concat(reqHeaders[name]).concat(value)
  229. : value
  230. })
  231. return reqHeaders
  232. }
  233. function sendToClient(client, message) {
  234. return new Promise((resolve, reject) => {
  235. const channel = new MessageChannel()
  236. channel.port1.onmessage = (event) => {
  237. if (event.data && event.data.error) {
  238. return reject(event.data.error)
  239. }
  240. resolve(event.data)
  241. }
  242. client.postMessage(JSON.stringify(message), [channel.port2])
  243. })
  244. }
  245. function delayPromise(cb, duration) {
  246. return new Promise((resolve) => {
  247. setTimeout(() => resolve(cb()), duration)
  248. })
  249. }
  250. function respondWithMock(clientMessage) {
  251. return new Response(clientMessage.payload.body, {
  252. ...clientMessage.payload,
  253. headers: clientMessage.payload.headers,
  254. })
  255. }
  256. function uuidv4() {
  257. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  258. const r = (Math.random() * 16) | 0
  259. const v = c == 'x' ? r : (r & 0x3) | 0x8
  260. return v.toString(16)
  261. })
  262. }