@bagaar/ember-graphql-mocking 0.9.0 → 0.11.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
@@ -1,24 +1,41 @@
1
1
 
2
+ ## v0.11.0 (2024-03-06)
2
3
 
4
+ #### :boom: Breaking Change
5
+ * [#196](https://github.com/Bagaar/ember-graphql-mocking/pull/196) Convert to v2 addon ([@bertdeblock](https://github.com/bertdeblock))
3
6
 
7
+ #### Committers: 1
8
+ - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
4
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))
5
16
 
17
+ #### :rocket: Enhancement
18
+ * [#194](https://github.com/bagaar/ember-graphql-mocking/pull/194) Convert to TS ([@bertdeblock](https://github.com/bertdeblock))
6
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))
7
22
 
23
+ #### Committers: 1
24
+ - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
8
25
 
9
26
  ## v0.9.0 (2023-11-27)
10
27
 
11
28
  #### :boom: Breaking Change
12
- * [#191](https://github.com/Bagaar/ember-graphql-mocking/pull/191) Support MSW v2 ([@bertdeblock](https://github.com/bertdeblock))
13
- * [#189](https://github.com/Bagaar/ember-graphql-mocking/pull/189) Drop support for Ember v4.4 ([@bertdeblock](https://github.com/bertdeblock))
14
- * [#177](https://github.com/Bagaar/ember-graphql-mocking/pull/177) Drop support for Node.js v16 ([@bertdeblock](https://github.com/bertdeblock))
29
+ * [#191](https://github.com/bagaar/ember-graphql-mocking/pull/191) Support MSW v2 ([@bertdeblock](https://github.com/bertdeblock))
30
+ * [#189](https://github.com/bagaar/ember-graphql-mocking/pull/189) Drop support for Ember v4.4 ([@bertdeblock](https://github.com/bertdeblock))
31
+ * [#177](https://github.com/bagaar/ember-graphql-mocking/pull/177) Drop support for Node.js v16 ([@bertdeblock](https://github.com/bertdeblock))
15
32
 
16
33
  #### :rocket: Enhancement
17
- * [#191](https://github.com/Bagaar/ember-graphql-mocking/pull/191) Support MSW v2 ([@bertdeblock](https://github.com/bertdeblock))
34
+ * [#191](https://github.com/bagaar/ember-graphql-mocking/pull/191) Support MSW v2 ([@bertdeblock](https://github.com/bertdeblock))
18
35
 
19
36
  #### :house: Internal
20
- * [#176](https://github.com/Bagaar/ember-graphql-mocking/pull/176) Update dependencies ([@bertdeblock](https://github.com/bertdeblock))
21
- * [#175](https://github.com/Bagaar/ember-graphql-mocking/pull/175) Update to Ember v5.4 ([@bertdeblock](https://github.com/bertdeblock))
37
+ * [#176](https://github.com/bagaar/ember-graphql-mocking/pull/176) Update dependencies ([@bertdeblock](https://github.com/bertdeblock))
38
+ * [#175](https://github.com/bagaar/ember-graphql-mocking/pull/175) Update to Ember v5.4 ([@bertdeblock](https://github.com/bertdeblock))
22
39
 
23
40
  #### Committers: 1
24
41
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -26,7 +43,7 @@
26
43
  ## v0.8.0 (2023-07-06)
27
44
 
28
45
  #### :boom: Breaking Change
29
- * [#143](https://github.com/Bagaar/ember-graphql-mocking/pull/143) Drop support for Ember versions below v4.4 and Node v14 ([@bertdeblock](https://github.com/bertdeblock))
46
+ * [#143](https://github.com/bagaar/ember-graphql-mocking/pull/143) Drop support for Ember versions below v4.4 and Node v14 ([@bertdeblock](https://github.com/bertdeblock))
30
47
 
31
48
  #### Committers: 1
32
49
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -34,14 +51,14 @@
34
51
  ## v0.7.0 (2023-02-22)
35
52
 
36
53
  #### :boom: Breaking Change
37
- * [#104](https://github.com/Bagaar/ember-graphql-mocking/pull/104) Update `msw` to v1 and make it a peer dependency ([@gvdp](https://github.com/gvdp))
54
+ * [#104](https://github.com/bagaar/ember-graphql-mocking/pull/104) Update `msw` to v1 and make it a peer dependency ([@gvdp](https://github.com/gvdp))
38
55
 
39
56
  #### :rocket: Enhancement
40
- * [#104](https://github.com/Bagaar/ember-graphql-mocking/pull/104) Update `msw` to v1 and make it a peer dependency ([@gvdp](https://github.com/gvdp))
41
- * [#100](https://github.com/Bagaar/ember-graphql-mocking/pull/100) Speed up requiring `index.js` file ([@bertdeblock](https://github.com/bertdeblock))
57
+ * [#104](https://github.com/bagaar/ember-graphql-mocking/pull/104) Update `msw` to v1 and make it a peer dependency ([@gvdp](https://github.com/gvdp))
58
+ * [#100](https://github.com/bagaar/ember-graphql-mocking/pull/100) Speed up requiring `index.js` file ([@bertdeblock](https://github.com/bertdeblock))
42
59
 
43
60
  #### :memo: Documentation
44
- * [#106](https://github.com/Bagaar/ember-graphql-mocking/pull/106) Update compatibility and installation section ([@bertdeblock](https://github.com/bertdeblock))
61
+ * [#106](https://github.com/bagaar/ember-graphql-mocking/pull/106) Update compatibility and installation section ([@bertdeblock](https://github.com/bertdeblock))
45
62
 
46
63
  #### Committers: 2
47
64
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -50,12 +67,12 @@
50
67
  ## v0.6.0 (2022-09-05)
51
68
 
52
69
  #### :boom: Breaking Change
53
- * [#38](https://github.com/Bagaar/ember-graphql-mocking/pull/38) Make `setupEmberGraphqlMocking` async ([@bertdeblock](https://github.com/bertdeblock))
54
- * [#37](https://github.com/Bagaar/ember-graphql-mocking/pull/37) Update `graphql` and `msw` dependencies ([@bertdeblock](https://github.com/bertdeblock))
55
- * [#34](https://github.com/Bagaar/ember-graphql-mocking/pull/34) Update `msw` to v0.43.0 ([@bertdeblock](https://github.com/bertdeblock))
70
+ * [#38](https://github.com/bagaar/ember-graphql-mocking/pull/38) Make `setupEmberGraphqlMocking` async ([@bertdeblock](https://github.com/bertdeblock))
71
+ * [#37](https://github.com/bagaar/ember-graphql-mocking/pull/37) Update `graphql` and `msw` dependencies ([@bertdeblock](https://github.com/bertdeblock))
72
+ * [#34](https://github.com/bagaar/ember-graphql-mocking/pull/34) Update `msw` to v0.43.0 ([@bertdeblock](https://github.com/bertdeblock))
56
73
 
57
74
  #### :bug: Bug Fix
58
- * [#38](https://github.com/Bagaar/ember-graphql-mocking/pull/38) Make `setupEmberGraphqlMocking` async ([@bertdeblock](https://github.com/bertdeblock))
75
+ * [#38](https://github.com/bagaar/ember-graphql-mocking/pull/38) Make `setupEmberGraphqlMocking` async ([@bertdeblock](https://github.com/bertdeblock))
59
76
 
60
77
  #### Committers: 1
61
78
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -63,9 +80,9 @@
63
80
  ## v0.5.0 (2022-06-24)
64
81
 
65
82
  #### :boom: Breaking Change
66
- * [#29](https://github.com/Bagaar/ember-graphql-mocking/pull/29) Update `msw` to v0.42.3 ([@bertdeblock](https://github.com/bertdeblock))
67
- * [#27](https://github.com/Bagaar/ember-graphql-mocking/pull/27) Drop support for Ember v3.24 ([@bertdeblock](https://github.com/bertdeblock))
68
- * [#26](https://github.com/Bagaar/ember-graphql-mocking/pull/26) Drop support for Node v12 ([@bertdeblock](https://github.com/bertdeblock))
83
+ * [#29](https://github.com/bagaar/ember-graphql-mocking/pull/29) Update `msw` to v0.42.3 ([@bertdeblock](https://github.com/bertdeblock))
84
+ * [#27](https://github.com/bagaar/ember-graphql-mocking/pull/27) Drop support for Ember v3.24 ([@bertdeblock](https://github.com/bertdeblock))
85
+ * [#26](https://github.com/bagaar/ember-graphql-mocking/pull/26) Drop support for Node v12 ([@bertdeblock](https://github.com/bertdeblock))
69
86
 
70
87
  #### Committers: 1
71
88
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -73,13 +90,13 @@
73
90
  ## v0.4.1 (2022-02-09)
74
91
 
75
92
  #### :bug: Bug Fix
76
- * [#24](https://github.com/Bagaar/ember-graphql-mocking/pull/24) Don't automatically stop the worker when all tests are done (fix compat with `ember-cli-code-coverage@v1`) ([@bertdeblock](https://github.com/bertdeblock))
93
+ * [#24](https://github.com/bagaar/ember-graphql-mocking/pull/24) Don't automatically stop the worker when all tests are done (fix compat with `ember-cli-code-coverage@v1`) ([@bertdeblock](https://github.com/bertdeblock))
77
94
 
78
95
  #### :memo: Documentation
79
- * [#19](https://github.com/Bagaar/ember-graphql-mocking/pull/19) Fix install command in docs ([@bertdeblock](https://github.com/bertdeblock))
96
+ * [#19](https://github.com/bagaar/ember-graphql-mocking/pull/19) Fix install command in docs ([@bertdeblock](https://github.com/bertdeblock))
80
97
 
81
98
  #### :house: Internal
82
- * [#22](https://github.com/Bagaar/ember-graphql-mocking/pull/22) Don't publish `.husky` folder and `RELEASE.md` file ([@bertdeblock](https://github.com/bertdeblock))
99
+ * [#22](https://github.com/bagaar/ember-graphql-mocking/pull/22) Don't publish `.husky` folder and `RELEASE.md` file ([@bertdeblock](https://github.com/bertdeblock))
83
100
 
84
101
  #### Committers: 1
85
102
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -87,7 +104,7 @@
87
104
  ## v0.4.0 (2022-02-03)
88
105
 
89
106
  #### :rocket: Enhancement
90
- * [#18](https://github.com/Bagaar/ember-graphql-mocking/pull/18) Make `msw` start options configurable ([@bertdeblock](https://github.com/bertdeblock))
107
+ * [#18](https://github.com/bagaar/ember-graphql-mocking/pull/18) Make `msw` start options configurable ([@bertdeblock](https://github.com/bertdeblock))
91
108
 
92
109
  #### Committers: 1
93
110
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -95,7 +112,7 @@
95
112
  ## v0.3.2 (2022-02-02)
96
113
 
97
114
  #### :house: Internal
98
- * [#17](https://github.com/Bagaar/ember-graphql-mocking/pull/17) Fix release commit message ([@bertdeblock](https://github.com/bertdeblock))
115
+ * [#17](https://github.com/bagaar/ember-graphql-mocking/pull/17) Fix release commit message ([@bertdeblock](https://github.com/bertdeblock))
99
116
 
100
117
  #### Committers: 1
101
118
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -104,7 +121,7 @@
104
121
  ## v0.3.1 (2022-02-02)
105
122
 
106
123
  #### :house: Internal
107
- * [#16](https://github.com/Bagaar/ember-graphql-mocking/pull/16) Update publish config ([@bertdeblock](https://github.com/bertdeblock))
124
+ * [#16](https://github.com/bagaar/ember-graphql-mocking/pull/16) Update publish config ([@bertdeblock](https://github.com/bertdeblock))
108
125
 
109
126
  #### Committers: 1
110
127
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
@@ -113,8 +130,7 @@
113
130
  ## v0.2.2 (2022-02-02)
114
131
 
115
132
  #### :house: Internal
116
- * [#14](https://github.com/Bagaar/ember-graphql-mocking/pull/14) Release setup ([@bertdeblock](https://github.com/bertdeblock))
133
+ * [#14](https://github.com/bagaar/ember-graphql-mocking/pull/14) Release setup ([@bertdeblock](https://github.com/bertdeblock))
117
134
 
118
135
  #### Committers: 1
119
136
  - Bert De Block ([@bertdeblock](https://github.com/bertdeblock))
120
-
package/LICENSE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2021
3
+ Copyright (c) Bagaar NV
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
6
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Ember GraphQL Mocking
1
+ # @bagaar/ember-graphql-mocking
2
2
 
3
- [![CI](https://github.com/Bagaar/ember-graphql-mocking/workflows/CI/badge.svg)](https://github.com/Bagaar/ember-graphql-mocking/actions?query=workflow%3ACI)
3
+ [![CI](https://github.com/bagaar/ember-graphql-mocking/workflows/CI/badge.svg)](https://github.com/bagaar/ember-graphql-mocking/actions?query=workflow%3ACI)
4
4
  [![NPM Version](https://badge.fury.io/js/%40bagaar%2Fember-graphql-mocking.svg)](https://badge.fury.io/js/%40bagaar%2Fember-graphql-mocking)
5
5
 
6
6
  Ember addon for mocking GraphQL requests using [Mock Service Worker (MSW)](https://github.com/mswjs/msw).
@@ -8,8 +8,7 @@ Ember addon for mocking GraphQL requests using [Mock Service Worker (MSW)](https
8
8
  ## Compatibility
9
9
 
10
10
  - Ember.js v4.8 or above
11
- - Ember CLI v4.8 or above
12
- - Node.js v18 or above
11
+ - Embroider or ember-auto-import v2
13
12
  - MSW v2 or above
14
13
 
15
14
  ## Installation
@@ -121,7 +120,7 @@ module('Acceptance | ember graphql mocking', function (hooks) {
121
120
  > Calling `mockResolvers` multiple times within a single test, will simply merge all resolvers into a single root.
122
121
 
123
122
  > [!NOTE]
124
- > Working versions of these code examples can be found in [this addon's `tests` folder](./tests/).
123
+ > Working versions of these code examples can be found in [this addon's test app](./test-app/).
125
124
 
126
125
  ## Contributing
127
126
 
package/addon-main.cjs ADDED
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ const { addonV1Shim } = require('@embroider/addon-shim');
4
+ module.exports = addonV1Shim(__dirname);
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+ export default interface Registry {
2
+ }
3
+ //# sourceMappingURL=template-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template-registry.d.ts","sourceRoot":"","sources":["../src/template-registry.ts"],"names":[],"mappings":"AAQA,MAAM,CAAC,OAAO,WAAW,QAAQ;CAEhC"}
@@ -0,0 +1,17 @@
1
+ import { type DocumentNode } from 'graphql';
2
+ import { type SetupWorker, type StartOptions } from 'msw/browser';
3
+ interface Options {
4
+ mswStartOptions: StartOptions;
5
+ }
6
+ type Hooks = {
7
+ after(fn: () => void | Promise<void>): void;
8
+ afterEach(fn: () => void | Promise<void>): void;
9
+ before(fn: () => void | Promise<void>): void;
10
+ };
11
+ export declare function setupEmberGraphqlMocking(schemaDocument: DocumentNode, providedOptions?: Options): Promise<void>;
12
+ export declare function setupGraphqlTest(hooks: Hooks): void;
13
+ export declare function mockResolvers(resolvers: object): void;
14
+ export declare function getWorker(): SetupWorker;
15
+ export declare function destroyWorker(): void;
16
+ export {};
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/test-support/index.ts"],"names":[],"mappings":"AACA,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;AAGD,KAAK,KAAK,GAAG;IACX,KAAK,CAAC,EAAE,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC5C,SAAS,CAAC,EAAE,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAChD,MAAM,CAAC,EAAE,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAC9C,CAAC;AAkBF,wBAAsB,wBAAwB,CAC5C,cAAc,EAAE,YAAY,EAC5B,eAAe,CAAC,EAAE,OAAO,iBAQ1B;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,KAAK,QAe5C;AAED,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,QAO9C;AAED,wBAAgB,SAAS,gBAOxB;AAED,wBAAgB,aAAa,SAS5B"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=template-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template-registry.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,94 @@
1
+ import { assert } from '@ember/debug';
2
+ import { buildASTSchema, graphql as graphql$1 } from 'graphql';
3
+ import merge from 'lodash.merge';
4
+ import { graphql, 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
+ let isSetupGraphqlTestCalled = false;
19
+ let root = null;
20
+ let worker = null;
21
+ async function setupEmberGraphqlMocking(schemaDocument, providedOptions) {
22
+ const options = merge({}, DEFAULT_OPTIONS, providedOptions);
23
+ createWorker();
24
+ createGraphqlOperationHandler(schemaDocument);
25
+ await startWorker(options.mswStartOptions);
26
+ }
27
+ function setupGraphqlTest(hooks) {
28
+ assert('Cannot call `setupGraphqlTest` without providing the `hooks` argument. Please make sure to call `setupGraphqlTest(hooks);`.', hooks);
29
+ hooks.before(() => {
30
+ isSetupGraphqlTestCalled = true;
31
+ });
32
+ hooks.after(() => {
33
+ isSetupGraphqlTestCalled = false;
34
+ });
35
+ hooks.afterEach(clearRoot);
36
+ }
37
+ function mockResolvers(resolvers) {
38
+ assert('Cannot call `mockResolvers` before calling `setupGraphqlTest`. Please make sure to call `setupGraphqlTest(hooks);`.', isSetupGraphqlTestCalled);
39
+ root = {
40
+ ...root,
41
+ ...resolvers
42
+ };
43
+ }
44
+ function getWorker() {
45
+ assert('Cannot call `getWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.', worker);
46
+ return worker;
47
+ }
48
+ function destroyWorker() {
49
+ assert('Cannot call `destroyWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.', worker);
50
+ worker.stop();
51
+ worker = null;
52
+ }
53
+ function createWorker() {
54
+ worker = setupWorker();
55
+ }
56
+ function createGraphqlOperationHandler(schemaDocument) {
57
+ assert('[BUG] `worker` is not set.', worker);
58
+ const schema = buildASTSchema(schemaDocument);
59
+ const graphqlOperation = graphql.operation(async ({
60
+ request
61
+ }) => {
62
+ const {
63
+ query,
64
+ variables
65
+ } = (await request.json()) || {
66
+ query: '',
67
+ variables: {}
68
+ };
69
+ const {
70
+ data,
71
+ errors
72
+ } = await graphql$1({
73
+ rootValue: root,
74
+ schema,
75
+ source: query,
76
+ variableValues: variables
77
+ });
78
+ return HttpResponse.json({
79
+ data,
80
+ errors
81
+ });
82
+ });
83
+ worker.use(graphqlOperation);
84
+ }
85
+ async function startWorker(mswStartOptions) {
86
+ assert('[BUG] `worker` is not set.', worker);
87
+ await worker.start(mswStartOptions);
88
+ }
89
+ function clearRoot() {
90
+ root = null;
91
+ }
92
+
93
+ export { destroyWorker, getWorker, mockResolvers, setupEmberGraphqlMocking, setupGraphqlTest };
94
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/test-support/index.ts"],"sourcesContent":["import { assert } from '@ember/debug';\nimport { buildASTSchema, graphql, type DocumentNode } from 'graphql';\nimport merge from 'lodash.merge';\nimport { graphql as mswGraphql, HttpResponse } from 'msw';\nimport { setupWorker, type SetupWorker, type StartOptions } from 'msw/browser';\n\ninterface Options {\n mswStartOptions: StartOptions;\n}\n\ntype WindowWithTestem = typeof window & { Testem: unknown };\ntype Hooks = {\n after(fn: () => void | Promise<void>): void;\n afterEach(fn: () => void | Promise<void>): void;\n before(fn: () => void | Promise<void>): void;\n};\n\nconst IS_TESTEM = Boolean((window as WindowWithTestem).Testem);\nconst DEFAULT_OPTIONS: Options = {\n mswStartOptions: {\n quiet: IS_TESTEM,\n serviceWorker: {\n options: {\n scope: IS_TESTEM ? window.location.pathname : '/tests',\n },\n },\n },\n};\n\nlet isSetupGraphqlTestCalled = false;\nlet root: object | null = null;\nlet worker: SetupWorker | null = null;\n\nexport async function setupEmberGraphqlMocking(\n schemaDocument: DocumentNode,\n providedOptions?: Options,\n) {\n const options = merge({}, DEFAULT_OPTIONS, providedOptions);\n\n createWorker();\n createGraphqlOperationHandler(schemaDocument);\n\n await startWorker(options.mswStartOptions);\n}\n\nexport function setupGraphqlTest(hooks: Hooks) {\n assert(\n 'Cannot call `setupGraphqlTest` without providing the `hooks` argument. Please make sure to call `setupGraphqlTest(hooks);`.',\n hooks,\n );\n\n hooks.before(() => {\n isSetupGraphqlTestCalled = true;\n });\n\n hooks.after(() => {\n isSetupGraphqlTestCalled = false;\n });\n\n hooks.afterEach(clearRoot);\n}\n\nexport function mockResolvers(resolvers: object) {\n assert(\n 'Cannot call `mockResolvers` before calling `setupGraphqlTest`. Please make sure to call `setupGraphqlTest(hooks);`.',\n isSetupGraphqlTestCalled,\n );\n\n root = { ...root, ...resolvers };\n}\n\nexport function getWorker() {\n assert(\n 'Cannot call `getWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.',\n worker,\n );\n\n return worker;\n}\n\nexport function destroyWorker() {\n assert(\n 'Cannot call `destroyWorker` before calling `setupEmberGraphqlMocking`. Please make sure to call `setupEmberGraphqlMocking(yourSchemaDocument[, yourProvidedOptions]);`.',\n worker,\n );\n\n worker.stop();\n\n worker = null;\n}\n\nfunction createWorker() {\n worker = setupWorker();\n}\n\nfunction createGraphqlOperationHandler(schemaDocument: DocumentNode) {\n assert('[BUG] `worker` is not set.', worker);\n\n const schema = buildASTSchema(schemaDocument);\n const graphqlOperation = mswGraphql.operation(async ({ request }) => {\n const { query, variables } = (await request.json()) || {\n query: '',\n variables: {},\n };\n\n const { data, errors } = await graphql({\n rootValue: root,\n schema,\n source: query,\n variableValues: variables,\n });\n\n return HttpResponse.json({ data, errors });\n });\n\n worker.use(graphqlOperation);\n}\n\nasync function startWorker(mswStartOptions: Options['mswStartOptions']) {\n assert('[BUG] `worker` is not set.', worker);\n\n await worker.start(mswStartOptions);\n}\n\nfunction clearRoot() {\n root = null;\n}\n"],"names":["IS_TESTEM","Boolean","window","Testem","DEFAULT_OPTIONS","mswStartOptions","quiet","serviceWorker","options","scope","location","pathname","isSetupGraphqlTestCalled","root","worker","setupEmberGraphqlMocking","schemaDocument","providedOptions","merge","createWorker","createGraphqlOperationHandler","startWorker","setupGraphqlTest","hooks","assert","before","after","afterEach","clearRoot","mockResolvers","resolvers","getWorker","destroyWorker","stop","setupWorker","schema","buildASTSchema","graphqlOperation","mswGraphql","operation","request","query","variables","json","data","errors","graphql","rootValue","source","variableValues","HttpResponse","use","start"],"mappings":";;;;;;AAiBA,MAAMA,SAAS,GAAGC,OAAO,CAAEC,MAAM,CAAsBC,MAAM,CAAC,CAAA;AAC9D,MAAMC,eAAwB,GAAG;AAC/BC,EAAAA,eAAe,EAAE;AACfC,IAAAA,KAAK,EAAEN,SAAS;AAChBO,IAAAA,aAAa,EAAE;AACbC,MAAAA,OAAO,EAAE;QACPC,KAAK,EAAET,SAAS,GAAGE,MAAM,CAACQ,QAAQ,CAACC,QAAQ,GAAG,QAAA;AAChD,OAAA;AACF,KAAA;AACF,GAAA;AACF,CAAC,CAAA;AAED,IAAIC,wBAAwB,GAAG,KAAK,CAAA;AACpC,IAAIC,IAAmB,GAAG,IAAI,CAAA;AAC9B,IAAIC,MAA0B,GAAG,IAAI,CAAA;AAE9B,eAAeC,wBAAwBA,CAC5CC,cAA4B,EAC5BC,eAAyB,EACzB;EACA,MAAMT,OAAO,GAAGU,KAAK,CAAC,EAAE,EAAEd,eAAe,EAAEa,eAAe,CAAC,CAAA;AAE3DE,EAAAA,YAAY,EAAE,CAAA;EACdC,6BAA6B,CAACJ,cAAc,CAAC,CAAA;AAE7C,EAAA,MAAMK,WAAW,CAACb,OAAO,CAACH,eAAe,CAAC,CAAA;AAC5C,CAAA;AAEO,SAASiB,gBAAgBA,CAACC,KAAY,EAAE;AAC7CC,EAAAA,MAAM,CACJ,6HAA6H,EAC7HD,KACF,CAAC,CAAA;EAEDA,KAAK,CAACE,MAAM,CAAC,MAAM;AACjBb,IAAAA,wBAAwB,GAAG,IAAI,CAAA;AACjC,GAAC,CAAC,CAAA;EAEFW,KAAK,CAACG,KAAK,CAAC,MAAM;AAChBd,IAAAA,wBAAwB,GAAG,KAAK,CAAA;AAClC,GAAC,CAAC,CAAA;AAEFW,EAAAA,KAAK,CAACI,SAAS,CAACC,SAAS,CAAC,CAAA;AAC5B,CAAA;AAEO,SAASC,aAAaA,CAACC,SAAiB,EAAE;AAC/CN,EAAAA,MAAM,CACJ,qHAAqH,EACrHZ,wBACF,CAAC,CAAA;AAEDC,EAAAA,IAAI,GAAG;AAAE,IAAA,GAAGA,IAAI;IAAE,GAAGiB,SAAAA;GAAW,CAAA;AAClC,CAAA;AAEO,SAASC,SAASA,GAAG;AAC1BP,EAAAA,MAAM,CACJ,qKAAqK,EACrKV,MACF,CAAC,CAAA;AAED,EAAA,OAAOA,MAAM,CAAA;AACf,CAAA;AAEO,SAASkB,aAAaA,GAAG;AAC9BR,EAAAA,MAAM,CACJ,yKAAyK,EACzKV,MACF,CAAC,CAAA;EAEDA,MAAM,CAACmB,IAAI,EAAE,CAAA;AAEbnB,EAAAA,MAAM,GAAG,IAAI,CAAA;AACf,CAAA;AAEA,SAASK,YAAYA,GAAG;EACtBL,MAAM,GAAGoB,WAAW,EAAE,CAAA;AACxB,CAAA;AAEA,SAASd,6BAA6BA,CAACJ,cAA4B,EAAE;AACnEQ,EAAAA,MAAM,CAAC,4BAA4B,EAAEV,MAAM,CAAC,CAAA;AAE5C,EAAA,MAAMqB,MAAM,GAAGC,cAAc,CAACpB,cAAc,CAAC,CAAA;AAC7C,EAAA,MAAMqB,gBAAgB,GAAGC,OAAU,CAACC,SAAS,CAAC,OAAO;AAAEC,IAAAA,OAAAA;AAAQ,GAAC,KAAK;IACnE,MAAM;MAAEC,KAAK;AAAEC,MAAAA,SAAAA;KAAW,GAAG,CAAC,MAAMF,OAAO,CAACG,IAAI,EAAE,KAAK;AACrDF,MAAAA,KAAK,EAAE,EAAE;AACTC,MAAAA,SAAS,EAAE,EAAC;KACb,CAAA;IAED,MAAM;MAAEE,IAAI;AAAEC,MAAAA,MAAAA;KAAQ,GAAG,MAAMC,SAAO,CAAC;AACrCC,MAAAA,SAAS,EAAElC,IAAI;MACfsB,MAAM;AACNa,MAAAA,MAAM,EAAEP,KAAK;AACbQ,MAAAA,cAAc,EAAEP,SAAAA;AAClB,KAAC,CAAC,CAAA;IAEF,OAAOQ,YAAY,CAACP,IAAI,CAAC;MAAEC,IAAI;AAAEC,MAAAA,MAAAA;AAAO,KAAC,CAAC,CAAA;AAC5C,GAAC,CAAC,CAAA;AAEF/B,EAAAA,MAAM,CAACqC,GAAG,CAACd,gBAAgB,CAAC,CAAA;AAC9B,CAAA;AAEA,eAAehB,WAAWA,CAAChB,eAA2C,EAAE;AACtEmB,EAAAA,MAAM,CAAC,4BAA4B,EAAEV,MAAM,CAAC,CAAA;AAE5C,EAAA,MAAMA,MAAM,CAACsC,KAAK,CAAC/C,eAAe,CAAC,CAAA;AACrC,CAAA;AAEA,SAASuB,SAASA,GAAG;AACnBf,EAAAA,IAAI,GAAG,IAAI,CAAA;AACb;;;;"}
package/package.json CHANGED
@@ -1,129 +1,137 @@
1
1
  {
2
2
  "name": "@bagaar/ember-graphql-mocking",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Ember addon for mocking GraphQL requests using Mock Service Worker (MSW).",
5
5
  "keywords": [
6
- "ember-addon"
6
+ "ember-addon",
7
+ "graphql",
8
+ "msw"
7
9
  ],
8
- "repository": "https://github.com/Bagaar/ember-graphql-mocking",
10
+ "repository": "https://github.com/bagaar/ember-graphql-mocking",
9
11
  "license": "MIT",
10
12
  "author": "Bagaar",
11
- "directories": {
12
- "doc": "doc",
13
- "test": "tests"
13
+ "exports": {
14
+ ".": {
15
+ "types": "./declarations/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "./*": {
19
+ "types": "./declarations/*.d.ts",
20
+ "default": "./dist/*.js"
21
+ },
22
+ "./addon-main.js": "./addon-main.cjs",
23
+ "./test-support": {
24
+ "types": "./declarations/test-support/index.d.ts",
25
+ "default": "./dist/test-support/index.js"
26
+ }
14
27
  },
28
+ "typesVersions": {
29
+ "*": {
30
+ "test-support": [
31
+ "declarations/test-support/index.d.ts"
32
+ ],
33
+ "*": [
34
+ "declarations/*"
35
+ ]
36
+ }
37
+ },
38
+ "files": [
39
+ "addon-main.cjs",
40
+ "CHANGELOG.md",
41
+ "declarations",
42
+ "dist"
43
+ ],
15
44
  "scripts": {
16
- "build": "ember build --environment=production",
17
- "lint": "concurrently \"npm:lint:*(!fix)\" --names \"lint:\"",
18
- "lint:css": "stylelint \"**/*.css\"",
19
- "lint:css:fix": "concurrently \"npm:lint:css -- --fix\"",
20
- "lint:fix": "concurrently \"npm:lint:*:fix\" --names \"fix:\"",
21
- "lint:hbs": "ember-template-lint .",
22
- "lint:hbs:fix": "ember-template-lint . --fix",
45
+ "build": "concurrently 'npm:build:*'",
46
+ "build:js": "rollup --config",
47
+ "build:types": "glint --declaration",
48
+ "lint": "concurrently 'npm:lint:*(!fix)' --names 'lint:'",
49
+ "lint:fix": "concurrently 'npm:lint:*:fix' --names 'fix:'",
50
+ "lint:hbs": "ember-template-lint . --no-error-on-unmatched-pattern",
51
+ "lint:hbs:fix": "ember-template-lint . --fix --no-error-on-unmatched-pattern",
23
52
  "lint:js": "eslint . --cache",
24
53
  "lint:js:fix": "eslint . --fix",
25
- "prepare": "husky install",
26
- "start": "ember serve",
27
- "test": "concurrently \"npm:lint\" \"npm:test:*\" --names \"lint,test:\"",
28
- "test:ember": "ember test",
29
- "test:ember-compatibility": "ember try:each"
30
- },
31
- "commitlint": {
32
- "extends": [
33
- "@commitlint/config-conventional"
34
- ]
54
+ "lint:types": "glint",
55
+ "prepack": "rollup --config",
56
+ "start": "concurrently 'npm:start:*'",
57
+ "start:js": "rollup --config --watch --no-watch.clearScreen",
58
+ "start:types": "glint --declaration --watch",
59
+ "test": "echo 'A v2 addon does not have tests, run tests in test-app'"
35
60
  },
36
61
  "dependencies": {
37
- "@babel/core": "^7.23.3",
38
- "broccoli-funnel": "^3.0.5",
39
- "broccoli-merge-trees": "^4.2.0",
40
- "ember-auto-import": "^2.7.0",
41
- "ember-cli-babel": "^8.2.0",
42
- "graphql": "^16.8.1",
62
+ "@embroider/addon-shim": "^1.8.7",
63
+ "decorator-transforms": "^1.0.1",
43
64
  "lodash.merge": "^4.6.2"
44
65
  },
45
66
  "devDependencies": {
46
- "@apollo/client": "^3.8.7",
47
- "@babel/eslint-parser": "^7.23.3",
48
- "@babel/plugin-proposal-decorators": "^7.23.3",
49
- "@commitlint/cli": "^18.4.3",
50
- "@commitlint/config-conventional": "^18.4.3",
51
- "@ember/optional-features": "^2.0.0",
52
- "@ember/test-helpers": "^3.2.1",
53
- "@embroider/test-setup": "^3.0.3",
54
- "@glimmer/component": "^1.1.2",
55
- "@glimmer/tracking": "^1.1.2",
67
+ "@babel/core": "^7.23.6",
68
+ "@babel/plugin-transform-typescript": "^7.23.6",
69
+ "@babel/runtime": "^7.17.0",
70
+ "@embroider/addon-dev": "^4.1.0",
71
+ "@glint/core": "^1.2.1",
72
+ "@glint/environment-ember-loose": "^1.2.1",
73
+ "@glint/environment-ember-template-imports": "^1.2.1",
74
+ "@glint/template": "^1.2.1",
56
75
  "@release-it-plugins/lerna-changelog": "^6.0.0",
57
- "broccoli-asset-rev": "^3.0.0",
76
+ "@rollup/plugin-babel": "^6.0.4",
77
+ "@tsconfig/ember": "^3.0.2",
78
+ "@types/lodash.merge": "^4.6.9",
79
+ "@typescript-eslint/eslint-plugin": "^6.14.0",
80
+ "@typescript-eslint/parser": "^6.14.0",
81
+ "babel-plugin-ember-template-compilation": "^2.2.1",
58
82
  "concurrently": "^8.2.2",
59
- "ember-cli": "~5.4.1",
60
- "ember-cli-clean-css": "^3.0.0",
61
- "ember-cli-dependency-checker": "^3.3.2",
62
- "ember-cli-htmlbars": "^6.3.0",
63
- "ember-cli-inject-live-reload": "^2.1.0",
64
- "ember-cli-sri": "^2.1.1",
65
- "ember-cli-terser": "^4.0.2",
66
- "ember-fetch": "^8.1.2",
67
- "ember-load-initializers": "^2.1.2",
68
- "ember-page-title": "^8.0.0",
69
- "ember-qunit": "^8.0.1",
70
- "ember-resolver": "^11.0.1",
71
- "ember-source": "~5.4.0",
72
- "ember-source-channel-url": "^3.0.0",
83
+ "ember-source": "~5.6.0",
73
84
  "ember-template-lint": "^5.13.0",
74
- "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",
85
+ "eslint": "^8.56.0",
86
+ "eslint-config-prettier": "^9.1.0",
87
+ "eslint-plugin-ember": "^11.12.0",
88
+ "eslint-plugin-n": "^16.4.0",
79
89
  "eslint-plugin-prettier": "^5.0.1",
80
- "eslint-plugin-qunit": "^8.0.1",
81
- "husky": "^8.0.3",
82
- "loader.js": "^4.7.0",
83
- "msw": "^2.0.9",
84
- "prettier": "^3.1.0",
85
- "qunit": "^2.20.0",
86
- "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",
91
- "webpack": "^5.89.0"
90
+ "graphql": "^16.8.1",
91
+ "msw": "^2.2.2",
92
+ "prettier": "^3.1.1",
93
+ "prettier-plugin-ember-template-tag": "^1.1.0",
94
+ "release-it": "^17.0.3",
95
+ "rollup": "^4.9.1",
96
+ "rollup-plugin-copy": "^3.5.0",
97
+ "typescript": "^5.3.3"
92
98
  },
93
99
  "peerDependencies": {
94
100
  "ember-source": ">= 4.8.0",
95
- "msw": "^2.0.0"
96
- },
97
- "engines": {
98
- "node": ">= 18"
101
+ "graphql": ">= 16.0.0",
102
+ "msw": ">= 2.0.0"
99
103
  },
100
104
  "publishConfig": {
101
- "access": "public",
102
105
  "registry": "https://registry.npmjs.org"
103
106
  },
104
107
  "ember": {
105
108
  "edition": "octane"
106
109
  },
107
110
  "ember-addon": {
108
- "configPath": "tests/dummy/config"
109
- },
110
- "msw": {
111
- "workerDirectory": "public"
111
+ "version": 2,
112
+ "type": "addon",
113
+ "main": "addon-main.cjs",
114
+ "app-js": {}
112
115
  },
113
116
  "release-it": {
114
- "plugins": {
115
- "@release-it-plugins/lerna-changelog": {
116
- "infile": "CHANGELOG.md",
117
- "launchEditor": false
118
- }
119
- },
120
117
  "git": {
121
- "commitMessage": "chore(release): ${version}",
118
+ "commitMessage": "Release v${version}",
122
119
  "tagName": "v${version}"
123
120
  },
124
121
  "github": {
125
- "release": true,
126
- "tokenRef": "GITHUB_AUTH"
122
+ "release": true
123
+ },
124
+ "hooks": {
125
+ "before:git:release": "git add ../"
126
+ },
127
+ "plugins": {
128
+ "@release-it-plugins/lerna-changelog": {
129
+ "infile": "../CHANGELOG.md",
130
+ "launchEditor": false
131
+ }
127
132
  }
133
+ },
134
+ "volta": {
135
+ "extends": "../package.json"
128
136
  }
129
137
  }
@@ -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
- }
package/index.js DELETED
@@ -1,21 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = {
4
- name: require('./package').name,
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
- });
20
- },
21
- };
@@ -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
- }