Skip to content

Commit 07b60f1

Browse files
authored
fix: disable code blocks (#742)
* fix: all monospace, no code blocks * fix: restore markdown with code edition * fix: setup https dev, msw, and mocks * style: package.json * ci: fix vite config for ci * build: vite config defaults to http if no certificates * fix: disable code-blocks see #731 for future fix
1 parent 25f1ed6 commit 07b60f1

File tree

13 files changed

+522
-107
lines changed

13 files changed

+522
-107
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,8 @@ cypress/downloads/
4343

4444
# Sentry Config File
4545
.env.sentry-build-plugin
46+
47+
# Certificates
48+
*.pem
49+
*.crt
50+
*.key

package.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,5 +162,10 @@
162162
"src/**/*.test.ts"
163163
]
164164
},
165-
"packageManager": "[email protected]"
165+
"packageManager": "[email protected]",
166+
"msw": {
167+
"workerDirectory": [
168+
"public"
169+
]
170+
}
166171
}

public/mockServiceWorker.js

Lines changed: 295 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
/* eslint-disable */
2+
/* tslint:disable */
3+
4+
/**
5+
* Mock Service Worker.
6+
* @see https://github.com/mswjs/msw
7+
* - Please do NOT modify this file.
8+
* - Please do NOT serve this file on production.
9+
*/
10+
11+
const PACKAGE_VERSION = '2.6.5'
12+
const INTEGRITY_CHECKSUM = 'ca7800994cc8bfb5eb961e037c877074'
13+
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
14+
const activeClientIds = new Set()
15+
16+
self.addEventListener('install', function () {
17+
self.skipWaiting()
18+
})
19+
20+
self.addEventListener('activate', function (event) {
21+
event.waitUntil(self.clients.claim())
22+
})
23+
24+
self.addEventListener('message', async function (event) {
25+
const clientId = event.source.id
26+
27+
if (!clientId || !self.clients) {
28+
return
29+
}
30+
31+
const client = await self.clients.get(clientId)
32+
33+
if (!client) {
34+
return
35+
}
36+
37+
const allClients = await self.clients.matchAll({
38+
type: 'window',
39+
})
40+
41+
switch (event.data) {
42+
case 'KEEPALIVE_REQUEST': {
43+
sendToClient(client, {
44+
type: 'KEEPALIVE_RESPONSE',
45+
})
46+
break
47+
}
48+
49+
case 'INTEGRITY_CHECK_REQUEST': {
50+
sendToClient(client, {
51+
type: 'INTEGRITY_CHECK_RESPONSE',
52+
payload: {
53+
packageVersion: PACKAGE_VERSION,
54+
checksum: INTEGRITY_CHECKSUM,
55+
},
56+
})
57+
break
58+
}
59+
60+
case 'MOCK_ACTIVATE': {
61+
activeClientIds.add(clientId)
62+
63+
sendToClient(client, {
64+
type: 'MOCKING_ENABLED',
65+
payload: {
66+
client: {
67+
id: client.id,
68+
frameType: client.frameType,
69+
},
70+
},
71+
})
72+
break
73+
}
74+
75+
case 'MOCK_DEACTIVATE': {
76+
activeClientIds.delete(clientId)
77+
break
78+
}
79+
80+
case 'CLIENT_CLOSED': {
81+
activeClientIds.delete(clientId)
82+
83+
const remainingClients = allClients.filter((client) => {
84+
return client.id !== clientId
85+
})
86+
87+
// Unregister itself when there are no more clients
88+
if (remainingClients.length === 0) {
89+
self.registration.unregister()
90+
}
91+
92+
break
93+
}
94+
}
95+
})
96+
97+
self.addEventListener('fetch', function (event) {
98+
const { request } = event
99+
100+
// Bypass navigation requests.
101+
if (request.mode === 'navigate') {
102+
return
103+
}
104+
105+
// Opening the DevTools triggers the "only-if-cached" request
106+
// that cannot be handled by the worker. Bypass such requests.
107+
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
108+
return
109+
}
110+
111+
// Bypass all requests when there are no active clients.
112+
// Prevents the self-unregistered worked from handling requests
113+
// after it's been deleted (still remains active until the next reload).
114+
if (activeClientIds.size === 0) {
115+
return
116+
}
117+
118+
// Generate unique request ID.
119+
const requestId = crypto.randomUUID()
120+
event.respondWith(handleRequest(event, requestId))
121+
})
122+
123+
async function handleRequest(event, requestId) {
124+
const client = await resolveMainClient(event)
125+
const response = await getResponse(event, client, requestId)
126+
127+
// Send back the response clone for the "response:*" life-cycle events.
128+
// Ensure MSW is active and ready to handle the message, otherwise
129+
// this message will pend indefinitely.
130+
if (client && activeClientIds.has(client.id)) {
131+
;(async function () {
132+
const responseClone = response.clone()
133+
134+
sendToClient(
135+
client,
136+
{
137+
type: 'RESPONSE',
138+
payload: {
139+
requestId,
140+
isMockedResponse: IS_MOCKED_RESPONSE in response,
141+
type: responseClone.type,
142+
status: responseClone.status,
143+
statusText: responseClone.statusText,
144+
body: responseClone.body,
145+
headers: Object.fromEntries(responseClone.headers.entries()),
146+
},
147+
},
148+
[responseClone.body],
149+
)
150+
})()
151+
}
152+
153+
return response
154+
}
155+
156+
// Resolve the main client for the given event.
157+
// Client that issues a request doesn't necessarily equal the client
158+
// that registered the worker. It's with the latter the worker should
159+
// communicate with during the response resolving phase.
160+
async function resolveMainClient(event) {
161+
const client = await self.clients.get(event.clientId)
162+
163+
if (activeClientIds.has(event.clientId)) {
164+
return client
165+
}
166+
167+
if (client?.frameType === 'top-level') {
168+
return client
169+
}
170+
171+
const allClients = await self.clients.matchAll({
172+
type: 'window',
173+
})
174+
175+
return allClients
176+
.filter((client) => {
177+
// Get only those clients that are currently visible.
178+
return client.visibilityState === 'visible'
179+
})
180+
.find((client) => {
181+
// Find the client ID that's recorded in the
182+
// set of clients that have registered the worker.
183+
return activeClientIds.has(client.id)
184+
})
185+
}
186+
187+
async function getResponse(event, client, requestId) {
188+
const { request } = event
189+
190+
// Clone the request because it might've been already used
191+
// (i.e. its body has been read and sent to the client).
192+
const requestClone = request.clone()
193+
194+
function passthrough() {
195+
// Cast the request headers to a new Headers instance
196+
// so the headers can be manipulated with.
197+
const headers = new Headers(requestClone.headers)
198+
199+
// Remove the "accept" header value that marked this request as passthrough.
200+
// This prevents request alteration and also keeps it compliant with the
201+
// user-defined CORS policies.
202+
headers.delete('accept', 'msw/passthrough')
203+
204+
return fetch(requestClone, { headers })
205+
}
206+
207+
// Bypass mocking when the client is not active.
208+
if (!client) {
209+
return passthrough()
210+
}
211+
212+
// Bypass initial page load requests (i.e. static assets).
213+
// The absence of the immediate/parent client in the map of the active clients
214+
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
215+
// and is not ready to handle requests.
216+
if (!activeClientIds.has(client.id)) {
217+
return passthrough()
218+
}
219+
220+
// Notify the client that a request has been intercepted.
221+
const requestBuffer = await request.arrayBuffer()
222+
const clientMessage = await sendToClient(
223+
client,
224+
{
225+
type: 'REQUEST',
226+
payload: {
227+
id: requestId,
228+
url: request.url,
229+
mode: request.mode,
230+
method: request.method,
231+
headers: Object.fromEntries(request.headers.entries()),
232+
cache: request.cache,
233+
credentials: request.credentials,
234+
destination: request.destination,
235+
integrity: request.integrity,
236+
redirect: request.redirect,
237+
referrer: request.referrer,
238+
referrerPolicy: request.referrerPolicy,
239+
body: requestBuffer,
240+
keepalive: request.keepalive,
241+
},
242+
},
243+
[requestBuffer],
244+
)
245+
246+
switch (clientMessage.type) {
247+
case 'MOCK_RESPONSE': {
248+
return respondWithMock(clientMessage.data)
249+
}
250+
251+
case 'PASSTHROUGH': {
252+
return passthrough()
253+
}
254+
}
255+
256+
return passthrough()
257+
}
258+
259+
function sendToClient(client, message, transferrables = []) {
260+
return new Promise((resolve, reject) => {
261+
const channel = new MessageChannel()
262+
263+
channel.port1.onmessage = (event) => {
264+
if (event.data && event.data.error) {
265+
return reject(event.data.error)
266+
}
267+
268+
resolve(event.data)
269+
}
270+
271+
client.postMessage(
272+
message,
273+
[channel.port2].concat(transferrables.filter(Boolean)),
274+
)
275+
})
276+
}
277+
278+
async function respondWithMock(response) {
279+
// Setting response status code to 0 is a no-op.
280+
// However, when responding with a "Response.error()", the produced Response
281+
// instance will have status code set to 0. Since it's not possible to create
282+
// a Response instance with status code 0, handle that use-case separately.
283+
if (response.status === 0) {
284+
return Response.error()
285+
}
286+
287+
const mockedResponse = new Response(response.body, response)
288+
289+
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
290+
value: true,
291+
enumerable: true,
292+
})
293+
294+
return mockedResponse
295+
}

src/hooks/utils/responses.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ import cloneDeep from 'lodash.clonedeep';
22
import { afterAll, beforeAll, expect, test, vi } from 'vitest';
33

44
import { ResponseAppData } from '@/config/appDataTypes';
5+
import { mockItem } from '@/mocks/mockItem';
6+
import { mockMembers } from '@/mocks/mockMembers';
57

6-
import { mockItem, mockMembers } from '../../mocks/db';
78
import {
89
buildMockBotResponses,
910
buildMockResponses,

src/main.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import * as Sentry from '@sentry/react';
88
import { MOCK_API } from './config/env';
99
import { generateSentryConfig } from './config/sentry';
1010
import './index.css';
11-
import buildDatabase, { defaultMockContext, mockMembers } from './mocks/db';
11+
import buildDatabase, { defaultMockContext } from './mocks/db';
1212
import Root from './modules/Root';
1313

1414
Sentry.init({
@@ -25,9 +25,9 @@ if (MOCK_API) {
2525
mockApi(
2626
{
2727
externalUrls: [],
28-
dbName: window.Cypress ? 'graasp-app-cypress' : undefined,
28+
dbName: window.Cypress ? 'graasp-app-cypress' : 'msw-indexed-db',
2929
appContext: window.Cypress ? window.appContext : defaultMockContext,
30-
database: window.Cypress ? window.database : buildDatabase(mockMembers),
30+
database: window.Cypress ? window.database : buildDatabase(),
3131
},
3232
window.Cypress ? MockSolution.MirageJS : MockSolution.ServiceWorker,
3333
);

0 commit comments

Comments
 (0)