@bagaar/ember-graphql-mocking 0.9.0 → 0.10.0

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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,23 @@
6
6
 
7
7
 
8
8
 
9
+
10
+ ## v0.10.0 (2024-02-08)
11
+
12
+ #### :boom: Breaking Change
13
+ * [#195](https://github.com/Bagaar/ember-graphql-mocking/pull/195) Remove automatic inclusion/exclusion of msw's worker file ([@bertdeblock](https://github.com/bertdeblock))
14
+ * [#194](https://github.com/Bagaar/ember-graphql-mocking/pull/194) Convert to TS ([@bertdeblock](https://github.com/bertdeblock))
15
+ * [#193](https://github.com/Bagaar/ember-graphql-mocking/pull/193) Don't leak msw `worker.start` return value ([@bertdeblock](https://github.com/bertdeblock))
16
+
17
+ #### :rocket: Enhancement
18
+ * [#194](https://github.com/Bagaar/ember-graphql-mocking/pull/194) Convert to TS ([@bertdeblock](https://github.com/bertdeblock))
19
+
20
+ #### :bug: Bug Fix
21
+ * [#193](https://github.com/Bagaar/ember-graphql-mocking/pull/193) Don't leak msw `worker.start` return value ([@bertdeblock](https://github.com/bertdeblock))
22
+
23
+ #### Committers: 1
24
+ - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
25
+
9
26
  ## v0.9.0 (2023-11-27)
10
27
 
11
28
  #### :boom: Breaking Change
@@ -0,0 +1,125 @@
1
+ import { assert } from '@ember/debug';
2
+ import { type setupApplicationTest } from 'ember-qunit';
3
+ import { buildASTSchema, graphql, type DocumentNode } from 'graphql';
4
+ import merge from 'lodash.merge';
5
+ import { graphql as mswGraphql, HttpResponse } from 'msw';
6
+ import { setupWorker, type SetupWorker, type StartOptions } from 'msw/browser';
7
+
8
+ interface Options {
9
+ mswStartOptions: StartOptions;
10
+ }
11
+
12
+ type WindowWithTestem = typeof window & { Testem: unknown };
13
+
14
+ const IS_TESTEM = Boolean((window as WindowWithTestem).Testem);
15
+ const DEFAULT_OPTIONS: Options = {
16
+ mswStartOptions: {
17
+ quiet: IS_TESTEM,
18
+ serviceWorker: {
19
+ options: {
20
+ scope: IS_TESTEM ? window.location.pathname : '/tests',
21
+ },
22
+ },
23
+ },
24
+ };
25
+
26
+ let isSetupGraphqlTestCalled = false;
27
+ let root: object | null = null;
28
+ let worker: SetupWorker | null = null;
29
+
30
+ export async function setupEmberGraphqlMocking(
31
+ schemaDocument: DocumentNode,
32
+ providedOptions?: Options,
33
+ ) {
34
+ const options = merge({}, DEFAULT_OPTIONS, providedOptions);
35
+
36
+ createWorker();
37
+ createGraphqlOperationHandler(schemaDocument);
38
+
39
+ await startWorker(options.mswStartOptions);
40
+ }
41
+
42
+ export function setupGraphqlTest(
43
+ hooks: Parameters<typeof setupApplicationTest>[0],
44
+ ) {
45
+ assert(
46
+ 'Cannot call `setupGraphqlTest` without providing the `hooks` argument. Please make sure to call `setupGraphqlTest(hooks);`.',
47
+ hooks,
48
+ );
49
+
50
+ hooks.before(() => {
51
+ isSetupGraphqlTestCalled = true;
52
+ });
53
+
54
+ hooks.after(() => {
55
+ isSetupGraphqlTestCalled = false;
56
+ });
57
+
58
+ hooks.afterEach(clearRoot);
59
+ }
60
+
61
+ export function mockResolvers(resolvers: object) {
62
+ assert(
63
+ 'Cannot call `mockResolvers` before calling `setupGraphqlTest`. Please make sure to call `setupGraphqlTest(hooks);`.',
64
+ isSetupGraphqlTestCalled,
65
+ );
66
+
67
+ root = { ...root, ...resolvers };
68
+ }
69
+
70
+ export function getWorker() {
71
+ assert(
72
+ 'Cannot call `getWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.',
73
+ worker,
74
+ );
75
+
76
+ return worker;
77
+ }
78
+
79
+ export function destroyWorker() {
80
+ assert(
81
+ 'Cannot call `destroyWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.',
82
+ worker,
83
+ );
84
+
85
+ worker.stop();
86
+
87
+ worker = null;
88
+ }
89
+
90
+ function createWorker() {
91
+ worker = setupWorker();
92
+ }
93
+
94
+ function createGraphqlOperationHandler(schemaDocument: DocumentNode) {
95
+ assert('[BUG] `worker` is not set.', worker);
96
+
97
+ const schema = buildASTSchema(schemaDocument);
98
+ const graphqlOperation = mswGraphql.operation(async ({ request }) => {
99
+ const { query, variables } = (await request.json()) || {
100
+ query: '',
101
+ variables: {},
102
+ };
103
+
104
+ const { data, errors } = await graphql({
105
+ rootValue: root,
106
+ schema,
107
+ source: query,
108
+ variableValues: variables,
109
+ });
110
+
111
+ return HttpResponse.json({ data, errors });
112
+ });
113
+
114
+ worker.use(graphqlOperation);
115
+ }
116
+
117
+ async function startWorker(mswStartOptions: Options['mswStartOptions']) {
118
+ assert('[BUG] `worker` is not set.', worker);
119
+
120
+ await worker.start(mswStartOptions);
121
+ }
122
+
123
+ function clearRoot() {
124
+ root = null;
125
+ }
@@ -0,0 +1,13 @@
1
+ import { type setupApplicationTest } from 'ember-qunit';
2
+ import { type DocumentNode } from 'graphql';
3
+ import { type SetupWorker, type StartOptions } from 'msw/browser';
4
+ interface Options {
5
+ mswStartOptions: StartOptions;
6
+ }
7
+ export declare function setupEmberGraphqlMocking(schemaDocument: DocumentNode, providedOptions?: Options): Promise<void>;
8
+ export declare function setupGraphqlTest(hooks: Parameters<typeof setupApplicationTest>[0]): void;
9
+ export declare function mockResolvers(resolvers: object): void;
10
+ export declare function getWorker(): SetupWorker;
11
+ export declare function destroyWorker(): void;
12
+ export {};
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../addon-test-support/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAA2B,KAAK,YAAY,EAAE,MAAM,SAAS,CAAC;AAGrE,OAAO,EAAe,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAE/E,UAAU,OAAO;IACf,eAAe,EAAE,YAAY,CAAC;CAC/B;AAoBD,wBAAsB,wBAAwB,CAC5C,cAAc,EAAE,YAAY,EAC5B,eAAe,CAAC,EAAE,OAAO,iBAQ1B;AAED,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC,CAAC,QAgBlD;AAED,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,QAO9C;AAED,wBAAgB,SAAS,gBAOxB;AAED,wBAAgB,aAAa,SAS5B"}
package/index.js CHANGED
@@ -3,19 +3,9 @@
3
3
  module.exports = {
4
4
  name: require('./package').name,
5
5
 
6
- treeForPublic(tree) {
7
- const host = this._findHost();
8
- const shouldExcludePublicFiles = host.env === 'production';
9
-
10
- if (shouldExcludePublicFiles) {
11
- return;
12
- }
13
-
14
- const funnel = require('broccoli-funnel');
15
- const mergeTrees = require('broccoli-merge-trees');
16
-
17
- return mergeTrees([tree, funnel(host.trees.public)], {
18
- overwrite: true,
19
- });
6
+ options: {
7
+ 'ember-cli-babel': {
8
+ enableTypeScriptTransform: true,
9
+ },
20
10
  },
21
11
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bagaar/ember-graphql-mocking",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Ember addon for mocking GraphQL requests using Mock Service Worker (MSW).",
5
5
  "keywords": [
6
6
  "ember-addon"
@@ -8,6 +8,21 @@
8
8
  "repository": "https://github.com/Bagaar/ember-graphql-mocking",
9
9
  "license": "MIT",
10
10
  "author": "Bagaar",
11
+ "typesVersions": {
12
+ "*": {
13
+ "test-support": [
14
+ "declarations/addon-test-support/index.d.ts"
15
+ ],
16
+ "test-support/*": [
17
+ "declarations/addon-test-support/*",
18
+ "declarations/addon-test-support/*/index.d.ts"
19
+ ],
20
+ "*": [
21
+ "declarations/addon/*",
22
+ "declarations/addon/*/index.d.ts"
23
+ ]
24
+ }
25
+ },
11
26
  "directories": {
12
27
  "doc": "doc",
13
28
  "test": "tests"
@@ -22,6 +37,9 @@
22
37
  "lint:hbs:fix": "ember-template-lint . --fix",
23
38
  "lint:js": "eslint . --cache",
24
39
  "lint:js:fix": "eslint . --fix",
40
+ "lint:types": "tsc --noEmit",
41
+ "prepack": "tsc --project tsconfig.declarations.json",
42
+ "postpack": "rimraf declarations",
25
43
  "prepare": "husky install",
26
44
  "start": "ember serve",
27
45
  "test": "concurrently \"npm:lint\" \"npm:test:*\" --names \"lint,test:\"",
@@ -35,17 +53,12 @@
35
53
  },
36
54
  "dependencies": {
37
55
  "@babel/core": "^7.23.3",
38
- "broccoli-funnel": "^3.0.5",
39
- "broccoli-merge-trees": "^4.2.0",
40
56
  "ember-auto-import": "^2.7.0",
41
57
  "ember-cli-babel": "^8.2.0",
42
- "graphql": "^16.8.1",
43
58
  "lodash.merge": "^4.6.2"
44
59
  },
45
60
  "devDependencies": {
46
- "@apollo/client": "^3.8.7",
47
- "@babel/eslint-parser": "^7.23.3",
48
- "@babel/plugin-proposal-decorators": "^7.23.3",
61
+ "@apollo/client": "^3.9.4",
49
62
  "@commitlint/cli": "^18.4.3",
50
63
  "@commitlint/config-conventional": "^18.4.3",
51
64
  "@ember/optional-features": "^2.0.0",
@@ -54,44 +67,54 @@
54
67
  "@glimmer/component": "^1.1.2",
55
68
  "@glimmer/tracking": "^1.1.2",
56
69
  "@release-it-plugins/lerna-changelog": "^6.0.0",
70
+ "@tsconfig/ember": "^3.0.3",
71
+ "@types/lodash.merge": "^4.6.9",
72
+ "@types/qunit": "^2.19.10",
73
+ "@types/rsvp": "^4.0.9",
74
+ "@typescript-eslint/eslint-plugin": "^6.19.1",
75
+ "@typescript-eslint/parser": "^6.19.1",
57
76
  "broccoli-asset-rev": "^3.0.0",
58
77
  "concurrently": "^8.2.2",
59
- "ember-cli": "~5.4.1",
78
+ "ember-cli": "~5.6.0",
60
79
  "ember-cli-clean-css": "^3.0.0",
61
80
  "ember-cli-dependency-checker": "^3.3.2",
62
81
  "ember-cli-htmlbars": "^6.3.0",
63
82
  "ember-cli-inject-live-reload": "^2.1.0",
64
83
  "ember-cli-sri": "^2.1.1",
65
84
  "ember-cli-terser": "^4.0.2",
66
- "ember-fetch": "^8.1.2",
67
85
  "ember-load-initializers": "^2.1.2",
68
- "ember-page-title": "^8.0.0",
69
- "ember-qunit": "^8.0.1",
86
+ "ember-page-title": "^8.2.0",
87
+ "ember-qunit": "^8.0.2",
70
88
  "ember-resolver": "^11.0.1",
71
- "ember-source": "~5.4.0",
89
+ "ember-source": "~5.6.0",
72
90
  "ember-source-channel-url": "^3.0.0",
73
91
  "ember-template-lint": "^5.13.0",
74
92
  "ember-try": "^3.0.0",
75
- "eslint": "^8.54.0",
76
- "eslint-config-prettier": "^9.0.0",
77
- "eslint-plugin-ember": "^11.11.1",
78
- "eslint-plugin-n": "^16.3.1",
79
- "eslint-plugin-prettier": "^5.0.1",
93
+ "eslint": "^8.56.0",
94
+ "eslint-config-prettier": "^9.1.0",
95
+ "eslint-plugin-ember": "^12.0.0",
96
+ "eslint-plugin-n": "^16.6.2",
97
+ "eslint-plugin-prettier": "^5.1.3",
80
98
  "eslint-plugin-qunit": "^8.0.1",
81
- "husky": "^8.0.3",
99
+ "graphql": "^16.8.1",
100
+ "husky": "^9.0.10",
82
101
  "loader.js": "^4.7.0",
83
102
  "msw": "^2.0.9",
84
- "prettier": "^3.1.0",
103
+ "prettier": "^3.2.4",
85
104
  "qunit": "^2.20.0",
86
105
  "qunit-dom": "^3.0.0",
87
- "release-it": "^16.2.1",
88
- "stylelint": "^15.11.0",
89
- "stylelint-config-standard": "^34.0.0",
90
- "stylelint-prettier": "^4.1.0",
106
+ "release-it": "^17.0.3",
107
+ "rimraf": "^5.0.1",
108
+ "stylelint": "^16.2.1",
109
+ "stylelint-config-standard": "^36.0.0",
110
+ "stylelint-prettier": "^5.0.0",
111
+ "typescript": "^5.3.3",
91
112
  "webpack": "^5.89.0"
92
113
  },
93
114
  "peerDependencies": {
115
+ "ember-qunit": "^8.0.0",
94
116
  "ember-source": ">= 4.8.0",
117
+ "graphql": "^16.0.0",
95
118
  "msw": "^2.0.0"
96
119
  },
97
120
  "engines": {
@@ -108,7 +131,7 @@
108
131
  "configPath": "tests/dummy/config"
109
132
  },
110
133
  "msw": {
111
- "workerDirectory": "public"
134
+ "workerDirectory": "tests/dummy/public"
112
135
  },
113
136
  "release-it": {
114
137
  "plugins": {
@@ -1,84 +0,0 @@
1
- import { assert } from '@ember/debug';
2
- import { buildASTSchema, graphql } from 'graphql';
3
- import merge from 'lodash.merge';
4
- import { graphql as mswGraphql, HttpResponse } from 'msw';
5
- import { setupWorker } from 'msw/browser';
6
-
7
- const IS_TESTEM = Boolean(window.Testem);
8
- const DEFAULT_OPTIONS = {
9
- mswStartOptions: {
10
- quiet: IS_TESTEM,
11
- serviceWorker: {
12
- options: {
13
- scope: IS_TESTEM ? window.location.pathname : '/tests',
14
- },
15
- },
16
- },
17
- };
18
-
19
- let isSetupGraphqlTestCalled = false;
20
- let root = null;
21
- let worker = null;
22
-
23
- export function setupEmberGraphqlMocking(schemaDocument, providedOptions) {
24
- const options = merge({}, DEFAULT_OPTIONS, providedOptions);
25
-
26
- createWorker();
27
- createGraphqlOperationHandler(schemaDocument);
28
-
29
- return startWorker(options.mswStartOptions);
30
- }
31
-
32
- export function setupGraphqlTest(hooks) {
33
- hooks.before(() => (isSetupGraphqlTestCalled = true));
34
- hooks.after(() => (isSetupGraphqlTestCalled = false));
35
- hooks.afterEach(clearRoot);
36
- }
37
-
38
- export function mockResolvers(resolvers) {
39
- assert(
40
- 'Cannot call `mockResolvers` before calling `setupGraphqlTest`. Please make sure to call `setupGraphqlTest(hooks);`.',
41
- isSetupGraphqlTestCalled,
42
- );
43
-
44
- root = { ...root, ...resolvers };
45
- }
46
-
47
- export function getWorker() {
48
- return worker;
49
- }
50
-
51
- export function destroyWorker() {
52
- worker.stop();
53
-
54
- worker = null;
55
- }
56
-
57
- function createWorker() {
58
- worker = setupWorker();
59
- }
60
-
61
- function createGraphqlOperationHandler(schemaDocument) {
62
- const schema = buildASTSchema(schemaDocument);
63
- const graphqlOperation = mswGraphql.operation(async ({ request }) => {
64
- const { query, variables } = await request.json();
65
- const { data, errors } = await graphql({
66
- rootValue: root,
67
- schema,
68
- source: query,
69
- variableValues: variables,
70
- });
71
-
72
- return HttpResponse.json({ data, errors });
73
- });
74
-
75
- worker.use(graphqlOperation);
76
- }
77
-
78
- function startWorker(mswStartOptions) {
79
- return worker.start(mswStartOptions);
80
- }
81
-
82
- function clearRoot() {
83
- root = null;
84
- }
@@ -1,292 +0,0 @@
1
- /* eslint-disable */
2
- /* tslint:disable */
3
-
4
- /**
5
- * Mock Service Worker (2.0.9).
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 INTEGRITY_CHECKSUM = '0877fcdc026242810f5bfde0d7178db4'
12
- const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13
- const activeClientIds = new Set()
14
-
15
- self.addEventListener('install', function () {
16
- self.skipWaiting()
17
- })
18
-
19
- self.addEventListener('activate', function (event) {
20
- event.waitUntil(self.clients.claim())
21
- })
22
-
23
- self.addEventListener('message', async function (event) {
24
- const clientId = 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: INTEGRITY_CHECKSUM,
52
- })
53
- break
54
- }
55
-
56
- case 'MOCK_ACTIVATE': {
57
- activeClientIds.add(clientId)
58
-
59
- sendToClient(client, {
60
- type: 'MOCKING_ENABLED',
61
- payload: true,
62
- })
63
- break
64
- }
65
-
66
- case 'MOCK_DEACTIVATE': {
67
- activeClientIds.delete(clientId)
68
- break
69
- }
70
-
71
- case 'CLIENT_CLOSED': {
72
- activeClientIds.delete(clientId)
73
-
74
- const remainingClients = allClients.filter((client) => {
75
- return client.id !== clientId
76
- })
77
-
78
- // Unregister itself when there are no more clients
79
- if (remainingClients.length === 0) {
80
- self.registration.unregister()
81
- }
82
-
83
- break
84
- }
85
- }
86
- })
87
-
88
- self.addEventListener('fetch', function (event) {
89
- const { request } = event
90
-
91
- // Bypass navigation requests.
92
- if (request.mode === 'navigate') {
93
- return
94
- }
95
-
96
- // Opening the DevTools triggers the "only-if-cached" request
97
- // that cannot be handled by the worker. Bypass such requests.
98
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
99
- return
100
- }
101
-
102
- // Bypass all requests when there are no active clients.
103
- // Prevents the self-unregistered worked from handling requests
104
- // after it's been deleted (still remains active until the next reload).
105
- if (activeClientIds.size === 0) {
106
- return
107
- }
108
-
109
- // Generate unique request ID.
110
- const requestId = crypto.randomUUID()
111
- event.respondWith(handleRequest(event, requestId))
112
- })
113
-
114
- async function handleRequest(event, requestId) {
115
- const client = await resolveMainClient(event)
116
- const response = await getResponse(event, client, requestId)
117
-
118
- // Send back the response clone for the "response:*" life-cycle events.
119
- // Ensure MSW is active and ready to handle the message, otherwise
120
- // this message will pend indefinitely.
121
- if (client && activeClientIds.has(client.id)) {
122
- ;(async function () {
123
- const responseClone = response.clone()
124
- // When performing original requests, response body will
125
- // always be a ReadableStream, even for 204 responses.
126
- // But when creating a new Response instance on the client,
127
- // the body for a 204 response must be null.
128
- const responseBody = response.status === 204 ? null : responseClone.body
129
-
130
- sendToClient(
131
- client,
132
- {
133
- type: 'RESPONSE',
134
- payload: {
135
- requestId,
136
- isMockedResponse: IS_MOCKED_RESPONSE in response,
137
- type: responseClone.type,
138
- status: responseClone.status,
139
- statusText: responseClone.statusText,
140
- body: responseBody,
141
- headers: Object.fromEntries(responseClone.headers.entries()),
142
- },
143
- },
144
- [responseBody],
145
- )
146
- })()
147
- }
148
-
149
- return response
150
- }
151
-
152
- // Resolve the main client for the given event.
153
- // Client that issues a request doesn't necessarily equal the client
154
- // that registered the worker. It's with the latter the worker should
155
- // communicate with during the response resolving phase.
156
- async function resolveMainClient(event) {
157
- const client = await self.clients.get(event.clientId)
158
-
159
- if (client?.frameType === 'top-level') {
160
- return client
161
- }
162
-
163
- const allClients = await self.clients.matchAll({
164
- type: 'window',
165
- })
166
-
167
- return allClients
168
- .filter((client) => {
169
- // Get only those clients that are currently visible.
170
- return client.visibilityState === 'visible'
171
- })
172
- .find((client) => {
173
- // Find the client ID that's recorded in the
174
- // set of clients that have registered the worker.
175
- return activeClientIds.has(client.id)
176
- })
177
- }
178
-
179
- async function getResponse(event, client, requestId) {
180
- const { request } = event
181
-
182
- // Clone the request because it might've been already used
183
- // (i.e. its body has been read and sent to the client).
184
- const requestClone = request.clone()
185
-
186
- function passthrough() {
187
- const headers = Object.fromEntries(requestClone.headers.entries())
188
-
189
- // Remove internal MSW request header so the passthrough request
190
- // complies with any potential CORS preflight checks on the server.
191
- // Some servers forbid unknown request headers.
192
- delete headers['x-msw-intention']
193
-
194
- return fetch(requestClone, { headers })
195
- }
196
-
197
- // Bypass mocking when the client is not active.
198
- if (!client) {
199
- return passthrough()
200
- }
201
-
202
- // Bypass initial page load requests (i.e. static assets).
203
- // The absence of the immediate/parent client in the map of the active clients
204
- // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
205
- // and is not ready to handle requests.
206
- if (!activeClientIds.has(client.id)) {
207
- return passthrough()
208
- }
209
-
210
- // Bypass requests with the explicit bypass header.
211
- // Such requests can be issued by "ctx.fetch()".
212
- const mswIntention = request.headers.get('x-msw-intention')
213
- if (['bypass', 'passthrough'].includes(mswIntention)) {
214
- return passthrough()
215
- }
216
-
217
- // Notify the client that a request has been intercepted.
218
- const requestBuffer = await request.arrayBuffer()
219
- const clientMessage = await sendToClient(
220
- client,
221
- {
222
- type: 'REQUEST',
223
- payload: {
224
- id: requestId,
225
- url: request.url,
226
- mode: request.mode,
227
- method: request.method,
228
- headers: Object.fromEntries(request.headers.entries()),
229
- cache: request.cache,
230
- credentials: request.credentials,
231
- destination: request.destination,
232
- integrity: request.integrity,
233
- redirect: request.redirect,
234
- referrer: request.referrer,
235
- referrerPolicy: request.referrerPolicy,
236
- body: requestBuffer,
237
- keepalive: request.keepalive,
238
- },
239
- },
240
- [requestBuffer],
241
- )
242
-
243
- switch (clientMessage.type) {
244
- case 'MOCK_RESPONSE': {
245
- return respondWithMock(clientMessage.data)
246
- }
247
-
248
- case 'MOCK_NOT_FOUND': {
249
- return passthrough()
250
- }
251
- }
252
-
253
- return passthrough()
254
- }
255
-
256
- function sendToClient(client, message, transferrables = []) {
257
- return new Promise((resolve, reject) => {
258
- const channel = new MessageChannel()
259
-
260
- channel.port1.onmessage = (event) => {
261
- if (event.data && event.data.error) {
262
- return reject(event.data.error)
263
- }
264
-
265
- resolve(event.data)
266
- }
267
-
268
- client.postMessage(
269
- message,
270
- [channel.port2].concat(transferrables.filter(Boolean)),
271
- )
272
- })
273
- }
274
-
275
- async function respondWithMock(response) {
276
- // Setting response status code to 0 is a no-op.
277
- // However, when responding with a "Response.error()", the produced Response
278
- // instance will have status code set to 0. Since it's not possible to create
279
- // a Response instance with status code 0, handle that use-case separately.
280
- if (response.status === 0) {
281
- return Response.error()
282
- }
283
-
284
- const mockedResponse = new Response(response.body, response)
285
-
286
- Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
287
- value: true,
288
- enumerable: true,
289
- })
290
-
291
- return mockedResponse
292
- }