msw 2.12.10 → 2.12.12
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/config/scripts/postinstall.js +2 -2
- package/lib/core/{HttpResponse-Cw4ELwIN.d.mts → HttpResponse-B9rGc56D.d.mts} +1 -1
- package/lib/core/{HttpResponse-CVs3ngx3.d.ts → HttpResponse-Dz84tqeA.d.ts} +1 -1
- package/lib/core/HttpResponse.d.mts +1 -1
- package/lib/core/HttpResponse.d.ts +1 -1
- package/lib/core/SetupApi.d.mts +1 -1
- package/lib/core/SetupApi.d.ts +1 -1
- package/lib/core/delay.js +7 -1
- package/lib/core/delay.js.map +1 -1
- package/lib/core/delay.mjs +7 -1
- package/lib/core/delay.mjs.map +1 -1
- package/lib/core/getResponse.d.mts +1 -1
- package/lib/core/getResponse.d.ts +1 -1
- package/lib/core/graphql.d.mts +1 -1
- package/lib/core/graphql.d.ts +1 -1
- package/lib/core/handlers/GraphQLHandler.d.mts +1 -1
- package/lib/core/handlers/GraphQLHandler.d.ts +1 -1
- package/lib/core/handlers/GraphQLHandler.js.map +1 -1
- package/lib/core/handlers/GraphQLHandler.mjs.map +1 -1
- package/lib/core/handlers/HttpHandler.d.mts +1 -1
- package/lib/core/handlers/HttpHandler.d.ts +1 -1
- package/lib/core/handlers/RequestHandler.d.mts +1 -1
- package/lib/core/handlers/RequestHandler.d.ts +1 -1
- package/lib/core/http.d.mts +1 -1
- package/lib/core/http.d.ts +1 -1
- package/lib/core/index.d.mts +3 -3
- package/lib/core/index.d.ts +3 -3
- package/lib/core/index.js +6 -4
- package/lib/core/index.js.map +1 -1
- package/lib/core/index.mjs +8 -3
- package/lib/core/index.mjs.map +1 -1
- package/lib/core/passthrough.d.mts +1 -1
- package/lib/core/passthrough.d.ts +1 -1
- package/lib/core/sse.d.mts +1 -1
- package/lib/core/sse.d.ts +1 -1
- package/lib/core/sse.js +1 -1
- package/lib/core/sse.js.map +1 -1
- package/lib/core/sse.mjs +1 -1
- package/lib/core/sse.mjs.map +1 -1
- package/lib/core/utils/HttpResponse/decorators.d.mts +1 -1
- package/lib/core/utils/HttpResponse/decorators.d.ts +1 -1
- package/lib/core/utils/executeHandlers.d.mts +1 -1
- package/lib/core/utils/executeHandlers.d.ts +1 -1
- package/lib/core/utils/handleRequest.d.mts +1 -1
- package/lib/core/utils/handleRequest.d.ts +1 -1
- package/lib/core/utils/internal/hasRefCounted.d.mts +3 -0
- package/lib/core/utils/internal/hasRefCounted.d.ts +3 -0
- package/lib/core/utils/internal/hasRefCounted.js +27 -0
- package/lib/core/utils/internal/hasRefCounted.js.map +1 -0
- package/lib/core/utils/internal/hasRefCounted.mjs +7 -0
- package/lib/core/utils/internal/hasRefCounted.mjs.map +1 -0
- package/lib/core/utils/internal/isHandlerKind.d.mts +1 -1
- package/lib/core/utils/internal/isHandlerKind.d.ts +1 -1
- package/lib/core/utils/internal/parseGraphQLRequest.d.mts +1 -1
- package/lib/core/utils/internal/parseGraphQLRequest.d.ts +1 -1
- package/lib/core/utils/internal/parseGraphQLRequest.js +1 -1
- package/lib/core/utils/internal/parseGraphQLRequest.js.map +1 -1
- package/lib/core/utils/internal/parseGraphQLRequest.mjs +1 -1
- package/lib/core/utils/internal/parseGraphQLRequest.mjs.map +1 -1
- package/lib/core/utils/internal/parseMultipartData.d.mts +1 -1
- package/lib/core/utils/internal/parseMultipartData.d.ts +1 -1
- package/lib/core/utils/internal/parseMultipartData.js +3 -1
- package/lib/core/utils/internal/parseMultipartData.js.map +1 -1
- package/lib/core/utils/internal/parseMultipartData.mjs +3 -1
- package/lib/core/utils/internal/parseMultipartData.mjs.map +1 -1
- package/lib/core/utils/internal/requestHandlerUtils.d.mts +1 -1
- package/lib/core/utils/internal/requestHandlerUtils.d.ts +1 -1
- package/lib/core/ws/WebSocketIndexedDBClientStore.js +1 -1
- package/lib/core/ws/WebSocketIndexedDBClientStore.js.map +1 -1
- package/lib/core/ws/WebSocketIndexedDBClientStore.mjs +1 -1
- package/lib/core/ws/WebSocketIndexedDBClientStore.mjs.map +1 -1
- package/lib/core/ws/handleWebSocketEvent.d.mts +1 -1
- package/lib/core/ws/handleWebSocketEvent.d.ts +1 -1
- package/lib/core/ws.js +2 -4
- package/lib/core/ws.js.map +1 -1
- package/lib/core/ws.mjs +2 -4
- package/lib/core/ws.mjs.map +1 -1
- package/lib/iife/index.js +18 -14
- package/lib/iife/index.js.map +1 -1
- package/lib/mockServiceWorker.js +1 -1
- package/package.json +3 -3
- package/src/core/delay.ts +13 -1
- package/src/core/handlers/GraphQLHandler.ts +1 -1
- package/src/core/index.ts +8 -3
- package/src/core/sse.ts +1 -1
- package/src/core/utils/internal/hasRefCounted.test.ts +16 -0
- package/src/core/utils/internal/hasRefCounted.ts +8 -0
- package/src/core/utils/internal/parseGraphQLRequest.ts +1 -1
- package/src/core/utils/internal/parseMultipartData.ts +3 -1
- package/src/core/ws/WebSocketIndexedDBClientStore.ts +1 -2
- package/src/core/ws.ts +2 -7
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import fs from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
-
import {
|
|
3
|
+
import { execFileSync } from 'node:child_process'
|
|
4
4
|
|
|
5
5
|
// When executing the "postinstall" script, the "process.cwd" equals
|
|
6
6
|
// the package directory, not the parent project where the package is installed.
|
|
@@ -23,7 +23,7 @@ function postInstall() {
|
|
|
23
23
|
* @note Call the "init" command directly. It will now copy the worker script
|
|
24
24
|
* to all saved paths in "msw.workerDirectory"
|
|
25
25
|
*/
|
|
26
|
-
|
|
26
|
+
execFileSync(process.execPath, [cliExecutable, 'init'], {
|
|
27
27
|
cwd: parentPackageCwd,
|
|
28
28
|
})
|
|
29
29
|
} catch (error) {
|
|
@@ -329,4 +329,4 @@ declare class HttpResponse<BodyType extends DefaultBodyType> extends FetchRespon
|
|
|
329
329
|
static formData(body?: FormData, init?: HttpResponseInit): HttpResponse<FormData>;
|
|
330
330
|
}
|
|
331
331
|
|
|
332
|
-
export { type AsyncResponseResolverReturnType as A,
|
|
332
|
+
export { type AsyncResponseResolverReturnType as A, type GraphQLHandlerNameSelector as B, type GraphQLHandlerInfo as C, type DefaultBodyType as D, type GraphQLRequestParsedResult as E, type GraphQLCustomPredicateResult as F, GraphQLHandler as G, HttpResponse as H, isDocumentNode as I, type JsonBodyType as J, type RequestHandlerInternalInfo as K, type RequestHandlerArgs as L, type MaybeAsyncResponseResolverReturnType as M, type RequestHandlerExecutionResult as N, bodyType as O, type ParsedGraphQLRequest as P, type DefaultUnsafeFetchResponse as Q, RequestHandler as R, type StrictRequest as S, type ResponseResolver as a, type ResponseResolverReturnType as b, type RequestHandlerOptions as c, type DefaultRequestMultipartBody as d, type ResponseResolverInfo as e, type GraphQLQuery as f, type GraphQLVariables as g, type GraphQLRequestBody as h, type GraphQLResponseBody as i, type GraphQLJsonRequestBody as j, type GraphQLOperationType as k, type GraphQLCustomPredicate as l, type ResponseResolutionContext as m, type HttpResponseInit as n, type StrictResponse as o, type GraphQLPredicate as p, type GraphQLResolverExtras as q, type RequestHandlerDefaultInfo as r, type HandlersExecutionResult as s, executeHandlers as t, type ParsedGraphQLQuery as u, parseDocumentNode as v, type GraphQLParsedOperationsMap as w, type GraphQLMultipartRequestBody as x, parseGraphQLRequest as y, type DocumentTypeDecoration as z };
|
|
@@ -329,4 +329,4 @@ declare class HttpResponse<BodyType extends DefaultBodyType> extends FetchRespon
|
|
|
329
329
|
static formData(body?: FormData, init?: HttpResponseInit): HttpResponse<FormData>;
|
|
330
330
|
}
|
|
331
331
|
|
|
332
|
-
export { type AsyncResponseResolverReturnType as A,
|
|
332
|
+
export { type AsyncResponseResolverReturnType as A, type GraphQLHandlerNameSelector as B, type GraphQLHandlerInfo as C, type DefaultBodyType as D, type GraphQLRequestParsedResult as E, type GraphQLCustomPredicateResult as F, GraphQLHandler as G, HttpResponse as H, isDocumentNode as I, type JsonBodyType as J, type RequestHandlerInternalInfo as K, type RequestHandlerArgs as L, type MaybeAsyncResponseResolverReturnType as M, type RequestHandlerExecutionResult as N, bodyType as O, type ParsedGraphQLRequest as P, type DefaultUnsafeFetchResponse as Q, RequestHandler as R, type StrictRequest as S, type ResponseResolver as a, type ResponseResolverReturnType as b, type RequestHandlerOptions as c, type DefaultRequestMultipartBody as d, type ResponseResolverInfo as e, type GraphQLQuery as f, type GraphQLVariables as g, type GraphQLRequestBody as h, type GraphQLResponseBody as i, type GraphQLJsonRequestBody as j, type GraphQLOperationType as k, type GraphQLCustomPredicate as l, type ResponseResolutionContext as m, type HttpResponseInit as n, type StrictResponse as o, type GraphQLPredicate as p, type GraphQLResolverExtras as q, type RequestHandlerDefaultInfo as r, type HandlersExecutionResult as s, executeHandlers as t, type ParsedGraphQLQuery as u, parseDocumentNode as v, type GraphQLParsedOperationsMap as w, type GraphQLMultipartRequestBody as x, parseGraphQLRequest as y, type DocumentTypeDecoration as z };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import '@mswjs/interceptors';
|
|
2
|
-
export {
|
|
2
|
+
export { Q as DefaultUnsafeFetchResponse, H as HttpResponse, n as HttpResponseInit, S as StrictRequest, o as StrictResponse, O as bodyType } from './HttpResponse-B9rGc56D.mjs';
|
|
3
3
|
import './typeUtils.mjs';
|
|
4
4
|
import './utils/internal/isIterable.mjs';
|
|
5
5
|
import 'graphql';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import '@mswjs/interceptors';
|
|
2
|
-
export {
|
|
2
|
+
export { Q as DefaultUnsafeFetchResponse, H as HttpResponse, n as HttpResponseInit, S as StrictRequest, o as StrictResponse, O as bodyType } from './HttpResponse-Dz84tqeA.js';
|
|
3
3
|
import './typeUtils.js';
|
|
4
4
|
import './utils/internal/isIterable.js';
|
|
5
5
|
import 'graphql';
|
package/lib/core/SetupApi.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventMap, Emitter } from 'strict-event-emitter';
|
|
2
|
-
import { R as RequestHandler } from './HttpResponse-
|
|
2
|
+
import { R as RequestHandler } from './HttpResponse-B9rGc56D.mjs';
|
|
3
3
|
import { LifeCycleEventEmitter } from './sharedOptions.mjs';
|
|
4
4
|
import { Disposable } from './utils/internal/Disposable.mjs';
|
|
5
5
|
import { WebSocketHandler } from './handlers/WebSocketHandler.mjs';
|
package/lib/core/SetupApi.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventMap, Emitter } from 'strict-event-emitter';
|
|
2
|
-
import { R as RequestHandler } from './HttpResponse-
|
|
2
|
+
import { R as RequestHandler } from './HttpResponse-Dz84tqeA.js';
|
|
3
3
|
import { LifeCycleEventEmitter } from './sharedOptions.js';
|
|
4
4
|
import { Disposable } from './utils/internal/Disposable.js';
|
|
5
5
|
import { WebSocketHandler } from './handlers/WebSocketHandler.js';
|
package/lib/core/delay.js
CHANGED
|
@@ -26,6 +26,7 @@ __export(delay_exports, {
|
|
|
26
26
|
});
|
|
27
27
|
module.exports = __toCommonJS(delay_exports);
|
|
28
28
|
var import_is_node_process = require("is-node-process");
|
|
29
|
+
var import_hasRefCounted = require("./utils/internal/hasRefCounted");
|
|
29
30
|
const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
|
|
30
31
|
const MIN_SERVER_RESPONSE_TIME = 100;
|
|
31
32
|
const MAX_SERVER_RESPONSE_TIME = 400;
|
|
@@ -66,6 +67,11 @@ async function delay(durationOrMode) {
|
|
|
66
67
|
}
|
|
67
68
|
delayTime = durationOrMode;
|
|
68
69
|
}
|
|
69
|
-
return new Promise((resolve) =>
|
|
70
|
+
return new Promise((resolve) => {
|
|
71
|
+
const timeoutId = setTimeout(resolve, delayTime);
|
|
72
|
+
if (delayTime === SET_TIMEOUT_MAX_ALLOWED_INT && (0, import_is_node_process.isNodeProcess)() && (0, import_hasRefCounted.hasRefCounted)(timeoutId)) {
|
|
73
|
+
timeoutId.unref();
|
|
74
|
+
}
|
|
75
|
+
});
|
|
70
76
|
}
|
|
71
77
|
//# sourceMappingURL=delay.js.map
|
package/lib/core/delay.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/delay.ts"],"sourcesContent":["import { isNodeProcess } from 'is-node-process'\n\nexport const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647\nexport const MIN_SERVER_RESPONSE_TIME = 100\nexport const MAX_SERVER_RESPONSE_TIME = 400\nexport const NODE_SERVER_RESPONSE_TIME = 5\n\nfunction getRealisticResponseTime(): number {\n if (isNodeProcess()) {\n return NODE_SERVER_RESPONSE_TIME\n }\n\n return Math.floor(\n Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) +\n MIN_SERVER_RESPONSE_TIME,\n )\n}\n\nexport type DelayMode = 'real' | 'infinite'\n\n/**\n * Delays the response by the given duration (ms).\n *\n * @example\n * await delay() // emulate realistic server response time\n * await delay(1200) // delay response by 1200ms\n * await delay('infinite') // delay response infinitely\n *\n * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference}\n */\nexport async function delay(\n durationOrMode?: DelayMode | number,\n): Promise<void> {\n let delayTime: number\n\n if (typeof durationOrMode === 'string') {\n switch (durationOrMode) {\n case 'infinite': {\n // Using `Infinity` as a delay value executes the response timeout immediately.\n // Instead, use the maximum allowed integer for `setTimeout`.\n delayTime = SET_TIMEOUT_MAX_ALLOWED_INT\n break\n }\n case 'real': {\n delayTime = getRealisticResponseTime()\n break\n }\n default: {\n throw new Error(\n `Failed to delay a response: unknown delay mode \"${durationOrMode}\". Please make sure you provide one of the supported modes (\"real\", \"infinite\") or a number.`,\n )\n }\n }\n } else if (typeof durationOrMode === 'undefined') {\n // Use random realistic server response time when no explicit delay duration was provided.\n delayTime = getRealisticResponseTime()\n } else {\n // Guard against passing values like `Infinity` or `Number.MAX_VALUE`\n // as the response delay duration. They don't produce the result you may expect.\n if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {\n throw new Error(\n `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.`,\n )\n }\n\n delayTime = durationOrMode\n }\n\n return new Promise((resolve) => setTimeout(resolve, delayTime))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAA8B;AAEvB,MAAM,8BAA8B;AACpC,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAEzC,SAAS,2BAAmC;AAC1C,UAAI,sCAAc,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AAAA,IACV,KAAK,OAAO,KAAK,2BAA2B,4BAC1C;AAAA,EACJ;AACF;AAcA,eAAsB,MACpB,gBACe;AACf,MAAI;AAEJ,MAAI,OAAO,mBAAmB,UAAU;AACtC,YAAQ,gBAAgB;AAAA,MACtB,KAAK,YAAY;AAGf,oBAAY;AACZ;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,oBAAY,yBAAyB;AACrC;AAAA,MACF;AAAA,MACA,SAAS;AACP,cAAM,IAAI;AAAA,UACR,mDAAmD,cAAc;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,OAAO,mBAAmB,aAAa;AAEhD,gBAAY,yBAAyB;AAAA,EACvC,OAAO;AAGL,QAAI,iBAAiB,6BAA6B;AAChD,YAAM,IAAI;AAAA,QACR,wDAAwD,cAAc,4DAA4D,2BAA2B;AAAA,MAC/J;AAAA,IACF;AAEA,gBAAY;AAAA,EACd;AAEA,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,SAAS,CAAC;
|
|
1
|
+
{"version":3,"sources":["../../src/core/delay.ts"],"sourcesContent":["import { isNodeProcess } from 'is-node-process'\nimport { hasRefCounted } from './utils/internal/hasRefCounted'\n\nexport const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647\nexport const MIN_SERVER_RESPONSE_TIME = 100\nexport const MAX_SERVER_RESPONSE_TIME = 400\nexport const NODE_SERVER_RESPONSE_TIME = 5\n\nfunction getRealisticResponseTime(): number {\n if (isNodeProcess()) {\n return NODE_SERVER_RESPONSE_TIME\n }\n\n return Math.floor(\n Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) +\n MIN_SERVER_RESPONSE_TIME,\n )\n}\n\nexport type DelayMode = 'real' | 'infinite'\n\n/**\n * Delays the response by the given duration (ms).\n *\n * @example\n * await delay() // emulate realistic server response time\n * await delay(1200) // delay response by 1200ms\n * await delay('infinite') // delay response infinitely\n *\n * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference}\n */\nexport async function delay(\n durationOrMode?: DelayMode | number,\n): Promise<void> {\n let delayTime: number\n\n if (typeof durationOrMode === 'string') {\n switch (durationOrMode) {\n case 'infinite': {\n // Using `Infinity` as a delay value executes the response timeout immediately.\n // Instead, use the maximum allowed integer for `setTimeout`.\n delayTime = SET_TIMEOUT_MAX_ALLOWED_INT\n break\n }\n case 'real': {\n delayTime = getRealisticResponseTime()\n break\n }\n default: {\n throw new Error(\n `Failed to delay a response: unknown delay mode \"${durationOrMode}\". Please make sure you provide one of the supported modes (\"real\", \"infinite\") or a number.`,\n )\n }\n }\n } else if (typeof durationOrMode === 'undefined') {\n // Use random realistic server response time when no explicit delay duration was provided.\n delayTime = getRealisticResponseTime()\n } else {\n // Guard against passing values like `Infinity` or `Number.MAX_VALUE`\n // as the response delay duration. They don't produce the result you may expect.\n if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {\n throw new Error(\n `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.`,\n )\n }\n\n delayTime = durationOrMode\n }\n\n return new Promise((resolve) => {\n const timeoutId = setTimeout(resolve, delayTime)\n\n if (\n delayTime === SET_TIMEOUT_MAX_ALLOWED_INT &&\n isNodeProcess() &&\n hasRefCounted(timeoutId)\n ) {\n // Prevent the process from hanging if this is the only active ref.\n timeoutId.unref()\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAA8B;AAC9B,2BAA8B;AAEvB,MAAM,8BAA8B;AACpC,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAEzC,SAAS,2BAAmC;AAC1C,UAAI,sCAAc,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AAAA,IACV,KAAK,OAAO,KAAK,2BAA2B,4BAC1C;AAAA,EACJ;AACF;AAcA,eAAsB,MACpB,gBACe;AACf,MAAI;AAEJ,MAAI,OAAO,mBAAmB,UAAU;AACtC,YAAQ,gBAAgB;AAAA,MACtB,KAAK,YAAY;AAGf,oBAAY;AACZ;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,oBAAY,yBAAyB;AACrC;AAAA,MACF;AAAA,MACA,SAAS;AACP,cAAM,IAAI;AAAA,UACR,mDAAmD,cAAc;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,OAAO,mBAAmB,aAAa;AAEhD,gBAAY,yBAAyB;AAAA,EACvC,OAAO;AAGL,QAAI,iBAAiB,6BAA6B;AAChD,YAAM,IAAI;AAAA,QACR,wDAAwD,cAAc,4DAA4D,2BAA2B;AAAA,MAC/J;AAAA,IACF;AAEA,gBAAY;AAAA,EACd;AAEA,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,YAAY,WAAW,SAAS,SAAS;AAE/C,QACE,cAAc,mCACd,sCAAc,SACd,oCAAc,SAAS,GACvB;AAEA,gBAAU,MAAM;AAAA,IAClB;AAAA,EACF,CAAC;AACH;","names":[]}
|
package/lib/core/delay.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isNodeProcess } from "is-node-process";
|
|
2
|
+
import { hasRefCounted } from './utils/internal/hasRefCounted.mjs';
|
|
2
3
|
const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647;
|
|
3
4
|
const MIN_SERVER_RESPONSE_TIME = 100;
|
|
4
5
|
const MAX_SERVER_RESPONSE_TIME = 400;
|
|
@@ -39,7 +40,12 @@ async function delay(durationOrMode) {
|
|
|
39
40
|
}
|
|
40
41
|
delayTime = durationOrMode;
|
|
41
42
|
}
|
|
42
|
-
return new Promise((resolve) =>
|
|
43
|
+
return new Promise((resolve) => {
|
|
44
|
+
const timeoutId = setTimeout(resolve, delayTime);
|
|
45
|
+
if (delayTime === SET_TIMEOUT_MAX_ALLOWED_INT && isNodeProcess() && hasRefCounted(timeoutId)) {
|
|
46
|
+
timeoutId.unref();
|
|
47
|
+
}
|
|
48
|
+
});
|
|
43
49
|
}
|
|
44
50
|
export {
|
|
45
51
|
MAX_SERVER_RESPONSE_TIME,
|
package/lib/core/delay.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/delay.ts"],"sourcesContent":["import { isNodeProcess } from 'is-node-process'\n\nexport const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647\nexport const MIN_SERVER_RESPONSE_TIME = 100\nexport const MAX_SERVER_RESPONSE_TIME = 400\nexport const NODE_SERVER_RESPONSE_TIME = 5\n\nfunction getRealisticResponseTime(): number {\n if (isNodeProcess()) {\n return NODE_SERVER_RESPONSE_TIME\n }\n\n return Math.floor(\n Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) +\n MIN_SERVER_RESPONSE_TIME,\n )\n}\n\nexport type DelayMode = 'real' | 'infinite'\n\n/**\n * Delays the response by the given duration (ms).\n *\n * @example\n * await delay() // emulate realistic server response time\n * await delay(1200) // delay response by 1200ms\n * await delay('infinite') // delay response infinitely\n *\n * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference}\n */\nexport async function delay(\n durationOrMode?: DelayMode | number,\n): Promise<void> {\n let delayTime: number\n\n if (typeof durationOrMode === 'string') {\n switch (durationOrMode) {\n case 'infinite': {\n // Using `Infinity` as a delay value executes the response timeout immediately.\n // Instead, use the maximum allowed integer for `setTimeout`.\n delayTime = SET_TIMEOUT_MAX_ALLOWED_INT\n break\n }\n case 'real': {\n delayTime = getRealisticResponseTime()\n break\n }\n default: {\n throw new Error(\n `Failed to delay a response: unknown delay mode \"${durationOrMode}\". Please make sure you provide one of the supported modes (\"real\", \"infinite\") or a number.`,\n )\n }\n }\n } else if (typeof durationOrMode === 'undefined') {\n // Use random realistic server response time when no explicit delay duration was provided.\n delayTime = getRealisticResponseTime()\n } else {\n // Guard against passing values like `Infinity` or `Number.MAX_VALUE`\n // as the response delay duration. They don't produce the result you may expect.\n if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {\n throw new Error(\n `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.`,\n )\n }\n\n delayTime = durationOrMode\n }\n\n return new Promise((resolve) => setTimeout(resolve, delayTime))\n}\n"],"mappings":"AAAA,SAAS,qBAAqB;AAEvB,MAAM,8BAA8B;AACpC,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAEzC,SAAS,2BAAmC;AAC1C,MAAI,cAAc,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AAAA,IACV,KAAK,OAAO,KAAK,2BAA2B,4BAC1C;AAAA,EACJ;AACF;AAcA,eAAsB,MACpB,gBACe;AACf,MAAI;AAEJ,MAAI,OAAO,mBAAmB,UAAU;AACtC,YAAQ,gBAAgB;AAAA,MACtB,KAAK,YAAY;AAGf,oBAAY;AACZ;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,oBAAY,yBAAyB;AACrC;AAAA,MACF;AAAA,MACA,SAAS;AACP,cAAM,IAAI;AAAA,UACR,mDAAmD,cAAc;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,OAAO,mBAAmB,aAAa;AAEhD,gBAAY,yBAAyB;AAAA,EACvC,OAAO;AAGL,QAAI,iBAAiB,6BAA6B;AAChD,YAAM,IAAI;AAAA,QACR,wDAAwD,cAAc,4DAA4D,2BAA2B;AAAA,MAC/J;AAAA,IACF;AAEA,gBAAY;AAAA,EACd;AAEA,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,SAAS,CAAC;
|
|
1
|
+
{"version":3,"sources":["../../src/core/delay.ts"],"sourcesContent":["import { isNodeProcess } from 'is-node-process'\nimport { hasRefCounted } from './utils/internal/hasRefCounted'\n\nexport const SET_TIMEOUT_MAX_ALLOWED_INT = 2147483647\nexport const MIN_SERVER_RESPONSE_TIME = 100\nexport const MAX_SERVER_RESPONSE_TIME = 400\nexport const NODE_SERVER_RESPONSE_TIME = 5\n\nfunction getRealisticResponseTime(): number {\n if (isNodeProcess()) {\n return NODE_SERVER_RESPONSE_TIME\n }\n\n return Math.floor(\n Math.random() * (MAX_SERVER_RESPONSE_TIME - MIN_SERVER_RESPONSE_TIME) +\n MIN_SERVER_RESPONSE_TIME,\n )\n}\n\nexport type DelayMode = 'real' | 'infinite'\n\n/**\n * Delays the response by the given duration (ms).\n *\n * @example\n * await delay() // emulate realistic server response time\n * await delay(1200) // delay response by 1200ms\n * await delay('infinite') // delay response infinitely\n *\n * @see {@link https://mswjs.io/docs/api/delay `delay()` API reference}\n */\nexport async function delay(\n durationOrMode?: DelayMode | number,\n): Promise<void> {\n let delayTime: number\n\n if (typeof durationOrMode === 'string') {\n switch (durationOrMode) {\n case 'infinite': {\n // Using `Infinity` as a delay value executes the response timeout immediately.\n // Instead, use the maximum allowed integer for `setTimeout`.\n delayTime = SET_TIMEOUT_MAX_ALLOWED_INT\n break\n }\n case 'real': {\n delayTime = getRealisticResponseTime()\n break\n }\n default: {\n throw new Error(\n `Failed to delay a response: unknown delay mode \"${durationOrMode}\". Please make sure you provide one of the supported modes (\"real\", \"infinite\") or a number.`,\n )\n }\n }\n } else if (typeof durationOrMode === 'undefined') {\n // Use random realistic server response time when no explicit delay duration was provided.\n delayTime = getRealisticResponseTime()\n } else {\n // Guard against passing values like `Infinity` or `Number.MAX_VALUE`\n // as the response delay duration. They don't produce the result you may expect.\n if (durationOrMode > SET_TIMEOUT_MAX_ALLOWED_INT) {\n throw new Error(\n `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.`,\n )\n }\n\n delayTime = durationOrMode\n }\n\n return new Promise((resolve) => {\n const timeoutId = setTimeout(resolve, delayTime)\n\n if (\n delayTime === SET_TIMEOUT_MAX_ALLOWED_INT &&\n isNodeProcess() &&\n hasRefCounted(timeoutId)\n ) {\n // Prevent the process from hanging if this is the only active ref.\n timeoutId.unref()\n }\n })\n}\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAEvB,MAAM,8BAA8B;AACpC,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAEzC,SAAS,2BAAmC;AAC1C,MAAI,cAAc,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,SAAO,KAAK;AAAA,IACV,KAAK,OAAO,KAAK,2BAA2B,4BAC1C;AAAA,EACJ;AACF;AAcA,eAAsB,MACpB,gBACe;AACf,MAAI;AAEJ,MAAI,OAAO,mBAAmB,UAAU;AACtC,YAAQ,gBAAgB;AAAA,MACtB,KAAK,YAAY;AAGf,oBAAY;AACZ;AAAA,MACF;AAAA,MACA,KAAK,QAAQ;AACX,oBAAY,yBAAyB;AACrC;AAAA,MACF;AAAA,MACA,SAAS;AACP,cAAM,IAAI;AAAA,UACR,mDAAmD,cAAc;AAAA,QACnE;AAAA,MACF;AAAA,IACF;AAAA,EACF,WAAW,OAAO,mBAAmB,aAAa;AAEhD,gBAAY,yBAAyB;AAAA,EACvC,OAAO;AAGL,QAAI,iBAAiB,6BAA6B;AAChD,YAAM,IAAI;AAAA,QACR,wDAAwD,cAAc,4DAA4D,2BAA2B;AAAA,MAC/J;AAAA,IACF;AAEA,gBAAY;AAAA,EACd;AAEA,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,YAAY,WAAW,SAAS,SAAS;AAE/C,QACE,cAAc,+BACd,cAAc,KACd,cAAc,SAAS,GACvB;AAEA,gBAAU,MAAM;AAAA,IAClB;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as RequestHandler, m as ResponseResolutionContext } from './HttpResponse-
|
|
1
|
+
import { R as RequestHandler, m as ResponseResolutionContext } from './HttpResponse-B9rGc56D.mjs';
|
|
2
2
|
import '@mswjs/interceptors';
|
|
3
3
|
import './utils/internal/isIterable.mjs';
|
|
4
4
|
import './typeUtils.mjs';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as RequestHandler, m as ResponseResolutionContext } from './HttpResponse-
|
|
1
|
+
import { R as RequestHandler, m as ResponseResolutionContext } from './HttpResponse-Dz84tqeA.js';
|
|
2
2
|
import '@mswjs/interceptors';
|
|
3
3
|
import './utils/internal/isIterable.js';
|
|
4
4
|
import './typeUtils.js';
|
package/lib/core/graphql.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as GraphQLQuery, g as GraphQLVariables,
|
|
1
|
+
import { f as GraphQLQuery, g as GraphQLVariables, p as GraphQLPredicate, a as ResponseResolver, q as GraphQLResolverExtras, i as GraphQLResponseBody, c as RequestHandlerOptions, G as GraphQLHandler } from './HttpResponse-B9rGc56D.mjs';
|
|
2
2
|
import { Path } from './utils/matching/matchRequestUrl.mjs';
|
|
3
3
|
import '@mswjs/interceptors';
|
|
4
4
|
import './utils/internal/isIterable.mjs';
|
package/lib/core/graphql.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as GraphQLQuery, g as GraphQLVariables,
|
|
1
|
+
import { f as GraphQLQuery, g as GraphQLVariables, p as GraphQLPredicate, a as ResponseResolver, q as GraphQLResolverExtras, i as GraphQLResponseBody, c as RequestHandlerOptions, G as GraphQLHandler } from './HttpResponse-Dz84tqeA.js';
|
|
2
2
|
import { Path } from './utils/matching/matchRequestUrl.js';
|
|
3
3
|
import '@mswjs/interceptors';
|
|
4
4
|
import './utils/internal/isIterable.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import 'graphql';
|
|
2
|
-
export {
|
|
2
|
+
export { z as DocumentTypeDecoration, l as GraphQLCustomPredicate, F as GraphQLCustomPredicateResult, G as GraphQLHandler, C as GraphQLHandlerInfo, B as GraphQLHandlerNameSelector, j as GraphQLJsonRequestBody, k as GraphQLOperationType, p as GraphQLPredicate, f as GraphQLQuery, h as GraphQLRequestBody, E as GraphQLRequestParsedResult, q as GraphQLResolverExtras, i as GraphQLResponseBody, g as GraphQLVariables, I as isDocumentNode } from '../HttpResponse-B9rGc56D.mjs';
|
|
3
3
|
import '../utils/matching/matchRequestUrl.mjs';
|
|
4
4
|
import '@mswjs/interceptors';
|
|
5
5
|
import '../utils/internal/isIterable.mjs';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import 'graphql';
|
|
2
|
-
export {
|
|
2
|
+
export { z as DocumentTypeDecoration, l as GraphQLCustomPredicate, F as GraphQLCustomPredicateResult, G as GraphQLHandler, C as GraphQLHandlerInfo, B as GraphQLHandlerNameSelector, j as GraphQLJsonRequestBody, k as GraphQLOperationType, p as GraphQLPredicate, f as GraphQLQuery, h as GraphQLRequestBody, E as GraphQLRequestParsedResult, q as GraphQLResolverExtras, i as GraphQLResponseBody, g as GraphQLVariables, I as isDocumentNode } from '../HttpResponse-Dz84tqeA.js';
|
|
3
3
|
import '../utils/matching/matchRequestUrl.js';
|
|
4
4
|
import '@mswjs/interceptors';
|
|
5
5
|
import '../utils/internal/isIterable.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import {\n parse,\n type DocumentNode,\n type GraphQLError,\n type OperationTypeNode,\n} from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n ParsedGraphQLQuery,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { invariant } from 'outvariant'\n\nexport interface DocumentTypeDecoration<\n Result = { [key: string]: any },\n Variables = { [key: string]: any },\n> {\n __apiType?: (variables: Variables) => Result\n __resultType?: Result\n __variablesType?: Variables\n}\n\nexport type GraphQLOperationType = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any> | null\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: GraphQLOperationType\n operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n extensions?: Record<string, any>\n }\n | null\n | undefined\n\nexport type GraphQLCustomPredicate = (args: {\n request: Request\n query: string\n operationType: GraphQLOperationType\n operationName: string\n variables: GraphQLVariables\n cookies: Record<string, string>\n}) => GraphQLCustomPredicateResult | Promise<GraphQLCustomPredicateResult>\n\nexport type GraphQLCustomPredicateResult = boolean | { matches: boolean }\n\nexport type GraphQLPredicate<Query = any, Variables = any> =\n | GraphQLHandlerNameSelector\n | DocumentTypeDecoration<Query, Variables>\n | GraphQLCustomPredicate\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nfunction isDocumentTypeDecoration(\n value: any,\n): value is DocumentTypeDecoration<any, any> {\n return value instanceof String\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n static #parseOperationName(\n predicate: GraphQLPredicate,\n operationType: GraphQLOperationType,\n ): GraphQLHandlerInfo['operationName'] {\n const getOperationName = (node: ParsedGraphQLQuery): string => {\n invariant(\n node.operationType === operationType,\n 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"%s\" but got \"%s\").',\n operationType,\n node.operationType,\n )\n\n invariant(\n node.operationName,\n 'Failed to create a GraphQL handler: provided a DocumentNode without operation name',\n )\n\n return node.operationName\n }\n\n if (isDocumentNode(predicate)) {\n return getOperationName(parseDocumentNode(predicate))\n }\n\n if (isDocumentTypeDecoration(predicate)) {\n const documentNode = parse(predicate.toString())\n\n invariant(\n isDocumentNode(documentNode),\n 'Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode',\n predicate,\n )\n\n return getOperationName(parseDocumentNode(documentNode))\n }\n\n return predicate\n }\n\n constructor(\n operationType: GraphQLOperationType,\n predicate: GraphQLPredicate,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const operationName = GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n )\n\n const displayOperationName =\n typeof operationName === 'function' ? '[custom predicate]' : operationName\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ''} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n ),\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return {\n match,\n cookies,\n }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return {\n match,\n cookies,\n }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider 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/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n /**\n * Check if the operation name matches the outgoing GraphQL request.\n * @note Unlike the HTTP handler, the custom predicate functions are invoked\n * during predicate, not parsing, because GraphQL request parsing happens first,\n * and non-GraphQL requests are filtered out automatically.\n */\n const hasMatchingOperationName = await this.matchOperationName({\n request: args.request,\n parsedResult: args.parsedResult,\n })\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n private async matchOperationName(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (typeof this.info.operationName === 'function') {\n const customPredicateResult = await this.info.operationName({\n request: args.request,\n ...this.extendResolverArgs({\n request: args.request,\n parsedResult: args.parsedResult,\n }),\n })\n\n /**\n * @note Keep the { matches } signature in case we decide to support path parameters\n * in GraphQL handlers. If that happens, the custom predicate would have to be moved\n * to the parsing phase, the same as we have for the HttpHandler, and the user will\n * have a possibility to return parsed path parameters from the custom predicate.\n */\n return typeof customPredicateResult === 'boolean'\n ? customPredicateResult\n : customPredicateResult.matches\n }\n\n if (this.info.operationName instanceof RegExp) {\n return this.info.operationName.test(args.parsedResult.operationName || '')\n }\n\n return args.parsedResult.operationName === this.info.operationName\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationType: args.parsedResult.operationType!,\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAKO;AACP,4BAMO;AACP,0BAA6B;AAC7B,gCAAm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AmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAEhD,YAAQ;AAAA,MACN,yBAAS;AAAA,QACP,OAAG,kCAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AACvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import {\n parse,\n type DocumentNode,\n type GraphQLError,\n type OperationTypeNode,\n} from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n ParsedGraphQLQuery,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { invariant } from 'outvariant'\n\nexport interface DocumentTypeDecoration<\n Result = { [key: string]: any },\n Variables = { [key: string]: any },\n> {\n __apiType?: (variables: Variables) => Result\n __resultType?: Result\n __variablesType?: Variables\n}\n\nexport type GraphQLOperationType = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any> | null\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: GraphQLOperationType\n operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n extensions?: Record<string, any>\n }\n | null\n | undefined\n\nexport type GraphQLCustomPredicate = (args: {\n request: Request\n query: string\n operationType: GraphQLOperationType\n operationName: string\n variables: GraphQLVariables\n cookies: Record<string, string>\n}) => GraphQLCustomPredicateResult | Promise<GraphQLCustomPredicateResult>\n\nexport type GraphQLCustomPredicateResult = boolean | { matches: boolean }\n\nexport type GraphQLPredicate<Query = any, Variables = any> =\n | GraphQLHandlerNameSelector\n | DocumentTypeDecoration<Query, Variables>\n | GraphQLCustomPredicate\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nfunction isDocumentTypeDecoration(\n value: unknown,\n): value is DocumentTypeDecoration<any, any> {\n return value instanceof String\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n static #parseOperationName(\n predicate: GraphQLPredicate,\n operationType: GraphQLOperationType,\n ): GraphQLHandlerInfo['operationName'] {\n const getOperationName = (node: ParsedGraphQLQuery): string => {\n invariant(\n node.operationType === operationType,\n 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"%s\" but got \"%s\").',\n operationType,\n node.operationType,\n )\n\n invariant(\n node.operationName,\n 'Failed to create a GraphQL handler: provided a DocumentNode without operation name',\n )\n\n return node.operationName\n }\n\n if (isDocumentNode(predicate)) {\n return getOperationName(parseDocumentNode(predicate))\n }\n\n if (isDocumentTypeDecoration(predicate)) {\n const documentNode = parse(predicate.toString())\n\n invariant(\n isDocumentNode(documentNode),\n 'Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode',\n predicate,\n )\n\n return getOperationName(parseDocumentNode(documentNode))\n }\n\n return predicate\n }\n\n constructor(\n operationType: GraphQLOperationType,\n predicate: GraphQLPredicate,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const operationName = GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n )\n\n const displayOperationName =\n typeof operationName === 'function' ? '[custom predicate]' : operationName\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ''} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n ),\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return {\n match,\n cookies,\n }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return {\n match,\n cookies,\n }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider 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/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n /**\n * Check if the operation name matches the outgoing GraphQL request.\n * @note Unlike the HTTP handler, the custom predicate functions are invoked\n * during predicate, not parsing, because GraphQL request parsing happens first,\n * and non-GraphQL requests are filtered out automatically.\n */\n const hasMatchingOperationName = await this.matchOperationName({\n request: args.request,\n parsedResult: args.parsedResult,\n })\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n private async matchOperationName(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (typeof this.info.operationName === 'function') {\n const customPredicateResult = await this.info.operationName({\n request: args.request,\n ...this.extendResolverArgs({\n request: args.request,\n parsedResult: args.parsedResult,\n }),\n })\n\n /**\n * @note Keep the { matches } signature in case we decide to support path parameters\n * in GraphQL handlers. If that happens, the custom predicate would have to be moved\n * to the parsing phase, the same as we have for the HttpHandler, and the user will\n * have a possibility to return parsed path parameters from the custom predicate.\n */\n return typeof customPredicateResult === 'boolean'\n ? customPredicateResult\n : customPredicateResult.matches\n }\n\n if (this.info.operationName instanceof RegExp) {\n return this.info.operationName.test(args.parsedResult.operationName || '')\n }\n\n return args.parsedResult.operationName === this.info.operationName\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationType: args.parsedResult.operationType!,\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAKO;AACP,4BAMO;AACP,0BAA6B;AAC7B,gCAAmC;AACnC,8BAAiC;AACjC,+BAAkC;AAClC,6BAA6C;AAC7C,iCAMO;AACP,yBAA4B;AAC5B,sBAAyB;AACzB,+BAAqC;AACrC,wBAA0B;AAmFnB,SAAS,eACd,OACuB;AACvB,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,UAAU,YAAY,UAAU,SAAS,iBAAiB;AAC1E;AAEA,SAAS,yBACP,OAC2C;AAC3C,SAAO,iBAAiB;AAC1B;AAEO,MAAM,uBAAuB,qCAIlC;AAAA,EACQ;AAAA,EAER,OAAO,qBAAqB,oBAAI,QAG9B;AAAA,EAEF,OAAO,oBACL,WACA,eACqC;AACrC,UAAM,mBAAmB,CAAC,SAAqC;AAC7D;AAAA,QACE,KAAK,kBAAkB;AAAA,QACvB;AAAA,QACA;AAAA,QACA,KAAK;AAAA,MACP;AAEA;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AAEA,aAAO,KAAK;AAAA,IACd;AAEA,QAAI,eAAe,SAAS,GAAG;AAC7B,aAAO,qBAAiB,8CAAkB,SAAS,CAAC;AAAA,IACtD;AAEA,QAAI,yBAAyB,SAAS,GAAG;AACvC,YAAM,mBAAe,sBAAM,UAAU,SAAS,CAAC;AAE/C;AAAA,QACE,eAAe,YAAY;AAAA,QAC3B;AAAA,QACA;AAAA,MACF;AAEA,aAAO,qBAAiB,8CAAkB,YAAY,CAAC;AAAA,IACzD;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,YACE,eACA,WACA,UACA,UACA,SACA;AACA,UAAM,gBAAgB,eAAe;AAAA,MACnC;AAAA,MACA;AAAA,IACF;AAEA,UAAM,uBACJ,OAAO,kBAAkB,aAAa,u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AK,aAAa;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,MAAM,IAAI,MAIP;AACD,UAAM,gBAAgB,UAAM,0CAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,UAAM,4CAAkB,KAAK,QAAQ;AAC5D,UAAM,kBAAc,8CAAmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAEhD,YAAQ;AAAA,MACN,yBAAS;AAAA,QACP,OAAG,kCAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AACvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import {\n parse,\n type DocumentNode,\n type GraphQLError,\n type OperationTypeNode,\n} from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n ParsedGraphQLQuery,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { invariant } from 'outvariant'\n\nexport interface DocumentTypeDecoration<\n Result = { [key: string]: any },\n Variables = { [key: string]: any },\n> {\n __apiType?: (variables: Variables) => Result\n __resultType?: Result\n __variablesType?: Variables\n}\n\nexport type GraphQLOperationType = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any> | null\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: GraphQLOperationType\n operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n extensions?: Record<string, any>\n }\n | null\n | undefined\n\nexport type GraphQLCustomPredicate = (args: {\n request: Request\n query: string\n operationType: GraphQLOperationType\n operationName: string\n variables: GraphQLVariables\n cookies: Record<string, string>\n}) => GraphQLCustomPredicateResult | Promise<GraphQLCustomPredicateResult>\n\nexport type GraphQLCustomPredicateResult = boolean | { matches: boolean }\n\nexport type GraphQLPredicate<Query = any, Variables = any> =\n | GraphQLHandlerNameSelector\n | DocumentTypeDecoration<Query, Variables>\n | GraphQLCustomPredicate\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nfunction isDocumentTypeDecoration(\n value: any,\n): value is DocumentTypeDecoration<any, any> {\n return value instanceof String\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n static #parseOperationName(\n predicate: GraphQLPredicate,\n operationType: GraphQLOperationType,\n ): GraphQLHandlerInfo['operationName'] {\n const getOperationName = (node: ParsedGraphQLQuery): string => {\n invariant(\n node.operationType === operationType,\n 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"%s\" but got \"%s\").',\n operationType,\n node.operationType,\n )\n\n invariant(\n node.operationName,\n 'Failed to create a GraphQL handler: provided a DocumentNode without operation name',\n )\n\n return node.operationName\n }\n\n if (isDocumentNode(predicate)) {\n return getOperationName(parseDocumentNode(predicate))\n }\n\n if (isDocumentTypeDecoration(predicate)) {\n const documentNode = parse(predicate.toString())\n\n invariant(\n isDocumentNode(documentNode),\n 'Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode',\n predicate,\n )\n\n return getOperationName(parseDocumentNode(documentNode))\n }\n\n return predicate\n }\n\n constructor(\n operationType: GraphQLOperationType,\n predicate: GraphQLPredicate,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const operationName = GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n )\n\n const displayOperationName =\n typeof operationName === 'function' ? '[custom predicate]' : operationName\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ''} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n ),\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return {\n match,\n cookies,\n }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return {\n match,\n cookies,\n }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider 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/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n /**\n * Check if the operation name matches the outgoing GraphQL request.\n * @note Unlike the HTTP handler, the custom predicate functions are invoked\n * during predicate, not parsing, because GraphQL request parsing happens first,\n * and non-GraphQL requests are filtered out automatically.\n */\n const hasMatchingOperationName = await this.matchOperationName({\n request: args.request,\n parsedResult: args.parsedResult,\n })\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n private async matchOperationName(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (typeof this.info.operationName === 'function') {\n const customPredicateResult = await this.info.operationName({\n request: args.request,\n ...this.extendResolverArgs({\n request: args.request,\n parsedResult: args.parsedResult,\n }),\n })\n\n /**\n * @note Keep the { matches } signature in case we decide to support path parameters\n * in GraphQL handlers. If that happens, the custom predicate would have to be moved\n * to the parsing phase, the same as we have for the HttpHandler, and the user will\n * have a possibility to return parsed path parameters from the custom predicate.\n */\n return typeof customPredicateResult === 'boolean'\n ? customPredicateResult\n : customPredicateResult.matches\n }\n\n if (this.info.operationName instanceof RegExp) {\n return this.info.operationName.test(args.parsedResult.operationName || '')\n }\n\n return args.parsedResult.operationName === this.info.operationName\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationType: args.parsedResult.operationType!,\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":"AAAA;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EAEE;AAAA,OAIK;AACP,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAgB,uBAA6B;AAC7C;AAAA,EAGE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,SAAS,iBAAiB;AAmFnB,SAAS,eACd,OACuB;AACvB,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,UAAU,YAAY,UAAU,SAAS,iBAAiB;AAC1E;AAEA,SAAS,yBACP,OAC2C;AAC3C,SAAO,iBAAiB;AAC1B;AAEO,MAAM,uBAAuB,eAIlC;AAAA,EACQ;AAAA,EAER,OAAO,qBAAqB,oBAAI,QAG9B;AAAA,EAEF,OAAO,oBACL,WACA,eACqC;AACrC,UAAM,mBAAmB,CAAC,SAAqC;AAC7D;AAAA,QACE,KAAK,kBAAkB;AAAA,QACvB;AAAA,QACA;AAAA,QACA,KAAK;AAAA,MACP;AAEA;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MACF;AAEA,aAAO,KAAK;AAAA,IACd;AAEA,QAAI,eAAe,SAAS,GAAG;AAC7B,aAAO,iBAAiB,kBAAkB,SAAS,CAAC;AAAA,IACtD;AAEA,QAAI,yBAAyB,SAAS,GAAG;AACvC,YAAM,eAAe,MAAM,UAAU,SAAS,CAAC;AAE/C;AAAA,QACE,eAAe,Y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O,KAAK,aAAa,kBAAkB,KAAK,KAAK;AAAA,EACvD;AAAA,EAEU,mBAAmB,MAG1B;AACD,WAAO;AAAA,MACL,OAAO,KAAK,aAAa,SAAS;AAAA,MAClC,eAAe,KAAK,aAAa;AAAA,MACjC,eAAe,KAAK,aAAa,iBAAiB;AAAA,MAClD,WAAW,KAAK,aAAa,aAAa,CAAC;AAAA,MAC3C,SAAS,KAAK,aAAa;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,MAAM,IAAI,MAIP;AACD,UAAM,gBAAgB,MAAM,iBAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,MAAM,kBAAkB,KAAK,QAAQ;AAC5D,UAAM,cAAc,mBAAmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAEhD,YAAQ;AAAA,MACN,SAAS;AAAA,QACP,GAAG,aAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AACvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/handlers/GraphQLHandler.ts"],"sourcesContent":["import {\n parse,\n type DocumentNode,\n type GraphQLError,\n type OperationTypeNode,\n} from 'graphql'\nimport {\n DefaultBodyType,\n RequestHandler,\n RequestHandlerDefaultInfo,\n RequestHandlerOptions,\n ResponseResolver,\n} from './RequestHandler'\nimport { getTimestamp } from '../utils/logging/getTimestamp'\nimport { getStatusCodeColor } from '../utils/logging/getStatusCodeColor'\nimport { serializeRequest } from '../utils/logging/serializeRequest'\nimport { serializeResponse } from '../utils/logging/serializeResponse'\nimport { Match, matchRequestUrl, Path } from '../utils/matching/matchRequestUrl'\nimport {\n ParsedGraphQLRequest,\n GraphQLMultipartRequestBody,\n parseGraphQLRequest,\n parseDocumentNode,\n ParsedGraphQLQuery,\n} from '../utils/internal/parseGraphQLRequest'\nimport { toPublicUrl } from '../utils/request/toPublicUrl'\nimport { devUtils } from '../utils/internal/devUtils'\nimport { getAllRequestCookies } from '../utils/request/getRequestCookies'\nimport { invariant } from 'outvariant'\n\nexport interface DocumentTypeDecoration<\n Result = { [key: string]: any },\n Variables = { [key: string]: any },\n> {\n __apiType?: (variables: Variables) => Result\n __resultType?: Result\n __variablesType?: Variables\n}\n\nexport type GraphQLOperationType = OperationTypeNode | 'all'\nexport type GraphQLHandlerNameSelector = DocumentNode | RegExp | string\n\nexport type GraphQLQuery = Record<string, any> | null\nexport type GraphQLVariables = Record<string, any>\n\nexport interface GraphQLHandlerInfo extends RequestHandlerDefaultInfo {\n operationType: GraphQLOperationType\n operationName: GraphQLHandlerNameSelector | GraphQLCustomPredicate\n}\n\nexport type GraphQLRequestParsedResult = {\n match: Match\n cookies: Record<string, string>\n} & (\n | ParsedGraphQLRequest<GraphQLVariables>\n /**\n * An empty version of the ParsedGraphQLRequest\n * which simplifies the return type of the resolver\n * when the request is to a non-matching endpoint\n */\n | {\n operationType?: undefined\n operationName?: undefined\n query?: undefined\n variables?: undefined\n }\n)\n\nexport type GraphQLResolverExtras<Variables extends GraphQLVariables> = {\n query: string\n operationName: string\n variables: Variables\n cookies: Record<string, string>\n}\n\nexport type GraphQLRequestBody<VariablesType extends GraphQLVariables> =\n | GraphQLJsonRequestBody<VariablesType>\n | GraphQLMultipartRequestBody\n | Record<string, any>\n | undefined\n\nexport interface GraphQLJsonRequestBody<Variables extends GraphQLVariables> {\n query: string\n variables?: Variables\n}\n\nexport type GraphQLResponseBody<BodyType extends DefaultBodyType> =\n | {\n data?: BodyType | null\n errors?: readonly Partial<GraphQLError>[] | null\n extensions?: Record<string, any>\n }\n | null\n | undefined\n\nexport type GraphQLCustomPredicate = (args: {\n request: Request\n query: string\n operationType: GraphQLOperationType\n operationName: string\n variables: GraphQLVariables\n cookies: Record<string, string>\n}) => GraphQLCustomPredicateResult | Promise<GraphQLCustomPredicateResult>\n\nexport type GraphQLCustomPredicateResult = boolean | { matches: boolean }\n\nexport type GraphQLPredicate<Query = any, Variables = any> =\n | GraphQLHandlerNameSelector\n | DocumentTypeDecoration<Query, Variables>\n | GraphQLCustomPredicate\n\nexport function isDocumentNode(\n value: DocumentNode | any,\n): value is DocumentNode {\n if (value == null) {\n return false\n }\n\n return typeof value === 'object' && 'kind' in value && 'definitions' in value\n}\n\nfunction isDocumentTypeDecoration(\n value: unknown,\n): value is DocumentTypeDecoration<any, any> {\n return value instanceof String\n}\n\nexport class GraphQLHandler extends RequestHandler<\n GraphQLHandlerInfo,\n GraphQLRequestParsedResult,\n GraphQLResolverExtras<any>\n> {\n private endpoint: Path\n\n static parsedRequestCache = new WeakMap<\n Request,\n ParsedGraphQLRequest<GraphQLVariables>\n >()\n\n static #parseOperationName(\n predicate: GraphQLPredicate,\n operationType: GraphQLOperationType,\n ): GraphQLHandlerInfo['operationName'] {\n const getOperationName = (node: ParsedGraphQLQuery): string => {\n invariant(\n node.operationType === operationType,\n 'Failed to create a GraphQL handler: provided a DocumentNode with a mismatched operation type (expected \"%s\" but got \"%s\").',\n operationType,\n node.operationType,\n )\n\n invariant(\n node.operationName,\n 'Failed to create a GraphQL handler: provided a DocumentNode without operation name',\n )\n\n return node.operationName\n }\n\n if (isDocumentNode(predicate)) {\n return getOperationName(parseDocumentNode(predicate))\n }\n\n if (isDocumentTypeDecoration(predicate)) {\n const documentNode = parse(predicate.toString())\n\n invariant(\n isDocumentNode(documentNode),\n 'Failed to create a GraphQL handler: given TypedDocumentString (%s) does not produce a valid DocumentNode',\n predicate,\n )\n\n return getOperationName(parseDocumentNode(documentNode))\n }\n\n return predicate\n }\n\n constructor(\n operationType: GraphQLOperationType,\n predicate: GraphQLPredicate,\n endpoint: Path,\n resolver: ResponseResolver<GraphQLResolverExtras<any>, any, any>,\n options?: RequestHandlerOptions,\n ) {\n const operationName = GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n )\n\n const displayOperationName =\n typeof operationName === 'function' ? '[custom predicate]' : operationName\n\n const header =\n operationType === 'all'\n ? `${operationType} (origin: ${endpoint.toString()})`\n : `${operationType}${displayOperationName ? ` ${displayOperationName}` : ''} (origin: ${endpoint.toString()})`\n\n super({\n info: {\n header,\n operationType,\n operationName: GraphQLHandler.#parseOperationName(\n predicate,\n operationType,\n ),\n },\n resolver,\n options,\n })\n\n this.endpoint = endpoint\n }\n\n /**\n * Parses the request body, once per request, cached across all\n * GraphQL handlers. This is done to avoid multiple parsing of the\n * request body, which each requires a clone of the request.\n */\n async parseGraphQLRequestOrGetFromCache(\n request: Request,\n ): Promise<ParsedGraphQLRequest<GraphQLVariables>> {\n if (!GraphQLHandler.parsedRequestCache.has(request)) {\n GraphQLHandler.parsedRequestCache.set(\n request,\n await parseGraphQLRequest(request).catch((error) => {\n console.error(error)\n return undefined\n }),\n )\n }\n\n return GraphQLHandler.parsedRequestCache.get(request)\n }\n\n async parse(args: { request: Request }): Promise<GraphQLRequestParsedResult> {\n /**\n * If the request doesn't match a specified endpoint, there's no\n * need to parse it since there's no case where we would handle this\n */\n const match = matchRequestUrl(new URL(args.request.url), this.endpoint)\n const cookies = getAllRequestCookies(args.request)\n\n if (!match.matches) {\n return {\n match,\n cookies,\n }\n }\n\n const parsedResult = await this.parseGraphQLRequestOrGetFromCache(\n args.request,\n )\n\n if (typeof parsedResult === 'undefined') {\n return {\n match,\n cookies,\n }\n }\n\n return {\n match,\n cookies,\n query: parsedResult.query,\n operationType: parsedResult.operationType,\n operationName: parsedResult.operationName,\n variables: parsedResult.variables,\n }\n }\n\n async predicate(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (args.parsedResult.operationType === undefined) {\n return false\n }\n\n if (!args.parsedResult.operationName && this.info.operationType !== 'all') {\n const publicUrl = toPublicUrl(args.request.url)\n\n devUtils.warn(`\\\nFailed to intercept a GraphQL request at \"${args.request.method} ${publicUrl}\": anonymous GraphQL operations are not supported.\n\nConsider 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/#graphqloperationresolver`)\n return false\n }\n\n const hasMatchingOperationType =\n this.info.operationType === 'all' ||\n args.parsedResult.operationType === this.info.operationType\n\n /**\n * Check if the operation name matches the outgoing GraphQL request.\n * @note Unlike the HTTP handler, the custom predicate functions are invoked\n * during predicate, not parsing, because GraphQL request parsing happens first,\n * and non-GraphQL requests are filtered out automatically.\n */\n const hasMatchingOperationName = await this.matchOperationName({\n request: args.request,\n parsedResult: args.parsedResult,\n })\n\n return (\n args.parsedResult.match.matches &&\n hasMatchingOperationType &&\n hasMatchingOperationName\n )\n }\n\n private async matchOperationName(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }): Promise<boolean> {\n if (typeof this.info.operationName === 'function') {\n const customPredicateResult = await this.info.operationName({\n request: args.request,\n ...this.extendResolverArgs({\n request: args.request,\n parsedResult: args.parsedResult,\n }),\n })\n\n /**\n * @note Keep the { matches } signature in case we decide to support path parameters\n * in GraphQL handlers. If that happens, the custom predicate would have to be moved\n * to the parsing phase, the same as we have for the HttpHandler, and the user will\n * have a possibility to return parsed path parameters from the custom predicate.\n */\n return typeof customPredicateResult === 'boolean'\n ? customPredicateResult\n : customPredicateResult.matches\n }\n\n if (this.info.operationName instanceof RegExp) {\n return this.info.operationName.test(args.parsedResult.operationName || '')\n }\n\n return args.parsedResult.operationName === this.info.operationName\n }\n\n protected extendResolverArgs(args: {\n request: Request\n parsedResult: GraphQLRequestParsedResult\n }) {\n return {\n query: args.parsedResult.query || '',\n operationType: args.parsedResult.operationType!,\n operationName: args.parsedResult.operationName || '',\n variables: args.parsedResult.variables || {},\n cookies: args.parsedResult.cookies,\n }\n }\n\n async log(args: {\n request: Request\n response: Response\n parsedResult: GraphQLRequestParsedResult\n }) {\n const loggedRequest = await serializeRequest(args.request)\n const loggedResponse = await serializeResponse(args.response)\n const statusColor = getStatusCodeColor(loggedResponse.status)\n const requestInfo = args.parsedResult.operationName\n ? `${args.parsedResult.operationType} ${args.parsedResult.operationName}`\n : `anonymous ${args.parsedResult.operationType}`\n\n console.groupCollapsed(\n devUtils.formatMessage(\n `${getTimestamp()} ${requestInfo} (%c${loggedResponse.status} ${\n loggedResponse.statusText\n }%c)`,\n ),\n `color:${statusColor}`,\n 'color:inherit',\n )\n // eslint-disable-next-line no-console\n console.log('Request:', loggedRequest)\n // eslint-disable-next-line no-console\n console.log('Handler:', this)\n // eslint-disable-next-line no-console\n console.log('Response:', loggedResponse)\n console.groupEnd()\n }\n}\n"],"mappings":"AAAA;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EAEE;AAAA,OAIK;AACP,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAgB,uBAA6B;AAC7C;AAAA,EAGE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,4BAA4B;AACrC,SAAS,iBAAiB;AAmFnB,SAAS,eACd,OACuB;AACvB,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,UAAU,YAAY,UAAU,SAAS,iBAAiB;AAC1E;AAEA,SAAS,yBACP,OAC2C;AAC3C,SAAO,iBAAiB;AAC1B;AAEO,MAAM,uBAAuB,eAIlC;AAAA,EACQ;AAAA,EAER,OAAO,qBAAqB,oBAAI,QAG9B;AAAA,EAEF,OAAO,oBACL,WACA,eACqC;AACrC,UAAM,mBAAmB,CAAC,SAAqC;AAC7D;AAAA,QACE,KAAK,kBAAkB;AAAA,QACvB;AAAA,QACA;AAAA,QACA,KAAK;AAAA,MACP;AAEA;AAAA,QACE,KAAK;AAAA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c,KAAK;AAAA,QACrB,CAAC;AAAA,MACH,CAAC;AAQD,aAAO,OAAO,0BAA0B,YACpC,wBACA,sBAAsB;AAAA,IAC5B;AAEA,QAAI,KAAK,KAAK,yBAAyB,QAAQ;AAC7C,aAAO,KAAK,KAAK,cAAc,KAAK,KAAK,aAAa,iBAAiB,EAAE;AAAA,IAC3E;AAEA,WAAO,KAAK,aAAa,kBAAkB,KAAK,KAAK;AAAA,EACvD;AAAA,EAEU,mBAAmB,MAG1B;AACD,WAAO;AAAA,MACL,OAAO,KAAK,aAAa,SAAS;AAAA,MAClC,eAAe,KAAK,aAAa;AAAA,MACjC,eAAe,KAAK,aAAa,iBAAiB;AAAA,MAClD,WAAW,KAAK,aAAa,aAAa,CAAC;AAAA,MAC3C,SAAS,KAAK,aAAa;AAAA,IAC7B;AAAA,EACF;AAAA,EAEA,MAAM,IAAI,MAIP;AACD,UAAM,gBAAgB,MAAM,iBAAiB,KAAK,OAAO;AACzD,UAAM,iBAAiB,MAAM,kBAAkB,KAAK,QAAQ;AAC5D,UAAM,cAAc,mBAAmB,eAAe,MAAM;AAC5D,UAAM,cAAc,KAAK,aAAa,gBAClC,GAAG,KAAK,aAAa,aAAa,IAAI,KAAK,aAAa,aAAa,KACrE,aAAa,KAAK,aAAa,aAAa;AAEhD,YAAQ;AAAA,MACN,SAAS;AAAA,QACP,GAAG,aAAa,CAAC,IAAI,WAAW,OAAO,eAAe,MAAM,IAC1D,eAAe,UACjB;AAAA,MACF;AAAA,MACA,SAAS,WAAW;AAAA,MACpB;AAAA,IACF;AAEA,YAAQ,IAAI,YAAY,aAAa;AAErC,YAAQ,IAAI,YAAY,IAAI;AAE5B,YAAQ,IAAI,aAAa,cAAc;AACvC,YAAQ,SAAS;AAAA,EACnB;AACF;","names":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as RequestHandler,
|
|
1
|
+
import { R as RequestHandler, r as RequestHandlerDefaultInfo, a as ResponseResolver, c as RequestHandlerOptions, m as ResponseResolutionContext } from '../HttpResponse-B9rGc56D.mjs';
|
|
2
2
|
import { PathParams, Path, Match } from '../utils/matching/matchRequestUrl.mjs';
|
|
3
3
|
import '@mswjs/interceptors';
|
|
4
4
|
import '../utils/internal/isIterable.mjs';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as RequestHandler,
|
|
1
|
+
import { R as RequestHandler, r as RequestHandlerDefaultInfo, a as ResponseResolver, c as RequestHandlerOptions, m as ResponseResolutionContext } from '../HttpResponse-Dz84tqeA.js';
|
|
2
2
|
import { PathParams, Path, Match } from '../utils/matching/matchRequestUrl.js';
|
|
3
3
|
import '@mswjs/interceptors';
|
|
4
4
|
import '../utils/internal/isIterable.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import '../utils/internal/isIterable.mjs';
|
|
2
|
-
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, J as JsonBodyType,
|
|
2
|
+
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, J as JsonBodyType, M as MaybeAsyncResponseResolverReturnType, R as RequestHandler, L as RequestHandlerArgs, r as RequestHandlerDefaultInfo, N as RequestHandlerExecutionResult, K as RequestHandlerInternalInfo, c as RequestHandlerOptions, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType } from '../HttpResponse-B9rGc56D.mjs';
|
|
3
3
|
import '../typeUtils.mjs';
|
|
4
4
|
import '@mswjs/interceptors';
|
|
5
5
|
import 'graphql';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import '../utils/internal/isIterable.js';
|
|
2
|
-
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, J as JsonBodyType,
|
|
2
|
+
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, J as JsonBodyType, M as MaybeAsyncResponseResolverReturnType, R as RequestHandler, L as RequestHandlerArgs, r as RequestHandlerDefaultInfo, N as RequestHandlerExecutionResult, K as RequestHandlerInternalInfo, c as RequestHandlerOptions, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType } from '../HttpResponse-Dz84tqeA.js';
|
|
3
3
|
import '../typeUtils.js';
|
|
4
4
|
import '@mswjs/interceptors';
|
|
5
5
|
import 'graphql';
|
package/lib/core/http.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as DefaultBodyType, a as ResponseResolver, c as RequestHandlerOptions } from './HttpResponse-
|
|
1
|
+
import { D as DefaultBodyType, a as ResponseResolver, c as RequestHandlerOptions } from './HttpResponse-B9rGc56D.mjs';
|
|
2
2
|
import { HttpRequestPredicate, HttpRequestResolverExtras, HttpHandler } from './handlers/HttpHandler.mjs';
|
|
3
3
|
import { PathParams } from './utils/matching/matchRequestUrl.mjs';
|
|
4
4
|
import '@mswjs/interceptors';
|
package/lib/core/http.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as DefaultBodyType, a as ResponseResolver, c as RequestHandlerOptions } from './HttpResponse-
|
|
1
|
+
import { D as DefaultBodyType, a as ResponseResolver, c as RequestHandlerOptions } from './HttpResponse-Dz84tqeA.js';
|
|
2
2
|
import { HttpRequestPredicate, HttpRequestResolverExtras, HttpHandler } from './handlers/HttpHandler.js';
|
|
3
3
|
import { PathParams } from './utils/matching/matchRequestUrl.js';
|
|
4
4
|
import '@mswjs/interceptors';
|
package/lib/core/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { SetupApi } from './SetupApi.mjs';
|
|
2
|
-
import { G as GraphQLHandler } from './HttpResponse-
|
|
3
|
-
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody,
|
|
2
|
+
import { G as GraphQLHandler } from './HttpResponse-B9rGc56D.mjs';
|
|
3
|
+
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, l as GraphQLCustomPredicate, j as GraphQLJsonRequestBody, k as GraphQLOperationType, f as GraphQLQuery, h as GraphQLRequestBody, i as GraphQLResponseBody, g as GraphQLVariables, H as HttpResponse, n as HttpResponseInit, J as JsonBodyType, P as ParsedGraphQLRequest, R as RequestHandler, c as RequestHandlerOptions, m as ResponseResolutionContext, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType, S as StrictRequest, o as StrictResponse } from './HttpResponse-B9rGc56D.mjs';
|
|
4
4
|
export { HttpRequestHandler, HttpResponseResolver, http } from './http.mjs';
|
|
5
5
|
import { HttpHandler } from './handlers/HttpHandler.mjs';
|
|
6
6
|
export { HttpCustomPredicate, HttpHandlerInfo, HttpHandlerMethod, HttpMethods, HttpRequestParsedResult, HttpRequestResolverExtras, RequestQuery } from './handlers/HttpHandler.mjs';
|
|
@@ -15,7 +15,7 @@ export { UnhandledRequestCallback, UnhandledRequestStrategy, onUnhandledRequest
|
|
|
15
15
|
export { getResponse } from './getResponse.mjs';
|
|
16
16
|
export { cleanUrl } from './utils/url/cleanUrl.mjs';
|
|
17
17
|
export { LifeCycleEventsMap, SharedOptions } from './sharedOptions.mjs';
|
|
18
|
-
export { DelayMode,
|
|
18
|
+
export { DelayMode, delay } from './delay.mjs';
|
|
19
19
|
export { bypass } from './bypass.mjs';
|
|
20
20
|
export { passthrough } from './passthrough.mjs';
|
|
21
21
|
export { isCommonAssetRequest } from './isCommonAssetRequest.mjs';
|
package/lib/core/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { SetupApi } from './SetupApi.js';
|
|
2
|
-
import { G as GraphQLHandler } from './HttpResponse-
|
|
3
|
-
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody,
|
|
2
|
+
import { G as GraphQLHandler } from './HttpResponse-Dz84tqeA.js';
|
|
3
|
+
export { A as AsyncResponseResolverReturnType, D as DefaultBodyType, d as DefaultRequestMultipartBody, l as GraphQLCustomPredicate, j as GraphQLJsonRequestBody, k as GraphQLOperationType, f as GraphQLQuery, h as GraphQLRequestBody, i as GraphQLResponseBody, g as GraphQLVariables, H as HttpResponse, n as HttpResponseInit, J as JsonBodyType, P as ParsedGraphQLRequest, R as RequestHandler, c as RequestHandlerOptions, m as ResponseResolutionContext, a as ResponseResolver, e as ResponseResolverInfo, b as ResponseResolverReturnType, S as StrictRequest, o as StrictResponse } from './HttpResponse-Dz84tqeA.js';
|
|
4
4
|
export { HttpRequestHandler, HttpResponseResolver, http } from './http.js';
|
|
5
5
|
import { HttpHandler } from './handlers/HttpHandler.js';
|
|
6
6
|
export { HttpCustomPredicate, HttpHandlerInfo, HttpHandlerMethod, HttpMethods, HttpRequestParsedResult, HttpRequestResolverExtras, RequestQuery } from './handlers/HttpHandler.js';
|
|
@@ -15,7 +15,7 @@ export { UnhandledRequestCallback, UnhandledRequestStrategy, onUnhandledRequest
|
|
|
15
15
|
export { getResponse } from './getResponse.js';
|
|
16
16
|
export { cleanUrl } from './utils/url/cleanUrl.js';
|
|
17
17
|
export { LifeCycleEventsMap, SharedOptions } from './sharedOptions.js';
|
|
18
|
-
export { DelayMode,
|
|
18
|
+
export { DelayMode, delay } from './delay.js';
|
|
19
19
|
export { bypass } from './bypass.js';
|
|
20
20
|
export { passthrough } from './passthrough.js';
|
|
21
21
|
export { isCommonAssetRequest } from './isCommonAssetRequest.js';
|
package/lib/core/index.js
CHANGED
|
@@ -15,20 +15,22 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
15
|
}
|
|
16
16
|
return to;
|
|
17
17
|
};
|
|
18
|
-
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
19
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
19
|
var index_exports = {};
|
|
21
20
|
__export(index_exports, {
|
|
22
21
|
GraphQLHandler: () => import_GraphQLHandler.GraphQLHandler,
|
|
23
22
|
HttpHandler: () => import_HttpHandler.HttpHandler,
|
|
24
23
|
HttpMethods: () => import_HttpHandler.HttpMethods,
|
|
24
|
+
HttpResponse: () => import_HttpResponse.HttpResponse,
|
|
25
25
|
RequestHandler: () => import_RequestHandler.RequestHandler,
|
|
26
26
|
SetupApi: () => import_SetupApi.SetupApi,
|
|
27
27
|
WebSocketHandler: () => import_WebSocketHandler.WebSocketHandler,
|
|
28
28
|
bypass: () => import_bypass.bypass,
|
|
29
29
|
cleanUrl: () => import_cleanUrl.cleanUrl,
|
|
30
|
+
delay: () => import_delay.delay,
|
|
30
31
|
getResponse: () => import_getResponse.getResponse,
|
|
31
32
|
graphql: () => import_graphql.graphql,
|
|
33
|
+
handleRequest: () => import_handleRequest.handleRequest,
|
|
32
34
|
http: () => import_http.http,
|
|
33
35
|
isCommonAssetRequest: () => import_isCommonAssetRequest.isCommonAssetRequest,
|
|
34
36
|
matchRequestUrl: () => import_matchRequestUrl.matchRequestUrl,
|
|
@@ -49,12 +51,12 @@ var import_ws = require("./ws");
|
|
|
49
51
|
var import_WebSocketHandler = require("./handlers/WebSocketHandler");
|
|
50
52
|
var import_sse = require("./sse");
|
|
51
53
|
var import_matchRequestUrl = require("./utils/matching/matchRequestUrl");
|
|
52
|
-
|
|
54
|
+
var import_handleRequest = require("./utils/handleRequest");
|
|
53
55
|
var import_onUnhandledRequest = require("./utils/request/onUnhandledRequest");
|
|
54
56
|
var import_getResponse = require("./getResponse");
|
|
55
57
|
var import_cleanUrl = require("./utils/url/cleanUrl");
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
var import_HttpResponse = require("./HttpResponse");
|
|
59
|
+
var import_delay = require("./delay");
|
|
58
60
|
var import_bypass = require("./bypass");
|
|
59
61
|
var import_passthrough = require("./passthrough");
|
|
60
62
|
var import_isCommonAssetRequest = require("./isCommonAssetRequest");
|
package/lib/core/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/index.ts"],"sourcesContent":["import { checkGlobals } from './utils/internal/checkGlobals'\n\nexport { SetupApi } from './SetupApi'\n\n/* HTTP handlers */\nexport { RequestHandler } from './handlers/RequestHandler'\nexport { http } from './http'\nexport { HttpHandler, HttpMethods } from './handlers/HttpHandler'\nexport { graphql } from './graphql'\nexport { GraphQLHandler } from './handlers/GraphQLHandler'\n\n/* WebSocket handler */\nexport { ws, type WebSocketLink } from './ws'\nexport {\n WebSocketHandler,\n type WebSocketHandlerEventMap,\n type WebSocketHandlerConnection,\n} from './handlers/WebSocketHandler'\n\n/* Server-Sent Events */\nexport {\n sse,\n type ServerSentEventRequestHandler,\n type ServerSentEventResolver,\n type ServerSentEventResolverExtras,\n type ServerSentEventMessage,\n} from './sse'\n\nimport type { HttpHandler } from './handlers/HttpHandler'\nimport type { GraphQLHandler } from './handlers/GraphQLHandler'\nimport type { WebSocketHandler } from './handlers/WebSocketHandler'\n\nexport type AnyHandler = HttpHandler | GraphQLHandler | WebSocketHandler\n\n/* Utils */\nexport { matchRequestUrl } from './utils/matching/matchRequestUrl'\nexport
|
|
1
|
+
{"version":3,"sources":["../../src/core/index.ts"],"sourcesContent":["import { checkGlobals } from './utils/internal/checkGlobals'\n\nexport { SetupApi } from './SetupApi'\n\n/* HTTP handlers */\nexport { RequestHandler } from './handlers/RequestHandler'\nexport { http } from './http'\nexport { HttpHandler, HttpMethods } from './handlers/HttpHandler'\nexport { graphql } from './graphql'\nexport { GraphQLHandler } from './handlers/GraphQLHandler'\n\n/* WebSocket handler */\nexport { ws, type WebSocketLink } from './ws'\nexport {\n WebSocketHandler,\n type WebSocketHandlerEventMap,\n type WebSocketHandlerConnection,\n} from './handlers/WebSocketHandler'\n\n/* Server-Sent Events */\nexport {\n sse,\n type ServerSentEventRequestHandler,\n type ServerSentEventResolver,\n type ServerSentEventResolverExtras,\n type ServerSentEventMessage,\n} from './sse'\n\nimport type { HttpHandler } from './handlers/HttpHandler'\nimport type { GraphQLHandler } from './handlers/GraphQLHandler'\nimport type { WebSocketHandler } from './handlers/WebSocketHandler'\n\nexport type AnyHandler = HttpHandler | GraphQLHandler | WebSocketHandler\n\n/* Utils */\nexport { matchRequestUrl } from './utils/matching/matchRequestUrl'\nexport { handleRequest, type HandleRequestOptions } from './utils/handleRequest'\nexport {\n onUnhandledRequest,\n type UnhandledRequestStrategy,\n type UnhandledRequestCallback,\n} from './utils/request/onUnhandledRequest'\nexport { getResponse } from './getResponse'\nexport { cleanUrl } from './utils/url/cleanUrl'\n\n/**\n * Type definitions.\n */\n\nexport type { SharedOptions, LifeCycleEventsMap } from './sharedOptions'\n\nexport type {\n ResponseResolver,\n ResponseResolverReturnType,\n AsyncResponseResolverReturnType,\n RequestHandlerOptions,\n DefaultBodyType,\n DefaultRequestMultipartBody,\n JsonBodyType,\n ResponseResolverInfo,\n} from './handlers/RequestHandler'\n\nexport type {\n RequestQuery,\n HttpRequestParsedResult,\n HttpHandlerInfo,\n HttpRequestResolverExtras,\n HttpHandlerMethod,\n HttpCustomPredicate,\n} from './handlers/HttpHandler'\nexport type { HttpRequestHandler, HttpResponseResolver } from './http'\n\nexport type {\n GraphQLQuery,\n GraphQLVariables,\n GraphQLRequestBody,\n GraphQLResponseBody,\n GraphQLJsonRequestBody,\n GraphQLOperationType,\n GraphQLCustomPredicate,\n} from './handlers/GraphQLHandler'\nexport type {\n GraphQLRequestHandler,\n GraphQLOperationHandler,\n GraphQLResponseResolver,\n GraphQLLinkHandlers,\n} from './graphql'\n\nexport type { WebSocketData, WebSocketEventListener } from './ws'\n\nexport type { Path, PathParams, Match } from './utils/matching/matchRequestUrl'\nexport type { ParsedGraphQLRequest } from './utils/internal/parseGraphQLRequest'\nexport type { ResponseResolutionContext } from './utils/executeHandlers'\n\nexport {\n HttpResponse,\n type HttpResponseInit,\n type StrictRequest,\n type StrictResponse,\n} from './HttpResponse'\nexport { delay, type DelayMode } from './delay'\nexport { bypass } from './bypass'\nexport { passthrough } from './passthrough'\nexport { isCommonAssetRequest } from './isCommonAssetRequest'\n\n// Validate environmental globals before executing any code.\n// This ensures that the library gives user-friendly errors\n// when ran in the environments that require additional polyfills\n// from the end user.\ncheckGlobals()\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA6B;AAE7B,sBAAyB;AAGzB,4BAA+B;AAC/B,kBAAqB;AACrB,yBAAyC;AACzC,qBAAwB;AACxB,4BAA+B;AAG/B,gBAAuC;AACvC,8BAIO;AAGP,iBAMO;AASP,6BAAgC;AAChC,2BAAyD;AACzD,gCAIO;AACP,yBAA4B;AAC5B,sBAAyB;AAmDzB,0BAKO;AACP,mBAAsC;AACtC,oBAAuB;AACvB,yBAA4B;AAC5B,kCAAqC;AAAA,IAMrC,kCAAa;","names":[]}
|
package/lib/core/index.mjs
CHANGED
|
@@ -13,14 +13,16 @@ import {
|
|
|
13
13
|
sse
|
|
14
14
|
} from './sse.mjs';
|
|
15
15
|
import { matchRequestUrl } from './utils/matching/matchRequestUrl.mjs';
|
|
16
|
-
|
|
16
|
+
import { handleRequest } from './utils/handleRequest.mjs';
|
|
17
17
|
import {
|
|
18
18
|
onUnhandledRequest
|
|
19
19
|
} from './utils/request/onUnhandledRequest.mjs';
|
|
20
20
|
import { getResponse } from './getResponse.mjs';
|
|
21
21
|
import { cleanUrl } from './utils/url/cleanUrl.mjs';
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
import {
|
|
23
|
+
HttpResponse
|
|
24
|
+
} from './HttpResponse.mjs';
|
|
25
|
+
import { delay } from './delay.mjs';
|
|
24
26
|
import { bypass } from './bypass.mjs';
|
|
25
27
|
import { passthrough } from './passthrough.mjs';
|
|
26
28
|
import { isCommonAssetRequest } from './isCommonAssetRequest.mjs';
|
|
@@ -29,13 +31,16 @@ export {
|
|
|
29
31
|
GraphQLHandler,
|
|
30
32
|
HttpHandler,
|
|
31
33
|
HttpMethods,
|
|
34
|
+
HttpResponse,
|
|
32
35
|
RequestHandler,
|
|
33
36
|
SetupApi,
|
|
34
37
|
WebSocketHandler,
|
|
35
38
|
bypass,
|
|
36
39
|
cleanUrl,
|
|
40
|
+
delay,
|
|
37
41
|
getResponse,
|
|
38
42
|
graphql,
|
|
43
|
+
handleRequest,
|
|
39
44
|
http,
|
|
40
45
|
isCommonAssetRequest,
|
|
41
46
|
matchRequestUrl,
|
package/lib/core/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/index.ts"],"sourcesContent":["import { checkGlobals } from './utils/internal/checkGlobals'\n\nexport { SetupApi } from './SetupApi'\n\n/* HTTP handlers */\nexport { RequestHandler } from './handlers/RequestHandler'\nexport { http } from './http'\nexport { HttpHandler, HttpMethods } from './handlers/HttpHandler'\nexport { graphql } from './graphql'\nexport { GraphQLHandler } from './handlers/GraphQLHandler'\n\n/* WebSocket handler */\nexport { ws, type WebSocketLink } from './ws'\nexport {\n WebSocketHandler,\n type WebSocketHandlerEventMap,\n type WebSocketHandlerConnection,\n} from './handlers/WebSocketHandler'\n\n/* Server-Sent Events */\nexport {\n sse,\n type ServerSentEventRequestHandler,\n type ServerSentEventResolver,\n type ServerSentEventResolverExtras,\n type ServerSentEventMessage,\n} from './sse'\n\nimport type { HttpHandler } from './handlers/HttpHandler'\nimport type { GraphQLHandler } from './handlers/GraphQLHandler'\nimport type { WebSocketHandler } from './handlers/WebSocketHandler'\n\nexport type AnyHandler = HttpHandler | GraphQLHandler | WebSocketHandler\n\n/* Utils */\nexport { matchRequestUrl } from './utils/matching/matchRequestUrl'\nexport
|
|
1
|
+
{"version":3,"sources":["../../src/core/index.ts"],"sourcesContent":["import { checkGlobals } from './utils/internal/checkGlobals'\n\nexport { SetupApi } from './SetupApi'\n\n/* HTTP handlers */\nexport { RequestHandler } from './handlers/RequestHandler'\nexport { http } from './http'\nexport { HttpHandler, HttpMethods } from './handlers/HttpHandler'\nexport { graphql } from './graphql'\nexport { GraphQLHandler } from './handlers/GraphQLHandler'\n\n/* WebSocket handler */\nexport { ws, type WebSocketLink } from './ws'\nexport {\n WebSocketHandler,\n type WebSocketHandlerEventMap,\n type WebSocketHandlerConnection,\n} from './handlers/WebSocketHandler'\n\n/* Server-Sent Events */\nexport {\n sse,\n type ServerSentEventRequestHandler,\n type ServerSentEventResolver,\n type ServerSentEventResolverExtras,\n type ServerSentEventMessage,\n} from './sse'\n\nimport type { HttpHandler } from './handlers/HttpHandler'\nimport type { GraphQLHandler } from './handlers/GraphQLHandler'\nimport type { WebSocketHandler } from './handlers/WebSocketHandler'\n\nexport type AnyHandler = HttpHandler | GraphQLHandler | WebSocketHandler\n\n/* Utils */\nexport { matchRequestUrl } from './utils/matching/matchRequestUrl'\nexport { handleRequest, type HandleRequestOptions } from './utils/handleRequest'\nexport {\n onUnhandledRequest,\n type UnhandledRequestStrategy,\n type UnhandledRequestCallback,\n} from './utils/request/onUnhandledRequest'\nexport { getResponse } from './getResponse'\nexport { cleanUrl } from './utils/url/cleanUrl'\n\n/**\n * Type definitions.\n */\n\nexport type { SharedOptions, LifeCycleEventsMap } from './sharedOptions'\n\nexport type {\n ResponseResolver,\n ResponseResolverReturnType,\n AsyncResponseResolverReturnType,\n RequestHandlerOptions,\n DefaultBodyType,\n DefaultRequestMultipartBody,\n JsonBodyType,\n ResponseResolverInfo,\n} from './handlers/RequestHandler'\n\nexport type {\n RequestQuery,\n HttpRequestParsedResult,\n HttpHandlerInfo,\n HttpRequestResolverExtras,\n HttpHandlerMethod,\n HttpCustomPredicate,\n} from './handlers/HttpHandler'\nexport type { HttpRequestHandler, HttpResponseResolver } from './http'\n\nexport type {\n GraphQLQuery,\n GraphQLVariables,\n GraphQLRequestBody,\n GraphQLResponseBody,\n GraphQLJsonRequestBody,\n GraphQLOperationType,\n GraphQLCustomPredicate,\n} from './handlers/GraphQLHandler'\nexport type {\n GraphQLRequestHandler,\n GraphQLOperationHandler,\n GraphQLResponseResolver,\n GraphQLLinkHandlers,\n} from './graphql'\n\nexport type { WebSocketData, WebSocketEventListener } from './ws'\n\nexport type { Path, PathParams, Match } from './utils/matching/matchRequestUrl'\nexport type { ParsedGraphQLRequest } from './utils/internal/parseGraphQLRequest'\nexport type { ResponseResolutionContext } from './utils/executeHandlers'\n\nexport {\n HttpResponse,\n type HttpResponseInit,\n type StrictRequest,\n type StrictResponse,\n} from './HttpResponse'\nexport { delay, type DelayMode } from './delay'\nexport { bypass } from './bypass'\nexport { passthrough } from './passthrough'\nexport { isCommonAssetRequest } from './isCommonAssetRequest'\n\n// Validate environmental globals before executing any code.\n// This ensures that the library gives user-friendly errors\n// when ran in the environments that require additional polyfills\n// from the end user.\ncheckGlobals()\n"],"mappings":"AAAA,SAAS,oBAAoB;AAE7B,SAAS,gBAAgB;AAGzB,SAAS,sBAAsB;AAC/B,SAAS,YAAY;AACrB,SAAS,aAAa,mBAAmB;AACzC,SAAS,eAAe;AACxB,SAAS,sBAAsB;AAG/B,SAAS,UAA8B;AACvC;AAAA,EACE;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,OAKK;AASP,SAAS,uBAAuB;AAChC,SAAS,qBAAgD;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AAmDzB;AAAA,EACE;AAAA,OAIK;AACP,SAAS,aAA6B;AACtC,SAAS,cAAc;AACvB,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AAMrC,aAAa;","names":[]}
|