From d29a6af20f414cbe2abe1a0b6915ba581b51fca1 Mon Sep 17 00:00:00 2001 From: Banks Nussman Date: Fri, 25 Feb 2022 11:44:17 -0500 Subject: [PATCH 1/3] initial work --- packages/manager/.storybook/preview.tsx | 26 ++--- packages/manager/package.json | 1 + yarn.lock | 149 +++++++++++++++++++++++- 3 files changed, 158 insertions(+), 18 deletions(-) diff --git a/packages/manager/.storybook/preview.tsx b/packages/manager/.storybook/preview.tsx index 220f8e2e7fc..a53b1f9b903 100644 --- a/packages/manager/.storybook/preview.tsx +++ b/packages/manager/.storybook/preview.tsx @@ -1,20 +1,27 @@ // .storybook/preview.js -import { select, withKnobs } from '@storybook/addon-knobs'; -import { MINIMAL_VIEWPORTS } from '@storybook/addon-viewport'; import React from 'react'; -import '../public/fonts/fonts.css'; import CssBaseline from '../src/components/core/CssBaseline'; +import { select, withKnobs } from '@storybook/addon-knobs'; +import { MINIMAL_VIEWPORTS } from '@storybook/addon-viewport'; import { ThemeProvider } from '../src/components/core/styles'; -import '../src/index.css'; import { dark, light } from '../src/themes'; import { wrapWithTheme } from '../src/utilities/testHelpers'; +import { initialize, mswDecorator } from 'msw-storybook-addon'; +import { handlers } from '../src/mocks/serverHandlers'; +import '../public/fonts/fonts.css'; +import '../src/index.css'; const options = { dark, light, }; +initialize({ + onUnhandledRequest: 'warn', +}); + export const decorators = [ + mswDecorator, withKnobs, (Story) => { const _key = select('theme', ['light', 'dark'], 'light'); @@ -51,14 +58,5 @@ export const parameters = { viewport: { viewports: MINIMAL_VIEWPORTS, }, + msw: handlers, }; - -// Use the Mock Service Worker to mock API requests. -if (typeof global.process === 'undefined') { - try { - const { worker } = require('../src/mocks/testBrowser'); - worker.start(); - } catch (e) { - console.warn('Unable to start the MSW', e); - } -} diff --git a/packages/manager/package.json b/packages/manager/package.json index 1a561e61f6a..c5b95e5d0bf 100644 --- a/packages/manager/package.json +++ b/packages/manager/package.json @@ -224,6 +224,7 @@ "mixin-deep": "^2.0.1", "mongodb": "^3.1.13", "msw": "~0.20.5", + "msw-storybook-addon": "^1.6.0", "prettier": "~2.2.1", "react-dev-utils": "^12.0.0-next.60", "redux-mock-store": "^1.5.3", diff --git a/yarn.lock b/yarn.lock index 61cd2215044..6036e72a857 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2438,6 +2438,23 @@ global "^4.4.0" regenerator-runtime "^0.13.7" +"@storybook/addons@^6.0.0": + version "6.4.19" + resolved "https://registry.yarnpkg.com/@storybook/addons/-/addons-6.4.19.tgz#797d912b8b5a86cd6e0d31fa4c42d1f80808a432" + integrity sha512-QNyRYhpqmHV8oJxxTBdkRlLSbDFhpBvfvMfIrIT1UXb/eemdBZTaCGVvXZ9UixoEEI7f8VwAQ44IvkU5B1509w== + dependencies: + "@storybook/api" "6.4.19" + "@storybook/channels" "6.4.19" + "@storybook/client-logger" "6.4.19" + "@storybook/core-events" "6.4.19" + "@storybook/csf" "0.0.2--canary.87bc651.0" + "@storybook/router" "6.4.19" + "@storybook/theming" "6.4.19" + "@types/webpack-env" "^1.16.0" + core-js "^3.8.2" + global "^4.4.0" + regenerator-runtime "^0.13.7" + "@storybook/api@6.2.9": version "6.2.9" resolved "https://registry.yarnpkg.com/@storybook/api/-/api-6.2.9.tgz#a9b46569192ad5d8da6435c9d63dc4b0c8463b51" @@ -2464,6 +2481,29 @@ ts-dedent "^2.0.0" util-deprecate "^1.0.2" +"@storybook/api@6.4.19": + version "6.4.19" + resolved "https://registry.yarnpkg.com/@storybook/api/-/api-6.4.19.tgz#8000a0e4c52c39b910b4ccc6731419e8e71800ef" + integrity sha512-aDvea+NpQCBjpNp9YidO1Pr7fzzCp15FSdkG+2ihGQfv5raxrN+IIJnGUXecpe71nvlYiB+29UXBVK7AL0j51Q== + dependencies: + "@storybook/channels" "6.4.19" + "@storybook/client-logger" "6.4.19" + "@storybook/core-events" "6.4.19" + "@storybook/csf" "0.0.2--canary.87bc651.0" + "@storybook/router" "6.4.19" + "@storybook/semver" "^7.3.2" + "@storybook/theming" "6.4.19" + core-js "^3.8.2" + fast-deep-equal "^3.1.3" + global "^4.4.0" + lodash "^4.17.21" + memoizerific "^1.11.3" + regenerator-runtime "^0.13.7" + store2 "^2.12.0" + telejson "^5.3.2" + ts-dedent "^2.0.0" + util-deprecate "^1.0.2" + "@storybook/api@6.5.0-alpha.38": version "6.5.0-alpha.38" resolved "https://registry.yarnpkg.com/@storybook/api/-/api-6.5.0-alpha.38.tgz#11501f750ed28b64b88b015a5ebddfceb1a5076c" @@ -2608,6 +2648,15 @@ ts-dedent "^2.0.0" util-deprecate "^1.0.2" +"@storybook/channels@6.4.19": + version "6.4.19" + resolved "https://registry.yarnpkg.com/@storybook/channels/-/channels-6.4.19.tgz#095bbaee494bf5b03f7cb92d34626f2f5063cb31" + integrity sha512-EwyoncFvTfmIlfsy8jTfayCxo2XchPkZk/9txipugWSmc057HdklMKPLOHWP0z5hLH0IbVIKXzdNISABm36jwQ== + dependencies: + core-js "^3.8.2" + ts-dedent "^2.0.0" + util-deprecate "^1.0.2" + "@storybook/channels@6.5.0-alpha.38": version "6.5.0-alpha.38" resolved "https://registry.yarnpkg.com/@storybook/channels/-/channels-6.5.0-alpha.38.tgz#ce2612409c8c71bacf2fb90e6db9f9a64a24f72c" @@ -2675,6 +2724,14 @@ core-js "^3.8.2" global "^4.4.0" +"@storybook/client-logger@6.4.19": + version "6.4.19" + resolved "https://registry.yarnpkg.com/@storybook/client-logger/-/client-logger-6.4.19.tgz#b2011ad2fa446cce4a9afdb41974b2a576e9fad2" + integrity sha512-zmg/2wyc9W3uZrvxaW4BfHcr40J0v7AGslqYXk9H+ERLVwIvrR4NhxQFaS6uITjBENyRDxwzfU3Va634WcmdDQ== + dependencies: + core-js "^3.8.2" + global "^4.4.0" + "@storybook/client-logger@6.5.0-alpha.38": version "6.5.0-alpha.38" resolved "https://registry.yarnpkg.com/@storybook/client-logger/-/client-logger-6.5.0-alpha.38.tgz#bcd97a9724dfbfaa350b52903cf1ad6512888b96" @@ -2813,6 +2870,13 @@ dependencies: core-js "^3.8.2" +"@storybook/core-events@6.4.19": + version "6.4.19" + resolved "https://registry.yarnpkg.com/@storybook/core-events/-/core-events-6.4.19.tgz#d2a03156783a3cb9bd9f7ba81a06a798a5c296ae" + integrity sha512-KICzUw6XVQUJzFSCXfvhfHAuyhn4Q5J4IZEfuZkcGJS4ODkrO6tmpdYE5Cfr+so95Nfp0ErWiLUuodBsW9/rtA== + dependencies: + core-js "^3.8.2" + "@storybook/core-events@6.5.0-alpha.38": version "6.5.0-alpha.38" resolved "https://registry.yarnpkg.com/@storybook/core-events/-/core-events-6.5.0-alpha.38.tgz#cff01b50afc40f486ad42793348990a354d2f02b" @@ -3055,6 +3119,23 @@ qs "^6.10.0" ts-dedent "^2.0.0" +"@storybook/router@6.4.19": + version "6.4.19" + resolved "https://registry.yarnpkg.com/@storybook/router/-/router-6.4.19.tgz#e653224dd9a521836bbd2610f604f609a2c77af2" + integrity sha512-KWWwIzuyeEIWVezkCihwY2A76Il9tUNg0I410g9qT7NrEsKyqXGRYOijWub7c1GGyNjLqz0jtrrehtixMcJkuA== + dependencies: + "@storybook/client-logger" "6.4.19" + core-js "^3.8.2" + fast-deep-equal "^3.1.3" + global "^4.4.0" + history "5.0.0" + lodash "^4.17.21" + memoizerific "^1.11.3" + qs "^6.10.0" + react-router "^6.0.0" + react-router-dom "^6.0.0" + ts-dedent "^2.0.0" + "@storybook/router@6.5.0-alpha.38": version "6.5.0-alpha.38" resolved "https://registry.yarnpkg.com/@storybook/router/-/router-6.5.0-alpha.38.tgz#dd756212f326388a8233ccd9f086208eddcf9eec" @@ -3126,6 +3207,24 @@ resolve-from "^5.0.0" ts-dedent "^2.0.0" +"@storybook/theming@6.4.19": + version "6.4.19" + resolved "https://registry.yarnpkg.com/@storybook/theming/-/theming-6.4.19.tgz#0a6834d91e0b0eadbb10282e7fb2947e2bbf9e9e" + integrity sha512-V4pWmTvAxmbHR6B3jA4hPkaxZPyExHvCToy7b76DpUTpuHihijNDMAn85KhOQYIeL9q14zP/aiz899tOHsOidg== + dependencies: + "@emotion/core" "^10.1.1" + "@emotion/is-prop-valid" "^0.8.6" + "@emotion/styled" "^10.0.27" + "@storybook/client-logger" "6.4.19" + core-js "^3.8.2" + deep-object-diff "^1.1.0" + emotion-theming "^10.0.27" + global "^4.4.0" + memoizerific "^1.11.3" + polished "^4.0.5" + resolve-from "^5.0.0" + ts-dedent "^2.0.0" + "@storybook/theming@6.5.0-alpha.38": version "6.5.0-alpha.38" resolved "https://registry.yarnpkg.com/@storybook/theming/-/theming-6.5.0-alpha.38.tgz#89efbe8cadab32842607c24c6e89ad8f30b6af3a" @@ -9823,6 +9922,13 @@ history@*: dependencies: "@babel/runtime" "^7.7.6" +history@5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/history/-/history-5.0.0.tgz#0cabbb6c4bbf835addb874f8259f6d25101efd08" + integrity sha512-3NyRMKIiFSJmIPdq7FxkNMJkQ7ZEtVblOQ38VtKaA0zZMW1Eo6Q6W8oDKEflr1kNNTItSnk4JMCO1deeSgbLLg== + dependencies: + "@babel/runtime" "^7.7.6" + history@^4.9.0: version "4.10.1" resolved "https://registry.yarnpkg.com/history/-/history-4.10.1.tgz#33371a65e3a83b267434e2b3f3b1b4c58aad4cf3" @@ -9835,6 +9941,13 @@ history@^4.9.0: tiny-warning "^1.0.0" value-equal "^1.0.1" +history@^5.2.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/history/-/history-5.3.0.tgz#1548abaa245ba47992f063a0783db91ef201c73b" + integrity sha512-ZqaKwjjrAYUYfLG+htGaIIZ4nioX2L70ZUMIFysS3xvBsSG4x/n1V6TXV3N8ZYNuFGlDirFg32T7B6WOUPDYcQ== + dependencies: + "@babel/runtime" "^7.7.6" + hmac-drbg@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" @@ -10575,6 +10688,11 @@ is-negative-zero@^2.0.1: resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.2.tgz#7bf6f03a28003b8b3965de3ac26f664d765f3150" integrity sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA== +is-node-process@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-node-process/-/is-node-process-1.0.1.tgz#4fc7ac3a91e8aac58175fe0578abbc56f2831b23" + integrity sha512-5IcdXuf++TTNt3oGl9EBdkvndXA8gmc4bz/Y+mdEpWh3Mcn/+kOw6hI7LD5CocqJWMzeb0I0ClndRVNdEPuJXQ== + is-number-object@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/is-number-object/-/is-number-object-1.0.6.tgz#6a7aaf838c7f0686a50b4553f7e54a96494e89f0" @@ -12644,6 +12762,14 @@ ms@2.1.3, ms@^2.1.1: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== +msw-storybook-addon@^1.6.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/msw-storybook-addon/-/msw-storybook-addon-1.6.0.tgz#85671ca4a685a29884fc09a1dcce5d16f3ee2c4c" + integrity sha512-M9QfrMrUykgGbHkVlyYSRFrkiDS+ibMedjWmFjm448TUl8QtvMpopM4ki9+NB2UeDLInMR9YkEmljFkT/q2gPw== + dependencies: + "@storybook/addons" "^6.0.0" + is-node-process "^1.0.1" + msw@~0.20.5: version "0.20.5" resolved "https://registry.yarnpkg.com/msw/-/msw-0.20.5.tgz#b6141080c0d8b17c451d9ca36c28cc47b4ac487a" @@ -13940,9 +14066,9 @@ pretty-hrtime@^1.0.3: integrity sha1-t+PqQkNaTJsnWdmeDyAesZWALuE= prismjs@^1.21.0, prismjs@^1.24.0, prismjs@~1.25.0: - version "1.26.0" - resolved "https://registry.yarnpkg.com/prismjs/-/prismjs-1.26.0.tgz#16881b594828bb6b45296083a8cbab46b0accd47" - integrity sha512-HUoH9C5Z3jKkl3UunCyiD5jwk0+Hz0fIgQ2nbwU2Oo/ceuTAQAg+pPVnfdt2TJWRVLcxKh9iuoYDUSc8clb5UQ== + version "1.27.0" + resolved "https://registry.yarnpkg.com/prismjs/-/prismjs-1.27.0.tgz#bb6ee3138a0b438a3653dd4d6ce0cc6510a45057" + integrity sha512-t13BGPUlFDR7wRB5kQDG4jjl7XeuH6jbJGt11JHPL96qwsEHNX2+68tFXqc1/k+/jALsbSWJKUOT/hcYAZ5LkA== process-nextick-args@~2.0.0: version "2.0.1" @@ -14489,6 +14615,14 @@ react-refresh@^0.11.0: resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.11.0.tgz#77198b944733f0f1f1a90e791de4541f9f074046" integrity sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A== +react-router-dom@^6.0.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-6.2.1.tgz#32ec81829152fbb8a7b045bf593a22eadf019bec" + integrity sha512-I6Zax+/TH/cZMDpj3/4Fl2eaNdcvoxxHoH1tYOREsQ22OKDYofGebrNm6CTPUcvLvZm63NL/vzCYdjf9CUhqmA== + dependencies: + history "^5.2.0" + react-router "6.2.1" + react-router-dom@~5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-5.1.2.tgz#06701b834352f44d37fbb6311f870f84c76b9c18" @@ -14525,6 +14659,13 @@ react-router@5.1.2: tiny-invariant "^1.0.2" tiny-warning "^1.0.0" +react-router@6.2.1, react-router@^6.0.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/react-router/-/react-router-6.2.1.tgz#be2a97a6006ce1d9123c28934e604faef51448a3" + integrity sha512-2fG0udBtxou9lXtK97eJeET2ki5//UWfQSl1rlJ7quwe6jrktK9FCCc8dQb5QY6jAv3jua8bBQRhhDOM/kVRsg== + dependencies: + history "^5.2.0" + react-select@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/react-select/-/react-select-3.2.0.tgz#de9284700196f5f9b5277c5d850a9ce85f5c72fe" @@ -16354,7 +16495,7 @@ tar@^6.0.2: mkdirp "^1.0.3" yallist "^4.0.0" -telejson@^5.1.0, telejson@^5.3.3: +telejson@^5.1.0, telejson@^5.3.2, telejson@^5.3.3: version "5.3.3" resolved "https://registry.yarnpkg.com/telejson/-/telejson-5.3.3.tgz#fa8ca84543e336576d8734123876a9f02bf41d2e" integrity sha512-PjqkJZpzEggA9TBpVtJi1LVptP7tYtXB6rEubwlHap76AMjzvOdKX41CxyaW7ahhzDU1aftXnMCx5kAPDZTQBA== From 15ae34186f2051df8e018dd3c0bc751d46bbc8d8 Mon Sep 17 00:00:00 2001 From: Banks Nussman Date: Fri, 25 Feb 2022 12:22:02 -0500 Subject: [PATCH 2/3] add msw js to public dir --- .../storybook-static/mockServiceWorker.js | 228 ++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 packages/manager/storybook-static/mockServiceWorker.js diff --git a/packages/manager/storybook-static/mockServiceWorker.js b/packages/manager/storybook-static/mockServiceWorker.js new file mode 100644 index 00000000000..9704362b77a --- /dev/null +++ b/packages/manager/storybook-static/mockServiceWorker.js @@ -0,0 +1,228 @@ +/** + * Mock Service Worker. + * @see https://github.com/mswjs/msw + * - Please do NOT modify this file. + * - Please do NOT serve this file on production. + */ +/* eslint-disable */ +/* tslint:disable */ + +const INTEGRITY_CHECKSUM = 'ca2c3cd7453d8c614e2c19db63ede1a1'; +const bypassHeaderName = 'x-msw-bypass'; + +let clients = {}; + +self.addEventListener('install', function() { + return self.skipWaiting(); +}); + +self.addEventListener('activate', async function(event) { + return self.clients.claim(); +}); + +self.addEventListener('message', async function(event) { + const clientId = event.source.id; + const client = await event.currentTarget.clients.get(clientId); + const allClients = await self.clients.matchAll(); + const allClientIds = allClients.map(client => client.id); + + switch (event.data) { + case 'INTEGRITY_CHECK_REQUEST': { + sendToClient(client, { + type: 'INTEGRITY_CHECK_RESPONSE', + payload: INTEGRITY_CHECKSUM + }); + break; + } + + case 'MOCK_ACTIVATE': { + clients = ensureKeys(allClientIds, clients); + clients[clientId] = true; + + sendToClient(client, { + type: 'MOCKING_ENABLED', + payload: true + }); + break; + } + + case 'MOCK_DEACTIVATE': { + clients = ensureKeys(allClientIds, clients); + clients[clientId] = false; + break; + } + + case 'CLIENT_CLOSED': { + const remainingClients = allClients.filter(client => { + return client.id !== clientId; + }); + + // Unregister itself when there are no more clients + if (remainingClients.length === 0) { + self.registration.unregister(); + } + + break; + } + } +}); + +self.addEventListener('fetch', async function(event) { + const { clientId, request } = event; + const requestClone = request.clone(); + const getOriginalResponse = () => fetch(requestClone); + + // Opening the DevTools triggers the "only-if-cached" request + // that cannot be handled by the worker. Bypass such requests. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + return; + } + + event.respondWith( + new Promise(async (resolve, reject) => { + const client = await event.target.clients.get(clientId); + + if ( + // Bypass mocking when no clients active + !client || + // Bypass mocking if the current client has mocking disabled + !clients[clientId] || + // Bypass mocking for navigation requests + request.mode === 'navigate' + ) { + return resolve(getOriginalResponse()); + } + + // Bypass requests with the explicit bypass header + if (requestClone.headers.get(bypassHeaderName) === 'true') { + const modifiedHeaders = serializeHeaders(requestClone.headers); + // Remove the bypass header to comply with the CORS preflight check + delete modifiedHeaders[bypassHeaderName]; + + const originalRequest = new Request(requestClone, { + headers: new Headers(modifiedHeaders) + }); + + return resolve(fetch(originalRequest)); + } + + const reqHeaders = serializeHeaders(request.headers); + const body = await request.text(); + + const rawClientMessage = await sendToClient(client, { + type: 'REQUEST', + payload: { + url: request.url, + method: request.method, + headers: reqHeaders, + cache: request.cache, + mode: request.mode, + credentials: request.credentials, + destination: request.destination, + integrity: request.integrity, + redirect: request.redirect, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + body, + bodyUsed: request.bodyUsed, + keepalive: request.keepalive + } + }); + + const clientMessage = rawClientMessage; + + switch (clientMessage.type) { + case 'MOCK_SUCCESS': { + setTimeout( + resolve.bind(this, createResponse(clientMessage)), + clientMessage.payload.delay + ); + break; + } + + case 'MOCK_NOT_FOUND': { + return resolve(getOriginalResponse()); + } + + case 'NETWORK_ERROR': { + const { name, message } = clientMessage.payload; + const networkError = new Error(message); + networkError.name = name; + + // Rejecting a request Promise emulates a network error. + return reject(networkError); + } + + case 'INTERNAL_ERROR': { + const parsedBody = JSON.parse(clientMessage.payload.body); + + console.error( + `\ +[MSW] Request handler function for "%s %s" has thrown the following exception: + +${parsedBody.errorType}: ${parsedBody.message} +(see more detailed error stack trace in the mocked response body) + +This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error. +If you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\ + `, + request.method, + request.url + ); + + return resolve(createResponse(clientMessage)); + } + } + }).catch(error => { + console.error( + '[MSW] Failed to mock a "%s" request to "%s": %s', + request.method, + request.url, + error + ); + }) + ); +}); + +function serializeHeaders(headers) { + const reqHeaders = {}; + headers.forEach((value, name) => { + reqHeaders[name] = reqHeaders[name] + ? [].concat(reqHeaders[name]).concat(value) + : value; + }); + return reqHeaders; +} + +function sendToClient(client, message) { + return new Promise((resolve, reject) => { + const channel = new MessageChannel(); + + channel.port1.onmessage = event => { + if (event.data && event.data.error) { + reject(event.data.error); + } else { + resolve(event.data); + } + }; + + client.postMessage(JSON.stringify(message), [channel.port2]); + }); +} + +function createResponse(clientMessage) { + return new Response(clientMessage.payload.body, { + ...clientMessage.payload, + headers: clientMessage.payload.headers + }); +} + +function ensureKeys(keys, obj) { + return Object.keys(obj).reduce((acc, key) => { + if (keys.includes(key)) { + acc[key] = obj[key]; + } + + return acc; + }, {}); +} From 62d466635676acd3409f5852e43455cb23947abd Mon Sep 17 00:00:00 2001 From: Banks Nussman Date: Fri, 25 Feb 2022 12:38:43 -0500 Subject: [PATCH 3/3] revert --- .../storybook-static/mockServiceWorker.js | 228 ------------------ 1 file changed, 228 deletions(-) delete mode 100644 packages/manager/storybook-static/mockServiceWorker.js diff --git a/packages/manager/storybook-static/mockServiceWorker.js b/packages/manager/storybook-static/mockServiceWorker.js deleted file mode 100644 index 9704362b77a..00000000000 --- a/packages/manager/storybook-static/mockServiceWorker.js +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Mock Service Worker. - * @see https://github.com/mswjs/msw - * - Please do NOT modify this file. - * - Please do NOT serve this file on production. - */ -/* eslint-disable */ -/* tslint:disable */ - -const INTEGRITY_CHECKSUM = 'ca2c3cd7453d8c614e2c19db63ede1a1'; -const bypassHeaderName = 'x-msw-bypass'; - -let clients = {}; - -self.addEventListener('install', function() { - return self.skipWaiting(); -}); - -self.addEventListener('activate', async function(event) { - return self.clients.claim(); -}); - -self.addEventListener('message', async function(event) { - const clientId = event.source.id; - const client = await event.currentTarget.clients.get(clientId); - const allClients = await self.clients.matchAll(); - const allClientIds = allClients.map(client => client.id); - - switch (event.data) { - case 'INTEGRITY_CHECK_REQUEST': { - sendToClient(client, { - type: 'INTEGRITY_CHECK_RESPONSE', - payload: INTEGRITY_CHECKSUM - }); - break; - } - - case 'MOCK_ACTIVATE': { - clients = ensureKeys(allClientIds, clients); - clients[clientId] = true; - - sendToClient(client, { - type: 'MOCKING_ENABLED', - payload: true - }); - break; - } - - case 'MOCK_DEACTIVATE': { - clients = ensureKeys(allClientIds, clients); - clients[clientId] = false; - break; - } - - case 'CLIENT_CLOSED': { - const remainingClients = allClients.filter(client => { - return client.id !== clientId; - }); - - // Unregister itself when there are no more clients - if (remainingClients.length === 0) { - self.registration.unregister(); - } - - break; - } - } -}); - -self.addEventListener('fetch', async function(event) { - const { clientId, request } = event; - const requestClone = request.clone(); - const getOriginalResponse = () => fetch(requestClone); - - // Opening the DevTools triggers the "only-if-cached" request - // that cannot be handled by the worker. Bypass such requests. - if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { - return; - } - - event.respondWith( - new Promise(async (resolve, reject) => { - const client = await event.target.clients.get(clientId); - - if ( - // Bypass mocking when no clients active - !client || - // Bypass mocking if the current client has mocking disabled - !clients[clientId] || - // Bypass mocking for navigation requests - request.mode === 'navigate' - ) { - return resolve(getOriginalResponse()); - } - - // Bypass requests with the explicit bypass header - if (requestClone.headers.get(bypassHeaderName) === 'true') { - const modifiedHeaders = serializeHeaders(requestClone.headers); - // Remove the bypass header to comply with the CORS preflight check - delete modifiedHeaders[bypassHeaderName]; - - const originalRequest = new Request(requestClone, { - headers: new Headers(modifiedHeaders) - }); - - return resolve(fetch(originalRequest)); - } - - const reqHeaders = serializeHeaders(request.headers); - const body = await request.text(); - - const rawClientMessage = await sendToClient(client, { - type: 'REQUEST', - payload: { - url: request.url, - method: request.method, - headers: reqHeaders, - cache: request.cache, - mode: request.mode, - credentials: request.credentials, - destination: request.destination, - integrity: request.integrity, - redirect: request.redirect, - referrer: request.referrer, - referrerPolicy: request.referrerPolicy, - body, - bodyUsed: request.bodyUsed, - keepalive: request.keepalive - } - }); - - const clientMessage = rawClientMessage; - - switch (clientMessage.type) { - case 'MOCK_SUCCESS': { - setTimeout( - resolve.bind(this, createResponse(clientMessage)), - clientMessage.payload.delay - ); - break; - } - - case 'MOCK_NOT_FOUND': { - return resolve(getOriginalResponse()); - } - - case 'NETWORK_ERROR': { - const { name, message } = clientMessage.payload; - const networkError = new Error(message); - networkError.name = name; - - // Rejecting a request Promise emulates a network error. - return reject(networkError); - } - - case 'INTERNAL_ERROR': { - const parsedBody = JSON.parse(clientMessage.payload.body); - - console.error( - `\ -[MSW] Request handler function for "%s %s" has thrown the following exception: - -${parsedBody.errorType}: ${parsedBody.message} -(see more detailed error stack trace in the mocked response body) - -This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error. -If you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\ - `, - request.method, - request.url - ); - - return resolve(createResponse(clientMessage)); - } - } - }).catch(error => { - console.error( - '[MSW] Failed to mock a "%s" request to "%s": %s', - request.method, - request.url, - error - ); - }) - ); -}); - -function serializeHeaders(headers) { - const reqHeaders = {}; - headers.forEach((value, name) => { - reqHeaders[name] = reqHeaders[name] - ? [].concat(reqHeaders[name]).concat(value) - : value; - }); - return reqHeaders; -} - -function sendToClient(client, message) { - return new Promise((resolve, reject) => { - const channel = new MessageChannel(); - - channel.port1.onmessage = event => { - if (event.data && event.data.error) { - reject(event.data.error); - } else { - resolve(event.data); - } - }; - - client.postMessage(JSON.stringify(message), [channel.port2]); - }); -} - -function createResponse(clientMessage) { - return new Response(clientMessage.payload.body, { - ...clientMessage.payload, - headers: clientMessage.payload.headers - }); -} - -function ensureKeys(keys, obj) { - return Object.keys(obj).reduce((acc, key) => { - if (keys.includes(key)) { - acc[key] = obj[key]; - } - - return acc; - }, {}); -}