msw 1.3.2 → 2.0.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.
Files changed (169) hide show
  1. package/README.md +32 -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 +751 -0
  7. package/lib/browser/index.mjs +733 -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 +6203 -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,130 @@
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 {
22
+ RequestHandler
23
+ } from './RequestHandler.mjs';
24
+ import { getTimestamp } from '../utils/logging/getTimestamp.mjs';
25
+ import { getStatusCodeColor } from '../utils/logging/getStatusCodeColor.mjs';
26
+ import { serializeRequest } from '../utils/logging/serializeRequest.mjs';
27
+ import { serializeResponse } from '../utils/logging/serializeResponse.mjs';
28
+ import { matchRequestUrl } from '../utils/matching/matchRequestUrl.mjs';
29
+ import {
30
+ parseGraphQLRequest,
31
+ parseDocumentNode
32
+ } from '../utils/internal/parseGraphQLRequest.mjs';
33
+ import { getPublicUrlFromRequest } from '../utils/request/getPublicUrlFromRequest.mjs';
34
+ import { devUtils } from '../utils/internal/devUtils.mjs';
35
+ function isDocumentNode(value) {
36
+ if (value == null) {
37
+ return false;
38
+ }
39
+ return typeof value === "object" && "kind" in value && "definitions" in value;
40
+ }
41
+ class GraphQLHandler extends RequestHandler {
42
+ constructor(operationType, operationName, endpoint, resolver, options) {
43
+ let resolvedOperationName = operationName;
44
+ if (isDocumentNode(operationName)) {
45
+ const parsedNode = parseDocumentNode(operationName);
46
+ if (parsedNode.operationType !== operationType) {
47
+ throw new Error(
48
+ `Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected "${operationType}", but got "${parsedNode.operationType}").`
49
+ );
50
+ }
51
+ if (!parsedNode.operationName) {
52
+ throw new Error(
53
+ `Failed to create a GraphQL handler: provided a DocumentNode with no operation name.`
54
+ );
55
+ }
56
+ resolvedOperationName = parsedNode.operationName;
57
+ }
58
+ const header = operationType === "all" ? `${operationType} (origin: ${endpoint.toString()})` : `${operationType} ${resolvedOperationName} (origin: ${endpoint.toString()})`;
59
+ super({
60
+ info: {
61
+ header,
62
+ operationType,
63
+ operationName: resolvedOperationName
64
+ },
65
+ resolver,
66
+ options
67
+ });
68
+ this.endpoint = endpoint;
69
+ }
70
+ parse(args) {
71
+ return __async(this, null, function* () {
72
+ return parseGraphQLRequest(args.request).catch((error) => {
73
+ console.error(error);
74
+ return void 0;
75
+ });
76
+ });
77
+ }
78
+ predicate(args) {
79
+ if (!args.parsedResult) {
80
+ return false;
81
+ }
82
+ if (!args.parsedResult.operationName && this.info.operationType !== "all") {
83
+ const publicUrl = getPublicUrlFromRequest(args.request);
84
+ devUtils.warn(`Failed to intercept a GraphQL request at "${args.request.method} ${publicUrl}": anonymous GraphQL operations are not supported.
85
+
86
+ 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`);
87
+ return false;
88
+ }
89
+ const hasMatchingUrl = matchRequestUrl(
90
+ new URL(args.request.url),
91
+ this.endpoint
92
+ );
93
+ const hasMatchingOperationType = this.info.operationType === "all" || args.parsedResult.operationType === this.info.operationType;
94
+ const hasMatchingOperationName = this.info.operationName instanceof RegExp ? this.info.operationName.test(args.parsedResult.operationName || "") : args.parsedResult.operationName === this.info.operationName;
95
+ return hasMatchingUrl.matches && hasMatchingOperationType && hasMatchingOperationName;
96
+ }
97
+ extendResolverArgs(args) {
98
+ var _a, _b, _c;
99
+ return {
100
+ query: ((_a = args.parsedResult) == null ? void 0 : _a.query) || "",
101
+ operationName: ((_b = args.parsedResult) == null ? void 0 : _b.operationName) || "",
102
+ variables: ((_c = args.parsedResult) == null ? void 0 : _c.variables) || {}
103
+ };
104
+ }
105
+ log(args) {
106
+ return __async(this, null, function* () {
107
+ var _a, _b, _c, _d;
108
+ const loggedRequest = yield serializeRequest(args.request);
109
+ const loggedResponse = yield serializeResponse(args.response);
110
+ const statusColor = getStatusCodeColor(loggedResponse.status);
111
+ 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}`;
112
+ console.groupCollapsed(
113
+ devUtils.formatMessage("%s %s (%c%s%c)"),
114
+ getTimestamp(),
115
+ `${requestInfo}`,
116
+ `color:${statusColor}`,
117
+ `${loggedResponse.status} ${loggedResponse.statusText}`,
118
+ "color:inherit"
119
+ );
120
+ console.log("Request:", loggedRequest);
121
+ console.log("Handler:", this);
122
+ console.log("Response:", loggedResponse);
123
+ console.groupEnd();
124
+ });
125
+ }
126
+ }
127
+ export {
128
+ GraphQLHandler,
129
+ isDocumentNode
130
+ };
@@ -0,0 +1,62 @@
1
+ import { g as RequestHandlerDefaultInfo, R as RequestHandler, a as ResponseResolver, c as RequestHandlerOptions, i as ResponseResolutionContext } from '../RequestHandler-1a5dbdc7.js';
2
+ import { Path, Match, PathParams } from '../utils/matching/matchRequestUrl.js';
3
+ import '../typeUtils.js';
4
+
5
+ type HttpHandlerMethod = string | RegExp;
6
+ interface HttpHandlerInfo extends RequestHandlerDefaultInfo {
7
+ method: HttpHandlerMethod;
8
+ path: Path;
9
+ }
10
+ declare enum HttpMethods {
11
+ HEAD = "HEAD",
12
+ GET = "GET",
13
+ POST = "POST",
14
+ PUT = "PUT",
15
+ PATCH = "PATCH",
16
+ OPTIONS = "OPTIONS",
17
+ DELETE = "DELETE"
18
+ }
19
+ type RequestQuery = {
20
+ [queryName: string]: string;
21
+ };
22
+ type HttpRequestParsedResult = {
23
+ match: Match;
24
+ cookies: Record<string, string>;
25
+ };
26
+ type HttpRequestResolverExtras<Params extends PathParams> = {
27
+ params: Params;
28
+ cookies: Record<string, string | Array<string>>;
29
+ };
30
+ /**
31
+ * Request handler for HTTP requests.
32
+ * Provides request matching based on method and URL.
33
+ */
34
+ declare class HttpHandler extends RequestHandler<HttpHandlerInfo, HttpRequestParsedResult, HttpRequestResolverExtras<any>> {
35
+ constructor(method: HttpHandlerMethod, path: Path, resolver: ResponseResolver<HttpRequestResolverExtras<any>, any, any>, options?: RequestHandlerOptions);
36
+ private checkRedundantQueryParameters;
37
+ parse(args: {
38
+ request: Request;
39
+ resolutionContext?: ResponseResolutionContext;
40
+ }): Promise<{
41
+ match: Match;
42
+ cookies: Record<string, string>;
43
+ }>;
44
+ predicate(args: {
45
+ request: Request;
46
+ parsedResult: HttpRequestParsedResult;
47
+ }): boolean;
48
+ private matchMethod;
49
+ protected extendResolverArgs(args: {
50
+ request: Request;
51
+ parsedResult: HttpRequestParsedResult;
52
+ }): {
53
+ params: PathParams<string>;
54
+ cookies: Record<string, string>;
55
+ };
56
+ log(args: {
57
+ request: Request;
58
+ response: Response;
59
+ }): Promise<void>;
60
+ }
61
+
62
+ export { HttpHandler, HttpHandlerInfo, HttpMethods, HttpRequestParsedResult, HttpRequestResolverExtras, RequestQuery };
@@ -0,0 +1,149 @@
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 HttpHandler_exports = {};
40
+ __export(HttpHandler_exports, {
41
+ HttpHandler: () => HttpHandler,
42
+ HttpMethods: () => HttpMethods
43
+ });
44
+ module.exports = __toCommonJS(HttpHandler_exports);
45
+ var import_devUtils = require("../utils/internal/devUtils.js");
46
+ var import_isStringEqual = require("../utils/internal/isStringEqual.js");
47
+ var import_getStatusCodeColor = require("../utils/logging/getStatusCodeColor.js");
48
+ var import_getTimestamp = require("../utils/logging/getTimestamp.js");
49
+ var import_serializeRequest = require("../utils/logging/serializeRequest.js");
50
+ var import_serializeResponse = require("../utils/logging/serializeResponse.js");
51
+ var import_matchRequestUrl = require("../utils/matching/matchRequestUrl.js");
52
+ var import_getPublicUrlFromRequest = require("../utils/request/getPublicUrlFromRequest.js");
53
+ var import_getRequestCookies = require("../utils/request/getRequestCookies.js");
54
+ var import_cleanUrl = require("../utils/url/cleanUrl.js");
55
+ var import_RequestHandler = require("./RequestHandler.js");
56
+ var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => {
57
+ HttpMethods2["HEAD"] = "HEAD";
58
+ HttpMethods2["GET"] = "GET";
59
+ HttpMethods2["POST"] = "POST";
60
+ HttpMethods2["PUT"] = "PUT";
61
+ HttpMethods2["PATCH"] = "PATCH";
62
+ HttpMethods2["OPTIONS"] = "OPTIONS";
63
+ HttpMethods2["DELETE"] = "DELETE";
64
+ return HttpMethods2;
65
+ })(HttpMethods || {});
66
+ class HttpHandler extends import_RequestHandler.RequestHandler {
67
+ constructor(method, path, resolver, options) {
68
+ super({
69
+ info: {
70
+ header: `${method} ${path}`,
71
+ path,
72
+ method
73
+ },
74
+ resolver,
75
+ options
76
+ });
77
+ this.checkRedundantQueryParameters();
78
+ }
79
+ checkRedundantQueryParameters() {
80
+ const { method, path } = this.info;
81
+ if (path instanceof RegExp) {
82
+ return;
83
+ }
84
+ const url = (0, import_cleanUrl.cleanUrl)(path);
85
+ if (url === path) {
86
+ return;
87
+ }
88
+ const searchParams = (0, import_cleanUrl.getSearchParams)(path);
89
+ const queryParams = [];
90
+ searchParams.forEach((_, paramName) => {
91
+ queryParams.push(paramName);
92
+ });
93
+ import_devUtils.devUtils.warn(
94
+ `Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".`
95
+ );
96
+ }
97
+ parse(args) {
98
+ return __async(this, null, function* () {
99
+ var _a;
100
+ const url = new URL(args.request.url);
101
+ const match = (0, import_matchRequestUrl.matchRequestUrl)(
102
+ url,
103
+ this.info.path,
104
+ (_a = args.resolutionContext) == null ? void 0 : _a.baseUrl
105
+ );
106
+ const cookies = (0, import_getRequestCookies.getAllRequestCookies)(args.request);
107
+ return {
108
+ match,
109
+ cookies
110
+ };
111
+ });
112
+ }
113
+ predicate(args) {
114
+ const hasMatchingMethod = this.matchMethod(args.request.method);
115
+ const hasMatchingUrl = args.parsedResult.match.matches;
116
+ return hasMatchingMethod && hasMatchingUrl;
117
+ }
118
+ matchMethod(actualMethod) {
119
+ return this.info.method instanceof RegExp ? this.info.method.test(actualMethod) : (0, import_isStringEqual.isStringEqual)(this.info.method, actualMethod);
120
+ }
121
+ extendResolverArgs(args) {
122
+ var _a;
123
+ return {
124
+ params: ((_a = args.parsedResult.match) == null ? void 0 : _a.params) || {},
125
+ cookies: args.parsedResult.cookies
126
+ };
127
+ }
128
+ log(args) {
129
+ return __async(this, null, function* () {
130
+ const publicUrl = (0, import_getPublicUrlFromRequest.getPublicUrlFromRequest)(args.request);
131
+ const loggedRequest = yield (0, import_serializeRequest.serializeRequest)(args.request);
132
+ const loggedResponse = yield (0, import_serializeResponse.serializeResponse)(args.response);
133
+ const statusColor = (0, import_getStatusCodeColor.getStatusCodeColor)(loggedResponse.status);
134
+ console.groupCollapsed(
135
+ import_devUtils.devUtils.formatMessage("%s %s %s (%c%s%c)"),
136
+ (0, import_getTimestamp.getTimestamp)(),
137
+ args.request.method,
138
+ publicUrl,
139
+ `color:${statusColor}`,
140
+ `${loggedResponse.status} ${loggedResponse.statusText}`,
141
+ "color:inherit"
142
+ );
143
+ console.log("Request", loggedRequest);
144
+ console.log("Handler:", this);
145
+ console.log("Response", loggedResponse);
146
+ console.groupEnd();
147
+ });
148
+ }
149
+ }
@@ -0,0 +1,133 @@
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 { devUtils } from '../utils/internal/devUtils.mjs';
22
+ import { isStringEqual } from '../utils/internal/isStringEqual.mjs';
23
+ import { getStatusCodeColor } from '../utils/logging/getStatusCodeColor.mjs';
24
+ import { getTimestamp } from '../utils/logging/getTimestamp.mjs';
25
+ import { serializeRequest } from '../utils/logging/serializeRequest.mjs';
26
+ import { serializeResponse } from '../utils/logging/serializeResponse.mjs';
27
+ import {
28
+ matchRequestUrl
29
+ } from '../utils/matching/matchRequestUrl.mjs';
30
+ import { getPublicUrlFromRequest } from '../utils/request/getPublicUrlFromRequest.mjs';
31
+ import { getAllRequestCookies } from '../utils/request/getRequestCookies.mjs';
32
+ import { cleanUrl, getSearchParams } from '../utils/url/cleanUrl.mjs';
33
+ import {
34
+ RequestHandler
35
+ } from './RequestHandler.mjs';
36
+ var HttpMethods = /* @__PURE__ */ ((HttpMethods2) => {
37
+ HttpMethods2["HEAD"] = "HEAD";
38
+ HttpMethods2["GET"] = "GET";
39
+ HttpMethods2["POST"] = "POST";
40
+ HttpMethods2["PUT"] = "PUT";
41
+ HttpMethods2["PATCH"] = "PATCH";
42
+ HttpMethods2["OPTIONS"] = "OPTIONS";
43
+ HttpMethods2["DELETE"] = "DELETE";
44
+ return HttpMethods2;
45
+ })(HttpMethods || {});
46
+ class HttpHandler extends RequestHandler {
47
+ constructor(method, path, resolver, options) {
48
+ super({
49
+ info: {
50
+ header: `${method} ${path}`,
51
+ path,
52
+ method
53
+ },
54
+ resolver,
55
+ options
56
+ });
57
+ this.checkRedundantQueryParameters();
58
+ }
59
+ checkRedundantQueryParameters() {
60
+ const { method, path } = this.info;
61
+ if (path instanceof RegExp) {
62
+ return;
63
+ }
64
+ const url = cleanUrl(path);
65
+ if (url === path) {
66
+ return;
67
+ }
68
+ const searchParams = getSearchParams(path);
69
+ const queryParams = [];
70
+ searchParams.forEach((_, paramName) => {
71
+ queryParams.push(paramName);
72
+ });
73
+ devUtils.warn(
74
+ `Found a redundant usage of query parameters in the request handler URL for "${method} ${path}". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".`
75
+ );
76
+ }
77
+ parse(args) {
78
+ return __async(this, null, function* () {
79
+ var _a;
80
+ const url = new URL(args.request.url);
81
+ const match = matchRequestUrl(
82
+ url,
83
+ this.info.path,
84
+ (_a = args.resolutionContext) == null ? void 0 : _a.baseUrl
85
+ );
86
+ const cookies = getAllRequestCookies(args.request);
87
+ return {
88
+ match,
89
+ cookies
90
+ };
91
+ });
92
+ }
93
+ predicate(args) {
94
+ const hasMatchingMethod = this.matchMethod(args.request.method);
95
+ const hasMatchingUrl = args.parsedResult.match.matches;
96
+ return hasMatchingMethod && hasMatchingUrl;
97
+ }
98
+ matchMethod(actualMethod) {
99
+ return this.info.method instanceof RegExp ? this.info.method.test(actualMethod) : isStringEqual(this.info.method, actualMethod);
100
+ }
101
+ extendResolverArgs(args) {
102
+ var _a;
103
+ return {
104
+ params: ((_a = args.parsedResult.match) == null ? void 0 : _a.params) || {},
105
+ cookies: args.parsedResult.cookies
106
+ };
107
+ }
108
+ log(args) {
109
+ return __async(this, null, function* () {
110
+ const publicUrl = getPublicUrlFromRequest(args.request);
111
+ const loggedRequest = yield serializeRequest(args.request);
112
+ const loggedResponse = yield serializeResponse(args.response);
113
+ const statusColor = getStatusCodeColor(loggedResponse.status);
114
+ console.groupCollapsed(
115
+ devUtils.formatMessage("%s %s %s (%c%s%c)"),
116
+ getTimestamp(),
117
+ args.request.method,
118
+ publicUrl,
119
+ `color:${statusColor}`,
120
+ `${loggedResponse.status} ${loggedResponse.statusText}`,
121
+ "color:inherit"
122
+ );
123
+ console.log("Request", loggedRequest);
124
+ console.log("Handler:", this);
125
+ console.log("Response", loggedResponse);
126
+ console.groupEnd();
127
+ });
128
+ }
129
+ }
130
+ export {
131
+ HttpHandler,
132
+ HttpMethods
133
+ };
@@ -0,0 +1,2 @@
1
+ export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, M as MaybeAsyncResponseResolverReturnType, R as RequestHandler, m as RequestHandlerArgs, g as RequestHandlerDefaultInfo, n as RequestHandlerExecutionResult, k as RequestHandlerInternalInfo, c as RequestHandlerOptions, a as ResponseResolver, l as ResponseResolverInfo, b as ResponseResolverReturnType } from '../RequestHandler-1a5dbdc7.js';
2
+ import '../typeUtils.js';
@@ -0,0 +1,180 @@
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 __async = (__this, __arguments, generator) => {
37
+ return new Promise((resolve, reject) => {
38
+ var fulfilled = (value) => {
39
+ try {
40
+ step(generator.next(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ };
45
+ var rejected = (value) => {
46
+ try {
47
+ step(generator.throw(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
53
+ step((generator = generator.apply(__this, __arguments)).next());
54
+ });
55
+ };
56
+ var RequestHandler_exports = {};
57
+ __export(RequestHandler_exports, {
58
+ RequestHandler: () => RequestHandler
59
+ });
60
+ module.exports = __toCommonJS(RequestHandler_exports);
61
+ var import_outvariant = require("outvariant");
62
+ var import_getCallFrame = require("../utils/internal/getCallFrame.js");
63
+ var import_isIterable = require("../utils/internal/isIterable.js");
64
+ class RequestHandler {
65
+ constructor(args) {
66
+ this.resolver = args.resolver;
67
+ this.options = args.options;
68
+ const callFrame = (0, import_getCallFrame.getCallFrame)(new Error());
69
+ this.info = __spreadProps(__spreadValues({}, args.info), {
70
+ callFrame
71
+ });
72
+ this.isUsed = false;
73
+ }
74
+ /**
75
+ * Parse the intercepted request to extract additional information from it.
76
+ * Parsed result is then exposed to other methods of this request handler.
77
+ */
78
+ parse(_args) {
79
+ return __async(this, null, function* () {
80
+ return {};
81
+ });
82
+ }
83
+ /**
84
+ * Test if this handler matches the given request.
85
+ */
86
+ test(args) {
87
+ return __async(this, null, function* () {
88
+ const parsedResult = yield this.parse({
89
+ request: args.request,
90
+ resolutionContext: args.resolutionContext
91
+ });
92
+ return this.predicate({
93
+ request: args.request,
94
+ parsedResult,
95
+ resolutionContext: args.resolutionContext
96
+ });
97
+ });
98
+ }
99
+ extendResolverArgs(_args) {
100
+ return {};
101
+ }
102
+ /**
103
+ * Execute this request handler and produce a mocked response
104
+ * using the given resolver function.
105
+ */
106
+ run(args) {
107
+ return __async(this, null, function* () {
108
+ var _a;
109
+ if (this.isUsed && ((_a = this.options) == null ? void 0 : _a.once)) {
110
+ return null;
111
+ }
112
+ const mainRequestRef = args.request.clone();
113
+ this.isUsed = true;
114
+ const parsedResult = yield this.parse({
115
+ request: args.request,
116
+ resolutionContext: args.resolutionContext
117
+ });
118
+ const shouldInterceptRequest = this.predicate({
119
+ request: args.request,
120
+ parsedResult,
121
+ resolutionContext: args.resolutionContext
122
+ });
123
+ if (!shouldInterceptRequest) {
124
+ return null;
125
+ }
126
+ const executeResolver = this.wrapResolver(this.resolver);
127
+ const resolverExtras = this.extendResolverArgs({
128
+ request: args.request,
129
+ parsedResult
130
+ });
131
+ const mockedResponse = yield executeResolver(__spreadProps(__spreadValues({}, resolverExtras), {
132
+ request: args.request
133
+ }));
134
+ const executionResult = this.createExecutionResult({
135
+ // Pass the cloned request to the result so that logging
136
+ // and other consumers could read its body once more.
137
+ request: mainRequestRef,
138
+ response: mockedResponse,
139
+ parsedResult
140
+ });
141
+ return executionResult;
142
+ });
143
+ }
144
+ wrapResolver(resolver) {
145
+ return (info) => __async(this, null, function* () {
146
+ const result = this.resolverGenerator || (yield resolver(info));
147
+ if ((0, import_isIterable.isIterable)(result)) {
148
+ this.isUsed = false;
149
+ const { value, done } = result[Symbol.iterator]().next();
150
+ const nextResponse = yield value;
151
+ if (done) {
152
+ this.isUsed = true;
153
+ }
154
+ if (!nextResponse && done) {
155
+ (0, import_outvariant.invariant)(
156
+ this.resolverGeneratorResult,
157
+ "Failed to returned a previously stored generator response: the value is not a valid Response."
158
+ );
159
+ return this.resolverGeneratorResult.clone();
160
+ }
161
+ if (!this.resolverGenerator) {
162
+ this.resolverGenerator = result;
163
+ }
164
+ if (nextResponse) {
165
+ this.resolverGeneratorResult = nextResponse == null ? void 0 : nextResponse.clone();
166
+ }
167
+ return nextResponse;
168
+ }
169
+ return result;
170
+ });
171
+ }
172
+ createExecutionResult(args) {
173
+ return {
174
+ handler: this,
175
+ request: args.request,
176
+ response: args.response,
177
+ parsedResult: args.parsedResult
178
+ };
179
+ }
180
+ }