@theholocron/react-template 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,114 +7,111 @@
7
7
  * - Please do NOT modify this file.
8
8
  */
9
9
 
10
- const PACKAGE_VERSION = '2.15.0'
11
- const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
12
- const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13
- const activeClientIds = new Set()
14
-
15
- addEventListener('install', function () {
16
- self.skipWaiting()
17
- })
18
-
19
- addEventListener('activate', function (event) {
20
- event.waitUntil(self.clients.claim())
21
- })
22
-
23
- addEventListener('message', async function (event) {
24
- const clientId = Reflect.get(event.source || {}, 'id')
25
-
26
- if (!clientId || !self.clients) {
27
- return
28
- }
29
-
30
- const client = await self.clients.get(clientId)
31
-
32
- if (!client) {
33
- return
34
- }
35
-
36
- const allClients = await self.clients.matchAll({
37
- type: 'window',
38
- })
39
-
40
- switch (event.data) {
41
- case 'KEEPALIVE_REQUEST': {
42
- sendToClient(client, {
43
- type: 'KEEPALIVE_RESPONSE',
44
- })
45
- break
46
- }
47
-
48
- case 'INTEGRITY_CHECK_REQUEST': {
49
- sendToClient(client, {
50
- type: 'INTEGRITY_CHECK_RESPONSE',
51
- payload: {
52
- packageVersion: PACKAGE_VERSION,
53
- checksum: INTEGRITY_CHECKSUM,
54
- },
55
- })
56
- break
57
- }
58
-
59
- case 'MOCK_ACTIVATE': {
60
- activeClientIds.add(clientId)
61
-
62
- sendToClient(client, {
63
- type: 'MOCKING_ENABLED',
64
- payload: {
65
- client: {
66
- id: client.id,
67
- frameType: client.frameType,
68
- },
69
- },
70
- })
71
- break
72
- }
73
-
74
- case 'CLIENT_CLOSED': {
75
- activeClientIds.delete(clientId)
76
-
77
- const remainingClients = allClients.filter((client) => {
78
- return client.id !== clientId
79
- })
80
-
81
- // Unregister itself when there are no more clients
82
- if (remainingClients.length === 0) {
83
- self.registration.unregister()
84
- }
85
-
86
- break
87
- }
88
- }
89
- })
90
-
91
- addEventListener('fetch', function (event) {
92
- const requestInterceptedAt = Date.now()
93
-
94
- // Bypass navigation requests.
95
- if (event.request.mode === 'navigate') {
96
- return
97
- }
98
-
99
- // Opening the DevTools triggers the "only-if-cached" request
100
- // that cannot be handled by the worker. Bypass such requests.
101
- if (
102
- event.request.cache === 'only-if-cached' &&
103
- event.request.mode !== 'same-origin'
104
- ) {
105
- return
106
- }
107
-
108
- // Bypass all requests when there are no active clients.
109
- // Prevents the self-unregistered worked from handling requests
110
- // after it's been terminated (still remains active until the next reload).
111
- if (activeClientIds.size === 0) {
112
- return
113
- }
114
-
115
- const requestId = crypto.randomUUID()
116
- event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
117
- })
10
+ const PACKAGE_VERSION = "2.15.0";
11
+ const INTEGRITY_CHECKSUM = "03cb67ac84128e63d7cd722a6e5b7f1e";
12
+ const IS_MOCKED_RESPONSE = Symbol("isMockedResponse");
13
+ const activeClientIds = new Set();
14
+
15
+ addEventListener("install", function () {
16
+ self.skipWaiting();
17
+ });
18
+
19
+ addEventListener("activate", function (event) {
20
+ event.waitUntil(self.clients.claim());
21
+ });
22
+
23
+ addEventListener("message", async function (event) {
24
+ const clientId = Reflect.get(event.source || {}, "id");
25
+
26
+ if (!clientId || !self.clients) {
27
+ return;
28
+ }
29
+
30
+ const client = await self.clients.get(clientId);
31
+
32
+ if (!client) {
33
+ return;
34
+ }
35
+
36
+ const allClients = await self.clients.matchAll({
37
+ type: "window",
38
+ });
39
+
40
+ switch (event.data) {
41
+ case "KEEPALIVE_REQUEST": {
42
+ sendToClient(client, {
43
+ type: "KEEPALIVE_RESPONSE",
44
+ });
45
+ break;
46
+ }
47
+
48
+ case "INTEGRITY_CHECK_REQUEST": {
49
+ sendToClient(client, {
50
+ type: "INTEGRITY_CHECK_RESPONSE",
51
+ payload: {
52
+ packageVersion: PACKAGE_VERSION,
53
+ checksum: INTEGRITY_CHECKSUM,
54
+ },
55
+ });
56
+ break;
57
+ }
58
+
59
+ case "MOCK_ACTIVATE": {
60
+ activeClientIds.add(clientId);
61
+
62
+ sendToClient(client, {
63
+ type: "MOCKING_ENABLED",
64
+ payload: {
65
+ client: {
66
+ id: client.id,
67
+ frameType: client.frameType,
68
+ },
69
+ },
70
+ });
71
+ break;
72
+ }
73
+
74
+ case "CLIENT_CLOSED": {
75
+ activeClientIds.delete(clientId);
76
+
77
+ const remainingClients = allClients.filter((client) => {
78
+ return client.id !== clientId;
79
+ });
80
+
81
+ // Unregister itself when there are no more clients
82
+ if (remainingClients.length === 0) {
83
+ self.registration.unregister();
84
+ }
85
+
86
+ break;
87
+ }
88
+ }
89
+ });
90
+
91
+ addEventListener("fetch", function (event) {
92
+ const requestInterceptedAt = Date.now();
93
+
94
+ // Bypass navigation requests.
95
+ if (event.request.mode === "navigate") {
96
+ return;
97
+ }
98
+
99
+ // Opening the DevTools triggers the "only-if-cached" request
100
+ // that cannot be handled by the worker. Bypass such requests.
101
+ if (event.request.cache === "only-if-cached" && event.request.mode !== "same-origin") {
102
+ return;
103
+ }
104
+
105
+ // Bypass all requests when there are no active clients.
106
+ // Prevents the self-unregistered worked from handling requests
107
+ // after it's been terminated (still remains active until the next reload).
108
+ if (activeClientIds.size === 0) {
109
+ return;
110
+ }
111
+
112
+ const requestId = crypto.randomUUID();
113
+ event.respondWith(handleRequest(event, requestId, requestInterceptedAt));
114
+ });
118
115
 
119
116
  /**
120
117
  * @param {FetchEvent} event
@@ -122,60 +119,53 @@ addEventListener('fetch', function (event) {
122
119
  * @param {number} requestInterceptedAt
123
120
  */
124
121
  async function handleRequest(event, requestId, requestInterceptedAt) {
125
- const client = await resolveMainClient(event)
126
- const requestCloneForEvents = event.request.clone()
127
- const response = await getResponse(
128
- event,
129
- client,
130
- requestId,
131
- requestInterceptedAt,
132
- )
133
-
134
- // Send back the response clone for the "response:*" life-cycle events.
135
- // Ensure MSW is active and ready to handle the message, otherwise
136
- // this message will pend indefinitely.
137
- if (client && activeClientIds.has(client.id)) {
138
- const serializedRequest = await serializeRequest(requestCloneForEvents)
139
-
140
- // Omit the body of server-sent event stream responses.
141
- // Cloning such responses would prevent client-side stream cancelations
142
- // from reaching the original stream (a teed stream only cancels its
143
- // source once both of its branches cancel) and would buffer the
144
- // entire stream into the unconsumed clone indefinitely.
145
- const isEventStreamResponse = response.headers
146
- .get('content-type')
147
- ?.toLowerCase()
148
- .startsWith('text/event-stream')
149
-
150
- // Clone the response so both the client and the library could consume it.
151
- const responseClone = isEventStreamResponse ? null : response.clone()
152
-
153
- sendToClient(
154
- client,
155
- {
156
- type: 'RESPONSE',
157
- payload: {
158
- isMockedResponse: IS_MOCKED_RESPONSE in response,
159
- request: {
160
- id: requestId,
161
- ...serializedRequest,
162
- },
163
- response: {
164
- type: response.type,
165
- status: response.status,
166
- statusText: response.statusText,
167
- headers: Object.fromEntries(response.headers.entries()),
168
- body: responseClone ? responseClone.body : null,
169
- },
170
- },
171
- },
172
- responseClone && responseClone.body
173
- ? [serializedRequest.body, responseClone.body]
174
- : [],
175
- )
176
- }
177
-
178
- return response
122
+ const client = await resolveMainClient(event);
123
+ const requestCloneForEvents = event.request.clone();
124
+ const response = await getResponse(event, client, requestId, requestInterceptedAt);
125
+
126
+ // Send back the response clone for the "response:*" life-cycle events.
127
+ // Ensure MSW is active and ready to handle the message, otherwise
128
+ // this message will pend indefinitely.
129
+ if (client && activeClientIds.has(client.id)) {
130
+ const serializedRequest = await serializeRequest(requestCloneForEvents);
131
+
132
+ // Omit the body of server-sent event stream responses.
133
+ // Cloning such responses would prevent client-side stream cancelations
134
+ // from reaching the original stream (a teed stream only cancels its
135
+ // source once both of its branches cancel) and would buffer the
136
+ // entire stream into the unconsumed clone indefinitely.
137
+ const isEventStreamResponse = response.headers
138
+ .get("content-type")
139
+ ?.toLowerCase()
140
+ .startsWith("text/event-stream");
141
+
142
+ // Clone the response so both the client and the library could consume it.
143
+ const responseClone = isEventStreamResponse ? null : response.clone();
144
+
145
+ sendToClient(
146
+ client,
147
+ {
148
+ type: "RESPONSE",
149
+ payload: {
150
+ isMockedResponse: IS_MOCKED_RESPONSE in response,
151
+ request: {
152
+ id: requestId,
153
+ ...serializedRequest,
154
+ },
155
+ response: {
156
+ type: response.type,
157
+ status: response.status,
158
+ statusText: response.statusText,
159
+ headers: Object.fromEntries(response.headers.entries()),
160
+ body: responseClone ? responseClone.body : null,
161
+ },
162
+ },
163
+ },
164
+ responseClone && responseClone.body ? [serializedRequest.body, responseClone.body] : []
165
+ );
166
+ }
167
+
168
+ return response;
179
169
  }
180
170
 
181
171
  /**
@@ -187,30 +177,30 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
187
177
  * @returns {Promise<Client | undefined>}
188
178
  */
189
179
  async function resolveMainClient(event) {
190
- const client = await self.clients.get(event.clientId)
191
-
192
- if (activeClientIds.has(event.clientId)) {
193
- return client
194
- }
195
-
196
- if (client?.frameType === 'top-level') {
197
- return client
198
- }
199
-
200
- const allClients = await self.clients.matchAll({
201
- type: 'window',
202
- })
203
-
204
- return allClients
205
- .filter((client) => {
206
- // Get only those clients that are currently visible.
207
- return client.visibilityState === 'visible'
208
- })
209
- .find((client) => {
210
- // Find the client ID that's recorded in the
211
- // set of clients that have registered the worker.
212
- return activeClientIds.has(client.id)
213
- })
180
+ const client = await self.clients.get(event.clientId);
181
+
182
+ if (activeClientIds.has(event.clientId)) {
183
+ return client;
184
+ }
185
+
186
+ if (client?.frameType === "top-level") {
187
+ return client;
188
+ }
189
+
190
+ const allClients = await self.clients.matchAll({
191
+ type: "window",
192
+ });
193
+
194
+ return allClients
195
+ .filter((client) => {
196
+ // Get only those clients that are currently visible.
197
+ return client.visibilityState === "visible";
198
+ })
199
+ .find((client) => {
200
+ // Find the client ID that's recorded in the
201
+ // set of clients that have registered the worker.
202
+ return activeClientIds.has(client.id);
203
+ });
214
204
  }
215
205
 
216
206
  /**
@@ -221,74 +211,72 @@ async function resolveMainClient(event) {
221
211
  * @returns {Promise<Response>}
222
212
  */
223
213
  async function getResponse(event, client, requestId, requestInterceptedAt) {
224
- // Clone the request because it might've been already used
225
- // (i.e. its body has been read and sent to the client).
226
- const requestClone = event.request.clone()
227
-
228
- function passthrough() {
229
- // Cast the request headers to a new Headers instance
230
- // so the headers can be manipulated with.
231
- const headers = new Headers(requestClone.headers)
232
-
233
- // Remove the "accept" header value that marked this request as passthrough.
234
- // This prevents request alteration and also keeps it compliant with the
235
- // user-defined CORS policies.
236
- const acceptHeader = headers.get('accept')
237
- if (acceptHeader) {
238
- const values = acceptHeader.split(',').map((value) => value.trim())
239
- const filteredValues = values.filter(
240
- (value) => value !== 'msw/passthrough',
241
- )
242
-
243
- if (filteredValues.length > 0) {
244
- headers.set('accept', filteredValues.join(', '))
245
- } else {
246
- headers.delete('accept')
247
- }
248
- }
249
-
250
- return fetch(requestClone, { headers })
251
- }
252
-
253
- // Bypass mocking when the client is not active.
254
- if (!client) {
255
- return passthrough()
256
- }
257
-
258
- // Bypass initial page load requests (i.e. static assets).
259
- // The absence of the immediate/parent client in the map of the active clients
260
- // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
261
- // and is not ready to handle requests.
262
- if (!activeClientIds.has(client.id)) {
263
- return passthrough()
264
- }
265
-
266
- // Notify the client that a request has been intercepted.
267
- const serializedRequest = await serializeRequest(event.request)
268
- const clientMessage = await sendToClient(
269
- client,
270
- {
271
- type: 'REQUEST',
272
- payload: {
273
- id: requestId,
274
- interceptedAt: requestInterceptedAt,
275
- ...serializedRequest,
276
- },
277
- },
278
- [serializedRequest.body],
279
- )
280
-
281
- switch (clientMessage.type) {
282
- case 'MOCK_RESPONSE': {
283
- return respondWithMock(clientMessage.data)
284
- }
285
-
286
- case 'PASSTHROUGH': {
287
- return passthrough()
288
- }
289
- }
290
-
291
- return passthrough()
214
+ // Clone the request because it might've been already used
215
+ // (i.e. its body has been read and sent to the client).
216
+ const requestClone = event.request.clone();
217
+
218
+ function passthrough() {
219
+ // Cast the request headers to a new Headers instance
220
+ // so the headers can be manipulated with.
221
+ const headers = new Headers(requestClone.headers);
222
+
223
+ // Remove the "accept" header value that marked this request as passthrough.
224
+ // This prevents request alteration and also keeps it compliant with the
225
+ // user-defined CORS policies.
226
+ const acceptHeader = headers.get("accept");
227
+ if (acceptHeader) {
228
+ const values = acceptHeader.split(",").map((value) => value.trim());
229
+ const filteredValues = values.filter((value) => value !== "msw/passthrough");
230
+
231
+ if (filteredValues.length > 0) {
232
+ headers.set("accept", filteredValues.join(", "));
233
+ } else {
234
+ headers.delete("accept");
235
+ }
236
+ }
237
+
238
+ return fetch(requestClone, { headers });
239
+ }
240
+
241
+ // Bypass mocking when the client is not active.
242
+ if (!client) {
243
+ return passthrough();
244
+ }
245
+
246
+ // Bypass initial page load requests (i.e. static assets).
247
+ // The absence of the immediate/parent client in the map of the active clients
248
+ // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
249
+ // and is not ready to handle requests.
250
+ if (!activeClientIds.has(client.id)) {
251
+ return passthrough();
252
+ }
253
+
254
+ // Notify the client that a request has been intercepted.
255
+ const serializedRequest = await serializeRequest(event.request);
256
+ const clientMessage = await sendToClient(
257
+ client,
258
+ {
259
+ type: "REQUEST",
260
+ payload: {
261
+ id: requestId,
262
+ interceptedAt: requestInterceptedAt,
263
+ ...serializedRequest,
264
+ },
265
+ },
266
+ [serializedRequest.body]
267
+ );
268
+
269
+ switch (clientMessage.type) {
270
+ case "MOCK_RESPONSE": {
271
+ return respondWithMock(clientMessage.data);
272
+ }
273
+
274
+ case "PASSTHROUGH": {
275
+ return passthrough();
276
+ }
277
+ }
278
+
279
+ return passthrough();
292
280
  }
293
281
 
294
282
  /**
@@ -298,22 +286,19 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
298
286
  * @returns {Promise<any>}
299
287
  */
300
288
  function sendToClient(client, message, transferrables = []) {
301
- return new Promise((resolve, reject) => {
302
- const channel = new MessageChannel()
303
-
304
- channel.port1.onmessage = (event) => {
305
- if (event.data && event.data.error) {
306
- return reject(event.data.error)
307
- }
308
-
309
- resolve(event.data)
310
- }
311
-
312
- client.postMessage(message, [
313
- channel.port2,
314
- ...transferrables.filter(Boolean),
315
- ])
316
- })
289
+ return new Promise((resolve, reject) => {
290
+ const channel = new MessageChannel();
291
+
292
+ channel.port1.onmessage = (event) => {
293
+ if (event.data && event.data.error) {
294
+ return reject(event.data.error);
295
+ }
296
+
297
+ resolve(event.data);
298
+ };
299
+
300
+ client.postMessage(message, [channel.port2, ...transferrables.filter(Boolean)]);
301
+ });
317
302
  }
318
303
 
319
304
  /**
@@ -321,41 +306,41 @@ function sendToClient(client, message, transferrables = []) {
321
306
  * @returns {Response}
322
307
  */
323
308
  function respondWithMock(response) {
324
- // Setting response status code to 0 is a no-op.
325
- // However, when responding with a "Response.error()", the produced Response
326
- // instance will have status code set to 0. Since it's not possible to create
327
- // a Response instance with status code 0, handle that use-case separately.
328
- if (response.status === 0) {
329
- return Response.error()
330
- }
331
-
332
- const mockedResponse = new Response(response.body, response)
333
-
334
- Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
335
- value: true,
336
- enumerable: true,
337
- })
338
-
339
- return mockedResponse
309
+ // Setting response status code to 0 is a no-op.
310
+ // However, when responding with a "Response.error()", the produced Response
311
+ // instance will have status code set to 0. Since it's not possible to create
312
+ // a Response instance with status code 0, handle that use-case separately.
313
+ if (response.status === 0) {
314
+ return Response.error();
315
+ }
316
+
317
+ const mockedResponse = new Response(response.body, response);
318
+
319
+ Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
320
+ value: true,
321
+ enumerable: true,
322
+ });
323
+
324
+ return mockedResponse;
340
325
  }
341
326
 
342
327
  /**
343
328
  * @param {Request} request
344
329
  */
345
330
  async function serializeRequest(request) {
346
- return {
347
- url: request.url,
348
- mode: request.mode,
349
- method: request.method,
350
- headers: Object.fromEntries(request.headers.entries()),
351
- cache: request.cache,
352
- credentials: request.credentials,
353
- destination: request.destination,
354
- integrity: request.integrity,
355
- redirect: request.redirect,
356
- referrer: request.referrer,
357
- referrerPolicy: request.referrerPolicy,
358
- body: await request.arrayBuffer(),
359
- keepalive: request.keepalive,
360
- }
331
+ return {
332
+ url: request.url,
333
+ mode: request.mode,
334
+ method: request.method,
335
+ headers: Object.fromEntries(request.headers.entries()),
336
+ cache: request.cache,
337
+ credentials: request.credentials,
338
+ destination: request.destination,
339
+ integrity: request.integrity,
340
+ redirect: request.redirect,
341
+ referrer: request.referrer,
342
+ referrerPolicy: request.referrerPolicy,
343
+ body: await request.arrayBuffer(),
344
+ keepalive: request.keepalive,
345
+ };
361
346
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/react-template",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "A modern React template with pre-configured tools, best practices, and CI/CD setup for rapid project development.",
5
5
  "homepage": "https://docs.theholocron.dev/react-template/",
6
6
  "bugs": "https://github.com/theholocron/react-template/issues",