msw 1.3.2 → 2.0.1

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.
Files changed (169) hide show
  1. package/README.md +45 -29
  2. package/browser/package.json +5 -0
  3. package/cli/init.js +3 -3
  4. package/config/constants.js +1 -2
  5. package/lib/browser/index.d.ts +104 -0
  6. package/lib/browser/index.js +752 -0
  7. package/lib/browser/index.mjs +734 -0
  8. package/lib/core/GraphQLHandler-b42ca96f.d.ts +74 -0
  9. package/lib/core/HttpResponse.d.ts +2 -0
  10. package/lib/core/HttpResponse.js +94 -0
  11. package/lib/core/HttpResponse.mjs +77 -0
  12. package/lib/core/RequestHandler-1a5dbdc7.d.ts +172 -0
  13. package/lib/core/SetupApi.d.ts +26 -0
  14. package/lib/core/SetupApi.js +83 -0
  15. package/lib/core/SetupApi.mjs +63 -0
  16. package/lib/core/bypass.d.ts +16 -0
  17. package/lib/core/bypass.js +36 -0
  18. package/lib/core/bypass.mjs +16 -0
  19. package/lib/core/delay.d.ts +18 -0
  20. package/lib/core/delay.js +92 -0
  21. package/lib/core/delay.mjs +72 -0
  22. package/lib/core/graphql.d.ts +109 -0
  23. package/lib/core/graphql.js +112 -0
  24. package/lib/core/graphql.mjs +96 -0
  25. package/lib/core/handlers/GraphQLHandler.d.ts +5 -0
  26. package/lib/core/handlers/GraphQLHandler.js +145 -0
  27. package/lib/core/handlers/GraphQLHandler.mjs +130 -0
  28. package/lib/core/handlers/HttpHandler.d.ts +62 -0
  29. package/lib/core/handlers/HttpHandler.js +149 -0
  30. package/lib/core/handlers/HttpHandler.mjs +133 -0
  31. package/lib/core/handlers/RequestHandler.d.ts +2 -0
  32. package/lib/core/handlers/RequestHandler.js +180 -0
  33. package/lib/core/handlers/RequestHandler.mjs +162 -0
  34. package/lib/core/http.d.ts +26 -0
  35. package/lib/core/http.js +39 -0
  36. package/lib/core/http.mjs +22 -0
  37. package/lib/core/http.spec.d.ts +2 -0
  38. package/lib/core/http.spec.js +15 -0
  39. package/lib/core/http.spec.mjs +14 -0
  40. package/lib/core/index.d.ts +18 -0
  41. package/lib/core/index.js +49 -0
  42. package/lib/core/index.mjs +28 -0
  43. package/lib/core/passthrough.d.ts +17 -0
  44. package/lib/core/passthrough.js +32 -0
  45. package/lib/core/passthrough.mjs +12 -0
  46. package/lib/core/sharedOptions.d.ts +66 -0
  47. package/lib/core/sharedOptions.js +16 -0
  48. package/lib/core/sharedOptions.mjs +0 -0
  49. package/lib/core/typeUtils.d.ts +7 -0
  50. package/lib/core/typeUtils.js +16 -0
  51. package/lib/core/typeUtils.mjs +0 -0
  52. package/lib/core/utils/HttpResponse/decorators.d.ts +12 -0
  53. package/lib/core/utils/HttpResponse/decorators.js +80 -0
  54. package/lib/core/utils/HttpResponse/decorators.mjs +52 -0
  55. package/lib/core/utils/getResponse.d.ts +2 -0
  56. package/lib/core/utils/getResponse.js +64 -0
  57. package/lib/core/utils/getResponse.mjs +44 -0
  58. package/lib/core/utils/handleRequest.d.ts +30 -0
  59. package/lib/core/utils/handleRequest.js +102 -0
  60. package/lib/core/utils/handleRequest.mjs +82 -0
  61. package/lib/core/utils/internal/Disposable.d.ts +7 -0
  62. package/lib/core/utils/internal/Disposable.js +53 -0
  63. package/lib/core/utils/internal/Disposable.mjs +33 -0
  64. package/lib/core/utils/internal/checkGlobals.d.ts +3 -0
  65. package/lib/core/utils/internal/checkGlobals.js +33 -0
  66. package/lib/core/utils/internal/checkGlobals.mjs +13 -0
  67. package/lib/core/utils/internal/devUtils.d.ts +19 -0
  68. package/lib/core/utils/internal/devUtils.js +40 -0
  69. package/lib/core/utils/internal/devUtils.mjs +20 -0
  70. package/lib/core/utils/internal/getCallFrame.d.ts +6 -0
  71. package/lib/core/utils/internal/getCallFrame.js +40 -0
  72. package/lib/core/utils/internal/getCallFrame.mjs +20 -0
  73. package/lib/core/utils/internal/isIterable.d.ts +6 -0
  74. package/lib/core/utils/internal/isIterable.js +29 -0
  75. package/lib/core/utils/internal/isIterable.mjs +9 -0
  76. package/lib/core/utils/internal/isObject.d.ts +6 -0
  77. package/lib/core/utils/internal/isObject.js +26 -0
  78. package/lib/core/utils/internal/isObject.mjs +6 -0
  79. package/lib/core/utils/internal/isStringEqual.d.ts +6 -0
  80. package/lib/core/utils/internal/isStringEqual.js +26 -0
  81. package/lib/core/utils/internal/isStringEqual.mjs +6 -0
  82. package/lib/core/utils/internal/jsonParse.d.ts +7 -0
  83. package/lib/core/utils/internal/jsonParse.js +30 -0
  84. package/lib/core/utils/internal/jsonParse.mjs +10 -0
  85. package/lib/core/utils/internal/mergeRight.d.ts +7 -0
  86. package/lib/core/utils/internal/mergeRight.js +39 -0
  87. package/lib/core/utils/internal/mergeRight.mjs +19 -0
  88. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +5 -0
  89. package/lib/core/utils/internal/parseGraphQLRequest.js +184 -0
  90. package/lib/core/utils/internal/parseGraphQLRequest.mjs +165 -0
  91. package/lib/core/utils/internal/parseMultipartData.d.ts +10 -0
  92. package/lib/core/utils/internal/parseMultipartData.js +81 -0
  93. package/lib/core/utils/internal/parseMultipartData.mjs +61 -0
  94. package/lib/core/utils/internal/pipeEvents.d.ts +8 -0
  95. package/lib/core/utils/internal/pipeEvents.js +34 -0
  96. package/lib/core/utils/internal/pipeEvents.mjs +14 -0
  97. package/lib/core/utils/internal/requestHandlerUtils.d.ts +8 -0
  98. package/lib/core/utils/internal/requestHandlerUtils.js +36 -0
  99. package/lib/core/utils/internal/requestHandlerUtils.mjs +16 -0
  100. package/lib/core/utils/internal/toReadonlyArray.d.ts +6 -0
  101. package/lib/core/utils/internal/toReadonlyArray.js +28 -0
  102. package/lib/core/utils/internal/toReadonlyArray.mjs +8 -0
  103. package/lib/core/utils/internal/tryCatch.d.ts +3 -0
  104. package/lib/core/utils/internal/tryCatch.js +31 -0
  105. package/lib/core/utils/internal/tryCatch.mjs +11 -0
  106. package/lib/core/utils/internal/uuidv4.d.ts +3 -0
  107. package/lib/core/utils/internal/uuidv4.js +26 -0
  108. package/lib/core/utils/internal/uuidv4.mjs +6 -0
  109. package/lib/core/utils/logging/getStatusCodeColor.d.ts +11 -0
  110. package/lib/core/utils/logging/getStatusCodeColor.js +39 -0
  111. package/lib/core/utils/logging/getStatusCodeColor.mjs +19 -0
  112. package/lib/core/utils/logging/getTimestamp.d.ts +6 -0
  113. package/lib/core/utils/logging/getTimestamp.js +27 -0
  114. package/lib/core/utils/logging/getTimestamp.mjs +7 -0
  115. package/lib/core/utils/logging/serializeRequest.d.ts +12 -0
  116. package/lib/core/utils/logging/serializeRequest.js +55 -0
  117. package/lib/core/utils/logging/serializeRequest.mjs +35 -0
  118. package/lib/core/utils/logging/serializeResponse.d.ts +9 -0
  119. package/lib/core/utils/logging/serializeResponse.js +69 -0
  120. package/lib/core/utils/logging/serializeResponse.mjs +39 -0
  121. package/lib/core/utils/matching/matchRequestUrl.d.ts +19 -0
  122. package/lib/core/utils/matching/matchRequestUrl.js +50 -0
  123. package/lib/core/utils/matching/matchRequestUrl.mjs +30 -0
  124. package/lib/core/utils/matching/normalizePath.d.ts +12 -0
  125. package/lib/core/utils/matching/normalizePath.js +32 -0
  126. package/lib/core/utils/matching/normalizePath.mjs +12 -0
  127. package/lib/core/utils/request/getPublicUrlFromRequest.d.ts +7 -0
  128. package/lib/core/utils/request/getPublicUrlFromRequest.js +30 -0
  129. package/lib/core/utils/request/getPublicUrlFromRequest.mjs +10 -0
  130. package/lib/core/utils/request/getRequestCookies.d.ts +8 -0
  131. package/lib/core/utils/request/getRequestCookies.js +88 -0
  132. package/lib/core/utils/request/getRequestCookies.mjs +60 -0
  133. package/lib/core/utils/request/onUnhandledRequest.d.ts +12 -0
  134. package/lib/core/utils/request/onUnhandledRequest.js +193 -0
  135. package/lib/core/utils/request/onUnhandledRequest.mjs +165 -0
  136. package/lib/core/utils/request/readResponseCookies.d.ts +3 -0
  137. package/lib/core/utils/request/readResponseCookies.js +45 -0
  138. package/lib/core/utils/request/readResponseCookies.mjs +27 -0
  139. package/lib/core/utils/toResponseInit.d.ts +3 -0
  140. package/lib/core/utils/toResponseInit.js +30 -0
  141. package/lib/core/utils/toResponseInit.mjs +10 -0
  142. package/lib/core/utils/url/cleanUrl.d.ts +7 -0
  143. package/lib/core/utils/url/cleanUrl.js +31 -0
  144. package/lib/core/utils/url/cleanUrl.mjs +11 -0
  145. package/lib/core/utils/url/getAbsoluteUrl.d.ts +6 -0
  146. package/lib/core/utils/url/getAbsoluteUrl.js +37 -0
  147. package/lib/core/utils/url/getAbsoluteUrl.mjs +17 -0
  148. package/lib/core/utils/url/isAbsoluteUrl.d.ts +6 -0
  149. package/lib/core/utils/url/isAbsoluteUrl.js +26 -0
  150. package/lib/core/utils/url/isAbsoluteUrl.mjs +6 -0
  151. package/lib/iife/index.js +6204 -12360
  152. package/lib/mockServiceWorker.js +82 -93
  153. package/lib/native/index.d.ts +67 -7
  154. package/lib/native/index.js +74 -1500
  155. package/lib/native/index.mjs +69 -1514
  156. package/lib/node/index.d.ts +68 -9
  157. package/lib/node/index.js +77 -1508
  158. package/lib/node/index.mjs +71 -1521
  159. package/native/package.json +2 -1
  160. package/node/package.json +2 -1
  161. package/package.json +53 -23
  162. package/lib/SetupServerApi-1855d9c6.d.ts +0 -20
  163. package/lib/glossary-de6278a9.d.ts +0 -385
  164. package/lib/iife/index.js.map +0 -1
  165. package/lib/index.d.ts +0 -365
  166. package/lib/index.js +0 -2295
  167. package/lib/index.js.map +0 -1
  168. package/lib/node/index.js.map +0 -1
  169. package/lib/node/index.mjs.map +0 -1
@@ -0,0 +1,18 @@
1
+ declare const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
2
+ declare const MIN_SERVER_RESPONSE_TIME = 100;
3
+ declare const MAX_SERVER_RESPONSE_TIME = 400;
4
+ declare const NODE_SERVER_RESPONSE_TIME = 5;
5
+ type DelayMode = 'real' | 'infinite';
6
+ /**
7
+ * Delays the response by the given duration (ms).
8
+ *
9
+ * @example
10
+ * await delay() // emulate realistic server response time
11
+ * await delay(1200) // delay response by 1200ms
12
+ * await delay('infinite') // delay response infinitely
13
+ *
14
+ * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference}
15
+ */
16
+ declare function delay(durationOrMode?: DelayMode | number): Promise<void>;
17
+
18
+ export { DelayMode, MAX_SERVER_RESPONSE_TIME, MIN_SERVER_RESPONSE_TIME, NODE_SERVER_RESPONSE_TIME, SET_TIMEOUT_MAX_ALLOWED_INT, delay };
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __async = (__this, __arguments, generator) => {
20
+ return new Promise((resolve, reject) => {
21
+ var fulfilled = (value) => {
22
+ try {
23
+ step(generator.next(value));
24
+ } catch (e) {
25
+ reject(e);
26
+ }
27
+ };
28
+ var rejected = (value) => {
29
+ try {
30
+ step(generator.throw(value));
31
+ } catch (e) {
32
+ reject(e);
33
+ }
34
+ };
35
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
36
+ step((generator = generator.apply(__this, __arguments)).next());
37
+ });
38
+ };
39
+ var delay_exports = {};
40
+ __export(delay_exports, {
41
+ MAX_SERVER_RESPONSE_TIME: () => MAX_SERVER_RESPONSE_TIME,
42
+ MIN_SERVER_RESPONSE_TIME: () => MIN_SERVER_RESPONSE_TIME,
43
+ NODE_SERVER_RESPONSE_TIME: () => NODE_SERVER_RESPONSE_TIME,
44
+ SET_TIMEOUT_MAX_ALLOWED_INT: () => SET_TIMEOUT_MAX_ALLOWED_INT,
45
+ delay: () => delay
46
+ });
47
+ module.exports = __toCommonJS(delay_exports);
48
+ var import_is_node_process = require("is-node-process");
49
+ const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
50
+ const MIN_SERVER_RESPONSE_TIME = 100;
51
+ const MAX_SERVER_RESPONSE_TIME = 400;
52
+ const NODE_SERVER_RESPONSE_TIME = 5;
53
+ function getRealisticResponseTime() {
54
+ if ((0, import_is_node_process.isNodeProcess)()) {
55
+ return NODE_SERVER_RESPONSE_TIME;
56
+ }
57
+ return Math.floor(
58
+ Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
59
+ );
60
+ }
61
+ function delay(durationOrMode) {
62
+ return __async(this, null, function* () {
63
+ let delayTime;
64
+ if (typeof durationOrMode === "string") {
65
+ switch (durationOrMode) {
66
+ case "infinite": {
67
+ delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
68
+ break;
69
+ }
70
+ case "real": {
71
+ delayTime = getRealisticResponseTime();
72
+ break;
73
+ }
74
+ default: {
75
+ throw new Error(
76
+ `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
77
+ );
78
+ }
79
+ }
80
+ } else if (typeof durationOrMode === "undefined") {
81
+ delayTime = getRealisticResponseTime();
82
+ } else {
83
+ if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
84
+ throw new Error(
85
+ `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`
86
+ );
87
+ }
88
+ delayTime = durationOrMode;
89
+ }
90
+ return new Promise((resolve) => setTimeout(resolve, delayTime));
91
+ });
92
+ }
@@ -0,0 +1,72 @@
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ import { isNodeProcess } from "is-node-process";
22
+ const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
23
+ const MIN_SERVER_RESPONSE_TIME = 100;
24
+ const MAX_SERVER_RESPONSE_TIME = 400;
25
+ const NODE_SERVER_RESPONSE_TIME = 5;
26
+ function getRealisticResponseTime() {
27
+ if (isNodeProcess()) {
28
+ return NODE_SERVER_RESPONSE_TIME;
29
+ }
30
+ return Math.floor(
31
+ Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) + MIN_SERVER_RESPONSE_TIME
32
+ );
33
+ }
34
+ function delay(durationOrMode) {
35
+ return __async(this, null, function* () {
36
+ let delayTime;
37
+ if (typeof durationOrMode === "string") {
38
+ switch (durationOrMode) {
39
+ case "infinite": {
40
+ delayTime = SET_TIMEOUT_MAX_ALLOWED_INT;
41
+ break;
42
+ }
43
+ case "real": {
44
+ delayTime = getRealisticResponseTime();
45
+ break;
46
+ }
47
+ default: {
48
+ throw new Error(
49
+ `Failed to delay a response: unknown delay mode "${durationOrMode}". Please make sure you provide one of the supported modes ("real", "infinite") or a number.`
50
+ );
51
+ }
52
+ }
53
+ } else if (typeof durationOrMode === "undefined") {
54
+ delayTime = getRealisticResponseTime();
55
+ } else {
56
+ if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {
57
+ throw new Error(
58
+ `Failed to delay a response: provided delay duration (${durationOrMode}) exceeds the maximum allowed duration for "setTimeout" (${SET_TIMEOUT_MAX_ALLOWED_INT}). This will cause the response to be returned immediately. Please use a number within the allowed range to delay the response by exact duration, or consider the "infinite" delay mode to delay the response indefinitely.`
59
+ );
60
+ }
61
+ delayTime = durationOrMode;
62
+ }
63
+ return new Promise((resolve) => setTimeout(resolve, delayTime));
64
+ });
65
+ }
66
+ export {
67
+ MAX_SERVER_RESPONSE_TIME,
68
+ MIN_SERVER_RESPONSE_TIME,
69
+ NODE_SERVER_RESPONSE_TIME,
70
+ SET_TIMEOUT_MAX_ALLOWED_INT,
71
+ delay
72
+ };
@@ -0,0 +1,109 @@
1
+ import { DocumentNode } from 'graphql';
2
+ import { a as ResponseResolver, c as RequestHandlerOptions } from './RequestHandler-1a5dbdc7.js';
3
+ import { a as GraphQLVariables, d as GraphQLHandlerNameSelector, e as GraphQLResolverExtras, f as GraphQLResponseBody, G as GraphQLHandler } from './GraphQLHandler-b42ca96f.js';
4
+ import { Path } from './utils/matching/matchRequestUrl.js';
5
+ import './typeUtils.js';
6
+
7
+ interface TypedDocumentNode<Result = {
8
+ [key: string]: any;
9
+ }, Variables = {
10
+ [key: string]: any;
11
+ }> extends DocumentNode {
12
+ __apiType?: (variables: Variables) => Result;
13
+ __resultType?: Result;
14
+ __variablesType?: Variables;
15
+ }
16
+ declare const standardGraphQLHandlers: {
17
+ /**
18
+ * Intercepts a GraphQL query by a given name.
19
+ *
20
+ * @example
21
+ * graphql.query('GetUser', () => {
22
+ * return HttpResponse.json({ data: { user: { name: 'John' } } })
23
+ * })
24
+ *
25
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference}
26
+ */
27
+ query: <Query extends Record<string, any>, Variables extends GraphQLVariables = GraphQLVariables>(operationName: GraphQLHandlerNameSelector | TypedDocumentNode<Query, Variables>, resolver: ResponseResolver<GraphQLResolverExtras<Variables>, null, GraphQLResponseBody<Query>>, options?: RequestHandlerOptions) => GraphQLHandler;
28
+ /**
29
+ * Intercepts a GraphQL mutation by its name.
30
+ *
31
+ * @example
32
+ * graphql.mutation('SavePost', () => {
33
+ * return HttpResponse.json({ data: { post: { id: 'abc-123 } } })
34
+ * })
35
+ *
36
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference}
37
+ *
38
+ */
39
+ mutation: <Query extends Record<string, any>, Variables extends GraphQLVariables = GraphQLVariables>(operationName: GraphQLHandlerNameSelector | TypedDocumentNode<Query, Variables>, resolver: ResponseResolver<GraphQLResolverExtras<Variables>, null, GraphQLResponseBody<Query>>, options?: RequestHandlerOptions) => GraphQLHandler;
40
+ /**
41
+ * Intercepts any GraphQL operation, regardless of its type or name.
42
+ *
43
+ * @example
44
+ * graphql.operation(() => {
45
+ * return HttpResponse.json({ data: { name: 'John' } })
46
+ * })
47
+ *
48
+ * @see {@link https://mswjs.io/docs/api/graphql#graphloperationresolver `graphql.operation()` API reference}
49
+ */
50
+ operation: <Query_1 extends Record<string, any>, Variables_1 extends GraphQLVariables = GraphQLVariables>(resolver: ResponseResolver<GraphQLResolverExtras<Variables_1>, null, GraphQLResponseBody<Query_1>>) => GraphQLHandler;
51
+ };
52
+ declare function createGraphQLLink(url: Path): typeof standardGraphQLHandlers;
53
+ /**
54
+ * A namespace to intercept and mock GraphQL operations
55
+ *
56
+ * @example
57
+ * graphql.query('GetUser', resolver)
58
+ * graphql.mutation('DeletePost', resolver)
59
+ *
60
+ * @see {@link https://mswjs.io/docs/api/graphql `graphql` API reference}
61
+ */
62
+ declare const graphql: {
63
+ /**
64
+ * Intercepts GraphQL operations scoped by the given URL.
65
+ *
66
+ * @example
67
+ * const github = graphql.link('https://api.github.com/graphql')
68
+ * github.query('GetRepo', resolver)
69
+ *
70
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}
71
+ */
72
+ link: typeof createGraphQLLink;
73
+ /**
74
+ * Intercepts a GraphQL query by a given name.
75
+ *
76
+ * @example
77
+ * graphql.query('GetUser', () => {
78
+ * return HttpResponse.json({ data: { user: { name: 'John' } } })
79
+ * })
80
+ *
81
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference}
82
+ */
83
+ query: <Query extends Record<string, any>, Variables extends GraphQLVariables = GraphQLVariables>(operationName: GraphQLHandlerNameSelector | TypedDocumentNode<Query, Variables>, resolver: ResponseResolver<GraphQLResolverExtras<Variables>, null, GraphQLResponseBody<Query>>, options?: RequestHandlerOptions) => GraphQLHandler;
84
+ /**
85
+ * Intercepts a GraphQL mutation by its name.
86
+ *
87
+ * @example
88
+ * graphql.mutation('SavePost', () => {
89
+ * return HttpResponse.json({ data: { post: { id: 'abc-123 } } })
90
+ * })
91
+ *
92
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference}
93
+ *
94
+ */
95
+ mutation: <Query extends Record<string, any>, Variables extends GraphQLVariables = GraphQLVariables>(operationName: GraphQLHandlerNameSelector | TypedDocumentNode<Query, Variables>, resolver: ResponseResolver<GraphQLResolverExtras<Variables>, null, GraphQLResponseBody<Query>>, options?: RequestHandlerOptions) => GraphQLHandler;
96
+ /**
97
+ * Intercepts any GraphQL operation, regardless of its type or name.
98
+ *
99
+ * @example
100
+ * graphql.operation(() => {
101
+ * return HttpResponse.json({ data: { name: 'John' } })
102
+ * })
103
+ *
104
+ * @see {@link https://mswjs.io/docs/api/graphql#graphloperationresolver `graphql.operation()` API reference}
105
+ */
106
+ operation: <Query_1 extends Record<string, any>, Variables_1 extends GraphQLVariables = GraphQLVariables>(resolver: ResponseResolver<GraphQLResolverExtras<Variables_1>, null, GraphQLResponseBody<Query_1>>) => GraphQLHandler;
107
+ };
108
+
109
+ export { TypedDocumentNode, graphql };
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+ var graphql_exports = {};
37
+ __export(graphql_exports, {
38
+ graphql: () => graphql
39
+ });
40
+ module.exports = __toCommonJS(graphql_exports);
41
+ var import_GraphQLHandler = require("./handlers/GraphQLHandler.js");
42
+ function createScopedGraphQLHandler(operationType, url) {
43
+ return (operationName, resolver, options = {}) => {
44
+ return new import_GraphQLHandler.GraphQLHandler(
45
+ operationType,
46
+ operationName,
47
+ url,
48
+ resolver,
49
+ options
50
+ );
51
+ };
52
+ }
53
+ function createGraphQLOperationHandler(url) {
54
+ return (resolver) => {
55
+ return new import_GraphQLHandler.GraphQLHandler("all", new RegExp(".*"), url, resolver);
56
+ };
57
+ }
58
+ const standardGraphQLHandlers = {
59
+ /**
60
+ * Intercepts a GraphQL query by a given name.
61
+ *
62
+ * @example
63
+ * graphql.query('GetUser', () => {
64
+ * return HttpResponse.json({ data: { user: { name: 'John' } } })
65
+ * })
66
+ *
67
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference}
68
+ */
69
+ query: createScopedGraphQLHandler("query", "*"),
70
+ /**
71
+ * Intercepts a GraphQL mutation by its name.
72
+ *
73
+ * @example
74
+ * graphql.mutation('SavePost', () => {
75
+ * return HttpResponse.json({ data: { post: { id: 'abc-123 } } })
76
+ * })
77
+ *
78
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference}
79
+ *
80
+ */
81
+ mutation: createScopedGraphQLHandler("mutation", "*"),
82
+ /**
83
+ * Intercepts any GraphQL operation, regardless of its type or name.
84
+ *
85
+ * @example
86
+ * graphql.operation(() => {
87
+ * return HttpResponse.json({ data: { name: 'John' } })
88
+ * })
89
+ *
90
+ * @see {@link https://mswjs.io/docs/api/graphql#graphloperationresolver `graphql.operation()` API reference}
91
+ */
92
+ operation: createGraphQLOperationHandler("*")
93
+ };
94
+ function createGraphQLLink(url) {
95
+ return {
96
+ operation: createGraphQLOperationHandler(url),
97
+ query: createScopedGraphQLHandler("query", url),
98
+ mutation: createScopedGraphQLHandler("mutation", url)
99
+ };
100
+ }
101
+ const graphql = __spreadProps(__spreadValues({}, standardGraphQLHandlers), {
102
+ /**
103
+ * Intercepts GraphQL operations scoped by the given URL.
104
+ *
105
+ * @example
106
+ * const github = graphql.link('https://api.github.com/graphql')
107
+ * github.query('GetRepo', resolver)
108
+ *
109
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}
110
+ */
111
+ link: createGraphQLLink
112
+ });
@@ -0,0 +1,96 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ import {
21
+ GraphQLHandler
22
+ } from './handlers/GraphQLHandler.mjs';
23
+ function createScopedGraphQLHandler(operationType, url) {
24
+ return (operationName, resolver, options = {}) => {
25
+ return new GraphQLHandler(
26
+ operationType,
27
+ operationName,
28
+ url,
29
+ resolver,
30
+ options
31
+ );
32
+ };
33
+ }
34
+ function createGraphQLOperationHandler(url) {
35
+ return (resolver) => {
36
+ return new GraphQLHandler("all", new RegExp(".*"), url, resolver);
37
+ };
38
+ }
39
+ const standardGraphQLHandlers = {
40
+ /**
41
+ * Intercepts a GraphQL query by a given name.
42
+ *
43
+ * @example
44
+ * graphql.query('GetUser', () => {
45
+ * return HttpResponse.json({ data: { user: { name: 'John' } } })
46
+ * })
47
+ *
48
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlqueryqueryname-resolver `graphql.query()` API reference}
49
+ */
50
+ query: createScopedGraphQLHandler("query", "*"),
51
+ /**
52
+ * Intercepts a GraphQL mutation by its name.
53
+ *
54
+ * @example
55
+ * graphql.mutation('SavePost', () => {
56
+ * return HttpResponse.json({ data: { post: { id: 'abc-123 } } })
57
+ * })
58
+ *
59
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqlmutationmutationname-resolver `graphql.query()` API reference}
60
+ *
61
+ */
62
+ mutation: createScopedGraphQLHandler("mutation", "*"),
63
+ /**
64
+ * Intercepts any GraphQL operation, regardless of its type or name.
65
+ *
66
+ * @example
67
+ * graphql.operation(() => {
68
+ * return HttpResponse.json({ data: { name: 'John' } })
69
+ * })
70
+ *
71
+ * @see {@link https://mswjs.io/docs/api/graphql#graphloperationresolver `graphql.operation()` API reference}
72
+ */
73
+ operation: createGraphQLOperationHandler("*")
74
+ };
75
+ function createGraphQLLink(url) {
76
+ return {
77
+ operation: createGraphQLOperationHandler(url),
78
+ query: createScopedGraphQLHandler("query", url),
79
+ mutation: createScopedGraphQLHandler("mutation", url)
80
+ };
81
+ }
82
+ const graphql = __spreadProps(__spreadValues({}, standardGraphQLHandlers), {
83
+ /**
84
+ * Intercepts GraphQL operations scoped by the given URL.
85
+ *
86
+ * @example
87
+ * const github = graphql.link('https://api.github.com/graphql')
88
+ * github.query('GetRepo', resolver)
89
+ *
90
+ * @see {@link https://mswjs.io/docs/api/graphql#graphqllinkurl `graphql.link()` API reference}
91
+ */
92
+ link: createGraphQLLink
93
+ });
94
+ export {
95
+ graphql
96
+ };
@@ -0,0 +1,5 @@
1
+ import 'graphql';
2
+ import '../RequestHandler-1a5dbdc7.js';
3
+ import '../utils/matching/matchRequestUrl.js';
4
+ export { E as ExpectedOperationTypeNode, G as GraphQLHandler, k as GraphQLHandlerInfo, d as GraphQLHandlerNameSelector, c as GraphQLJsonRequestBody, b as GraphQLRequestBody, e as GraphQLResolverExtras, f as GraphQLResponseBody, a as GraphQLVariables, l as isDocumentNode } from '../GraphQLHandler-b42ca96f.js';
5
+ import '../typeUtils.js';
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __async = (__this, __arguments, generator) => {
20
+ return new Promise((resolve, reject) => {
21
+ var fulfilled = (value) => {
22
+ try {
23
+ step(generator.next(value));
24
+ } catch (e) {
25
+ reject(e);
26
+ }
27
+ };
28
+ var rejected = (value) => {
29
+ try {
30
+ step(generator.throw(value));
31
+ } catch (e) {
32
+ reject(e);
33
+ }
34
+ };
35
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
36
+ step((generator = generator.apply(__this, __arguments)).next());
37
+ });
38
+ };
39
+ var GraphQLHandler_exports = {};
40
+ __export(GraphQLHandler_exports, {
41
+ GraphQLHandler: () => GraphQLHandler,
42
+ isDocumentNode: () => isDocumentNode
43
+ });
44
+ module.exports = __toCommonJS(GraphQLHandler_exports);
45
+ var import_RequestHandler = require("./RequestHandler.js");
46
+ var import_getTimestamp = require("../utils/logging/getTimestamp.js");
47
+ var import_getStatusCodeColor = require("../utils/logging/getStatusCodeColor.js");
48
+ var import_serializeRequest = require("../utils/logging/serializeRequest.js");
49
+ var import_serializeResponse = require("../utils/logging/serializeResponse.js");
50
+ var import_matchRequestUrl = require("../utils/matching/matchRequestUrl.js");
51
+ var import_parseGraphQLRequest = require("../utils/internal/parseGraphQLRequest.js");
52
+ var import_getPublicUrlFromRequest = require("../utils/request/getPublicUrlFromRequest.js");
53
+ var import_devUtils = require("../utils/internal/devUtils.js");
54
+ function isDocumentNode(value) {
55
+ if (value == null) {
56
+ return false;
57
+ }
58
+ return typeof value === "object" && "kind" in value && "definitions" in value;
59
+ }
60
+ class GraphQLHandler extends import_RequestHandler.RequestHandler {
61
+ constructor(operationType, operationName, endpoint, resolver, options) {
62
+ let resolvedOperationName = operationName;
63
+ if (isDocumentNode(operationName)) {
64
+ const parsedNode = (0, import_parseGraphQLRequest.parseDocumentNode)(operationName);
65
+ if (parsedNode.operationType !== operationType) {
66
+ throw new Error(
67
+ `Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`
68
+ );
69
+ }
70
+ if (!parsedNode.operationName) {
71
+ throw new Error(
72
+ `Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`
73
+ );
74
+ }
75
+ resolvedOperationName = parsedNode.operationName;
76
+ }
77
+ const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
78
+ super({
79
+ info: {
80
+ header,
81
+ operationType,
82
+ operationName: resolvedOperationName
83
+ },
84
+ resolver,
85
+ options
86
+ });
87
+ this.endpoint = endpoint;
88
+ }
89
+ parse(args) {
90
+ return __async(this, null, function* () {
91
+ return (0, import_parseGraphQLRequest.parseGraphQLRequest)(args.request).catch((error) => {
92
+ console.error(error);
93
+ return void 0;
94
+ });
95
+ });
96
+ }
97
+ predicate(args) {
98
+ if (!args.parsedResult) {
99
+ return false;
100
+ }
101
+ if (!args.parsedResult.operationName && this.info.operationType !== "all") {
102
+ const publicUrl = (0, import_getPublicUrlFromRequest.getPublicUrlFromRequest)(args.request);
103
+ import_devUtils.devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
104
+
105
+ Consider naming this operation or using "graphql.operation()" request handler to intercept GraphQL requests regardless of their operation name/type. Read more: https://mswjs.io/docs/api/graphql/operation`);
106
+ return false;
107
+ }
108
+ const hasMatchingUrl = (0, import_matchRequestUrl.matchRequestUrl)(
109
+ new URL(args.request.url),
110
+ this.endpoint
111
+ );
112
+ const hasMatchingOperationType = this.info.operationType === "all" || args.parsedResult.operationType === this.info.operationType;
113
+ const hasMatchingOperationName = this.info.operationName instanceof RegExp ? this.info.operationName.test(args.parsedResult.operationName || "") : args.parsedResult.operationName === this.info.operationName;
114
+ return hasMatchingUrl.matches && hasMatchingOperationType && hasMatchingOperationName;
115
+ }
116
+ extendResolverArgs(args) {
117
+ var _a, _b, _c;
118
+ return {
119
+ query: ((_a = args.parsedResult) == null ? void 0 : _a.query) || "",
120
+ operationName: ((_b = args.parsedResult) == null ? void 0 : _b.operationName) || "",
121
+ variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {}
122
+ };
123
+ }
124
+ log(args) {
125
+ return __async(this, null, function* () {
126
+ var _a, _b, _c, _d;
127
+ const loggedRequest = yield (0, import_serializeRequest.serializeRequest)(args.request);
128
+ const loggedResponse = yield (0, import_serializeResponse.serializeResponse)(args.response);
129
+ const statusColor = (0, import_getStatusCodeColor.getStatusCodeColor)(loggedResponse.status);
130
+ const requestInfo = ((_a = args.parsedResult) == null ? void 0 : _a.operationName) ? `${(_b = args.parsedResult) == null ? void 0 : _b.operationType} ${(_c = args.parsedResult) == null ? void 0 : _c.operationName}` : `anonymous ${(_d = args.parsedResult) == null ? void 0 : _d.operationType}`;
131
+ console.groupCollapsed(
132
+ import_devUtils.devUtils.formatMessage("%s %s (%c%s%c)"),
133
+ (0, import_getTimestamp.getTimestamp)(),
134
+ `${requestInfo}`,
135
+ `color:${statusColor}`,
136
+ `${loggedResponse.status} ${loggedResponse.statusText}`,
137
+ "color:inherit"
138
+ );
139
+ console.log("Request:", loggedRequest);
140
+ console.log("Handler:", this);
141
+ console.log("Response:", loggedResponse);
142
+ console.groupEnd();
143
+ });
144
+ }
145
+ }