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K,IAAMA,EAAE,IAAM,EAAI,IAAa,IAAPA,EAAE,GACxV,G,8EEvFA,QAAe,YAJf,SAAkBnE,GAChB,MAAuB,iBAATA,GAAqB,IAAM1kB,KAAK0kB,EAChD,EAEuB,I,8ECIvB,QAAe,YARf,SAAiBA,GACf,KAAK,OAASA,GACZ,MAAM3K,UAAU,gBAGlB,OAAOrE,SAASgP,EAAKQ,OAAO,GAAI,GAAI,GACtC,EAEsB,I","sources":["webpack://httptoolkit-ui/./node_modules/mockttp/dist/client/admin-client.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/client/admin-query.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/client/mocked-endpoint-client.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/client/mockttp-admin-request-builder.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/client/mockttp-client.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/client/schema-introspection.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/main.browser.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/mockttp.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/pluggable-admin-api/mockttp-pluggable-admin.browser.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/pluggable-admin-api/pluggable-admin.browser.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/base-rule-builder.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/completion-checkers.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/matchers.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/requests/request-handler-definitions.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/requests/request-rule-builder.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/rule-parameters.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/rule-serialization.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/websockets/websocket-handler-definitions.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/rules/websockets/websocket-rule-builder.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/serialization/body-serialization.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/serialization/serialization.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/types.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/util/buffer-utils.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/util/error.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/util/header-utils.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/util/promise.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/util/request-utils.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/util/url.js","webpack://httptoolkit-ui/./node_modules/mockttp/dist/util/util.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/@httptoolkit/subscriptions-transport-ws/dist/client.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/@httptoolkit/subscriptions-transport-ws/dist/defaults.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/@httptoolkit/subscriptions-transport-ws/dist/message-types.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/@httptoolkit/subscriptions-transport-ws/dist/protocol.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/@httptoolkit/subscriptions-transport-ws/dist/utils/is-object.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/@httptoolkit/subscriptions-transport-ws/dist/utils/is-string.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/base64-arraybuffer/lib/base64-arraybuffer.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/nil.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/parse.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/regex.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/rng.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/stringify.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/v1.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/md5.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/v3.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/v35.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/v4.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/sha1.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/v5.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/validate.js","webpack://httptoolkit-ui/./node_modules/mockttp/node_modules/uuid/dist/esm-browser/version.js"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AdminClient = exports.GraphQLError = exports.RequestError = exports.ConnectionError = void 0;\nexports.resetAdminServer = resetAdminServer;\nconst _ = require(\"lodash\");\nconst events_1 = require(\"events\");\nconst DuplexPair = require(\"native-duplexpair\");\nconst typed_error_1 = require(\"typed-error\");\nconst CrossFetch = require(\"cross-fetch\");\nconst WebSocket = require(\"isomorphic-ws\");\nconst connectWebSocketStream = require(\"@httptoolkit/websocket-stream\");\nconst subscriptions_transport_ws_1 = require(\"@httptoolkit/subscriptions-transport-ws\");\nconst graphql_1 = require(\"graphql\");\nconst types_1 = require(\"../types\");\nconst util_1 = require(\"../util/util\");\nconst error_1 = require(\"../util/error\");\nconst promise_1 = require(\"../util/promise\");\nconst schema_introspection_1 = require(\"./schema-introspection\");\nconst schema_introspection_2 = require(\"./schema-introspection\");\nconst admin_query_1 = require(\"./admin-query\");\nconst { fetch, Headers } = util_1.isNode || typeof globalThis.fetch === 'undefined'\n ? CrossFetch\n : globalThis;\nclass ConnectionError extends typed_error_1.TypedError {\n}\nexports.ConnectionError = ConnectionError;\nclass RequestError extends typed_error_1.TypedError {\n constructor(message, response) {\n super(message);\n this.response = response;\n }\n}\nexports.RequestError = RequestError;\nclass GraphQLError extends RequestError {\n constructor(response, errors) {\n super(errors.length === 0\n ? `GraphQL request failed with ${response.status} response`\n : errors.length === 1\n ? `GraphQL request failed with: ${errors[0].message}`\n : // >1\n `GraphQL request failed, with errors:\\n${errors.map((e) => e.message).join('\\n')}`, response);\n this.errors = errors;\n }\n}\nexports.GraphQLError = GraphQLError;\nconst mergeClientOptions = (options, defaultOptions) => {\n if (!defaultOptions)\n return options;\n if (!options)\n return defaultOptions;\n if (defaultOptions.headers) {\n if (!options.headers) {\n options.headers = defaultOptions.headers;\n }\n else if (options.headers instanceof Headers) {\n _.forEach(defaultOptions.headers, (value, key) => {\n options.headers.append(key, value);\n });\n }\n else if (_.isObject(options.headers)) {\n Object.assign(options.headers, defaultOptions.headers);\n }\n }\n return options;\n};\nasync function requestFromAdminServer(serverUrl, path, options) {\n const url = `${serverUrl}${path}`;\n let response;\n try {\n response = await fetch(url, options);\n }\n catch (e) {\n if ((0, error_1.isErrorLike)(e) && e.code === 'ECONNREFUSED') {\n throw new ConnectionError(`Failed to connect to admin server at ${serverUrl}`);\n }\n else\n throw e;\n }\n if (response.status >= 400) {\n let body = await response.text();\n let jsonBody = null;\n try {\n jsonBody = JSON.parse(body);\n }\n catch (e) { }\n if (jsonBody && jsonBody.error) {\n throw new RequestError(jsonBody.error, response);\n }\n else {\n throw new RequestError(`Request to ${url} failed, with status ${response.status} and response body: ${body}`, response);\n }\n }\n else {\n return response.json();\n }\n}\n/**\n * Reset a remote admin server, shutting down all Mockttp servers controlled by that\n * admin server. This is equivalent to calling `client.stop()` for all remote\n * clients of the target server.\n *\n * This can be useful in some rare cases, where a client might fail to reliably tear down\n * its own server, e.g. in Cypress testing. In this case, it's useful to reset the\n * admin server completely remotely without needing access to any previous client\n * instances, to ensure all servers from previous test runs have been shut down.\n *\n * After this is called, behaviour of any previously connected clients is undefined, and\n * it's likely that they may throw errors or experience other undefined behaviour. Ensure\n * that `client.stop()` has been called on all active clients before calling this method.\n */\nasync function resetAdminServer(options = {}) {\n const serverUrl = options.adminServerUrl ||\n `http://localhost:${types_1.DEFAULT_ADMIN_SERVER_PORT}`;\n await requestFromAdminServer(serverUrl, '/reset', {\n ...options.requestOptions,\n method: 'POST'\n });\n}\n/**\n * A bare admin server client. This is not intended for general use, but can be useful when\n * building admin server plugins to mock non-HTTP protocols and other advanced use cases.\n *\n * For normal usage of Mockttp, you should use `Mockttp.getRemote()` instead, to get a Mockttp\n * remote client, which wraps this class with the full Mockttp API for mocking HTTP.\n *\n * This is part of Mockttp's experimental 'pluggable admin' API. It may change\n * unpredictably, even in minor releases.\n */\nclass AdminClient extends events_1.EventEmitter {\n constructor(options = {}) {\n super();\n this.debug = false;\n // True if server is entirely initialized, false if it's entirely shut down, or a promise\n // that resolves to one or the other if it's currently changing state.\n this.running = false;\n this.enableDebug = async () => {\n this.debug = true;\n return (await this.queryMockServer(`mutation EnableDebug {\n enableDebug\n }`));\n };\n this.reset = async () => {\n return (await this.queryMockServer(`mutation Reset {\n reset\n }`));\n };\n this.debug = !!options.debug;\n this.adminClientOptions = _.defaults(options, {\n adminServerUrl: `http://localhost:${types_1.DEFAULT_ADMIN_SERVER_PORT}`,\n adminStreamReconnectAttempts: 5\n });\n }\n attachStreamWebsocket(adminSessionBaseUrl, targetStream) {\n const adminSessionBaseWSUrl = adminSessionBaseUrl.replace(/^http/, 'ws');\n const wsStream = connectWebSocketStream(`${adminSessionBaseWSUrl}/stream`, {\n headers: this.adminClientOptions.requestOptions?.headers // Only used in Node.js (via WS)\n });\n let streamConnected = false;\n wsStream.on('connect', () => {\n streamConnected = true;\n targetStream.pipe(wsStream);\n wsStream.pipe(targetStream, { end: false });\n });\n // We ignore errors, but websocket closure eventually results in reconnect or shutdown\n wsStream.on('error', (e) => {\n if (this.debug)\n console.warn('Admin client stream error', e);\n this.emit('stream-error', e);\n });\n // When the websocket closes (after connect, either close frame, error, or socket shutdown):\n wsStream.on('ws-close', async (closeEvent) => {\n targetStream.unpipe(wsStream);\n const serverShutdown = closeEvent.code === 1000;\n if (serverShutdown) {\n // Clean shutdown implies the server is gone, and we need to shutdown & cleanup.\n targetStream.emit('server-shutdown');\n }\n else if (streamConnected && (await this.running) === true) {\n console.warn('Admin client stream unexpectedly disconnected', closeEvent);\n if (this.adminClientOptions.adminStreamReconnectAttempts > 0) {\n this.tryToReconnectStream(adminSessionBaseUrl, targetStream);\n }\n else {\n // If retries are disabled, shut down immediately:\n console.log('Admin client stream reconnect disabled, shutting down');\n targetStream.emit('server-shutdown');\n }\n }\n // If never connected successfully, we do nothing.\n });\n targetStream.on('finish', () => {\n // Ignore any further WebSocket events - the websocket stream is no longer useful\n wsStream.removeAllListeners('connect');\n wsStream.removeAllListeners('ws-close');\n wsStream.destroy();\n });\n return wsStream;\n }\n /**\n * Attempt to recreate a stream after disconnection, up to a limited number of retries. This is\n * different to normal connection setup, as it assumes the target stream is otherwise already\n * set up and active.\n */\n async tryToReconnectStream(adminSessionBaseUrl, targetStream, retries = this.adminClientOptions.adminStreamReconnectAttempts) {\n this.emit('stream-reconnecting');\n // Unclean shutdown means something has gone wrong somewhere. Try to reconnect.\n const newStream = this.attachStreamWebsocket(adminSessionBaseUrl, targetStream);\n new Promise((resolve, reject) => {\n newStream.once('connect', resolve);\n newStream.once('error', reject);\n }).then(() => {\n // On a successful connect, business resumes as normal.\n console.warn('Admin client stream reconnected');\n this.emit('stream-reconnected');\n }).catch(async (err) => {\n if (retries > 0) {\n // We delay re-retrying briefly - this helps to handle cases like the computer going\n // to sleep (where the server & client pause in parallel, but race to do so).\n // The delay increases exponentially with retry attempts (10ms, 50, 250, 1250, 6250)\n const retryAttempt = this.adminClientOptions.adminStreamReconnectAttempts - retries;\n await (0, util_1.delay)(10 * Math.pow(5, retryAttempt));\n return this.tryToReconnectStream(adminSessionBaseUrl, targetStream, retries - 1);\n }\n // Otherwise, once retries have failed, we give up entirely:\n console.warn('Admin client stream reconnection failed, shutting down:', err.message);\n if (this.debug)\n console.warn(err);\n this.emit('stream-reconnect-failed', err);\n targetStream.emit('server-shutdown');\n });\n }\n openStreamToMockServer(adminSessionBaseUrl) {\n // To allow reconnects, we need to not end the client stream when an individual web socket ends.\n // To make that work, we return a separate stream, which isn't directly connected to the websocket\n // and doesn't receive WS 'end' events, and then we can swap the WS inputs accordingly.\n const { socket1: wsTarget, socket2: exposedStream } = new DuplexPair();\n const wsStream = this.attachStreamWebsocket(adminSessionBaseUrl, wsTarget);\n wsTarget.on('error', (e) => exposedStream.emit('error', e));\n // When the server stream ends, end the target stream, which will automatically end all websockets.\n exposedStream.on('finish', () => wsTarget.end());\n // Propagate 'server is definitely no longer available' back from the websockets:\n wsTarget.on('server-shutdown', () => exposedStream.emit('server-shutdown'));\n // These receive a lot of listeners! One channel per matcher, handler & completion checker,\n // and each adds listeners for data/error/finish/etc. That's OK, it's not generally a leak,\n // but maybe 100 would be a bit suspicious (unless you have 30+ active rules).\n exposedStream.setMaxListeners(100);\n return new Promise((resolve, reject) => {\n wsStream.once('connect', () => resolve(exposedStream));\n wsStream.once('error', reject);\n });\n }\n prepareSubscriptionClientToAdminServer(adminSessionBaseUrl) {\n const adminSessionBaseWSUrl = adminSessionBaseUrl.replace(/^http/, 'ws');\n const subscriptionUrl = `${adminSessionBaseWSUrl}/subscription`;\n this.subscriptionClient = new subscriptions_transport_ws_1.SubscriptionClient(subscriptionUrl, {\n lazy: true, // Doesn't actually connect until you use subscriptions\n reconnect: true,\n reconnectionAttempts: 8,\n wsOptionArguments: [this.adminClientOptions.requestOptions]\n }, WebSocket);\n this.subscriptionClient.onError((e) => {\n this.emit('subscription-error', e);\n if (this.debug)\n console.error(\"Subscription error\", e);\n });\n this.subscriptionClient.onReconnecting(() => {\n this.emit('subscription-reconnecting');\n console.warn('Reconnecting Mockttp subscription client');\n });\n }\n async requestFromMockServer(path, options) {\n // Must check for session URL, not this.running, or we can't send the /stop request during shutdown!\n if (!this.adminSessionBaseUrl)\n throw new Error('Not connected to mock server');\n let url = this.adminSessionBaseUrl + path;\n let response = await fetch(url, mergeClientOptions(options, this.adminClientOptions.requestOptions));\n if (response.status >= 400) {\n if (this.debug)\n console.error(`Remote client server request failed with status ${response.status}`);\n throw new RequestError(`Request to ${url} failed, with status ${response.status}`, response);\n }\n else {\n return response;\n }\n }\n async queryMockServer(query, variables) {\n try {\n const response = (await this.requestFromMockServer('/', {\n method: 'POST',\n headers: new Headers({\n 'Content-Type': 'application/json'\n }),\n body: JSON.stringify({ query, variables })\n }));\n const { data, errors } = await response.json();\n if (errors && errors.length) {\n throw new GraphQLError(response, errors);\n }\n else {\n return data;\n }\n }\n catch (e) {\n if (this.debug)\n console.error(`Remote client query error: ${e}`);\n if (!(e instanceof RequestError))\n throw e;\n let graphQLErrors = undefined;\n try {\n graphQLErrors = (await e.response.json()).errors;\n }\n catch (e2) { }\n if (graphQLErrors) {\n throw new GraphQLError(e.response, graphQLErrors);\n }\n else {\n throw e;\n }\n }\n }\n async start(pluginStartParams) {\n if (this.adminSessionBaseUrl || await this.running)\n throw new Error('Server is already started');\n if (this.debug)\n console.log(`Starting remote mock server`);\n this.emit('starting');\n const startPromise = (0, promise_1.getDeferred)();\n this.running = startPromise.then((result) => {\n this.emit(result ? 'started' : 'start-failed');\n this.running = result;\n return result;\n });\n try {\n const supportOldServers = 'http' in pluginStartParams;\n const portConfig = supportOldServers\n ? pluginStartParams['http'].port\n : undefined;\n const path = portConfig ? `/start?port=${JSON.stringify(portConfig)}` : '/start';\n const adminServerResponse = await requestFromAdminServer(this.adminClientOptions.adminServerUrl, path, mergeClientOptions({\n method: 'POST',\n headers: new Headers({\n 'Content-Type': 'application/json'\n }),\n body: JSON.stringify({\n plugins: pluginStartParams,\n // Include all the Mockttp params at the root too, for backward compat with old admin servers:\n ...pluginStartParams.http?.options\n })\n }, this.adminClientOptions.requestOptions));\n // Backward compat for old servers\n const isPluginAwareServer = 'id' in adminServerResponse;\n const sessionId = isPluginAwareServer\n ? adminServerResponse.id\n : adminServerResponse.port.toString();\n const adminSessionBaseUrl = `${this.adminClientOptions.adminServerUrl}/${isPluginAwareServer ? 'session' : 'server'}/${sessionId}`;\n // Also open a stream connection, for 2-way communication we might need later.\n const adminServerStream = await this.openStreamToMockServer(adminSessionBaseUrl);\n adminServerStream.on('server-shutdown', () => {\n // When the server remotely disconnects the stream, shut down the client iff the client hasn't\n // stopped & restarted in the meantime (can happen, since all shutdown is async).\n if (this.adminServerStream === adminServerStream) {\n console.warn('Client stopping due to admin server shutdown');\n this.stop();\n }\n });\n this.adminServerStream = adminServerStream;\n // Create a subscription client, preconfigured & ready to connect if on() is called later:\n this.prepareSubscriptionClientToAdminServer(adminSessionBaseUrl);\n // We don't persist the id or resolve the start promise until everything is set up\n this.adminSessionBaseUrl = adminSessionBaseUrl;\n // Load the schema on server start, so we can check for feature support\n this.adminServerSchema = new schema_introspection_2.SchemaIntrospector((await this.queryMockServer(schema_introspection_1.introspectionQuery)).__schema);\n if (this.debug)\n console.log('Started remote mock server');\n const serverMetadata = this.adminServerMetadata = // Set field before we resolve the promise\n 'pluginData' in adminServerResponse\n ? adminServerResponse.pluginData\n : {\n // Backward compat - convert old always-HTTP data into per-plugin format:\n http: adminServerResponse\n };\n startPromise.resolve(true);\n return serverMetadata;\n }\n catch (e) {\n startPromise.resolve(false);\n throw e;\n }\n }\n isRunning() {\n return this.running === true;\n }\n get metadata() {\n if (!this.isRunning())\n throw new Error(\"Metadata is not available until the mock server is started\");\n return this.adminServerMetadata;\n }\n get schema() {\n if (!this.isRunning())\n throw new Error(\"Admin schema is not available until the mock server is started\");\n return this.adminServerSchema;\n }\n get adminStream() {\n if (!this.isRunning())\n throw new Error(\"Admin stream is not available until the mock server is started\");\n return this.adminServerStream;\n }\n // Call when either we want the server to stop, or it appears that the server has already stopped,\n // and we just want to ensure that's happened and clean everything up.\n async stop() {\n if (await this.running === false)\n return; // If stopped or stopping, do nothing.\n this.emit('stopping');\n const stopPromise = (0, promise_1.getDeferred)();\n this.running = stopPromise.then((result) => {\n this.emit('stopped');\n this.running = result;\n return result;\n });\n try {\n if (this.debug)\n console.log('Stopping remote mock server');\n try {\n this.subscriptionClient?.close();\n }\n catch (e) {\n console.log(e);\n }\n this.subscriptionClient = undefined;\n try {\n this.adminServerStream?.end();\n }\n catch (e) {\n console.log(e);\n }\n this.adminServerStream = undefined;\n await this.requestServerStop();\n }\n finally {\n // The client is always stopped (and so restartable) once stopping completes, in all\n // cases, since it can always be started again to reset it. The promise is just here\n // so that we successfully handle (and always wait for) parallel stops.\n stopPromise.resolve(false);\n }\n }\n requestServerStop() {\n return this.requestFromMockServer('/stop', {\n method: 'POST'\n }).catch((e) => {\n if (e instanceof RequestError && e.response.status === 404) {\n // 404 means it doesn't exist, generally because it was already stopped\n // by some other parallel shutdown process.\n return;\n }\n else {\n throw e;\n }\n }).then(() => {\n this.adminSessionBaseUrl = undefined;\n this.adminServerSchema = undefined;\n this.adminServerMetadata = undefined;\n });\n }\n async sendQuery(query) {\n return (await this.sendQueries(query))[0];\n }\n async sendQueries(...queries) {\n const results = queries.map(async ({ query, variables, transformResponse }) => {\n const result = await this.queryMockServer((0, graphql_1.print)(query), variables);\n return transformResponse\n ? transformResponse(result, { adminClient: this })\n : result;\n });\n return Promise.all(results);\n }\n async subscribe(query, callback) {\n if (await this.running === false)\n throw new Error('Not connected to mock server');\n const fieldName = (0, admin_query_1.getSingleSelectedFieldName)(query);\n if (!this.schema.typeHasField('Subscription', fieldName)) {\n console.warn(`Ignoring client subscription for event unrecognized by Mockttp server: ${fieldName}`);\n return Promise.resolve();\n }\n // This isn't 100% correct (you can be WS-connected, but still negotiating some GQL\n // setup) but it's good enough for our purposes (knowing-ish if the connection worked).\n let isConnected = !!this.subscriptionClient.client;\n this.subscriptionClient.request(query).subscribe({\n next: async (value) => {\n if (value.data) {\n const response = value.data[fieldName];\n const result = query.transformResponse\n ? await query.transformResponse(response, { adminClient: this })\n : response;\n callback(result);\n }\n else if (value.errors) {\n console.error('Error in subscription', value.errors);\n }\n },\n error: (e) => this.debug && console.warn('Error in remote subscription:', e)\n });\n return new Promise((resolve, reject) => {\n if (isConnected)\n resolve();\n else {\n this.subscriptionClient.onConnected(resolve);\n this.subscriptionClient.onDisconnected(reject);\n this.subscriptionClient.onError(reject);\n }\n });\n }\n /**\n * List the names of the rule parameters defined by the admin server. This can be\n * used in some advanced use cases to confirm that the parameters a client wishes to\n * reference are available.\n *\n * Only defined for remote clients.\n */\n async getRuleParameterKeys() {\n if (await this.running === false) {\n throw new Error('Cannot query rule parameters before the server is started');\n }\n if (!this.schema.queryTypeDefined('ruleParameterKeys')) {\n // If this endpoint isn't supported, that's because parameters aren't supported\n // at all, so we can safely report that immediately.\n return [];\n }\n let result = await this.queryMockServer(`query GetRuleParameterNames {\n ruleParameterKeys\n }`);\n return result.ruleParameterKeys;\n }\n}\nexports.AdminClient = AdminClient;\n//# sourceMappingURL=admin-client.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSingleSelectedFieldName = getSingleSelectedFieldName;\nfunction isFieldSelection(selection) {\n return selection.kind === 'Field';\n}\nfunction getQuerySelectionNode(gqlQuery) {\n const { definitions } = gqlQuery;\n if (definitions.length !== 1 || definitions[0].kind !== 'OperationDefinition') {\n throw new Error(\"Admin queries must be defined as a single operation definition\");\n }\n return definitions[0].selectionSet;\n}\n// Enforces that the query selects only one field (this is relevant for subscriptions),\n// and extracts and returns the name of that field.\nfunction getSingleSelectedFieldName(query) {\n const selectedFieldNames = getQuerySelectionNode(query.query)\n .selections\n .filter(isFieldSelection)\n .map(selection => selection.name.value);\n if (selectedFieldNames.length !== 1) {\n throw new Error(`This admin query must select only one field, but it selects ${selectedFieldNames.length}: ${selectedFieldNames.join(', ')}`);\n }\n return selectedFieldNames[0];\n}\n//# sourceMappingURL=admin-query.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MockedEndpointClient = void 0;\nclass MockedEndpointClient {\n constructor(id, explanation, endpointDataGetter) {\n this.id = id;\n this.explanation = explanation;\n this.endpointDataGetter = endpointDataGetter;\n }\n async getMockedEndpointData() {\n const mockedEndpointData = await this.endpointDataGetter();\n if (mockedEndpointData === null)\n throw new Error(\"Can't get seen requests for unknown mocked endpoint\");\n else\n return mockedEndpointData;\n }\n async getSeenRequests() {\n return (await this.getMockedEndpointData()).seenRequests;\n }\n async isPending() {\n return (await this.getMockedEndpointData()).isPending;\n }\n toString() {\n if (this.explanation) {\n return \"Mocked endpoint: \" + this.explanation;\n }\n else {\n return Object.toString.call(this);\n }\n }\n}\nexports.MockedEndpointClient = MockedEndpointClient;\n//# sourceMappingURL=mocked-endpoint-client.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MockttpAdminRequestBuilder = void 0;\nconst _ = require(\"lodash\");\nconst graphql_tag_1 = require(\"graphql-tag\");\nconst request_utils_1 = require(\"../util/request-utils\");\nconst header_utils_1 = require(\"../util/header-utils\");\nconst mocked_endpoint_client_1 = require(\"./mocked-endpoint-client\");\nconst rule_serialization_1 = require(\"../rules/rule-serialization\");\nfunction normalizeHttpMessage(message, event) {\n if (message.timingEvents) {\n // Timing events are serialized as raw JSON\n message.timingEvents = JSON.parse(message.timingEvents);\n }\n else if (event !== 'tls-client-error' && event !== 'client-error') {\n // For backwards compat, all except errors should have timing events if they're missing\n message.timingEvents = {};\n }\n if (message.rawHeaders) {\n message.rawHeaders = JSON.parse(message.rawHeaders);\n // We use raw headers where possible to derive headers, instead of using any pre-derived\n // header data, for maximum accuracy (and to avoid any need to query for both).\n message.headers = (0, header_utils_1.rawHeadersToObject)(message.rawHeaders);\n }\n else if (message.headers) {\n // Backward compat for older servers:\n message.headers = JSON.parse(message.headers);\n message.rawHeaders = (0, header_utils_1.objectHeadersToRaw)(message.headers);\n }\n if (message.rawTrailers) {\n message.rawTrailers = JSON.parse(message.rawTrailers);\n message.trailers = (0, header_utils_1.rawHeadersToObject)(message.rawTrailers);\n }\n else if (message.rawHeaders && message.body) { // HTTP events with bodies should have trailers\n message.rawTrailers = [];\n message.trailers = {};\n }\n if (message.body !== undefined) {\n // Body is serialized as the raw encoded buffer in base64\n message.body = (0, request_utils_1.buildBodyReader)(Buffer.from(message.body, 'base64'), message.headers);\n }\n // For backwards compat, all except errors should have tags if they're missing\n if (!message.tags)\n message.tags = [];\n if (event?.startsWith('tls-')) {\n // TLS passthrough & error events should have raw JSON socket metadata:\n if (message.tlsMetadata) {\n message.tlsMetadata = JSON.parse(message.tlsMetadata);\n }\n else {\n // For old servers, just use empty metadata:\n message.tlsMetadata = {};\n }\n }\n}\nfunction normalizeWebSocketMessage(message) {\n // Timing events are serialized as raw JSON\n message.timingEvents = JSON.parse(message.timingEvents);\n // Content is serialized as the raw encoded buffer in base64\n message.content = Buffer.from(message.content, 'base64');\n}\n/**\n * This is part of Mockttp's experimental 'pluggable admin' API. This may change\n * unpredictably, even in minor releases.\n *\n * @internal\n */\nclass MockttpAdminRequestBuilder {\n constructor(schema) {\n this.schema = schema;\n this.getEndpointDataGetter = (adminClient, ruleId) => async () => {\n let result = await adminClient.sendQuery({\n query: (0, graphql_tag_1.default) `\n query GetEndpointData($id: ID!) {\n mockedEndpoint(id: $id) {\n seenRequests {\n id,\n protocol,\n method,\n url,\n path,\n hostname\n\n ${this.schema.typeHasField('Request', 'rawHeaders')\n ? 'rawHeaders'\n : 'headers'}\n\n body,\n ${this.schema.asOptionalField('Request', 'timingEvents')}\n ${this.schema.asOptionalField('Request', 'httpVersion')}\n }\n ${this.schema.asOptionalField('MockedEndpoint', 'isPending')}\n }\n }\n `,\n variables: { id: ruleId }\n });\n const mockedEndpoint = result.mockedEndpoint;\n if (!mockedEndpoint)\n return null;\n mockedEndpoint.seenRequests.forEach(req => normalizeHttpMessage(req));\n return mockedEndpoint;\n };\n }\n buildAddRequestRulesQuery(rules, reset, adminStream) {\n const requestName = (reset ? 'Set' : 'Add') + 'Rules';\n const mutationName = (reset ? 'set' : 'add') + 'Rules';\n const serializedRules = rules.map((rule) => {\n const serializedRule = (0, rule_serialization_1.serializeRuleData)(rule, adminStream);\n if (!this.schema.typeHasInputField('MockRule', 'id')) {\n delete serializedRule.id;\n }\n return serializedRule;\n });\n return {\n query: (0, graphql_tag_1.default) `\n mutation ${requestName}($newRules: [MockRule!]!) {\n endpoints: ${mutationName}(input: $newRules) {\n id,\n ${this.schema.asOptionalField('MockedEndpoint', 'explanation')}\n }\n }\n `,\n variables: {\n newRules: serializedRules\n },\n transformResponse: (response, { adminClient }) => {\n return response.endpoints.map(({ id, explanation }) => new mocked_endpoint_client_1.MockedEndpointClient(id, explanation, this.getEndpointDataGetter(adminClient, id)));\n }\n };\n }\n buildAddWebSocketRulesQuery(rules, reset, adminStream) {\n // Seperate and simpler than buildAddRequestRulesQuery, because it doesn't have to\n // deal with backward compatibility.\n const requestName = (reset ? 'Set' : 'Add') + 'WebSocketRules';\n const mutationName = (reset ? 'set' : 'add') + 'WebSocketRules';\n const serializedRules = rules.map((rule) => (0, rule_serialization_1.serializeRuleData)(rule, adminStream));\n return {\n query: (0, graphql_tag_1.default) `\n mutation ${requestName}($newRules: [WebSocketMockRule!]!) {\n endpoints: ${mutationName}(input: $newRules) {\n id,\n explanation\n }\n }\n `,\n variables: {\n newRules: serializedRules\n },\n transformResponse: (response, { adminClient }) => {\n return response.endpoints.map(({ id, explanation }) => new mocked_endpoint_client_1.MockedEndpointClient(id, explanation, this.getEndpointDataGetter(adminClient, id)));\n }\n };\n }\n ;\n buildMockedEndpointsQuery() {\n return {\n query: (0, graphql_tag_1.default) `\n query GetAllEndpointData {\n mockedEndpoints {\n id,\n ${this.schema.asOptionalField('MockedEndpoint', 'explanation')}\n }\n }\n `,\n transformResponse: (response, { adminClient }) => {\n const mockedEndpoints = response.mockedEndpoints;\n return mockedEndpoints.map(({ id, explanation }) => new mocked_endpoint_client_1.MockedEndpointClient(id, explanation, this.getEndpointDataGetter(adminClient, id)));\n }\n };\n }\n buildPendingEndpointsQuery() {\n return {\n query: (0, graphql_tag_1.default) `\n query GetPendingEndpointData {\n pendingEndpoints {\n id,\n explanation\n }\n }\n `,\n transformResponse: (response, { adminClient }) => {\n const pendingEndpoints = response.pendingEndpoints;\n return pendingEndpoints.map(({ id, explanation }) => new mocked_endpoint_client_1.MockedEndpointClient(id, explanation, this.getEndpointDataGetter(adminClient, id)));\n }\n };\n }\n buildSubscriptionRequest(event) {\n // Note the asOptionalField checks - these are a quick hack for backward compatibility,\n // introspecting the server schema to avoid requesting fields that don't exist on old servers.\n const query = {\n 'request-initiated': (0, graphql_tag_1.default) `subscription OnRequestInitiated {\n requestInitiated {\n id\n protocol\n method\n url\n path\n ${this.schema.asOptionalField('InitiatedRequest', 'remoteIpAddress')}\n ${this.schema.asOptionalField('InitiatedRequest', 'remotePort')}\n hostname\n\n ${this.schema.typeHasField('InitiatedRequest', 'rawHeaders')\n ? 'rawHeaders'\n : 'headers'}\n timingEvents\n httpVersion\n ${this.schema.asOptionalField('InitiatedRequest', 'tags')}\n }\n }`,\n request: (0, graphql_tag_1.default) `subscription OnRequest {\n requestReceived {\n id\n ${this.schema.asOptionalField('Request', 'matchedRuleId')}\n protocol\n method\n url\n path\n ${this.schema.asOptionalField('Request', 'remoteIpAddress')}\n ${this.schema.asOptionalField('Request', 'remotePort')}\n hostname\n\n ${this.schema.typeHasField('Request', 'rawHeaders')\n ? 'rawHeaders'\n : 'headers'}\n\n body\n ${this.schema.asOptionalField('Request', 'rawTrailers')}\n\n ${this.schema.asOptionalField('Request', 'timingEvents')}\n ${this.schema.asOptionalField('Request', 'httpVersion')}\n ${this.schema.asOptionalField('Request', 'tags')}\n }\n }`,\n response: (0, graphql_tag_1.default) `subscription OnResponse {\n responseCompleted {\n id\n statusCode\n statusMessage\n\n ${this.schema.typeHasField('Response', 'rawHeaders')\n ? 'rawHeaders'\n : 'headers'}\n\n body\n ${this.schema.asOptionalField('Response', 'rawTrailers')}\n\n ${this.schema.asOptionalField('Response', 'timingEvents')}\n ${this.schema.asOptionalField('Response', 'tags')}\n }\n }`,\n 'websocket-request': (0, graphql_tag_1.default) `subscription OnWebSocketRequest {\n webSocketRequest {\n id\n matchedRuleId\n protocol\n method\n url\n path\n remoteIpAddress\n remotePort\n hostname\n\n rawHeaders\n body\n ${this.schema.asOptionalField('Request', 'rawTrailers')}\n\n timingEvents\n httpVersion\n tags\n }\n }`,\n 'websocket-accepted': (0, graphql_tag_1.default) `subscription OnWebSocketAccepted {\n webSocketAccepted {\n id\n statusCode\n statusMessage\n\n rawHeaders\n body\n ${this.schema.asOptionalField('Response', 'rawTrailers')}\n\n timingEvents\n tags\n }\n }`,\n 'websocket-message-received': (0, graphql_tag_1.default) `subscription OnWebSocketMessageReceived {\n webSocketMessageReceived {\n streamId\n direction\n content\n isBinary\n eventTimestamp\n\n timingEvents\n tags\n }\n }`,\n 'websocket-message-sent': (0, graphql_tag_1.default) `subscription OnWebSocketMessageSent {\n webSocketMessageSent {\n streamId\n direction\n content\n isBinary\n eventTimestamp\n\n timingEvents\n tags\n }\n }`,\n 'websocket-close': (0, graphql_tag_1.default) `subscription OnWebSocketClose {\n webSocketClose {\n streamId\n\n closeCode\n closeReason\n\n timingEvents\n tags\n }\n }`,\n abort: (0, graphql_tag_1.default) `subscription OnAbort {\n requestAborted {\n id,\n protocol,\n method,\n url,\n path,\n hostname,\n\n ${this.schema.typeHasField('Request', 'rawHeaders')\n ? 'rawHeaders'\n : 'headers'}\n\n ${this.schema.asOptionalField('Request', 'timingEvents')}\n ${this.schema.asOptionalField('Request', 'tags')}\n ${this.schema.asOptionalField('AbortedRequest', 'error')}\n }\n }`,\n 'tls-passthrough-opened': (0, graphql_tag_1.default) `subscription OnTlsPassthroughOpened {\n tlsPassthroughOpened {\n id\n upstreamPort\n\n hostname\n remoteIpAddress\n remotePort\n tags\n timingEvents\n ${this.schema.asOptionalField('TlsPassthroughEvent', 'tlsMetadata')}\n }\n }`,\n 'tls-passthrough-closed': (0, graphql_tag_1.default) `subscription OnTlsPassthroughClosed {\n tlsPassthroughClosed {\n id\n upstreamPort\n\n hostname\n remoteIpAddress\n remotePort\n tags\n timingEvents\n ${this.schema.asOptionalField('TlsPassthroughEvent', 'tlsMetadata')}\n }\n }`,\n 'tls-client-error': (0, graphql_tag_1.default) `subscription OnTlsClientError {\n failedTlsRequest {\n failureCause\n hostname\n remoteIpAddress\n ${this.schema.asOptionalField(['TlsHandshakeFailure', 'TlsRequest'], 'remotePort')}\n ${this.schema.asOptionalField(['TlsHandshakeFailure', 'TlsRequest'], 'tags')}\n ${this.schema.asOptionalField(['TlsHandshakeFailure', 'TlsRequest'], 'timingEvents')}\n ${this.schema.asOptionalField(['TlsHandshakeFailure', 'TlsRequest'], 'tlsMetadata')}\n }\n }`,\n 'client-error': (0, graphql_tag_1.default) `subscription OnClientError {\n failedClientRequest {\n errorCode\n request {\n id\n timingEvents\n tags\n protocol\n httpVersion\n method\n url\n path\n\n ${this.schema.typeHasField('ClientErrorRequest', 'rawHeaders')\n ? 'rawHeaders'\n : 'headers'}\n\n ${this.schema.asOptionalField('ClientErrorRequest', 'remoteIpAddress')}\n ${this.schema.asOptionalField('ClientErrorRequest', 'remotePort')}\n }\n response {\n id\n timingEvents\n tags\n statusCode\n statusMessage\n\n ${this.schema.typeHasField('Response', 'rawHeaders')\n ? 'rawHeaders'\n : 'headers'}\n\n body\n ${this.schema.asOptionalField('Response', 'rawTrailers')}\n }\n }\n }`,\n 'rule-event': (0, graphql_tag_1.default) `subscription OnRuleEvent {\n ruleEvent {\n requestId\n ruleId\n eventType\n eventData\n }\n }`\n }[event];\n if (!query)\n return; // Unrecognized event, we can't subscribe to this.\n return {\n query,\n transformResponse: (data) => {\n if (event === 'client-error') {\n data.request = _.mapValues(data.request, (v) => \n // Normalize missing values to undefined to match the local result\n v === null ? undefined : v);\n normalizeHttpMessage(data.request, event);\n if (data.response) {\n normalizeHttpMessage(data.response, event);\n }\n else {\n data.response = 'aborted';\n }\n }\n else if (event === 'websocket-message-received' || event === 'websocket-message-sent') {\n normalizeWebSocketMessage(data);\n }\n else if (event === 'abort') {\n normalizeHttpMessage(data, event);\n data.error = data.error ? JSON.parse(data.error) : undefined;\n }\n else if (event === 'rule-event') {\n const { eventData } = data;\n // Events may include raw body data buffers, serialized as base64:\n if (eventData.rawBody !== undefined) {\n eventData.rawBody = Buffer.from(eventData.rawBody, 'base64');\n }\n }\n else {\n normalizeHttpMessage(data, event);\n }\n return data;\n }\n };\n }\n}\nexports.MockttpAdminRequestBuilder = MockttpAdminRequestBuilder;\n//# sourceMappingURL=mockttp-admin-request-builder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MockttpClient = void 0;\nconst _ = require(\"lodash\");\nconst mockttp_1 = require(\"../mockttp\");\nconst admin_client_1 = require(\"./admin-client\");\nconst mockttp_admin_request_builder_1 = require(\"./mockttp-admin-request-builder\");\n/**\n * A Mockttp implementation, controlling a remote Mockttp admin server.\n *\n * A MockttpClient supports the exact same Mockttp API as MockttpServer, but rather\n * than directly using Node.js APIs to start a mock server and rewrite traffic, it\n * makes calls to a remote admin server to start a mock server and rewrite traffic\n * there. This is useful to allow proxy configuration from inside browser tests, and\n * to allow creating mock proxies that run on remote machines.\n */\nclass MockttpClient extends mockttp_1.AbstractMockttp {\n constructor(options = {}) {\n super(_.defaults(options, {\n // Browser clients generally want cors enabled. For other clients, it doesn't hurt.\n // TODO: Maybe detect whether we're in a browser in future\n cors: true,\n }));\n this.reset = () => {\n return this.adminClient.reset();\n };\n this.addRequestRules = async (...rules) => {\n return this._addRequestRules(rules, false);\n };\n this.setRequestRules = async (...rules) => {\n return this._addRequestRules(rules, true);\n };\n this.addWebSocketRules = async (...rules) => {\n return this._addWsRules(rules, false);\n };\n this.setWebSocketRules = async (...rules) => {\n return this._addWsRules(rules, true);\n };\n this._addRequestRules = async (rules, reset) => {\n if (!this.requestBuilder)\n throw new Error('Cannot add rules before the server is started');\n const { adminStream } = this.adminClient;\n return this.adminClient.sendQuery(this.requestBuilder.buildAddRequestRulesQuery(rules, reset, adminStream));\n };\n this._addWsRules = async (rules, reset) => {\n if (!this.requestBuilder)\n throw new Error('Cannot add rules before the server is started');\n const { adminStream } = this.adminClient;\n return this.adminClient.sendQuery(this.requestBuilder.buildAddWebSocketRulesQuery(rules, reset, adminStream));\n };\n this.mockServerOptions = options;\n this.adminClient = new admin_client_1.AdminClient({\n adminServerUrl: options.adminServerUrl,\n requestOptions: options.client\n });\n }\n enableDebug() {\n return this.adminClient.enableDebug();\n }\n get url() {\n return this.adminClient.metadata.http.mockRoot;\n }\n get port() {\n return this.adminClient.metadata.http.port;\n }\n async start(port) {\n await this.adminClient.start({\n http: {\n port,\n options: this.mockServerOptions\n }\n });\n this.requestBuilder = new mockttp_admin_request_builder_1.MockttpAdminRequestBuilder(this.adminClient.schema);\n }\n stop() {\n return this.adminClient.stop();\n }\n async getMockedEndpoints() {\n if (!this.requestBuilder)\n throw new Error('Cannot query mocked endpoints before the server is started');\n return this.adminClient.sendQuery(this.requestBuilder.buildMockedEndpointsQuery());\n }\n async getPendingEndpoints() {\n if (!this.requestBuilder)\n throw new Error('Cannot query pending endpoints before the server is started');\n return this.adminClient.sendQuery(this.requestBuilder.buildPendingEndpointsQuery());\n }\n async getRuleParameterKeys() {\n return this.adminClient.getRuleParameterKeys();\n }\n on(event, callback) {\n if (event.startsWith('admin-client:')) {\n // All MockttpClient events come from the internal admin-client instance:\n this.adminClient.on(event.slice('admin-client:'.length), callback);\n return Promise.resolve();\n }\n if (!this.requestBuilder)\n throw new Error('Cannot subscribe to Mockttp events before the server is started');\n const subRequest = this.requestBuilder.buildSubscriptionRequest(event);\n if (!subRequest) {\n // We just return an immediately promise if we don't recognize the event, which will quietly\n // succeed but never call the corresponding callback (the same as the server and most event\n // sources in the same kind of situation). This is what happens when the *client* doesn't\n // recognize the event. Subscribe() below handles the unknown-to-server case.\n console.warn(`Ignoring subscription for event unrecognized by Mockttp client: ${event}`);\n return Promise.resolve();\n }\n return this.adminClient.subscribe(subRequest, callback);\n }\n}\nexports.MockttpClient = MockttpClient;\n//# sourceMappingURL=mockttp-client.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.introspectionQuery = exports.SchemaIntrospector = void 0;\nconst _ = require(\"lodash\");\nclass SchemaIntrospector {\n constructor(adminServerSchema) {\n this.adminServerSchema = adminServerSchema;\n }\n queryTypeDefined(queryType) {\n return this.typeHasField('Query', queryType);\n }\n isTypeDefined(typeName) {\n return _.some(this.adminServerSchema.types, { name: typeName });\n }\n typeHasField(typeName, fieldName) {\n const type = _.find(this.adminServerSchema.types, { name: typeName });\n if (!type)\n return false;\n return !!_.find(type.fields, { name: fieldName });\n }\n asOptionalField(typeName, fieldName) {\n const possibleNames = !Array.isArray(typeName) ? [typeName] : typeName;\n const firstAvailableName = possibleNames.find((name) => this.isTypeDefined(name));\n if (!firstAvailableName)\n return '';\n return (this.typeHasField(firstAvailableName, fieldName))\n ? fieldName\n : '';\n }\n typeHasInputField(typeName, fieldName) {\n const type = _.find(this.adminServerSchema.types, { name: typeName });\n if (!type)\n return false;\n return !!_.find(type.inputFields, { name: fieldName });\n }\n}\nexports.SchemaIntrospector = SchemaIntrospector;\n// Taken from src/utilities/introspectionQuery.js in GraphQL-js\n// Copied directly, to avoid bundling the whole thing into frontend code.\nexports.introspectionQuery = `\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n fields(includeDeprecated: true) {\n name\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n`;\n//# sourceMappingURL=schema-introspection.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MockttpPluggableAdmin = exports.PluggableAdmin = exports.resetAdminServer = exports.MOCKTTP_PARAM_REF = exports.webSocketHandlers = exports.requestHandlers = exports.completionCheckers = exports.webSocketHandlerDefinitions = exports.requestHandlerDefinitions = exports.matchers = exports.RulePriority = exports.Method = void 0;\nexports.getLocal = getLocal;\nexports.getRemote = getRemote;\nexports.getAdminServer = getAdminServer;\nconst mockttp_client_1 = require(\"./client/mockttp-client\");\nvar types_1 = require(\"./types\");\nObject.defineProperty(exports, \"Method\", { enumerable: true, get: function () { return types_1.Method; } });\nObject.defineProperty(exports, \"RulePriority\", { enumerable: true, get: function () { return types_1.RulePriority; } });\n// Export rule data builders:\nconst matchers = require(\"./rules/matchers\");\nexports.matchers = matchers;\nconst requestHandlerDefinitions = require(\"./rules/requests/request-handler-definitions\");\nexports.requestHandlerDefinitions = requestHandlerDefinitions;\nconst webSocketHandlerDefinitions = require(\"./rules/websockets/websocket-handler-definitions\");\nexports.webSocketHandlerDefinitions = webSocketHandlerDefinitions;\nconst completionCheckers = require(\"./rules/completion-checkers\");\nexports.completionCheckers = completionCheckers;\n// We re-export definitions to pretend they're real handlers in the browser. This should be safe\n// because the missing methods (i.e. handle()) were always unusable in non-Node environments anyway.\n// In practice though, new browser code using this should actively use requestHandlerDefinitions instead.\n// In future, we should probably expose definitions only for both browsers & node, but that's a\n// breaking change.\nexports.requestHandlers = {\n 'SimpleHandler': requestHandlerDefinitions.SimpleHandlerDefinition,\n 'CallbackHandler': requestHandlerDefinitions.CallbackHandlerDefinition,\n 'StreamHandler': requestHandlerDefinitions.StreamHandlerDefinition,\n 'FileHandler': requestHandlerDefinitions.FileHandlerDefinition,\n 'PassThroughHandler': requestHandlerDefinitions.PassThroughHandlerDefinition,\n 'CloseConnectionHandler': requestHandlerDefinitions.CloseConnectionHandlerDefinition,\n 'TimeoutHandler': requestHandlerDefinitions.TimeoutHandlerDefinition,\n 'HandlerLookup': requestHandlerDefinitions.HandlerDefinitionLookup\n};\nexports.webSocketHandlers = {\n 'PassThroughWebSocketHandler': webSocketHandlerDefinitions.PassThroughWebSocketHandlerDefinition,\n 'CloseConnectionHandler': webSocketHandlerDefinitions.CloseConnectionHandlerDefinition,\n 'TimeoutHandler': webSocketHandlerDefinitions.TimeoutHandlerDefinition,\n 'WsHandlerLookup': webSocketHandlerDefinitions.WsHandlerDefinitionLookup\n};\nvar rule_parameters_1 = require(\"./rules/rule-parameters\");\nObject.defineProperty(exports, \"MOCKTTP_PARAM_REF\", { enumerable: true, get: function () { return rule_parameters_1.MOCKTTP_PARAM_REF; } });\n// Export the core API:\nfunction getLocal(options = {}) {\n return new mockttp_client_1.MockttpClient(options);\n}\nfunction getRemote(options = {}) {\n return new mockttp_client_1.MockttpClient(options);\n}\nfunction getAdminServer() {\n throw new Error('Cannot set up an admin server within a browser');\n}\nvar admin_client_1 = require(\"./client/admin-client\");\nObject.defineProperty(exports, \"resetAdminServer\", { enumerable: true, get: function () { return admin_client_1.resetAdminServer; } });\nexports.PluggableAdmin = require(\"./pluggable-admin-api/pluggable-admin\");\nexports.MockttpPluggableAdmin = require(\"./pluggable-admin-api/mockttp-pluggable-admin\");\n//# sourceMappingURL=main.browser.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AbstractMockttp = void 0;\nconst common_tags_1 = require(\"common-tags\");\nconst request_rule_builder_1 = require(\"./rules/requests/request-rule-builder\");\nconst websocket_rule_builder_1 = require(\"./rules/websockets/websocket-rule-builder\");\nconst types_1 = require(\"./types\");\n/**\n * @hidden\n */\nclass AbstractMockttp {\n constructor(options) {\n this.addRequestRule = (rule) => this.addRequestRules(rule).then((rules) => rules[0]);\n this.addWebSocketRule = (rule) => this.addWebSocketRules(rule).then((rules) => rules[0]);\n this.debug = options.debug || false;\n this.corsOptions = options.cors || false;\n this.recordTraffic = options.recordTraffic !== undefined\n ? options.recordTraffic\n : true;\n this.suggestChanges = options.suggestChanges !== undefined\n ? options.suggestChanges\n : true;\n }\n get proxyEnv() {\n return {\n HTTP_PROXY: this.url,\n HTTPS_PROXY: this.url\n };\n }\n urlFor(path) {\n return this.url + path;\n }\n forAnyRequest() {\n return new request_rule_builder_1.RequestRuleBuilder(this.addRequestRule);\n }\n forUnmatchedRequest() {\n return new request_rule_builder_1.RequestRuleBuilder(this.addRequestRule)\n .asPriority(types_1.RulePriority.FALLBACK);\n }\n forGet(url) {\n return new request_rule_builder_1.RequestRuleBuilder(types_1.Method.GET, url, this.addRequestRule);\n }\n forPost(url) {\n return new request_rule_builder_1.RequestRuleBuilder(types_1.Method.POST, url, this.addRequestRule);\n }\n forPut(url) {\n return new request_rule_builder_1.RequestRuleBuilder(types_1.Method.PUT, url, this.addRequestRule);\n }\n forDelete(url) {\n return new request_rule_builder_1.RequestRuleBuilder(types_1.Method.DELETE, url, this.addRequestRule);\n }\n forPatch(url) {\n return new request_rule_builder_1.RequestRuleBuilder(types_1.Method.PATCH, url, this.addRequestRule);\n }\n forHead(url) {\n return new request_rule_builder_1.RequestRuleBuilder(types_1.Method.HEAD, url, this.addRequestRule);\n }\n forOptions(url) {\n if (this.corsOptions) {\n throw new Error((0, common_tags_1.stripIndent) `\n Cannot mock OPTIONS requests with CORS enabled.\n\n You can disable CORS by passing { cors: false } to getLocal/getRemote, but this may cause issues ${''}connecting to your mock server from browsers, unless you mock all required OPTIONS preflight ${''}responses by hand.\n `);\n }\n return new request_rule_builder_1.RequestRuleBuilder(types_1.Method.OPTIONS, url, this.addRequestRule);\n }\n forJsonRpcRequest(match = {}) {\n return new request_rule_builder_1.RequestRuleBuilder(this.addRequestRule)\n .withJsonBodyIncluding({\n jsonrpc: '2.0',\n ...(match.method ? { method: match.method } : {}),\n ...(match.params ? { params: match.params } : {})\n });\n }\n forAnyWebSocket() {\n return new websocket_rule_builder_1.WebSocketRuleBuilder(this.addWebSocketRule);\n }\n}\nexports.AbstractMockttp = AbstractMockttp;\n//# sourceMappingURL=mockttp.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MockttpAdminRequestBuilder = exports.MockttpAdminPlugin = void 0;\nclass MockttpAdminPlugin {\n constructor() {\n throw new Error(\"MockttpAdminPlugin cannot be used within a browser\");\n }\n}\nexports.MockttpAdminPlugin = MockttpAdminPlugin;\nvar mockttp_admin_request_builder_1 = require(\"../client/mockttp-admin-request-builder\");\nObject.defineProperty(exports, \"MockttpAdminRequestBuilder\", { enumerable: true, get: function () { return mockttp_admin_request_builder_1.MockttpAdminRequestBuilder; } });\n//# sourceMappingURL=mockttp-pluggable-admin.browser.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Serialization = exports.AdminClient = exports.AdminServer = void 0;\nclass AdminServer {\n constructor() {\n throw new Error(\"AdminServer cannot be used within a browser\");\n }\n}\nexports.AdminServer = AdminServer;\nvar admin_client_1 = require(\"../client/admin-client\");\nObject.defineProperty(exports, \"AdminClient\", { enumerable: true, get: function () { return admin_client_1.AdminClient; } });\nexports.Serialization = require(\"../serialization/serialization\");\n//# sourceMappingURL=pluggable-admin.browser.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BaseRuleBuilder = void 0;\nconst lodash_1 = require(\"lodash\");\nconst types_1 = require(\"../types\");\nconst completion_checkers_1 = require(\"./completion-checkers\");\nconst matchers_1 = require(\"./matchers\");\n/**\n * @class BaseRuleBuilder\n *\n * Defines the base matching & completion methods, used for both normal\n * and websocket request handling, but excluding the handling itself\n * which differs between the two cases.\n */\nclass BaseRuleBuilder {\n /**\n * Mock rule builders should be constructed through the Mockttp instance you're\n * using, not directly. You shouldn't ever need to call this constructor.\n */\n constructor() {\n this.matchers = [];\n this.priority = types_1.RulePriority.DEFAULT;\n }\n buildBaseRuleData() {\n return {\n priority: this.priority,\n matchers: this.matchers,\n completionChecker: this.completionChecker\n };\n }\n /**\n * Set the rule priority. Any matching rule with a higher priority will always\n * take precedence over a matching lower-priority rule, unless the higher rule\n * has an explicit completion check (like `.once()`) that has already been\n * completed.\n *\n * The RulePriority enum defines the standard values useful for most cases,\n * but any positive number may be used for advanced configurations.\n *\n * In many cases it may be simpler to use forUnmatchedRequest() to set a fallback\n * rule explicitly, rather than manually setting the priority here.\n */\n asPriority(priority) {\n this.priority = priority;\n return this;\n }\n /**\n * Match only requests sent to the given host, i.e. the full hostname plus\n * port included in the request.\n *\n * This can behave somewhat confusingly when matching against the default\n * ports for a protocol (i.e. 80/443), or when specifying a hostname here\n * without specifying the port. In those cases it's usually better to use\n * forHostname and/or forPort instead to explicit match the content you're\n * interested in.\n *\n * @category Matching\n */\n forHost(host) {\n this.matchers.push(new matchers_1.HostMatcher(host));\n return this;\n }\n /**\n * Match only requests sent to the given hostname, ignoring the port.\n *\n * @category Matching\n */\n forHostname(hostname) {\n this.matchers.push(new matchers_1.HostnameMatcher(hostname));\n return this;\n }\n /**\n * Match only requests sent to the given port.\n *\n * @category Matching\n */\n forPort(port) {\n this.matchers.push(new matchers_1.PortMatcher(port));\n return this;\n }\n /**\n * Match only requests that include the given headers.\n * @category Matching\n */\n withHeaders(headers) {\n this.matchers.push(new matchers_1.HeaderMatcher(headers));\n return this;\n }\n /**\n * Match only requests that include the given query parameters.\n * @category Matching\n */\n withQuery(query) {\n this.matchers.push(new matchers_1.QueryMatcher(query));\n return this;\n }\n /**\n * Match only requests that include the exact query string provided.\n * The query string must start with a ? or be entirely empty.\n * @category Matching\n */\n withExactQuery(query) {\n this.matchers.push(new matchers_1.ExactQueryMatcher(query));\n return this;\n }\n /**\n * Match only requests whose bodies include the given URL-encoded form data.\n * @category Matching\n */\n withForm(formData) {\n this.matchers.push(new matchers_1.FormDataMatcher(formData));\n return this;\n }\n /**\n * Match only requests whose bodies include the given multipart form data.\n *\n * This can take any number of form parts to look for. Each part is specified\n * with {@link MultipartFieldMatchCondition} object containing one or more of\n * `name` (string), `filename` (string) and `content` (string or buffer) as\n * fields to match against in the form data.\n *\n * Requests are matched if all conditions match at least one part in the\n * request's form data.\n *\n * @category Matching\n */\n withMultipartForm(...matchConditions) {\n this.matchers.push(new matchers_1.MultipartFormDataMatcher(matchConditions));\n return this;\n }\n /**\n * Match only requests whose bodies either exactly match the given string\n * (if a string is passed) or whose bodies match a regular expression\n * (if a regex is passed).\n * @category Matching\n */\n withBody(content) {\n this.matchers.push((0, lodash_1.isString)(content)\n ? new matchers_1.RawBodyMatcher(content)\n : new matchers_1.RegexBodyMatcher(content));\n return this;\n }\n /**\n * Match only requests whose bodies include the given string.\n * @category Matching\n */\n withBodyIncluding(content) {\n this.matchers.push(new matchers_1.RawBodyIncludesMatcher(content));\n return this;\n }\n /**\n * Match only requests whose bodies exactly match the given\n * object, when parsed as JSON.\n *\n * Note that this only tests that the body can be parsed\n * as JSON - it doesn't require a content-type header.\n * @category Matching\n */\n withJsonBody(json) {\n this.matchers.push(new matchers_1.JsonBodyMatcher(json));\n return this;\n }\n /**\n * Match only requests whose bodies match (contain equivalent\n * values, ignoring extra values) the given object, when\n * parsed as JSON. Matching behaviour is the same as Lodash's\n * _.isMatch method.\n *\n * Note that this only tests that the body can be parsed\n * as JSON - it doesn't require a content-type header.\n * @category Matching\n */\n withJsonBodyIncluding(json) {\n this.matchers.push(new matchers_1.JsonBodyFlexibleMatcher(json));\n return this;\n }\n /**\n * Match only requests that include the given cookies\n * @category Matching\n */\n withCookie(cookie) {\n this.matchers.push(new matchers_1.CookieMatcher(cookie));\n return this;\n }\n /**\n * Match only requests sent with the given protocol.\n * @category Matching\n */\n withProtocol(protocol) {\n this.matchers.push(new matchers_1.ProtocolMatcher(protocol));\n return this;\n }\n /**\n * Match only requests whose absolute url matches the given RegExp.\n * @category Matching\n */\n withUrlMatching(pattern) {\n this.matchers.push(new matchers_1.RegexUrlMatcher(pattern));\n return this;\n }\n /**\n * Match only requests when the callback returns true\n * @category Matching\n */\n matching(content) {\n this.matchers.push(new matchers_1.CallbackMatcher(content));\n return this;\n }\n /**\n * Run this rule forever, for all matching requests\n * @category Completion\n */\n always() {\n this.completionChecker = new completion_checkers_1.Always();\n return this;\n }\n /**\n * Run this rule only once, for the first matching request\n * @category Completion\n */\n once() {\n this.completionChecker = new completion_checkers_1.Once();\n return this;\n }\n /**\n * Run this rule twice, for the first two matching requests\n * @category Completion\n */\n twice() {\n this.completionChecker = new completion_checkers_1.Twice();\n return this;\n }\n /**\n * Run this rule three times, for the first three matching requests\n * @category Completion\n */\n thrice() {\n this.completionChecker = new completion_checkers_1.Thrice();\n return this;\n }\n /**\n * Run this rule the given number of times, for the first matching requests\n * @category Completion\n */\n times(n) {\n this.completionChecker = new completion_checkers_1.NTimes(n);\n return this;\n }\n}\nexports.BaseRuleBuilder = BaseRuleBuilder;\n//# sourceMappingURL=base-rule-builder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CompletionCheckerLookup = exports.NTimes = exports.Thrice = exports.Twice = exports.Once = exports.Always = void 0;\nconst serialization_1 = require(\"../serialization/serialization\");\nclass Always extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'always';\n }\n isComplete() {\n return false;\n }\n explain(seenRequestCount) {\n return explainUntil(seenRequestCount, Infinity, 'always');\n }\n}\nexports.Always = Always;\nclass Once extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'once';\n }\n isComplete(seenRequestCount) {\n return seenRequestCount >= 1;\n }\n explain(seenRequestCount) {\n return explainUntil(seenRequestCount, 1, 'once');\n }\n}\nexports.Once = Once;\nclass Twice extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'twice';\n }\n isComplete(seenRequestCount) {\n return seenRequestCount >= 2;\n }\n explain(seenRequestCount) {\n return explainUntil(seenRequestCount, 2, 'twice');\n }\n}\nexports.Twice = Twice;\nclass Thrice extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'thrice';\n }\n isComplete(seenRequestCount) {\n return seenRequestCount >= 3;\n }\n explain(seenRequestCount) {\n return explainUntil(seenRequestCount, 3, 'thrice');\n }\n}\nexports.Thrice = Thrice;\nclass NTimes extends serialization_1.Serializable {\n constructor(count) {\n super();\n this.count = count;\n this.type = 'times';\n }\n isComplete(seenRequestCount) {\n return seenRequestCount >= this.count;\n }\n explain(seenRequestCount) {\n return explainUntil(seenRequestCount, this.count, `${this.count} times`);\n }\n}\nexports.NTimes = NTimes;\nexports.CompletionCheckerLookup = {\n 'always': Always,\n 'once': Once,\n 'twice': Twice,\n 'thrice': Thrice,\n 'times': NTimes\n};\nfunction explainUntil(seen, n, name) {\n if (seen === undefined) {\n // Generic explainer, without the specific count\n return name;\n }\n else {\n return name + \" \" + (seen < n ? `(seen ${seen})` : \"(done)\");\n }\n}\n//# sourceMappingURL=completion-checkers.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MatcherLookup = exports.CallbackMatcher = exports.CookieMatcher = exports.JsonBodyFlexibleMatcher = exports.JsonBodyMatcher = exports.RegexBodyMatcher = exports.RawBodyIncludesMatcher = exports.RawBodyMatcher = exports.MultipartFormDataMatcher = exports.FormDataMatcher = exports.QueryMatcher = exports.ExactQueryMatcher = exports.HeaderMatcher = exports.RegexUrlMatcher = exports.RegexPathMatcher = exports.SimplePathMatcher = exports.PortMatcher = exports.HostnameMatcher = exports.HostMatcher = exports.ProtocolMatcher = exports.MethodMatcher = exports.WildcardMatcher = void 0;\nexports.matchesAll = matchesAll;\nexports.explainMatchers = explainMatchers;\nconst _ = require(\"lodash\");\nconst url = require(\"url\");\nconst common_tags_1 = require(\"common-tags\");\nconst multipart = require(\"parse-multipart-data\");\nconst types_1 = require(\"../types\");\nconst url_1 = require(\"../util/url\");\nconst request_utils_1 = require(\"../util/request-utils\");\nconst serialization_1 = require(\"../serialization/serialization\");\nconst body_serialization_1 = require(\"../serialization/body-serialization\");\nfunction unescapeRegexp(input) {\n return input.replace(/\\\\\\//g, '/');\n}\nclass WildcardMatcher extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'wildcard';\n }\n matches() {\n return true;\n }\n explain() {\n return 'for anything';\n }\n}\nexports.WildcardMatcher = WildcardMatcher;\nclass MethodMatcher extends serialization_1.Serializable {\n constructor(method) {\n super();\n this.method = method;\n this.type = 'method';\n }\n matches(request) {\n return request.method === types_1.Method[this.method];\n }\n explain() {\n return `making ${types_1.Method[this.method]}s`;\n }\n}\nexports.MethodMatcher = MethodMatcher;\nclass ProtocolMatcher extends serialization_1.Serializable {\n constructor(protocol) {\n super();\n this.protocol = protocol;\n this.type = 'protocol';\n if (protocol !== \"http\" &&\n protocol !== \"https\" &&\n protocol !== \"ws\" &&\n protocol !== \"wss\") {\n throw new Error(\"Invalid protocol: protocol can only be 'http', 'https', 'ws' or 'wss'\");\n }\n }\n matches(request) {\n return request.protocol === this.protocol;\n }\n explain() {\n return `for protocol ${this.protocol}`;\n }\n}\nexports.ProtocolMatcher = ProtocolMatcher;\nclass HostMatcher extends serialization_1.Serializable {\n constructor(host) {\n super();\n this.host = host;\n this.type = 'host';\n // Validate the hostname. Goal here isn't to catch every bad hostname, but allow\n // every good hostname, and provide friendly errors for obviously bad hostnames.\n if (host.includes('/')) {\n throw new Error(\"Invalid hostname: hostnames can't contain slashes\");\n }\n else if (host.includes('?')) {\n throw new Error(\"Invalid hostname: hostnames can't contain query strings\");\n }\n else if (!host.match(/^([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+(:\\d+)?$/)) { // Port optional\n throw new Error(\"Hostname is invalid\");\n }\n }\n matches(request) {\n const parsedUrl = new url.URL(request.url);\n if ((this.host.endsWith(':80') && request.protocol === 'http') ||\n (this.host.endsWith(':443') && request.protocol === 'https')) {\n // On default ports, our URL normalization erases an explicit port, so that a\n // :80 here will never match anything. This handles that case: if you send HTTP\n // traffic on port 80 then the port is blank, but it should match for 'hostname:80'.\n return parsedUrl.hostname === this.host.split(':')[0] && parsedUrl.port === '';\n }\n else {\n return parsedUrl.host === this.host;\n }\n }\n explain() {\n return `for host ${this.host}`;\n }\n}\nexports.HostMatcher = HostMatcher;\nclass HostnameMatcher extends serialization_1.Serializable {\n constructor(hostname) {\n super();\n this.hostname = hostname;\n this.type = 'hostname';\n // Validate the hostname. Goal here isn't to catch every bad hostname, but allow\n // every good hostname, and provide friendly errors for obviously bad hostnames.\n if (hostname.includes('/')) {\n throw new Error(\"Invalid hostname: hostnames can't contain slashes\");\n }\n else if (hostname.includes('?')) {\n throw new Error(\"Invalid hostname: hostnames can't contain query strings\");\n }\n else if (!hostname.match(/^([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+$/)) { // No port\n throw new Error(\"Hostname is invalid\");\n }\n }\n matches(request) {\n return new url.URL(request.url).hostname === this.hostname;\n }\n explain() {\n return `for hostname ${this.hostname}`;\n }\n}\nexports.HostnameMatcher = HostnameMatcher;\nclass PortMatcher extends serialization_1.Serializable {\n constructor(port) {\n super();\n this.type = 'port';\n this.port = port.toString();\n }\n matches(request) {\n const parsedUrl = new url.URL(request.url);\n if ((this.port === '80' && request.protocol === 'http') ||\n (this.port === '443' && request.protocol === 'https')) {\n // The port is erased during our URL preprocessing if it's the default,\n // so for those cases we have to match that separately:\n return parsedUrl.port === '';\n }\n else {\n return new url.URL(request.url).port === this.port;\n }\n }\n explain() {\n return `for port ${this.port}`;\n }\n}\nexports.PortMatcher = PortMatcher;\nclass SimplePathMatcher extends serialization_1.Serializable {\n constructor(path) {\n super();\n this.path = path;\n this.type = 'simple-path';\n if (!this.path)\n throw new Error('Invalid URL: URL to match must not be empty');\n let { search, query } = url.parse(this.path, true);\n if (search) {\n throw new Error((0, common_tags_1.oneLine) `\n Tried to match a path that contained a query (${search}).\n To match query parameters, use .withQuery(${JSON.stringify(query)}) instead,\n or .withExactQuery('${search}') to match this exact query string.\n `);\n }\n (0, url_1.normalizeUrl)(this.path); // Fail if URL can't be normalized\n }\n matches(request) {\n const expectedUrl = (0, url_1.normalizeUrl)(this.path);\n const reqUrl = (0, url_1.normalizeUrl)(request.url);\n // reqUrl is always absolute, expectedUrl can be absolute, relative or protocolless-absolute\n if ((0, url_1.isRelativeUrl)(expectedUrl)) {\n // Match the path only, for any host\n return (0, url_1.getPathFromAbsoluteUrl)(reqUrl) === expectedUrl;\n }\n else if ((0, url_1.isAbsoluteUrl)(expectedUrl)) {\n // Full absolute URL: match everything\n return reqUrl === expectedUrl;\n }\n else {\n // Absolute URL with no protocol\n return (0, url_1.getUrlWithoutProtocol)(reqUrl) === expectedUrl;\n }\n }\n explain() {\n return `for ${this.path}`;\n }\n}\nexports.SimplePathMatcher = SimplePathMatcher;\nclass RegexPathMatcher extends serialization_1.Serializable {\n constructor(regex) {\n super();\n this.type = 'regex-path';\n this.regexSource = regex.source;\n this.regexFlags = regex.flags;\n }\n matches(request) {\n const absoluteUrl = (0, url_1.normalizeUrl)(request.url);\n const urlPath = (0, url_1.getPathFromAbsoluteUrl)(absoluteUrl);\n // Test the matcher against both the path alone & the full URL\n const urlMatcher = new RegExp(this.regexSource, this.regexFlags);\n return urlMatcher.test(absoluteUrl) ||\n urlMatcher.test(urlPath);\n }\n explain() {\n return `matching /${unescapeRegexp(this.regexSource)}/${this.regexFlags ?? ''}`;\n }\n}\nexports.RegexPathMatcher = RegexPathMatcher;\nclass RegexUrlMatcher extends serialization_1.Serializable {\n constructor(regex) {\n super();\n this.type = 'regex-url';\n this.regexSource = regex.source;\n this.regexFlags = regex.flags;\n }\n matches(request) {\n const absoluteUrl = (0, url_1.normalizeUrl)(request.url);\n // Test the matcher against the full URL\n const urlMatcher = new RegExp(this.regexSource, this.regexFlags);\n return urlMatcher.test(absoluteUrl);\n }\n explain() {\n return `matching URL /${unescapeRegexp(this.regexSource)}/${this.regexFlags ?? ''}`;\n }\n}\nexports.RegexUrlMatcher = RegexUrlMatcher;\nclass HeaderMatcher extends serialization_1.Serializable {\n constructor(headersInput) {\n super();\n this.type = 'header';\n this.headers = _.mapKeys(headersInput, (_value, key) => key.toLowerCase());\n }\n matches(request) {\n return _.isMatch(request.headers, this.headers);\n }\n explain() {\n return `with headers including ${JSON.stringify(this.headers)}`;\n }\n}\nexports.HeaderMatcher = HeaderMatcher;\nclass ExactQueryMatcher extends serialization_1.Serializable {\n constructor(query) {\n super();\n this.query = query;\n this.type = 'exact-query-string';\n if (query !== '' && query[0] !== '?') {\n throw new Error('Exact query matches must start with ?, or be empty');\n }\n }\n matches(request) {\n const { search } = url.parse(request.url);\n return this.query === search || (!search && !this.query);\n }\n explain() {\n return this.query\n ? `with a query exactly matching \\`${this.query}\\``\n : 'with no query string';\n }\n}\nexports.ExactQueryMatcher = ExactQueryMatcher;\nclass QueryMatcher extends serialization_1.Serializable {\n constructor(queryObjectInput) {\n super();\n this.type = 'query';\n this.queryObject = _.mapValues(queryObjectInput, (v) => Array.isArray(v) ? v.map(av => av.toString()) : v.toString());\n }\n matches(request) {\n let { query } = url.parse(request.url, true);\n return _.isMatch(query, this.queryObject);\n }\n explain() {\n return `with a query including ${JSON.stringify(this.queryObject)}`;\n }\n}\nexports.QueryMatcher = QueryMatcher;\nclass FormDataMatcher extends serialization_1.Serializable {\n constructor(formData) {\n super();\n this.formData = formData;\n this.type = 'form-data';\n }\n async matches(request) {\n const contentType = request.headers['content-type'];\n return !!contentType &&\n contentType.indexOf(\"application/x-www-form-urlencoded\") !== -1 &&\n _.isMatch(await request.body.asFormData(), this.formData);\n }\n explain() {\n return `with form data including ${JSON.stringify(this.formData)}`;\n }\n}\nexports.FormDataMatcher = FormDataMatcher;\nclass MultipartFormDataMatcher extends serialization_1.Serializable {\n constructor(matchConditions) {\n super();\n this.matchConditions = matchConditions;\n this.type = 'multipart-form-data';\n }\n async matches(request) {\n const contentType = request.headers['content-type'];\n if (!contentType)\n return false;\n if (!contentType.includes(\"multipart/form-data\"))\n return false;\n const boundary = contentType.match(/;\\s*boundary=(\\S+)/);\n if (!boundary)\n return false;\n const parsedBody = multipart.parse(await request.body.asDecodedBuffer(), boundary[1]);\n return this.matchConditions.every((condition) => {\n const expectedContent = condition.content\n ? Buffer.from(condition.content)\n : undefined;\n return parsedBody.some((part) => (expectedContent?.equals(part.data) || expectedContent === undefined) &&\n (condition.filename === part.filename || condition.filename === undefined) &&\n (condition.name === part.name || condition.name === undefined));\n });\n }\n explain() {\n return `with multipart form data matching ${JSON.stringify(this.matchConditions)}`;\n }\n}\nexports.MultipartFormDataMatcher = MultipartFormDataMatcher;\nclass RawBodyMatcher extends serialization_1.Serializable {\n constructor(content) {\n super();\n this.content = content;\n this.type = 'raw-body';\n }\n async matches(request) {\n return (await request.body.asText()) === this.content;\n }\n explain() {\n return `with body '${this.content}'`;\n }\n}\nexports.RawBodyMatcher = RawBodyMatcher;\nclass RawBodyIncludesMatcher extends serialization_1.Serializable {\n constructor(content) {\n super();\n this.content = content;\n this.type = 'raw-body-includes';\n }\n async matches(request) {\n return (await request.body.asText()).includes(this.content);\n }\n explain() {\n return `with a body including '${this.content}'`;\n }\n}\nexports.RawBodyIncludesMatcher = RawBodyIncludesMatcher;\nclass RegexBodyMatcher extends serialization_1.Serializable {\n constructor(regex) {\n super();\n this.type = 'raw-body-regexp';\n this.regexString = regex.source;\n }\n async matches(request) {\n let bodyMatcher = new RegExp(this.regexString);\n return bodyMatcher.test(await request.body.asText());\n }\n explain() {\n return `with a body matching /${unescapeRegexp(this.regexString)}/`;\n }\n}\nexports.RegexBodyMatcher = RegexBodyMatcher;\nclass JsonBodyMatcher extends serialization_1.Serializable {\n constructor(body) {\n super();\n this.body = body;\n this.type = 'json-body';\n }\n async matches(request) {\n const receivedBody = await (request.body.asJson().catch(() => undefined));\n if (receivedBody === undefined)\n return false;\n else\n return _.isEqual(receivedBody, this.body);\n }\n explain() {\n return `with a JSON body equivalent to ${JSON.stringify(this.body)}`;\n }\n}\nexports.JsonBodyMatcher = JsonBodyMatcher;\nclass JsonBodyFlexibleMatcher extends serialization_1.Serializable {\n constructor(body) {\n super();\n this.body = body;\n this.type = 'json-body-matching';\n }\n async matches(request) {\n const receivedBody = await (request.body.asJson().catch(() => undefined));\n if (receivedBody === undefined)\n return false;\n else\n return _.isMatch(receivedBody, this.body);\n }\n explain() {\n return `with a JSON body including ${JSON.stringify(this.body)}`;\n }\n}\nexports.JsonBodyFlexibleMatcher = JsonBodyFlexibleMatcher;\nclass CookieMatcher extends serialization_1.Serializable {\n constructor(cookie) {\n super();\n this.cookie = cookie;\n this.type = 'cookie';\n }\n async matches(request) {\n if (!request.headers || !request.headers.cookie) {\n return false;\n }\n const cookies = request.headers.cookie.split(';').map(cookie => {\n const [key, value] = cookie.split('=');\n return { [key.trim()]: (value || '').trim() };\n });\n return cookies.some(element => _.isEqual(element, this.cookie));\n }\n explain() {\n return `with cookies including ${JSON.stringify(this.cookie)}`;\n }\n}\nexports.CookieMatcher = CookieMatcher;\nclass CallbackMatcher extends serialization_1.Serializable {\n constructor(callback) {\n super();\n this.callback = callback;\n this.type = 'callback';\n }\n async matches(request) {\n const completedRequest = await (0, request_utils_1.waitForCompletedRequest)(request);\n return this.callback(completedRequest);\n }\n explain() {\n return `matches using provided callback${this.callback.name ? ` (${this.callback.name})` : ''}`;\n }\n /**\n * @internal\n */\n serialize(channel) {\n channel.onRequest(async (streamMsg) => {\n const request = (0, body_serialization_1.withDeserializedBodyReader)(streamMsg);\n const callbackResult = await this.callback.call(null, request);\n return callbackResult;\n });\n return { type: this.type, name: this.callback.name, version: 1 };\n }\n /**\n * @internal\n */\n static deserialize({ name }, channel) {\n const rpcCallback = async (request) => {\n const callbackResult = channel.request((0, body_serialization_1.withSerializedBodyReader)(request));\n return callbackResult;\n };\n // Pass across the name from the real callback, for explain()\n Object.defineProperty(rpcCallback, 'name', { value: name });\n // Call the client's callback (via stream), and save a handler on our end for\n // the response that comes back.\n return new CallbackMatcher(rpcCallback);\n }\n}\nexports.CallbackMatcher = CallbackMatcher;\nexports.MatcherLookup = {\n 'wildcard': WildcardMatcher,\n 'method': MethodMatcher,\n 'protocol': ProtocolMatcher,\n 'host': HostMatcher,\n 'hostname': HostnameMatcher,\n 'port': PortMatcher,\n 'simple-path': SimplePathMatcher,\n 'regex-path': RegexPathMatcher,\n 'regex-url': RegexUrlMatcher,\n 'header': HeaderMatcher,\n 'query': QueryMatcher,\n 'exact-query-string': ExactQueryMatcher,\n 'form-data': FormDataMatcher,\n 'multipart-form-data': MultipartFormDataMatcher,\n 'raw-body': RawBodyMatcher,\n 'raw-body-regexp': RegexBodyMatcher,\n 'raw-body-includes': RawBodyIncludesMatcher,\n 'json-body': JsonBodyMatcher,\n 'json-body-matching': JsonBodyFlexibleMatcher,\n 'cookie': CookieMatcher,\n 'callback': CallbackMatcher,\n};\nasync function matchesAll(req, matchers) {\n return new Promise((resolve, reject) => {\n const resultsPromises = matchers.map((matcher) => matcher.matches(req));\n resultsPromises.forEach(async (maybePromiseResult) => {\n try {\n const result = await maybePromiseResult;\n if (!result)\n resolve(false); // Resolve mismatches immediately\n }\n catch (e) {\n reject(e); // Resolve matcher failures immediately\n }\n });\n // Otherwise resolve as normal: all true matches, exceptions reject.\n Promise.all(resultsPromises)\n .then((result) => resolve(_.every(result)))\n .catch((e) => reject(e));\n });\n}\nfunction explainMatchers(matchers) {\n if (matchers.length === 1)\n return matchers[0].explain();\n if (matchers.length === 2) {\n // With just two explanations, you can just combine them\n return `${matchers[0].explain()} ${matchers[1].explain()}`;\n }\n // With 3+, we need to oxford comma separate explanations to make them readable\n return matchers.slice(0, -1)\n .map((m) => m.explain())\n .join(', ') + ', and ' + matchers.slice(-1)[0].explain();\n}\n//# sourceMappingURL=matchers.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.HandlerDefinitionLookup = exports.JsonRpcResponseHandlerDefinition = exports.TimeoutHandlerDefinition = exports.ResetConnectionHandlerDefinition = exports.CloseConnectionHandlerDefinition = exports.PassThroughHandlerDefinition = exports.SERIALIZED_OMIT = exports.FileHandlerDefinition = exports.StreamHandlerDefinition = exports.CallbackHandlerDefinition = exports.SimpleHandlerDefinition = void 0;\nconst _ = require(\"lodash\");\nconst url = require(\"url\");\nconst base64_arraybuffer_1 = require(\"base64-arraybuffer\");\nconst stream_1 = require(\"stream\");\nconst common_tags_1 = require(\"common-tags\");\nconst fast_json_patch_1 = require(\"fast-json-patch\");\nconst request_utils_1 = require(\"../../util/request-utils\");\nconst buffer_utils_1 = require(\"../../util/buffer-utils\");\nconst serialization_1 = require(\"../../serialization/serialization\");\nconst body_serialization_1 = require(\"../../serialization/body-serialization\");\nfunction validateCustomHeaders(originalHeaders, modifiedHeaders, headerWhitelist = []) {\n if (!modifiedHeaders)\n return;\n // We ignore most returned pseudo headers, so we error if you try to manually set them\n const invalidHeaders = _(modifiedHeaders)\n .pickBy((value, name) => name.toString().startsWith(':') &&\n // We allow returning a preexisting header value - that's ignored\n // silently, so that mutating & returning the provided headers is always safe.\n value !== originalHeaders[name] &&\n // In some cases, specific custom pseudoheaders may be allowed, e.g. requests\n // can have custom :scheme and :authority headers set.\n !headerWhitelist.includes(name))\n .keys();\n if (invalidHeaders.size() > 0) {\n throw new Error(`Cannot set custom ${invalidHeaders.join(', ')} pseudoheader values`);\n }\n}\nclass SimpleHandlerDefinition extends serialization_1.Serializable {\n constructor(status, statusMessage, data, headers, trailers) {\n super();\n this.status = status;\n this.statusMessage = statusMessage;\n this.data = data;\n this.headers = headers;\n this.trailers = trailers;\n this.type = 'simple';\n validateCustomHeaders({}, headers);\n validateCustomHeaders({}, trailers);\n if (!_.isEmpty(trailers) && headers) {\n if (!Object.entries(headers).some(([key, value]) => key.toLowerCase() === 'transfer-encoding' && value === 'chunked')) {\n throw new Error(\"Trailers can only be set when using chunked transfer encoding\");\n }\n }\n }\n explain() {\n return `respond with status ${this.status}` +\n (this.statusMessage ? ` (${this.statusMessage})` : \"\") +\n (this.headers ? `, headers ${JSON.stringify(this.headers)}` : \"\") +\n (this.data ? ` and body \"${this.data}\"` : \"\") +\n (this.trailers ? `then trailers ${JSON.stringify(this.trailers)}` : \"\");\n }\n}\nexports.SimpleHandlerDefinition = SimpleHandlerDefinition;\nclass CallbackHandlerDefinition extends serialization_1.Serializable {\n constructor(callback) {\n super();\n this.callback = callback;\n this.type = 'callback';\n }\n explain() {\n return 'respond using provided callback' + (this.callback.name ? ` (${this.callback.name})` : '');\n }\n /**\n * @internal\n */\n serialize(channel) {\n channel.onRequest(async (streamMsg) => {\n const request = _.isString(streamMsg.args[0].body)\n ? (0, body_serialization_1.withDeserializedBodyReader)(// New format: body serialized as base64\n streamMsg.args[0])\n : {\n ...streamMsg.args[0],\n body: (0, request_utils_1.buildBodyReader)(streamMsg.args[0].body.buffer, streamMsg.args[0].headers)\n };\n const callbackResult = await this.callback.call(null, request);\n if (typeof callbackResult === 'string') {\n return callbackResult;\n }\n else {\n return (0, body_serialization_1.withSerializedCallbackBuffers)(callbackResult);\n }\n });\n return { type: this.type, name: this.callback.name, version: 2 };\n }\n}\nexports.CallbackHandlerDefinition = CallbackHandlerDefinition;\n;\nclass StreamHandlerDefinition extends serialization_1.Serializable {\n constructor(status, stream, headers) {\n super();\n this.status = status;\n this.stream = stream;\n this.headers = headers;\n this.type = 'stream';\n validateCustomHeaders({}, headers);\n }\n explain() {\n return `respond with status ${this.status}` +\n (this.headers ? `, headers ${JSON.stringify(this.headers)},` : \"\") +\n ' and a stream of response data';\n }\n /**\n * @internal\n */\n serialize(channel) {\n const serializationStream = new stream_1.Transform({\n objectMode: true,\n transform: function (chunk, _encoding, callback) {\n let serializedEventData = _.isString(chunk) ? { type: 'string', value: chunk } :\n _.isBuffer(chunk) ? { type: 'buffer', value: chunk.toString('base64') } :\n (_.isArrayBuffer(chunk) || _.isTypedArray(chunk)) ? { type: 'arraybuffer', value: (0, base64_arraybuffer_1.encode)(chunk) } :\n _.isNil(chunk) && { type: 'nil' };\n if (!serializedEventData) {\n callback(new Error(`Can't serialize streamed value: ${chunk.toString()}. Streaming must output strings, buffers or array buffers`));\n }\n callback(undefined, {\n event: 'data',\n content: serializedEventData\n });\n },\n flush: function (callback) {\n this.push({\n event: 'end'\n });\n callback();\n }\n });\n // When we get a ping from the server-side, pipe the real stream to serialize it and send the data across\n channel.once('data', () => {\n this.stream.pipe(serializationStream).pipe(channel, { end: false });\n });\n return { type: this.type, status: this.status, headers: this.headers };\n }\n}\nexports.StreamHandlerDefinition = StreamHandlerDefinition;\nclass FileHandlerDefinition extends serialization_1.Serializable {\n constructor(status, statusMessage, filePath, headers) {\n super();\n this.status = status;\n this.statusMessage = statusMessage;\n this.filePath = filePath;\n this.headers = headers;\n this.type = 'file';\n validateCustomHeaders({}, headers);\n }\n explain() {\n return `respond with status ${this.status}` +\n (this.statusMessage ? ` (${this.statusMessage})` : \"\") +\n (this.headers ? `, headers ${JSON.stringify(this.headers)}` : \"\") +\n (this.filePath ? ` and body from file ${this.filePath}` : \"\");\n }\n}\nexports.FileHandlerDefinition = FileHandlerDefinition;\n/**\n * Used in merging as a marker for values to omit, because lodash ignores undefineds.\n * @internal\n */\nexports.SERIALIZED_OMIT = \"__mockttp__transform__omit__\";\nclass PassThroughHandlerDefinition extends serialization_1.Serializable {\n constructor(options = {}) {\n super();\n this.type = 'passthrough';\n this.ignoreHostHttpsErrors = [];\n this.extraCACertificates = [];\n // Used in subclass - awkwardly needs to be initialized here to ensure that its set when using a\n // handler built from a definition. In future, we could improve this (compose instead of inheritance\n // to better control handler construction?) but this will do for now.\n this.outgoingSockets = new Set();\n // If a location is provided, and it's not a bare hostname, it must be parseable\n const { forwarding } = options;\n if (forwarding && forwarding.targetHost.includes('/')) {\n const { protocol, hostname, port, path } = url.parse(forwarding.targetHost);\n if (path && path.trim() !== \"/\") {\n const suggestion = url.format({ protocol, hostname, port }) ||\n forwarding.targetHost.slice(0, forwarding.targetHost.indexOf('/'));\n throw new Error((0, common_tags_1.stripIndent) `\n URLs for forwarding cannot include a path, but \"${forwarding.targetHost}\" does. ${''}Did you mean ${suggestion}?\n `);\n }\n }\n this.forwarding = forwarding;\n this.ignoreHostHttpsErrors = options.ignoreHostHttpsErrors || [];\n if (!Array.isArray(this.ignoreHostHttpsErrors) && typeof this.ignoreHostHttpsErrors !== 'boolean') {\n throw new Error(\"ignoreHostHttpsErrors must be an array or a boolean\");\n }\n this.lookupOptions = options.lookupOptions;\n this.proxyConfig = options.proxyConfig;\n this.simulateConnectionErrors = !!options.simulateConnectionErrors;\n this.extraCACertificates =\n options.additionalTrustedCAs ||\n options.trustAdditionalCAs ||\n [];\n this.clientCertificateHostMap = options.clientCertificateHostMap || {};\n if (options.beforeRequest && options.transformRequest && !_.isEmpty(options.transformRequest)) {\n throw new Error(\"BeforeRequest and transformRequest options are mutually exclusive\");\n }\n else if (options.beforeRequest) {\n this.beforeRequest = options.beforeRequest;\n }\n else if (options.transformRequest) {\n if ([\n options.transformRequest.updateHeaders,\n options.transformRequest.replaceHeaders\n ].filter(o => !!o).length > 1) {\n throw new Error(\"Only one request header transform can be specified at a time\");\n }\n if ([\n options.transformRequest.replaceBody,\n options.transformRequest.replaceBodyFromFile,\n options.transformRequest.updateJsonBody,\n options.transformRequest.patchJsonBody,\n options.transformRequest.matchReplaceBody\n ].filter(o => !!o).length > 1) {\n throw new Error(\"Only one request body transform can be specified at a time\");\n }\n if (options.transformRequest.patchJsonBody) {\n const validationError = (0, fast_json_patch_1.validate)(options.transformRequest.patchJsonBody);\n if (validationError)\n throw validationError;\n }\n this.transformRequest = options.transformRequest;\n }\n if (options.beforeResponse && options.transformResponse && !_.isEmpty(options.transformResponse)) {\n throw new Error(\"BeforeResponse and transformResponse options are mutually exclusive\");\n }\n else if (options.beforeResponse) {\n this.beforeResponse = options.beforeResponse;\n }\n else if (options.transformResponse) {\n if ([\n options.transformResponse.updateHeaders,\n options.transformResponse.replaceHeaders\n ].filter(o => !!o).length > 1) {\n throw new Error(\"Only one response header transform can be specified at a time\");\n }\n if ([\n options.transformResponse.replaceBody,\n options.transformResponse.replaceBodyFromFile,\n options.transformResponse.updateJsonBody,\n options.transformResponse.patchJsonBody,\n options.transformResponse.matchReplaceBody\n ].filter(o => !!o).length > 1) {\n throw new Error(\"Only one response body transform can be specified at a time\");\n }\n if (options.transformResponse.patchJsonBody) {\n const validationError = (0, fast_json_patch_1.validate)(options.transformResponse.patchJsonBody);\n if (validationError)\n throw validationError;\n }\n this.transformResponse = options.transformResponse;\n }\n }\n explain() {\n return this.forwarding\n ? `forward the request to ${this.forwarding.targetHost}`\n : 'pass the request through to the target host';\n }\n /**\n * @internal\n */\n serialize(channel) {\n if (this.beforeRequest) {\n channel.onRequest('beforeRequest', async (req) => {\n const callbackResult = await this.beforeRequest((0, body_serialization_1.withDeserializedBodyReader)(req.args[0]));\n const serializedResult = callbackResult\n ? (0, body_serialization_1.withSerializedCallbackBuffers)(callbackResult)\n : undefined;\n if (serializedResult?.response && typeof serializedResult?.response !== 'string') {\n serializedResult.response = (0, body_serialization_1.withSerializedCallbackBuffers)(serializedResult.response);\n }\n return serializedResult;\n });\n }\n if (this.beforeResponse) {\n channel.onRequest('beforeResponse', async (req) => {\n const callbackResult = await this.beforeResponse((0, body_serialization_1.withDeserializedBodyReader)(req.args[0]));\n if (typeof callbackResult === 'string') {\n return callbackResult;\n }\n else if (callbackResult) {\n return (0, body_serialization_1.withSerializedCallbackBuffers)(callbackResult);\n }\n else {\n return undefined;\n }\n });\n }\n return {\n type: this.type,\n ...this.forwarding ? {\n forwarding: this.forwarding,\n // Backward compat:\n forwardToLocation: this.forwarding.targetHost\n } : {},\n proxyConfig: (0, serialization_1.serializeProxyConfig)(this.proxyConfig, channel),\n lookupOptions: this.lookupOptions,\n simulateConnectionErrors: this.simulateConnectionErrors,\n ignoreHostCertificateErrors: this.ignoreHostHttpsErrors,\n extraCACertificates: this.extraCACertificates.map((certObject) => {\n // We use toString to make sure that buffers always end up as\n // as UTF-8 string, to avoid serialization issues. Strings are an\n // easy safe format here, since it's really all just plain-text PEM\n // under the hood.\n if ('cert' in certObject) {\n return { cert: certObject.cert.toString('utf8') };\n }\n else {\n return certObject;\n }\n }),\n clientCertificateHostMap: _.mapValues(this.clientCertificateHostMap, ({ pfx, passphrase }) => ({ pfx: (0, serialization_1.serializeBuffer)(pfx), passphrase })),\n transformRequest: this.transformRequest ? {\n ...this.transformRequest,\n // Body is always serialized as a base64 buffer:\n replaceBody: !!this.transformRequest?.replaceBody\n ? (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(this.transformRequest.replaceBody))\n : undefined,\n // Update objects need to capture undefined & null as distict values:\n updateHeaders: !!this.transformRequest?.updateHeaders\n ? JSON.stringify(this.transformRequest.updateHeaders, (k, v) => v === undefined ? exports.SERIALIZED_OMIT : v)\n : undefined,\n updateJsonBody: !!this.transformRequest?.updateJsonBody\n ? JSON.stringify(this.transformRequest.updateJsonBody, (k, v) => v === undefined ? exports.SERIALIZED_OMIT : v)\n : undefined,\n matchReplaceBody: !!this.transformRequest?.matchReplaceBody\n ? this.transformRequest.matchReplaceBody.map(([match, result]) => [\n _.isRegExp(match)\n ? { regexSource: match.source, flags: match.flags }\n : match,\n result\n ])\n : undefined,\n } : undefined,\n transformResponse: this.transformResponse ? {\n ...this.transformResponse,\n // Body is always serialized as a base64 buffer:\n replaceBody: !!this.transformResponse?.replaceBody\n ? (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(this.transformResponse.replaceBody))\n : undefined,\n // Update objects need to capture undefined & null as distict values:\n updateHeaders: !!this.transformResponse?.updateHeaders\n ? JSON.stringify(this.transformResponse.updateHeaders, (k, v) => v === undefined ? exports.SERIALIZED_OMIT : v)\n : undefined,\n updateJsonBody: !!this.transformResponse?.updateJsonBody\n ? JSON.stringify(this.transformResponse.updateJsonBody, (k, v) => v === undefined ? exports.SERIALIZED_OMIT : v)\n : undefined,\n matchReplaceBody: !!this.transformResponse?.matchReplaceBody\n ? this.transformResponse.matchReplaceBody.map(([match, result]) => [\n _.isRegExp(match)\n ? { regexSource: match.source, flags: match.flags }\n : match,\n result\n ])\n : undefined,\n } : undefined,\n hasBeforeRequestCallback: !!this.beforeRequest,\n hasBeforeResponseCallback: !!this.beforeResponse\n };\n }\n}\nexports.PassThroughHandlerDefinition = PassThroughHandlerDefinition;\nclass CloseConnectionHandlerDefinition extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'close-connection';\n }\n explain() {\n return 'close the connection';\n }\n}\nexports.CloseConnectionHandlerDefinition = CloseConnectionHandlerDefinition;\nclass ResetConnectionHandlerDefinition extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'reset-connection';\n }\n explain() {\n return 'reset the connection';\n }\n}\nexports.ResetConnectionHandlerDefinition = ResetConnectionHandlerDefinition;\nclass TimeoutHandlerDefinition extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'timeout';\n }\n explain() {\n return 'time out (never respond)';\n }\n}\nexports.TimeoutHandlerDefinition = TimeoutHandlerDefinition;\nclass JsonRpcResponseHandlerDefinition extends serialization_1.Serializable {\n constructor(result) {\n super();\n this.result = result;\n this.type = 'json-rpc-response';\n if (!('result' in result) && !('error' in result)) {\n throw new Error('JSON-RPC response must be either a result or an error');\n }\n }\n explain() {\n const resultType = 'result' in this.result\n ? 'result'\n : 'error';\n return `send a fixed JSON-RPC ${resultType} of ${JSON.stringify(this.result[resultType])}`;\n }\n}\nexports.JsonRpcResponseHandlerDefinition = JsonRpcResponseHandlerDefinition;\nexports.HandlerDefinitionLookup = {\n 'simple': SimpleHandlerDefinition,\n 'callback': CallbackHandlerDefinition,\n 'stream': StreamHandlerDefinition,\n 'file': FileHandlerDefinition,\n 'passthrough': PassThroughHandlerDefinition,\n 'close-connection': CloseConnectionHandlerDefinition,\n 'reset-connection': ResetConnectionHandlerDefinition,\n 'timeout': TimeoutHandlerDefinition,\n 'json-rpc-response': JsonRpcResponseHandlerDefinition\n};\n//# sourceMappingURL=request-handler-definitions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RequestRuleBuilder = void 0;\nconst lodash_1 = require(\"lodash\");\nconst request_handler_definitions_1 = require(\"./request-handler-definitions\");\nconst util_1 = require(\"../../util/util\");\nconst base_rule_builder_1 = require(\"../base-rule-builder\");\nconst matchers_1 = require(\"../matchers\");\n/**\n * @class RequestRuleBuilder\n\n * A builder for defining mock rules. Create one using a method like\n * `.forGet(path)` or `.forPost(path)` on a Mockttp instance, then call\n * whatever methods you'd like here to define more precise request\n * matching behaviour, control how the request is handled, and how\n * many times this rule should be applied.\n *\n * When you're done, call a `.thenX()` method to register the configured rule\n * with the server. These return a promise for a MockedEndpoint, which can be\n * used to verify the details of the requests matched by the rule.\n *\n * This returns a promise because rule registration can be asynchronous,\n * either when using a remote server or testing in the browser. Wait for the\n * promise returned by `.thenX()` methods to guarantee that the rule has taken\n * effect before sending requests to it.\n */\nclass RequestRuleBuilder extends base_rule_builder_1.BaseRuleBuilder {\n constructor(methodOrAddRule, path, addRule) {\n super();\n // Add the basic method and path matchers inititally, if provided:\n const method = methodOrAddRule instanceof Function ? undefined : methodOrAddRule;\n if (method === undefined && path === undefined) {\n this.matchers.push(new matchers_1.WildcardMatcher());\n }\n else {\n if (method !== undefined) {\n this.matchers.push(new matchers_1.MethodMatcher(method));\n }\n if (path instanceof RegExp) {\n this.matchers.push(new matchers_1.RegexPathMatcher(path));\n }\n else if (typeof path === 'string') {\n this.matchers.push(new matchers_1.SimplePathMatcher(path));\n }\n }\n // Store the addRule callback:\n if (methodOrAddRule instanceof Function) {\n this.addRule = methodOrAddRule;\n }\n else {\n this.addRule = addRule;\n }\n }\n thenReply(status, dataOrMessage, dataOrHeaders, headersOrTrailers, trailers) {\n let data;\n let statusMessage;\n let headers;\n if ((0, lodash_1.isBuffer)(dataOrHeaders) || (0, lodash_1.isString)(dataOrHeaders)) {\n data = dataOrHeaders;\n statusMessage = dataOrMessage;\n headers = headersOrTrailers;\n }\n else {\n data = dataOrMessage;\n headers = dataOrHeaders;\n trailers = headersOrTrailers;\n }\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.SimpleHandlerDefinition(status, statusMessage, data, headers, trailers)\n };\n return this.addRule(rule);\n }\n /**\n * Reply to matched requests with the given status & JSON and (optionally)\n * extra headers.\n *\n * This method is (approximately) shorthand for:\n * server.forGet(...).thenReply(status, JSON.stringify(data), { 'Content-Type': 'application/json' })\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenJson(status, data, headers = {}) {\n const jsonData = JSON.stringify(data);\n headers = (0, lodash_1.merge)({\n 'Content-Type': 'application/json',\n 'Content-Length': (0, util_1.byteLength)(jsonData).toString(),\n 'Connection': 'keep-alive'\n // ^ Neither strictly required, but without both Node will close the server\n // connection after the response is sent, which can confuse clients.\n }, headers);\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.SimpleHandlerDefinition(status, undefined, jsonData, headers)\n };\n return this.addRule(rule);\n }\n /**\n * Call the given callback for any matched requests that are received,\n * and build a response from the result.\n *\n * The callback should return a response object with the fields as\n * defined by {@link CallbackResponseMessageResult} to define the response,\n * or the string 'close' to immediately close the connection. The callback\n * can be asynchronous, in which case it should return this value wrapped\n * in a promise.\n *\n * If the callback throws an exception, the server will return a 500\n * with the exception message.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenCallback(callback) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.CallbackHandlerDefinition(callback)\n };\n return this.addRule(rule);\n }\n /**\n * Respond immediately with the given status (and optionally, headers),\n * and then stream the given stream directly as the response body.\n *\n * Note that streams can typically only be read once, and as such\n * this rule will only successfully trigger once. Subsequent requests\n * will receive a 500 and an explanatory error message. To mock\n * repeated requests with streams, create multiple streams and mock\n * them independently.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenStream(status, stream, headers) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.StreamHandlerDefinition(status, stream, headers)\n };\n return this.addRule(rule);\n }\n thenFromFile(status, pathOrMessage, pathOrHeaders, headers) {\n let path;\n let statusMessage;\n if ((0, lodash_1.isString)(pathOrHeaders)) {\n path = pathOrHeaders;\n statusMessage = pathOrMessage;\n }\n else {\n path = pathOrMessage;\n headers = pathOrHeaders;\n }\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.FileHandlerDefinition(status, statusMessage, path, headers)\n };\n return this.addRule(rule);\n }\n /**\n * Pass matched requests through to their real destination. This works\n * for proxied requests only, direct requests will be rejected with\n * an error.\n *\n * This method takes options to configure how the request is passed\n * through. See {@link PassThroughHandlerOptions} for the full details\n * of the options available.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenPassThrough(options) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.PassThroughHandlerDefinition(options)\n };\n return this.addRule(rule);\n }\n /**\n * Forward matched requests on to the specified forwardToUrl. The url\n * specified must not include a path. Otherwise, an error is thrown.\n * The path portion of the original request url is used instead.\n *\n * The url may optionally contain a protocol. If it does, it will override\n * the protocol (and potentially the port, if unspecified) of the request.\n * If no protocol is specified, the protocol (and potentially the port)\n * of the original request URL will be used instead.\n *\n * This method takes options to configure how the request is passed\n * through. See {@link PassThroughHandlerOptions} for the full details\n * of the options available.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n async thenForwardTo(forwardToLocation, options = {}) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.PassThroughHandlerDefinition({\n ...options,\n forwarding: {\n ...options.forwarding,\n targetHost: forwardToLocation\n }\n })\n };\n return this.addRule(rule);\n }\n /**\n * Close connections that match this rule immediately, without\n * any status code or response.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenCloseConnection() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.CloseConnectionHandlerDefinition()\n };\n return this.addRule(rule);\n }\n /**\n * Reset connections that match this rule immediately, sending a TCP\n * RST packet directly, without any status code or response, and without\n * cleanly closing the TCP connection.\n *\n * This is only supported in Node.js versions (>=16.17, >=18.3.0, or\n * later), where `net.Socket` includes the `resetAndDestroy` method.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenResetConnection() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.ResetConnectionHandlerDefinition()\n };\n return this.addRule(rule);\n }\n /**\n * Hold open connections that match this rule, but never respond\n * with anything at all, typically causing a timeout on the client side.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenTimeout() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.TimeoutHandlerDefinition()\n };\n return this.addRule(rule);\n }\n /**\n * Send a successful JSON-RPC response to a JSON-RPC request. The response data\n * can be any JSON-serializable value. If a matching request is received that\n * is not a valid JSON-RPC request, it will be rejected with an HTTP error.\n *\n * @category Responses\n */\n thenSendJsonRpcResult(result) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.JsonRpcResponseHandlerDefinition({ result })\n };\n return this.addRule(rule);\n }\n /**\n * Send a failing error JSON-RPC response to a JSON-RPC request. The error data\n * can be any JSON-serializable value. If a matching request is received that\n * is not a valid JSON-RPC request, it will be rejected with an HTTP error.\n *\n * @category Responses\n */\n thenSendJsonRpcError(error) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new request_handler_definitions_1.JsonRpcResponseHandlerDefinition({ error })\n };\n return this.addRule(rule);\n }\n}\nexports.RequestRuleBuilder = RequestRuleBuilder;\n//# sourceMappingURL=request-rule-builder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MOCKTTP_PARAM_REF = void 0;\nexports.isParamReference = isParamReference;\nexports.dereferenceParam = dereferenceParam;\nexports.assertParamDereferenced = assertParamDereferenced;\nexports.MOCKTTP_PARAM_REF = Symbol('MOCKTTP_PARAM_REF');\nfunction isParamReference(input) {\n return input && !!input[exports.MOCKTTP_PARAM_REF];\n}\n;\nfunction dereferenceParam(paramRef, params) {\n const paramKey = paramRef[exports.MOCKTTP_PARAM_REF];\n if (paramKey in params) {\n return params[paramKey];\n }\n else {\n throw new Error(`Invalid reference to undefined rule parameter '${paramKey}'`);\n }\n}\n;\nfunction assertParamDereferenced(maybeParamRef) {\n if (isParamReference(maybeParamRef)) {\n const paramKey = maybeParamRef[exports.MOCKTTP_PARAM_REF];\n throw new Error(`Non-dereferenced rule parameter used unexpectedly: ${paramKey}`);\n }\n else {\n return maybeParamRef;\n }\n}\n//# sourceMappingURL=rule-parameters.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateMockRuleData = validateMockRuleData;\nexports.serializeRuleData = serializeRuleData;\nconst serialization_1 = require(\"../serialization/serialization\");\nfunction validateMockRuleData(data) {\n if (!data.matchers || data.matchers.length === 0) {\n throw new Error('Cannot create a rule without at least one matcher');\n }\n if (!data.handler) {\n throw new Error('Cannot create a rule with no handler');\n }\n}\nfunction serializeRuleData(data, stream) {\n validateMockRuleData(data);\n return {\n id: data.id,\n priority: data.priority,\n matchers: data.matchers.map(m => (0, serialization_1.serialize)(m, stream)),\n handler: (0, serialization_1.serialize)(data.handler, stream),\n completionChecker: data.completionChecker && (0, serialization_1.serialize)(data.completionChecker, stream)\n };\n}\n;\n//# sourceMappingURL=rule-serialization.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WsHandlerDefinitionLookup = exports.TimeoutHandlerDefinition = exports.ResetConnectionHandlerDefinition = exports.CloseConnectionHandlerDefinition = exports.RejectWebSocketHandlerDefinition = exports.ListenWebSocketHandlerDefinition = exports.EchoWebSocketHandlerDefinition = exports.PassThroughWebSocketHandlerDefinition = void 0;\nconst _ = require(\"lodash\");\nconst url = require(\"url\");\nconst common_tags_1 = require(\"common-tags\");\nconst serialization_1 = require(\"../../serialization/serialization\");\nconst request_handler_definitions_1 = require(\"../requests/request-handler-definitions\");\nObject.defineProperty(exports, \"CloseConnectionHandlerDefinition\", { enumerable: true, get: function () { return request_handler_definitions_1.CloseConnectionHandlerDefinition; } });\nObject.defineProperty(exports, \"ResetConnectionHandlerDefinition\", { enumerable: true, get: function () { return request_handler_definitions_1.ResetConnectionHandlerDefinition; } });\nObject.defineProperty(exports, \"TimeoutHandlerDefinition\", { enumerable: true, get: function () { return request_handler_definitions_1.TimeoutHandlerDefinition; } });\nclass PassThroughWebSocketHandlerDefinition extends serialization_1.Serializable {\n constructor(options = {}) {\n super();\n this.type = 'ws-passthrough';\n this.ignoreHostHttpsErrors = [];\n this.extraCACertificates = [];\n // If a location is provided, and it's not a bare hostname, it must be parseable\n const { forwarding } = options;\n if (forwarding && forwarding.targetHost.includes('/')) {\n const { protocol, hostname, port, path } = url.parse(forwarding.targetHost);\n if (path && path.trim() !== \"/\") {\n const suggestion = url.format({ protocol, hostname, port }) ||\n forwarding.targetHost.slice(0, forwarding.targetHost.indexOf('/'));\n throw new Error((0, common_tags_1.stripIndent) `\n URLs for forwarding cannot include a path, but \"${forwarding.targetHost}\" does. ${''}Did you mean ${suggestion}?\n `);\n }\n }\n this.forwarding = options.forwarding;\n this.ignoreHostHttpsErrors = options.ignoreHostHttpsErrors || [];\n if (!Array.isArray(this.ignoreHostHttpsErrors) && typeof this.ignoreHostHttpsErrors !== 'boolean') {\n throw new Error(\"ignoreHostHttpsErrors must be an array or a boolean\");\n }\n this.lookupOptions = options.lookupOptions;\n this.proxyConfig = options.proxyConfig;\n this.extraCACertificates =\n options.additionalTrustedCAs ||\n options.trustAdditionalCAs ||\n [];\n this.clientCertificateHostMap = options.clientCertificateHostMap || {};\n }\n explain() {\n return this.forwarding\n ? `forward the websocket to ${this.forwarding.targetHost}`\n : 'pass the request through to the target host';\n }\n /**\n * @internal\n */\n serialize(channel) {\n return {\n type: this.type,\n forwarding: this.forwarding,\n lookupOptions: this.lookupOptions,\n proxyConfig: (0, serialization_1.serializeProxyConfig)(this.proxyConfig, channel),\n ignoreHostCertificateErrors: this.ignoreHostHttpsErrors,\n extraCACertificates: this.extraCACertificates.map((certObject) => {\n // We use toString to make sure that buffers always end up as\n // as UTF-8 string, to avoid serialization issues. Strings are an\n // easy safe format here, since it's really all just plain-text PEM\n // under the hood.\n if ('cert' in certObject) {\n return { cert: certObject.cert.toString('utf8') };\n }\n else {\n return certObject;\n }\n }),\n clientCertificateHostMap: _.mapValues(this.clientCertificateHostMap, ({ pfx, passphrase }) => ({ pfx: (0, serialization_1.serializeBuffer)(pfx), passphrase }))\n };\n }\n}\nexports.PassThroughWebSocketHandlerDefinition = PassThroughWebSocketHandlerDefinition;\nclass EchoWebSocketHandlerDefinition extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'ws-echo';\n }\n explain() {\n return \"echo all websocket messages\";\n }\n}\nexports.EchoWebSocketHandlerDefinition = EchoWebSocketHandlerDefinition;\nclass ListenWebSocketHandlerDefinition extends serialization_1.Serializable {\n constructor() {\n super(...arguments);\n this.type = 'ws-listen';\n }\n explain() {\n return \"silently accept websocket messages without responding\";\n }\n}\nexports.ListenWebSocketHandlerDefinition = ListenWebSocketHandlerDefinition;\nclass RejectWebSocketHandlerDefinition extends serialization_1.Serializable {\n constructor(statusCode, statusMessage = 'WebSocket rejected', headers = {}, body = '') {\n super();\n this.statusCode = statusCode;\n this.statusMessage = statusMessage;\n this.headers = headers;\n this.body = body;\n this.type = 'ws-reject';\n }\n explain() {\n return `explicitly reject the websocket upgrade with status ${this.statusCode}`;\n }\n}\nexports.RejectWebSocketHandlerDefinition = RejectWebSocketHandlerDefinition;\nexports.WsHandlerDefinitionLookup = {\n 'ws-passthrough': PassThroughWebSocketHandlerDefinition,\n 'ws-echo': EchoWebSocketHandlerDefinition,\n 'ws-listen': ListenWebSocketHandlerDefinition,\n 'ws-reject': RejectWebSocketHandlerDefinition,\n 'close-connection': request_handler_definitions_1.CloseConnectionHandlerDefinition,\n 'reset-connection': request_handler_definitions_1.ResetConnectionHandlerDefinition,\n 'timeout': request_handler_definitions_1.TimeoutHandlerDefinition\n};\n//# sourceMappingURL=websocket-handler-definitions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WebSocketRuleBuilder = void 0;\nconst websocket_handler_definitions_1 = require(\"./websocket-handler-definitions\");\nconst base_rule_builder_1 = require(\"../base-rule-builder\");\nconst matchers_1 = require(\"../matchers\");\n/**\n * @class WebSocketRuleBuilder\n\n * A builder for defining websocket mock rules. Create one using\n * `.forAnyWebSocket(path)` on a Mockttp instance, then call whatever\n * methods you'd like here to define more precise matching behaviour,\n * control how the connection is handled, and how many times this\n * rule should be applied.\n *\n * When you're done, call a `.thenX()` method to register the configured rule\n * with the server. These return a promise for a MockedEndpoint, which can be\n * used to verify the details of the requests matched by the rule.\n *\n * This returns a promise because rule registration can be asynchronous,\n * either when using a remote server or testing in the browser. Wait for the\n * promise returned by `.thenX()` methods to guarantee that the rule has taken\n * effect before sending requests to it.\n */\nclass WebSocketRuleBuilder extends base_rule_builder_1.BaseRuleBuilder {\n /**\n * Mock rule builders should be constructed through the Mockttp instance you're\n * using, not directly. You shouldn't ever need to call this constructor.\n */\n constructor(addRule) {\n super();\n this.addRule = addRule;\n // By default, websockets just match everything:\n this.matchers.push(new matchers_1.WildcardMatcher());\n }\n /**\n * Pass matched websockets through to their real destination. This works\n * for proxied requests only, and direct requests will be rejected with\n * an error.\n *\n * This method takes options to configure how the request is passed\n * through. See {@link PassThroughWebSocketHandlerOptions} for the full\n * details of the options available.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenPassThrough(options = {}) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.PassThroughWebSocketHandlerDefinition(options)\n };\n return this.addRule(rule);\n }\n /**\n * Forward matched websockets on to the specified forwardToUrl. The url\n * specified must not include a path or an error will be thrown.\n * The path portion of the original request url is used instead.\n *\n * The url may optionally contain a protocol. If it does, it will override\n * the protocol (and potentially the port, if unspecified) of the request.\n * If no protocol is specified, the protocol (and potentially the port)\n * of the original request URL will be used instead.\n *\n * This method takes options to configure how the request is passed\n * through. See {@link PassThroughWebSocketHandlerOptions} for the full\n * details of the options available.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n async thenForwardTo(forwardToLocation, options = {}) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.PassThroughWebSocketHandlerDefinition({\n ...options,\n forwarding: {\n ...options.forwarding,\n targetHost: forwardToLocation\n }\n })\n };\n return this.addRule(rule);\n }\n /**\n * Accept incoming WebSocket connections, and echo every message\n * received on the WebSocket back to the client.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenEcho() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.EchoWebSocketHandlerDefinition()\n };\n return this.addRule(rule);\n }\n /**\n * Accept incoming WebSocket connections, and simply listen to\n * incoming messages without ever sending anything in return.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenPassivelyListen() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.ListenWebSocketHandlerDefinition()\n };\n return this.addRule(rule);\n }\n /**\n * Rejects connections, sending an HTTP response with the given\n * status, message and body, to explicitly refuse the WebSocket\n * handshake.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenRejectConnection(statusCode, statusMessage, headers, body) {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.RejectWebSocketHandlerDefinition(statusCode, statusMessage, headers, body)\n };\n return this.addRule(rule);\n }\n /**\n * Close connections that match this rule immediately, without accepting\n * the socket or sending any other response.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenCloseConnection() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.CloseConnectionHandlerDefinition()\n };\n return this.addRule(rule);\n }\n /**\n * Reset connections that match this rule immediately, sending a TCP\n * RST packet directly, without accepting the socket or sending any\n * other response, and without cleanly closing the TCP connection.\n *\n * This is only supported in Node.js versions (>=16.17, >=18.3.0, or\n * later), where `net.Socket` includes the `resetAndDestroy` method.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenResetConnection() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.ResetConnectionHandlerDefinition()\n };\n return this.addRule(rule);\n }\n /**\n * Hold open connections that match this rule, but never respond\n * with anything at all, typically causing a timeout on the client side.\n *\n * Calling this method registers the rule with the server, so it\n * starts to handle requests.\n *\n * This method returns a promise that resolves with a mocked endpoint.\n * Wait for the promise to confirm that the rule has taken effect\n * before sending requests to be matched. The mocked endpoint\n * can be used to assert on the requests matched by this rule.\n *\n * @category Responses\n */\n thenTimeout() {\n const rule = {\n ...this.buildBaseRuleData(),\n handler: new websocket_handler_definitions_1.TimeoutHandlerDefinition()\n };\n return this.addRule(rule);\n }\n}\nexports.WebSocketRuleBuilder = WebSocketRuleBuilder;\n//# sourceMappingURL=websocket-rule-builder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.withSerializedBodyReader = withSerializedBodyReader;\nexports.withDeserializedBodyReader = withDeserializedBodyReader;\nexports.withSerializedCallbackBuffers = withSerializedCallbackBuffers;\nexports.withDeserializedCallbackBuffers = withDeserializedCallbackBuffers;\nconst _ = require(\"lodash\");\nconst base64_arraybuffer_1 = require(\"base64-arraybuffer\");\nconst buffer_utils_1 = require(\"../util/buffer-utils\");\nconst request_utils_1 = require(\"../util/request-utils\");\nconst serialization_1 = require(\"./serialization\");\nfunction withSerializedBodyReader(input) {\n return {\n ...input,\n body: (0, buffer_utils_1.asBuffer)(input.body.buffer).toString('base64')\n };\n}\nfunction withDeserializedBodyReader(input) {\n return {\n ...input,\n body: (0, request_utils_1.buildBodyReader)((0, serialization_1.deserializeBuffer)(input.body), input.headers)\n };\n}\n/**\n * Serialize a callback result (callback handlers, BeforeRequest/Response etc)\n * to transform all the many possible buffer formats into either base64-encoded\n * buffer data, or undefined.\n */\nfunction withSerializedCallbackBuffers(input) {\n let serializedBody;\n if (!input.body) {\n serializedBody = undefined;\n }\n else if (_.isString(input.body)) {\n serializedBody = (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(input.body));\n }\n else if (_.isBuffer(input.body)) {\n serializedBody = (0, serialization_1.serializeBuffer)(input.body);\n }\n else if (_.isArrayBuffer(input.body) || _.isTypedArray(input.body)) {\n serializedBody = (0, base64_arraybuffer_1.encode)(input.body);\n }\n else if ((0, request_utils_1.isMockttpBody)(input.body)) {\n serializedBody = (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(input.body.buffer));\n }\n return {\n ...input,\n body: serializedBody,\n rawBody: input.rawBody\n ? (0, serialization_1.serializeBuffer)((0, buffer_utils_1.asBuffer)(input.rawBody))\n : undefined\n };\n}\n/**\n * Deserialize a callback result (callback handlers, BeforeRequest/Response etc)\n * to build buffer data (or undefined) from the base64-serialized data\n * produced by withSerializedCallbackBuffers\n */\nfunction withDeserializedCallbackBuffers(input) {\n return {\n ...input,\n body: input.body !== undefined\n ? Buffer.from(input.body, 'base64')\n : undefined,\n rawBody: input.rawBody !== undefined\n ? Buffer.from(input.rawBody, 'base64')\n : undefined\n };\n}\n//# sourceMappingURL=body-serialization.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ClientServerChannel = exports.Serializable = void 0;\nexports.serialize = serialize;\nexports.deserialize = deserialize;\nexports.serializeBuffer = serializeBuffer;\nexports.deserializeBuffer = deserializeBuffer;\nexports.ensureParamsDeferenced = ensureParamsDeferenced;\nexports.serializeProxyConfig = serializeProxyConfig;\nexports.deserializeProxyConfig = deserializeProxyConfig;\nconst _ = require(\"lodash\");\nconst stream_1 = require(\"stream\");\nconst uuid_1 = require(\"uuid\");\nconst rule_parameters_1 = require(\"../rules/rule-parameters\");\nfunction serialize(obj, stream) {\n const channel = new ClientServerChannel(stream);\n const data = obj.serialize(channel);\n data.topicId = channel.topicId;\n return data;\n}\nfunction deserialize(data, stream, ruleParams, lookup) {\n const type = data.type;\n const channel = new ClientServerChannel(stream, data.topicId);\n const deserialized = lookup[type].deserialize(data, channel, ruleParams);\n // Wrap .dispose and ensure the channel is always disposed too.\n const builtinDispose = deserialized.dispose;\n deserialized.dispose = () => {\n builtinDispose();\n channel.dispose();\n };\n return deserialized;\n}\nclass Serializable {\n /**\n * @internal\n */\n serialize(_channel) {\n // By default, we assume data is transferrable as-is\n return this;\n }\n /**\n * @internal\n */\n static deserialize(data, _channel, _ruleParams) {\n // By default, we assume we just need to assign the right prototype\n return _.create(this.prototype, data);\n }\n // This rule is being unregistered. Any handlers who need to cleanup when they know\n // they're no longer in use should implement this and dispose accordingly.\n // Only deserialized rules are disposed - if the originating rule needs\n // disposing too, ping the channel and let it know.\n dispose() { }\n}\nexports.Serializable = Serializable;\nconst DISPOSE_MESSAGE = { disposeChannel: true };\n// Wraps another stream, ensuring that messages go only to the paired channel on the\n// other client/server. In practice, each handler gets one end of these streams in\n// their serialize/deserialize methods, and can use them to sync live data reliably.\nclass ClientServerChannel extends stream_1.Duplex {\n constructor(rawStream, topicId) {\n super({ objectMode: true });\n this.rawStream = rawStream;\n this._onRawStreamError = (error) => {\n this.destroy(error);\n };\n this._onRawStreamFinish = () => {\n this.end();\n };\n this._readFromRawStream = (rawData) => {\n const stringData = rawData.toString();\n stringData.split('\\n').filter(d => !!d).forEach((rawDataLine) => {\n let data;\n try {\n data = JSON.parse(rawDataLine);\n }\n catch (e) {\n console.log(e);\n console.log('Received unparseable message, dropping.', rawDataLine.toString());\n return;\n }\n if (data.topicId === this.topicId) {\n if (_.isEqual(_.omit(data, 'topicId'), DISPOSE_MESSAGE))\n this.dispose(true);\n else\n this.push(data);\n }\n });\n };\n this.reading = false;\n this.topicId = topicId || (0, uuid_1.v4)();\n this.rawStream.on('error', this._onRawStreamError);\n this.rawStream.on('finish', this._onRawStreamFinish);\n }\n /**\n * @internal @hidden\n */\n _write(message, encoding, callback) {\n message.topicId = this.topicId;\n const chunk = JSON.stringify(message) + '\\n';\n if (!this.rawStream.write(chunk, encoding)) {\n this.rawStream.once('drain', callback);\n }\n else {\n callback();\n }\n }\n _read() {\n if (!this.reading) {\n this.rawStream.on('data', this._readFromRawStream);\n this.reading = true;\n }\n }\n request(actionOrData, dataOrNothing) {\n let action;\n let data;\n if (_.isString(actionOrData)) {\n action = actionOrData;\n data = dataOrNothing;\n }\n else {\n data = actionOrData;\n }\n const requestId = (0, uuid_1.v4)();\n return new Promise((resolve, reject) => {\n const responseListener = (response) => {\n if (response.requestId === requestId) {\n if (response.error) {\n // Derialize error from plain object\n reject(Object.assign(new Error(), { stack: undefined }, response.error));\n }\n else {\n resolve(response.data);\n }\n this.removeListener('data', responseListener);\n }\n };\n const request = { data, requestId };\n if (action)\n request.action = action;\n this.write(request, (e) => {\n if (e)\n reject(e);\n else\n this.on('data', responseListener);\n });\n });\n }\n onRequest(cbOrAction, cbOrNothing) {\n let actionName;\n let cb;\n if (_.isString(cbOrAction)) {\n actionName = cbOrAction;\n cb = cbOrNothing;\n }\n else {\n cb = cbOrAction;\n }\n this.on('data', async (request) => {\n const { requestId, action } = request;\n // Filter by actionName, if set\n if (actionName !== undefined && action !== actionName)\n return;\n try {\n const response = {\n requestId,\n data: await cb(request.data)\n };\n if (!this.writable)\n return; // Response too slow - drop it\n this.write(response);\n }\n catch (error) {\n // Make the error serializable:\n error = _.pick(error, Object.getOwnPropertyNames(error));\n if (!this.writable)\n return; // Response too slow - drop it\n this.write({ requestId, error });\n }\n });\n }\n // Shuts down the channel. Only needs to be called on one side, the other side\n // will be shut down automatically when it receives DISPOSE_MESSAGE.\n dispose(disposeReceived = false) {\n this.on('error', () => { }); // Dispose is best effort - we don't care about errors\n // Only one side needs to send a dispose - we send first if we haven't seen one.\n if (!disposeReceived)\n this.end(DISPOSE_MESSAGE);\n else\n this.end();\n // Detach any remaining onRequest handlers:\n this.removeAllListeners('data');\n // Stop receiving upstream messages from the global stream:\n this.rawStream.removeListener('data', this._readFromRawStream);\n this.rawStream.removeListener('error', this._onRawStreamError);\n this.rawStream.removeListener('finish', this._onRawStreamFinish);\n }\n}\nexports.ClientServerChannel = ClientServerChannel;\nfunction serializeBuffer(buffer) {\n return buffer.toString('base64');\n}\nfunction deserializeBuffer(buffer) {\n return Buffer.from(buffer, 'base64');\n}\nconst SERIALIZED_PARAM_REFERENCE = \"__mockttp__param__reference__\";\nfunction serializeParam(value) {\n // Swap the symbol for a string, since we can't serialize symbols in JSON:\n return { [SERIALIZED_PARAM_REFERENCE]: value[rule_parameters_1.MOCKTTP_PARAM_REF] };\n}\nfunction isSerializedRuleParam(value) {\n return value && SERIALIZED_PARAM_REFERENCE in value;\n}\nfunction ensureParamsDeferenced(value, ruleParams) {\n if (isSerializedRuleParam(value)) {\n const paramRef = {\n [rule_parameters_1.MOCKTTP_PARAM_REF]: value[SERIALIZED_PARAM_REFERENCE]\n };\n return (0, rule_parameters_1.dereferenceParam)(paramRef, ruleParams);\n }\n else {\n return value;\n }\n}\nfunction serializeProxyConfig(proxyConfig, channel) {\n if (_.isFunction(proxyConfig)) {\n const callbackId = `proxyConfig-callback-${(0, uuid_1.v4)()}`;\n channel.onRequest(callbackId, proxyConfig);\n return callbackId;\n }\n else if (_.isArray(proxyConfig)) {\n return proxyConfig.map((config) => serializeProxyConfig(config, channel));\n }\n else if ((0, rule_parameters_1.isParamReference)(proxyConfig)) {\n return serializeParam(proxyConfig);\n }\n else if (proxyConfig) {\n return {\n ...proxyConfig,\n trustedCAs: proxyConfig.trustedCAs?.map((caDefinition) => typeof caDefinition !== 'string' && 'cert' in caDefinition\n ? { cert: caDefinition.cert.toString('utf8') } // Stringify in case of buffers\n : caDefinition),\n additionalTrustedCAs: proxyConfig.additionalTrustedCAs?.map((caDefinition) => 'cert' in caDefinition\n ? { cert: caDefinition.cert.toString('utf8') } // Stringify in case of buffers\n : caDefinition)\n };\n }\n}\nfunction deserializeProxyConfig(proxyConfig, channel, ruleParams) {\n if (_.isString(proxyConfig)) {\n const callbackId = proxyConfig;\n const proxyConfigCallback = async (options) => {\n return await channel.request(callbackId, options);\n };\n return proxyConfigCallback;\n }\n else if (_.isArray(proxyConfig)) {\n return proxyConfig.map((config) => deserializeProxyConfig(config, channel, ruleParams));\n }\n else {\n return ensureParamsDeferenced(proxyConfig, ruleParams);\n }\n}\n//# sourceMappingURL=serialization.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RulePriority = exports.Method = exports.DEFAULT_ADMIN_SERVER_PORT = void 0;\nexports.DEFAULT_ADMIN_SERVER_PORT = 45454;\nvar Method;\n(function (Method) {\n Method[Method[\"GET\"] = 0] = \"GET\";\n Method[Method[\"POST\"] = 1] = \"POST\";\n Method[Method[\"PUT\"] = 2] = \"PUT\";\n Method[Method[\"DELETE\"] = 3] = \"DELETE\";\n Method[Method[\"PATCH\"] = 4] = \"PATCH\";\n Method[Method[\"HEAD\"] = 5] = \"HEAD\";\n Method[Method[\"OPTIONS\"] = 6] = \"OPTIONS\";\n})(Method || (exports.Method = Method = {}));\nvar RulePriority;\n(function (RulePriority) {\n RulePriority[RulePriority[\"FALLBACK\"] = 0] = \"FALLBACK\";\n RulePriority[RulePriority[\"DEFAULT\"] = 1] = \"DEFAULT\";\n})(RulePriority || (exports.RulePriority = RulePriority = {}));\n//# sourceMappingURL=types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.streamToBuffer = exports.bufferToStream = exports.bufferThenStream = exports.asBuffer = void 0;\nexports.splitBuffer = splitBuffer;\nconst events_1 = require(\"events\");\nconst stream = require(\"stream\");\nconst util_1 = require(\"./util\");\nconst MAX_BUFFER_SIZE = util_1.isNode\n ? require('buffer').constants.MAX_LENGTH\n : Infinity;\nconst asBuffer = (input) => Buffer.isBuffer(input)\n ? input\n : typeof input === \"string\"\n ? Buffer.from(input, 'utf8')\n // Is Array:\n : Buffer.from(input);\nexports.asBuffer = asBuffer;\n// Takes a buffer and a stream, returns a simple stream that outputs the buffer then the stream. The stream\n// is lazy, so doesn't read data in from the buffer or input until something here starts reading.\nconst bufferThenStream = (buffer, inputStream) => {\n let active = false;\n const outputStream = new stream.PassThrough({\n // Note we use the default highWaterMark, which means this applies backpressure, pushing buffering\n // onto the OS & backpressure on network instead of accepting data before we're ready to stream it.\n // Without changing behaviour, we listen for read() events, and don't start streaming until we get one.\n read(size) {\n // On the first actual read of this stream, we pull from the buffer\n // and then hook it up to the input.\n if (!active) {\n if (buffer.failedWith) {\n outputStream.destroy(buffer.failedWith);\n }\n else {\n // First stream everything that's been buffered so far:\n outputStream.write(Buffer.concat(buffer.currentChunks));\n // Then start streaming all future incoming data:\n inputStream.pipe(outputStream);\n if (inputStream.readableEnded)\n outputStream.end();\n if (inputStream.readableAborted)\n outputStream.destroy();\n // Forward any future errors from the input stream:\n inputStream.on('error', (e) => {\n outputStream.emit('error', e);\n });\n // Silence 'unhandled rejection' warnings here, since we'll handle\n // them on the stream instead\n buffer.catch(() => { });\n }\n active = true;\n }\n // Except for the first activation logic (above) do the default transform read() steps just\n // like a normal PassThrough stream.\n return stream.Transform.prototype._read.call(this, size);\n }\n });\n buffer.events.on('truncate', (chunks) => {\n // If the stream hasn't started yet, start it now, so it grabs the buffer\n // data before it gets truncated:\n if (!active)\n outputStream.read(0);\n });\n return outputStream;\n};\nexports.bufferThenStream = bufferThenStream;\nconst bufferToStream = (buffer) => {\n const outputStream = new stream.PassThrough();\n outputStream.end(buffer);\n return outputStream;\n};\nexports.bufferToStream = bufferToStream;\nconst streamToBuffer = (input, maxSize = MAX_BUFFER_SIZE) => {\n let chunks = [];\n const bufferPromise = new Promise((resolve, reject) => {\n function failWithAbortError() {\n bufferPromise.failedWith = new Error('Aborted');\n reject(bufferPromise.failedWith);\n }\n // If stream has already finished/aborted, resolve accordingly immediately:\n if (input.readableEnded)\n return resolve(Buffer.from([]));\n if (input.readableAborted)\n return failWithAbortError();\n let currentSize = 0;\n const onData = (d) => {\n currentSize += d.length;\n chunks.push(d);\n // If we go over maxSize, drop the whole stream, so the buffer\n // resolves empty. MaxSize should be large, so this is rare,\n // and only happens as an alternative to crashing the process.\n if (currentSize > maxSize) {\n // Announce truncation, so that other mechanisms (asStream) can\n // capture this data if they're interested in it.\n bufferPromise.events.emit('truncate', chunks);\n // Drop all the data so far & stop reading\n bufferPromise.currentChunks = chunks = [];\n input.removeListener('data', onData);\n // We then resolve immediately - the buffer is done, even if the body\n // might still be streaming in we're not listening to it. This means\n // that requests can 'complete' for event/callback purposes while\n // they're actually still streaming, but only in this scenario where\n // the data is too large to really be used by the events/callbacks.\n // If we don't resolve, then cases which intentionally don't consume\n // the raw stream but do consume the buffer (beforeRequest) would\n // deadlock: beforeRequest must complete to begin streaming the\n // full body to the target clients.\n resolve(Buffer.from([]));\n }\n };\n input.on('data', onData);\n input.once('end', () => {\n resolve(Buffer.concat(chunks));\n });\n input.once('aborted', failWithAbortError);\n input.on('error', (e) => {\n bufferPromise.failedWith = bufferPromise.failedWith || e;\n reject(e);\n });\n });\n bufferPromise.currentChunks = chunks;\n bufferPromise.events = new events_1.EventEmitter();\n return bufferPromise;\n};\nexports.streamToBuffer = streamToBuffer;\nfunction splitBuffer(input, splitter, maxParts = Infinity) {\n const parts = [];\n let remainingBuffer = input;\n while (remainingBuffer.length) {\n let endOfPart = remainingBuffer.indexOf(splitter);\n if (endOfPart === -1)\n endOfPart = remainingBuffer.length;\n parts.push(remainingBuffer.slice(0, endOfPart));\n remainingBuffer = remainingBuffer.slice(endOfPart + splitter.length);\n if (parts.length === maxParts - 1) {\n parts.push(remainingBuffer);\n break;\n }\n }\n return parts;\n}\n//# sourceMappingURL=buffer-utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isErrorLike = isErrorLike;\n// Useful to easily cast and then examine errors that are otherwise 'unknown':\nfunction isErrorLike(error) {\n return typeof error === 'object' && (error instanceof Error ||\n error.message ||\n error.code ||\n error.stack);\n}\n//# sourceMappingURL=error.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.findRawHeaders = exports.findRawHeaderIndex = exports.findRawHeader = void 0;\nexports.pairFlatRawHeaders = pairFlatRawHeaders;\nexports.flattenPairedRawHeaders = flattenPairedRawHeaders;\nexports.rawHeadersToObject = rawHeadersToObject;\nexports.rawHeadersToObjectPreservingCase = rawHeadersToObjectPreservingCase;\nexports.objectHeadersToRaw = objectHeadersToRaw;\nexports.objectHeadersToFlat = objectHeadersToFlat;\nexports.h2HeadersToH1 = h2HeadersToH1;\nexports.h1HeadersToH2 = h1HeadersToH2;\nexports.dropDefaultHeaders = dropDefaultHeaders;\nexports.validateHeader = validateHeader;\nconst http = require(\"http\");\n/*\n\nThese utils support conversion between the various header representations that we deal\nwith. Those are:\n\n- Flat arrays of [key, value, key, value, key, ...]. This is the raw header format\n generally used by Node.js's APIs throughout.\n- Raw header tuple arrays like [[key, value], [key, value]]. This is our own raw header\n format, aiming to be fairly easy to use and to preserve header order, header dupes &\n header casing throughout.\n- Formatted header objects of { key: value, key: value }. These are returned as the most\n convenient and consistent header format: keys are lowercased, and values are either\n strings or arrays of strings (for duplicate headers). This is returned by Node's APIs,\n but with some unclear normalization rules, so in practice we build raw headers and\n reconstruct this ourselves everyhere, by lowercasing & building arrays of values.\n\n*/\nconst findRawHeader = (rawHeaders, targetKey) => rawHeaders.find(([key]) => key.toLowerCase() === targetKey);\nexports.findRawHeader = findRawHeader;\nconst findRawHeaderIndex = (rawHeaders, targetKey) => rawHeaders.findIndex(([key]) => key.toLowerCase() === targetKey);\nexports.findRawHeaderIndex = findRawHeaderIndex;\nconst findRawHeaders = (rawHeaders, targetKey) => rawHeaders.filter(([key]) => key.toLowerCase() === targetKey);\nexports.findRawHeaders = findRawHeaders;\n/**\n * Return node's _very_ raw headers ([k, v, k, v, ...]) into our slightly more convenient\n * pairwise tuples [[k, v], [k, v], ...] RawHeaders structure.\n */\nfunction pairFlatRawHeaders(flatRawHeaders) {\n const result = [];\n for (let i = 0; i < flatRawHeaders.length; i += 2 /* Move two at a time */) {\n result[i / 2] = [flatRawHeaders[i], flatRawHeaders[i + 1]];\n }\n return result;\n}\nfunction flattenPairedRawHeaders(rawHeaders) {\n return rawHeaders.flat();\n}\n/**\n * Take a raw headers, and turn them into headers, but without some of Node's concessions\n * to ease of use, i.e. keeping multiple values as arrays.\n *\n * This lowercases all names along the way, to provide a convenient header API for most\n * downstream use cases, and to match Node's own behaviour.\n */\nfunction rawHeadersToObject(rawHeaders) {\n return rawHeaders.reduce((headers, [key, value]) => {\n key = key.toLowerCase();\n const existingValue = headers[key];\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n }\n else if (existingValue) {\n headers[key] = [existingValue, value];\n }\n else {\n headers[key] = value;\n }\n return headers;\n }, {});\n}\n/**\n * Take raw headers, and turn them into headers just like `rawHeadersToObject` but\n * also preserves case en route.\n *\n * This is separated because our public APIs should _not_ do this, but there's a few\n * internal use cases where we want to, notably including passing headers to WS which\n * only accepts a headers object when sending upstream requests, but does preserve\n * case from the object.\n */\nfunction rawHeadersToObjectPreservingCase(rawHeaders) {\n // Duplicate keys with different cases in the final object clobber each other (last\n // value wins) so we need to pick a single casing for each header name. We don't want\n // to just use lowercase, because we want to preserve original casing wherever possible.\n // To make that work, we use the casing from the first instance of each header, along with\n // a lowercase -> first casing map here to look up that value later:\n const headerNameMap = {};\n return rawHeaders.reduce((headers, [key, value]) => {\n const lowerCaseKey = key.toLowerCase();\n if (headerNameMap[lowerCaseKey]) {\n // If we've already seen this header, we need to use the same\n // casing as before to avoid issues with duplicates:\n key = headerNameMap[lowerCaseKey];\n }\n else {\n // If we haven't, we store this key as the canonical format\n // to make it easy to merge with any duplicates:\n headerNameMap[lowerCaseKey] = key;\n }\n const existingValue = headers[key];\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n }\n else if (existingValue) {\n headers[key] = [existingValue, value];\n }\n else {\n headers[key] = value;\n }\n return headers;\n }, {});\n}\nfunction objectHeadersToRaw(headers) {\n const rawHeaders = [];\n for (let key in headers) {\n const value = headers[key];\n if (value === undefined)\n continue; // Drop undefined header values\n if (Array.isArray(value)) {\n value.forEach((v) => rawHeaders.push([key, v]));\n }\n else {\n rawHeaders.push([key, value]);\n }\n }\n return rawHeaders;\n}\nfunction objectHeadersToFlat(headers) {\n const flatHeaders = [];\n for (let key in headers) {\n const value = headers[key];\n if (value === undefined)\n continue; // Drop undefined header values\n if (Array.isArray(value)) {\n value.forEach((v) => {\n flatHeaders.push(key);\n flatHeaders.push(v);\n });\n }\n else {\n flatHeaders.push(key);\n flatHeaders.push(value);\n }\n }\n return flatHeaders;\n}\n// See https://httptoolkit.com/blog/translating-http-2-into-http-1/ for details on the\n// transformations required between H2 & H1 when proxying.\nfunction h2HeadersToH1(h2Headers) {\n let h1Headers = h2Headers.filter(([key]) => key[0] !== ':');\n if (!(0, exports.findRawHeader)(h1Headers, 'host') && (0, exports.findRawHeader)(h2Headers, ':authority')) {\n h1Headers.unshift(['Host', (0, exports.findRawHeader)(h2Headers, ':authority')[1]]);\n }\n // In HTTP/1 you MUST only send one cookie header - in HTTP/2 sending multiple is fine,\n // so we have to concatenate them:\n const cookieHeaders = (0, exports.findRawHeaders)(h1Headers, 'cookie');\n if (cookieHeaders.length > 1) {\n h1Headers = h1Headers.filter(([key]) => key.toLowerCase() !== 'cookie');\n h1Headers.push(['Cookie', cookieHeaders.join('; ')]);\n }\n return h1Headers;\n}\n// Take from http2/util.js in Node itself\nconst HTTP2_ILLEGAL_HEADERS = [\n 'connection',\n 'upgrade',\n 'host',\n 'http2-settings',\n 'keep-alive',\n 'proxy-connection',\n 'transfer-encoding'\n];\nfunction h1HeadersToH2(headers) {\n return headers.filter(([key]) => !HTTP2_ILLEGAL_HEADERS.includes(key.toLowerCase()));\n}\n// If the user explicitly specifies headers, we tell Node not to handle them,\n// so the user-defined headers are the full set.\nfunction dropDefaultHeaders(response) {\n // Drop the default headers, so only the headers we explicitly configure are included\n [\n 'connection',\n 'content-length',\n 'transfer-encoding',\n 'date'\n ].forEach((defaultHeader) => response.removeHeader(defaultHeader));\n}\nfunction validateHeader(name, value) {\n try {\n http.validateHeaderName(name);\n http.validateHeaderValue(name, value);\n return true;\n }\n catch (e) {\n return false;\n }\n}\n//# sourceMappingURL=header-utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.filter = filter;\nexports.objectAllPromise = objectAllPromise;\nexports.getDeferred = getDeferred;\nconst _ = require(\"lodash\");\nasync function filter(array, test) {\n let testResults = await Promise.all(array.map(test));\n return array.filter((v, i) => testResults[i]);\n}\nasync function objectAllPromise(obj) {\n return _.zipObject(Object.keys(obj), await Promise.all(Object.values(obj)));\n}\nfunction getDeferred() {\n let resolveCallback;\n let rejectCallback;\n let result = new Promise((resolve, reject) => {\n resolveCallback = resolve;\n rejectCallback = reject;\n });\n result.resolve = resolveCallback;\n result.reject = rejectCallback;\n return result;\n}\n//# sourceMappingURL=promise.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parseRequestBody = exports.buildBodyReader = exports.isMockttpBody = exports.writeHead = exports.shouldKeepAlive = void 0;\nexports.isHttp2 = isHttp2;\nexports.encodeBodyBuffer = encodeBodyBuffer;\nexports.decodeBodyBuffer = decodeBodyBuffer;\nexports.buildInitiatedRequest = buildInitiatedRequest;\nexports.waitForCompletedRequest = waitForCompletedRequest;\nexports.trackResponse = trackResponse;\nexports.waitForCompletedResponse = waitForCompletedResponse;\nexports.tryToParseHttpRequest = tryToParseHttpRequest;\nexports.parseRawHttpResponse = parseRawHttpResponse;\nconst _ = require(\"lodash\");\nconst tls_1 = require(\"tls\");\nconst http2 = require(\"http2\");\nconst stream = require(\"stream\");\nconst querystring = require(\"querystring\");\nconst multipart = require(\"parse-multipart-data\");\nconst now = require(\"performance-now\");\nconst url = require(\"url\");\nconst buffer_utils_1 = require(\"./buffer-utils\");\nconst header_utils_1 = require(\"./header-utils\");\nconst shouldKeepAlive = (req) => req.httpVersion !== '1.0' &&\n req.headers['connection'] !== 'close' &&\n req.headers['proxy-connection'] !== 'close';\nexports.shouldKeepAlive = shouldKeepAlive;\nconst writeHead = (response, status, statusMessage, headers) => {\n const flatHeaders = headers === undefined\n ? {}\n : isHttp2(response) && Array.isArray(headers)\n // H2 raw headers support is poor so we map to object here.\n // We should revert to flat headers once the below is resolved in LTS:\n // https://github.com/nodejs/node/issues/51402\n ? (0, header_utils_1.rawHeadersToObject)(headers)\n : isHttp2(response)\n ? headers // H2 supports object headers just fine\n : !Array.isArray(headers)\n ? (0, header_utils_1.objectHeadersToFlat)(headers)\n // RawHeaders for H1, must be flattened:\n : (0, header_utils_1.flattenPairedRawHeaders)(headers);\n // We aim to always pass flat headers to writeHead instead of calling setHeader because\n // in most cases it's more flexible about supporting raw data, e.g. multiple headers with\n // different casing can't be represented with setHeader at all (the latter overwrites).\n if (statusMessage === undefined) {\n // Cast is required as Node H2 types don't know about raw headers:\n response.writeHead(status, flatHeaders);\n }\n else {\n response.writeHead(status, statusMessage, flatHeaders);\n }\n};\nexports.writeHead = writeHead;\nfunction isHttp2(message) {\n return ('httpVersion' in message && !!message.httpVersion?.startsWith('2')) || // H2 request\n ('stream' in message && 'createPushResponse' in message); // H2 response\n}\nasync function encodeBodyBuffer(buffer, headers) {\n const contentEncoding = headers['content-encoding'];\n // We skip encodeBuffer entirely if possible - this isn't strictly necessary, but it's useful\n // so you can drop the http-encoding package in bundling downstream without issue in cases\n // where you don't actually use any encodings.\n if (!contentEncoding)\n return buffer;\n return await (await Promise.resolve().then(() => require('http-encoding'))).encodeBuffer(buffer, contentEncoding, { level: 1 });\n}\nasync function decodeBodyBuffer(buffer, headers) {\n const contentEncoding = headers['content-encoding'];\n // We skip decodeBuffer entirely if possible - this isn't strictly necessary, but it's useful\n // so you can drop the http-encoding package in bundling downstream without issue in cases\n // where you don't actually use any encodings.\n if (!contentEncoding)\n return buffer;\n return await (await Promise.resolve().then(() => require('http-encoding'))).decodeBuffer(buffer, contentEncoding);\n}\n// Parse an in-progress request or response stream, i.e. where the body or possibly even the headers have\n// not been fully received/sent yet.\nconst parseBodyStream = (bodyStream, maxSize, getHeaders) => {\n let bufferPromise = null;\n let completedBuffer = null;\n let body = {\n // Returns a stream for the full body, not the live streaming body.\n // Each call creates a new stream, which starts with the already seen\n // and buffered data, and then continues with the live stream, if active.\n // Listeners to this stream *must* be attached synchronously after this call.\n asStream() {\n // If we've already buffered the whole body, just stream it out:\n if (completedBuffer)\n return (0, buffer_utils_1.bufferToStream)(completedBuffer);\n // Otherwise, we want to start buffering now, and wrap that with\n // a stream that can live-stream the buffered data on demand:\n const buffer = body.asBuffer();\n buffer.catch(() => { }); // Errors will be handled via the stream, so silence unhandled rejections here.\n return (0, buffer_utils_1.bufferThenStream)(buffer, bodyStream);\n },\n asBuffer() {\n if (!bufferPromise) {\n bufferPromise = (0, buffer_utils_1.streamToBuffer)(bodyStream, maxSize);\n bufferPromise\n .then((buffer) => completedBuffer = buffer)\n .catch(() => { }); // If we get no body, completedBuffer stays null\n }\n return bufferPromise;\n },\n async asDecodedBuffer() {\n const buffer = await body.asBuffer();\n return decodeBodyBuffer(buffer, getHeaders());\n },\n asText(encoding = 'utf8') {\n return body.asDecodedBuffer().then((b) => b.toString(encoding));\n },\n asJson() {\n return body.asText().then((t) => JSON.parse(t));\n },\n asFormData() {\n return body.asText().then((t) => querystring.parse(t));\n },\n };\n return body;\n};\nasync function runAsyncOrUndefined(func) {\n try {\n return await func();\n }\n catch {\n return undefined;\n }\n}\nconst waitForBody = async (body, headers) => {\n const bufferBody = await body.asBuffer();\n return (0, exports.buildBodyReader)(bufferBody, headers);\n};\nconst isMockttpBody = (body) => {\n return body.hasOwnProperty('getDecodedBuffer');\n};\nexports.isMockttpBody = isMockttpBody;\nconst buildBodyReader = (body, headers) => {\n const completedBody = {\n buffer: body,\n async getDecodedBuffer() {\n return runAsyncOrUndefined(async () => (0, buffer_utils_1.asBuffer)(await decodeBodyBuffer(this.buffer, headers)));\n },\n async getText() {\n return runAsyncOrUndefined(async () => (await this.getDecodedBuffer()).toString());\n },\n async getJson() {\n return runAsyncOrUndefined(async () => JSON.parse((await completedBody.getText())));\n },\n async getUrlEncodedFormData() {\n return runAsyncOrUndefined(async () => {\n const contentType = headers[\"content-type\"];\n if (contentType?.includes(\"multipart/form-data\"))\n return; // Actively ignore multipart data - won't work as expected\n const text = await completedBody.getText();\n return text ? querystring.parse(text) : undefined;\n });\n },\n async getMultipartFormData() {\n return runAsyncOrUndefined(async () => {\n const contentType = headers[\"content-type\"];\n if (!contentType?.includes(\"multipart/form-data\"))\n return;\n const boundary = contentType.match(/;\\s*boundary=(\\S+)/);\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type#boundary\n // `boundary` is required for multipart entities.\n if (!boundary)\n return;\n const multipartBodyBuffer = (0, buffer_utils_1.asBuffer)(await decodeBodyBuffer(this.buffer, headers));\n return multipart.parse(multipartBodyBuffer, boundary[1]);\n });\n },\n async getFormData() {\n return runAsyncOrUndefined(async () => {\n // Return multi-part data if present, or fallback to default URL-encoded\n // parsing for all other cases. Data is returned in the same format regardless.\n const multiPartBody = await completedBody.getMultipartFormData();\n if (multiPartBody) {\n const formData = {};\n multiPartBody.forEach((part) => {\n const name = part.name;\n if (name === undefined) {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#as_a_header_for_a_multipart_body,\n // The header must include `name` property to identify the field name.\n // So we ignore parts without a name, treating it as invalid multipart form data.\n }\n else {\n // We do not use `filename` or `type` here, because return value of `getFormData` must be string or string array.\n const prevValue = formData[name];\n if (prevValue === undefined) {\n formData[name] = part.data.toString();\n }\n else if (Array.isArray(prevValue)) {\n prevValue.push(part.data.toString());\n }\n else {\n formData[name] = [prevValue, part.data.toString()];\n }\n }\n });\n return formData;\n }\n else {\n return completedBody.getUrlEncodedFormData();\n }\n });\n }\n };\n return completedBody;\n};\nexports.buildBodyReader = buildBodyReader;\nconst parseRequestBody = (req, options) => {\n let transformedRequest = req;\n transformedRequest.body = parseBodyStream(req, options.maxSize, () => req.headers);\n};\nexports.parseRequestBody = parseRequestBody;\n/**\n * Build an initiated request: the external representation of a request\n * that's just started.\n */\nfunction buildInitiatedRequest(request) {\n return {\n ..._.pick(request, 'id', 'matchedRuleId', 'protocol', 'httpVersion', 'method', 'url', 'path', 'remoteIpAddress', 'remotePort', 'hostname', 'headers', 'rawHeaders', 'tags'),\n timingEvents: request.timingEvents\n };\n}\n/**\n * Build a completed request: the external representation of a request\n * that's been completely received (but not necessarily replied to).\n */\nasync function waitForCompletedRequest(request) {\n const body = await waitForBody(request.body, request.headers);\n const requestData = buildInitiatedRequest(request);\n return {\n ...requestData,\n body,\n rawTrailers: request.rawTrailers ?? [],\n trailers: (0, header_utils_1.rawHeadersToObject)(request.rawTrailers ?? [])\n };\n}\n/**\n * Parse the accepted format of the headers argument for writeHead and addTrailers\n * into a single consistent paired-tuple format.\n */\nconst getHeaderPairsFromArgument = (headersArg) => {\n // Two legal formats of header args (flat & object), one unofficial (tuple array)\n if (Array.isArray(headersArg)) {\n if (!Array.isArray(headersArg[0])) {\n // Flat -> Raw tuples\n return (0, header_utils_1.pairFlatRawHeaders)(headersArg);\n }\n else {\n // Already raw tuples, cheeky\n return headersArg;\n }\n }\n else {\n // Headers object -> raw tuples\n return (0, header_utils_1.objectHeadersToRaw)(headersArg ?? {});\n }\n};\nfunction trackResponse(response, timingEvents, tags, options) {\n let trackedResponse = response;\n trackedResponse.timingEvents = timingEvents;\n trackedResponse.tags = tags;\n // Headers are sent when .writeHead or .write() are first called\n const trackingStream = new stream.PassThrough();\n const originalWriteHeader = trackedResponse.writeHead;\n const originalWrite = trackedResponse.write;\n const originalEnd = trackedResponse.end;\n const originalAddTrailers = trackedResponse.addTrailers;\n const originalGetHeaders = trackedResponse.getHeaders;\n let writtenHeaders;\n trackedResponse.getRawHeaders = () => writtenHeaders ?? [];\n trackedResponse.getHeaders = () => (0, header_utils_1.rawHeadersToObject)(trackedResponse.getRawHeaders());\n trackedResponse.writeHead = function (...args) {\n if (!timingEvents.headersSentTimestamp) {\n timingEvents.headersSentTimestamp = now();\n }\n // HTTP/2 responses shouldn't have a status message:\n if (isHttp2(trackedResponse) && typeof args[1] === 'string') {\n args[1] = undefined;\n }\n let headersArg;\n if (args[2]) {\n headersArg = args[2];\n }\n else if (typeof args[1] !== 'string') {\n headersArg = args[1];\n }\n writtenHeaders = getHeaderPairsFromArgument(headersArg);\n if (isHttp2(trackedResponse)) {\n writtenHeaders.unshift([':status', args[0].toString()]);\n }\n // Headers might also have been set with setHeader before. They'll be combined, with headers\n // here taking precendence. We simulate this by pulling in all values from getHeaders() and\n // remembering any of those that we're not about to override.\n const storedHeaders = originalGetHeaders.apply(this);\n const writtenHeaderKeys = writtenHeaders.map(([key]) => key.toLowerCase());\n const storedHeaderKeys = Object.keys(storedHeaders);\n if (storedHeaderKeys.length) {\n storedHeaderKeys\n .filter((key) => !writtenHeaderKeys.includes(key))\n .reverse() // We're unshifting (these were set first) so we have to reverse to keep order.\n .forEach((key) => {\n const value = storedHeaders[key];\n if (Array.isArray(value)) {\n value.reverse().forEach(v => writtenHeaders?.unshift([key, v]));\n }\n else if (value !== undefined) {\n writtenHeaders?.unshift([key, value]);\n }\n });\n }\n return originalWriteHeader.apply(this, args);\n };\n let writtenTrailers;\n trackedResponse.getRawTrailers = () => writtenTrailers ?? [];\n trackedResponse.addTrailers = function (...args) {\n const trailersArg = args[0];\n writtenTrailers = getHeaderPairsFromArgument(trailersArg);\n return originalAddTrailers.apply(this, args);\n };\n const trackingWrite = function (...args) {\n trackingStream.write.apply(trackingStream, args);\n return originalWrite.apply(this, args);\n };\n trackedResponse.write = trackingWrite;\n trackedResponse.end = function (...args) {\n // We temporarily disable write tracking here, as .end\n // can call this.write, but that write should not be\n // tracked, or we'll get duplicate writes when trackingStream\n // calls it on itself too.\n trackedResponse.write = originalWrite;\n trackingStream.end.apply(trackingStream, args);\n let result = originalEnd.apply(this, args);\n trackedResponse.write = trackingWrite;\n return result;\n };\n trackedResponse.body = parseBodyStream(trackingStream, options.maxSize, () => trackedResponse.getHeaders());\n // Proxy errors (e.g. write-after-end) to the response, so they can be\n // handled elsewhere, rather than killing the process outright.\n trackingStream.on('error', (e) => trackedResponse.emit('error', e));\n return trackedResponse;\n}\n/**\n * Build a completed response: the external representation of a response\n * that's been completely written out and sent back to the client.\n */\nasync function waitForCompletedResponse(response) {\n // Ongoing response has 'getHeaders' - completed has 'headers'.\n if ('headers' in response)\n return response;\n const body = await waitForBody(response.body, response.getHeaders());\n response.timingEvents.responseSentTimestamp = response.timingEvents.responseSentTimestamp || now();\n const completedResponse = _(response).pick([\n 'id',\n 'statusCode',\n 'timingEvents',\n 'tags'\n ]).assign({\n statusMessage: '',\n headers: response.getHeaders(),\n rawHeaders: response.getRawHeaders(),\n body: body,\n rawTrailers: response.getRawTrailers(),\n trailers: (0, header_utils_1.rawHeadersToObject)(response.getRawTrailers())\n }).valueOf();\n if (!(response instanceof http2.Http2ServerResponse)) {\n // H2 has no status messages, and generates a warning if you look for one\n completedResponse.statusMessage = response.statusMessage;\n }\n return completedResponse;\n}\n// Take raw HTTP request bytes received, have a go at parsing something useful out of them.\n// Very lax - this is a method to use when normal parsing has failed, not as standard\nfunction tryToParseHttpRequest(input, socket) {\n const req = {};\n try {\n req.protocol = socket.__lastHopEncrypted ? \"https\" : \"http\"; // Wild guess really\n // For TLS sockets, we default the hostname to the name given by SNI. Might be overridden\n // by the URL or Host header later, if available.\n if (socket instanceof tls_1.TLSSocket)\n req.hostname = socket.servername;\n const lines = (0, buffer_utils_1.splitBuffer)(input, '\\r\\n');\n const requestLine = lines[0].slice(0, lines[0].length).toString('ascii');\n const [method, rawUri, httpProtocol] = requestLine.split(\" \");\n if (method)\n req.method = method.slice(0, 15); // With overflows this could be *anything*. Limit it slightly.\n // An empty line delineates the headers from the body\n const emptyLineIndex = _.findIndex(lines, (line) => line.length === 0);\n try {\n const headerLines = lines.slice(1, emptyLineIndex === -1 ? undefined : emptyLineIndex);\n const rawHeaders = headerLines\n .map((line) => (0, buffer_utils_1.splitBuffer)(line, ':', 2))\n .filter((line) => line.length > 1)\n .map((headerParts) => headerParts.map(p => p.toString('utf8').trim()));\n req.rawHeaders = rawHeaders;\n req.headers = (0, header_utils_1.rawHeadersToObject)(rawHeaders);\n }\n catch (e) { }\n try {\n const parsedUrl = url.parse(rawUri);\n req.path = parsedUrl.path ?? undefined;\n const hostHeader = _.find(req.headers, (_value, key) => key.toLowerCase() === 'host');\n if (hostHeader) {\n req.hostname = Array.isArray(hostHeader) ? hostHeader[0] : hostHeader;\n }\n else if (parsedUrl.hostname) {\n req.hostname = parsedUrl.hostname;\n }\n if (rawUri.includes('://') || !req.hostname) {\n // URI is absolute, or we have no way to guess the host at all\n req.url = rawUri;\n }\n else {\n // URI is relative (or invalid) and we have a host: use it\n req.url = `${req.protocol}://${req.hostname}${rawUri.startsWith('/') ? '' : '/' // Add a slash if the URI is garbage\n }${rawUri}`;\n }\n }\n catch (e) { }\n try {\n const httpVersion = httpProtocol.split('/')[1];\n req.httpVersion = httpVersion;\n }\n catch (e) { }\n }\n catch (e) { }\n return req;\n}\n// Take raw HTTP response bytes received, parse something useful out of them. This is *not*\n// very lax, and will throw errors due to unexpected response data, but it's used when we\n// ourselves generate the data (for websocket responses that 'ws' writes directly to the\n// socket invisibly). Fortunately all responses are very simple:\nfunction parseRawHttpResponse(input, request) {\n const { id, tags, timingEvents } = request;\n const lines = (0, buffer_utils_1.splitBuffer)(input, '\\r\\n');\n const responseLine = lines[0].subarray(0, lines[0].length).toString('ascii');\n const [_httpVersion, rawStatusCode, ...restResponseLine] = responseLine.split(\" \");\n const statusCode = parseInt(rawStatusCode, 10);\n const statusMessage = restResponseLine.join(' ');\n // An empty line delineates the headers from the body\n const emptyLineIndex = _.findIndex(lines, (line) => line.length === 0);\n const headerLines = lines.slice(1, emptyLineIndex === -1 ? undefined : emptyLineIndex);\n const rawHeaders = headerLines\n .map((line) => (0, buffer_utils_1.splitBuffer)(line, ':', 2))\n .map((headerParts) => headerParts.map(p => p.toString('utf8').trim()));\n const headers = (0, header_utils_1.rawHeadersToObject)(rawHeaders);\n const body = (0, exports.buildBodyReader)(Buffer.from([]), {});\n return {\n id,\n tags,\n timingEvents,\n statusCode,\n statusMessage,\n rawHeaders,\n headers,\n body,\n rawTrailers: [],\n trailers: {}\n };\n}\n//# sourceMappingURL=request-utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.normalizeUrl = exports.getEffectivePort = exports.getPathFromAbsoluteUrl = exports.getUrlWithoutProtocol = exports.isAbsoluteProtocollessUrl = exports.isRelativeUrl = exports.isAbsoluteUrl = void 0;\nconst url = require(\"url\");\nconst _ = require(\"lodash\");\nconst util_1 = require(\"./util\");\n// Is this URL fully qualified?\n// Note that this supports only HTTP - no websockets or anything else.\nconst isAbsoluteUrl = (url) => url.toLowerCase().startsWith('http://') ||\n url.toLowerCase().startsWith('https://');\nexports.isAbsoluteUrl = isAbsoluteUrl;\nconst isRelativeUrl = (url) => url.startsWith('/');\nexports.isRelativeUrl = isRelativeUrl;\nconst isAbsoluteProtocollessUrl = (url) => !(0, exports.isAbsoluteUrl)(url) && !(0, exports.isRelativeUrl)(url);\nexports.isAbsoluteProtocollessUrl = isAbsoluteProtocollessUrl;\nconst getUrlWithoutProtocol = (url) => {\n return url.split('://', 2).slice(-1).join('');\n};\nexports.getUrlWithoutProtocol = getUrlWithoutProtocol;\nconst getPathFromAbsoluteUrl = (url) => {\n const pathIndex = (0, util_1.nthIndexOf)(url, '/', 3);\n if (pathIndex !== -1) {\n return url.slice(pathIndex);\n }\n else {\n return '';\n }\n};\nexports.getPathFromAbsoluteUrl = getPathFromAbsoluteUrl;\nconst getEffectivePort = (url) => {\n if (url.port) {\n return parseInt(url.port, 10);\n }\n else if (url.protocol === 'https:' || url.protocol === 'wss:') {\n return 443;\n }\n else {\n return 80;\n }\n};\nexports.getEffectivePort = getEffectivePort;\n/**\n * Normalizes URLs to the form used when matching them.\n *\n * This accepts URLs in all three formats: relative, absolute, and protocolless-absolute,\n * and returns them in the same format but normalized.\n */\nexports.normalizeUrl = _.memoize((urlInput) => {\n let parsedUrl;\n let isProtocolless = false;\n try {\n // Strip the query and anything following it\n const queryIndex = urlInput.indexOf('?');\n if (queryIndex !== -1) {\n urlInput = urlInput.slice(0, queryIndex);\n }\n if ((0, exports.isAbsoluteProtocollessUrl)(urlInput)) {\n parsedUrl = url.parse('http://' + urlInput);\n isProtocolless = true;\n }\n else {\n parsedUrl = url.parse(urlInput);\n }\n // Trim out lots of the bits we don't like:\n delete parsedUrl.host;\n delete parsedUrl.query;\n delete parsedUrl.search;\n delete parsedUrl.hash;\n if (parsedUrl.pathname) {\n parsedUrl.pathname = parsedUrl.pathname.replace(/\\%[A-Fa-z0-9]{2}/g, (encoded) => encoded.toUpperCase()).replace(/[^\\u0000-\\u007F]+/g, (unicodeChar) => encodeURIComponent(unicodeChar));\n }\n if (parsedUrl.hostname && parsedUrl.hostname.endsWith('.')) {\n parsedUrl.hostname = parsedUrl.hostname.slice(0, -1);\n }\n if ((parsedUrl.protocol === 'https:' && parsedUrl.port === '443') ||\n (parsedUrl.protocol === 'http:' && parsedUrl.port === '80')) {\n delete parsedUrl.port;\n }\n }\n catch (e) {\n console.log(`Failed to normalize URL ${urlInput}`);\n console.log(e);\n if (!parsedUrl)\n return urlInput; // Totally unparseble: use as-is\n // If we've successfully parsed it, we format what we managed\n // and leave it at that:\n }\n let normalizedUrl = url.format(parsedUrl);\n // If the URL came in with no protocol, it should leave with\n // no protocol (protocol added temporarily above to allow parsing)\n if (isProtocolless) {\n normalizedUrl = normalizedUrl.slice('http://'.length);\n }\n return normalizedUrl;\n});\n//# sourceMappingURL=url.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.makePropertyWritable = exports.isNode = exports.isWeb = exports.isWorker = void 0;\nexports.nthIndexOf = nthIndexOf;\nexports.byteLength = byteLength;\nexports.delay = delay;\nfunction nthIndexOf(input, matcher, n) {\n let index = -1;\n while (n > 0) {\n n = n - 1;\n index = input.indexOf(matcher, index + 1);\n if (index === -1)\n break;\n }\n return index;\n}\n// Get the length of the given data in bytes, not characters.\n// If that's a buffer, the length is used raw, but if it's a string\n// it returns the length when encoded as UTF8.\nfunction byteLength(input) {\n if (typeof input === 'string') {\n return exports.isNode\n ? Buffer.from(input, 'utf8').byteLength\n : new Blob([input]).size;\n }\n else {\n return input.length;\n }\n}\nfunction delay(t) {\n return new Promise((r) => setTimeout(r, t));\n}\nexports.isWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;\nexports.isWeb = typeof Window !== 'undefined' && self instanceof Window;\nexports.isNode = !exports.isWorker && !exports.isWeb && typeof process === 'object' && process.version;\nconst makePropertyWritable = (obj, property) => Object.defineProperty(obj, property, {\n value: obj[property],\n writable: true\n});\nexports.makePropertyWritable = makePropertyWritable;\n//# sourceMappingURL=util.js.map","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SubscriptionClient = void 0;\nvar _global = typeof global !== 'undefined' ? global : (typeof window !== 'undefined' ? window : {});\nvar NativeWebSocket = _global.WebSocket || _global.MozWebSocket;\nvar Backoff = require(\"backo2\");\nvar eventemitter3_1 = require(\"eventemitter3\");\nvar is_string_1 = require(\"./utils/is-string\");\nvar is_object_1 = require(\"./utils/is-object\");\nvar printer_1 = require(\"graphql/language/printer\");\nvar getOperationAST_1 = require(\"graphql/utilities/getOperationAST\");\nvar symbol_observable_1 = require(\"symbol-observable\");\nvar protocol_1 = require(\"./protocol\");\nvar defaults_1 = require(\"./defaults\");\nvar message_types_1 = require(\"./message-types\");\nvar SubscriptionClient = (function () {\n function SubscriptionClient(url, options, webSocketImpl, webSocketProtocols) {\n var _a = (options || {}), _b = _a.connectionCallback, connectionCallback = _b === void 0 ? undefined : _b, _c = _a.connectionParams, connectionParams = _c === void 0 ? {} : _c, _d = _a.minTimeout, minTimeout = _d === void 0 ? defaults_1.MIN_WS_TIMEOUT : _d, _e = _a.timeout, timeout = _e === void 0 ? defaults_1.WS_TIMEOUT : _e, _f = _a.reconnect, reconnect = _f === void 0 ? false : _f, _g = _a.reconnectionAttempts, reconnectionAttempts = _g === void 0 ? Infinity : _g, _h = _a.lazy, lazy = _h === void 0 ? false : _h, _j = _a.inactivityTimeout, inactivityTimeout = _j === void 0 ? 0 : _j, _k = _a.wsOptionArguments, wsOptionArguments = _k === void 0 ? [] : _k;\n this.wsImpl = webSocketImpl || NativeWebSocket;\n if (!this.wsImpl) {\n throw new Error('Unable to find native implementation, or alternative implementation for WebSocket!');\n }\n this.wsProtocols = webSocketProtocols || protocol_1.GRAPHQL_WS;\n this.connectionCallback = connectionCallback;\n this.url = url;\n this.operations = {};\n this.nextOperationId = 0;\n this.minWsTimeout = minTimeout;\n this.wsTimeout = timeout;\n this.unsentMessagesQueue = [];\n this.reconnect = reconnect;\n this.reconnecting = false;\n this.reconnectionAttempts = reconnectionAttempts;\n this.lazy = !!lazy;\n this.inactivityTimeout = inactivityTimeout;\n this.closedByUser = false;\n this.backoff = new Backoff({ jitter: 0.5 });\n this.eventEmitter = new eventemitter3_1.EventEmitter();\n this.middlewares = [];\n this.client = null;\n this.maxConnectTimeGenerator = this.createMaxConnectTimeGenerator();\n this.connectionParams = this.getConnectionParams(connectionParams);\n this.wsOptionArguments = wsOptionArguments;\n if (!this.lazy) {\n this.connect();\n }\n }\n Object.defineProperty(SubscriptionClient.prototype, \"status\", {\n get: function () {\n if (this.client === null) {\n return this.wsImpl.CLOSED;\n }\n return this.client.readyState;\n },\n enumerable: false,\n configurable: true\n });\n SubscriptionClient.prototype.close = function (isForced, closedByUser) {\n if (isForced === void 0) { isForced = true; }\n if (closedByUser === void 0) { closedByUser = true; }\n this.clearInactivityTimeout();\n if (this.client !== null) {\n this.closedByUser = closedByUser;\n if (isForced) {\n this.clearCheckConnectionInterval();\n this.clearMaxConnectTimeout();\n this.clearTryReconnectTimeout();\n this.unsubscribeAll();\n this.sendMessage(undefined, message_types_1.default.GQL_CONNECTION_TERMINATE, null);\n }\n this.client.close();\n this.client.onopen = null;\n this.client.onclose = null;\n this.client.onmessage = null;\n this.client.onerror = function () { };\n this.client = null;\n this.eventEmitter.emit('disconnected');\n if (!isForced) {\n this.tryReconnect();\n }\n }\n };\n SubscriptionClient.prototype.request = function (request) {\n var _a;\n var getObserver = this.getObserver.bind(this);\n var executeOperation = this.executeOperation.bind(this);\n var unsubscribe = this.unsubscribe.bind(this);\n var opId;\n this.clearInactivityTimeout();\n return _a = {},\n _a[symbol_observable_1.default] = function () {\n return this;\n },\n _a.subscribe = function (observerOrNext, onError, onComplete) {\n var observer = getObserver(observerOrNext, onError, onComplete);\n opId = executeOperation(request, function (error, result) {\n if (error === null && result === null) {\n if (observer.complete) {\n observer.complete();\n }\n }\n else if (error) {\n if (observer.error) {\n observer.error(error[0]);\n }\n }\n else {\n if (observer.next) {\n observer.next(result);\n }\n }\n });\n return {\n unsubscribe: function () {\n if (opId) {\n unsubscribe(opId);\n opId = null;\n }\n },\n };\n },\n _a;\n };\n SubscriptionClient.prototype.on = function (eventName, callback, context) {\n var handler = this.eventEmitter.on(eventName, callback, context);\n return function () {\n handler.off(eventName, callback, context);\n };\n };\n SubscriptionClient.prototype.onConnected = function (callback, context) {\n return this.on('connected', callback, context);\n };\n SubscriptionClient.prototype.onConnecting = function (callback, context) {\n return this.on('connecting', callback, context);\n };\n SubscriptionClient.prototype.onDisconnected = function (callback, context) {\n return this.on('disconnected', callback, context);\n };\n SubscriptionClient.prototype.onReconnected = function (callback, context) {\n return this.on('reconnected', callback, context);\n };\n SubscriptionClient.prototype.onReconnecting = function (callback, context) {\n return this.on('reconnecting', callback, context);\n };\n SubscriptionClient.prototype.onError = function (callback, context) {\n return this.on('error', callback, context);\n };\n SubscriptionClient.prototype.unsubscribeAll = function () {\n var _this = this;\n Object.keys(this.operations).forEach(function (subId) {\n _this.unsubscribe(subId);\n });\n };\n SubscriptionClient.prototype.applyMiddlewares = function (options) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n var queue = function (funcs, scope) {\n var next = function (error) {\n if (error) {\n reject(error);\n }\n else {\n if (funcs.length > 0) {\n var f = funcs.shift();\n if (f) {\n f.applyMiddleware.apply(scope, [options, next]);\n }\n }\n else {\n resolve(options);\n }\n }\n };\n next();\n };\n queue(__spreadArray([], _this.middlewares, true), _this);\n });\n };\n SubscriptionClient.prototype.use = function (middlewares) {\n var _this = this;\n middlewares.map(function (middleware) {\n if (typeof middleware.applyMiddleware === 'function') {\n _this.middlewares.push(middleware);\n }\n else {\n throw new Error('Middleware must implement the applyMiddleware function.');\n }\n });\n return this;\n };\n SubscriptionClient.prototype.getConnectionParams = function (connectionParams) {\n return function () { return new Promise(function (resolve, reject) {\n if (typeof connectionParams === 'function') {\n try {\n return resolve(connectionParams.call(null));\n }\n catch (error) {\n return reject(error);\n }\n }\n resolve(connectionParams);\n }); };\n };\n SubscriptionClient.prototype.executeOperation = function (options, handler) {\n var _this = this;\n if (this.client === null) {\n this.connect();\n }\n var opId = this.generateOperationId();\n this.operations[opId] = { options: options, handler: handler };\n this.applyMiddlewares(options)\n .then(function (processedOptions) {\n _this.checkOperationOptions(processedOptions, handler);\n if (_this.operations[opId]) {\n _this.operations[opId] = { options: processedOptions, handler: handler };\n _this.sendMessage(opId, message_types_1.default.GQL_START, processedOptions);\n }\n })\n .catch(function (error) {\n _this.unsubscribe(opId);\n handler(_this.formatErrors(error));\n });\n return opId;\n };\n SubscriptionClient.prototype.getObserver = function (observerOrNext, error, complete) {\n if (typeof observerOrNext === 'function') {\n return {\n next: function (v) { return observerOrNext(v); },\n error: function (e) { return error && error(e); },\n complete: function () { return complete && complete(); },\n };\n }\n return observerOrNext;\n };\n SubscriptionClient.prototype.createMaxConnectTimeGenerator = function () {\n var minValue = this.minWsTimeout;\n var maxValue = this.wsTimeout;\n return new Backoff({\n min: minValue,\n max: maxValue,\n factor: 1.2,\n });\n };\n SubscriptionClient.prototype.clearCheckConnectionInterval = function () {\n if (this.checkConnectionIntervalId) {\n clearInterval(this.checkConnectionIntervalId);\n this.checkConnectionIntervalId = null;\n }\n };\n SubscriptionClient.prototype.clearMaxConnectTimeout = function () {\n if (this.maxConnectTimeoutId) {\n clearTimeout(this.maxConnectTimeoutId);\n this.maxConnectTimeoutId = null;\n }\n };\n SubscriptionClient.prototype.clearTryReconnectTimeout = function () {\n if (this.tryReconnectTimeoutId) {\n clearTimeout(this.tryReconnectTimeoutId);\n this.tryReconnectTimeoutId = null;\n }\n };\n SubscriptionClient.prototype.clearInactivityTimeout = function () {\n if (this.inactivityTimeoutId) {\n clearTimeout(this.inactivityTimeoutId);\n this.inactivityTimeoutId = null;\n }\n };\n SubscriptionClient.prototype.setInactivityTimeout = function () {\n var _this = this;\n if (this.inactivityTimeout > 0 && Object.keys(this.operations).length === 0) {\n this.inactivityTimeoutId = setTimeout(function () {\n if (Object.keys(_this.operations).length === 0) {\n _this.close();\n }\n }, this.inactivityTimeout);\n }\n };\n SubscriptionClient.prototype.checkOperationOptions = function (options, handler) {\n var query = options.query, variables = options.variables, operationName = options.operationName;\n if (!query) {\n throw new Error('Must provide a query.');\n }\n if (!handler) {\n throw new Error('Must provide an handler.');\n }\n if ((!(0, is_string_1.default)(query) && !(0, getOperationAST_1.getOperationAST)(query, operationName)) ||\n (operationName && !(0, is_string_1.default)(operationName)) ||\n (variables && !(0, is_object_1.default)(variables))) {\n throw new Error('Incorrect option types. query must be a string or a document,' +\n '`operationName` must be a string, and `variables` must be an object.');\n }\n };\n SubscriptionClient.prototype.buildMessage = function (id, type, payload) {\n var payloadToReturn = payload && payload.query ? __assign(__assign({}, payload), { query: typeof payload.query === 'string' ? payload.query : (0, printer_1.print)(payload.query) }) :\n payload;\n return {\n id: id,\n type: type,\n payload: payloadToReturn,\n };\n };\n SubscriptionClient.prototype.formatErrors = function (errors) {\n if (Array.isArray(errors)) {\n return errors;\n }\n if (errors && errors.errors) {\n return this.formatErrors(errors.errors);\n }\n if (errors && errors.message) {\n return [errors];\n }\n return [{\n name: 'FormatedError',\n message: 'Unknown error',\n originalError: errors,\n }];\n };\n SubscriptionClient.prototype.sendMessage = function (id, type, payload) {\n this.sendMessageRaw(this.buildMessage(id, type, payload));\n };\n SubscriptionClient.prototype.sendMessageRaw = function (message) {\n switch (this.status) {\n case this.wsImpl.OPEN:\n var serializedMessage = JSON.stringify(message);\n try {\n JSON.parse(serializedMessage);\n }\n catch (e) {\n this.eventEmitter.emit('error', new Error(\"Message must be JSON-serializable. Got: \".concat(message)));\n }\n this.client.send(serializedMessage);\n break;\n case this.wsImpl.CONNECTING:\n this.unsentMessagesQueue.push(message);\n break;\n default:\n if (!this.reconnecting) {\n this.eventEmitter.emit('error', new Error('A message was not sent because socket is not connected, is closing or ' +\n 'is already closed. Message was: ' + JSON.stringify(message)));\n }\n }\n };\n SubscriptionClient.prototype.generateOperationId = function () {\n return String(++this.nextOperationId);\n };\n SubscriptionClient.prototype.tryReconnect = function () {\n var _this = this;\n if (!this.reconnect || this.backoff.attempts >= this.reconnectionAttempts) {\n return;\n }\n if (!this.reconnecting) {\n Object.keys(this.operations).forEach(function (key) {\n _this.unsentMessagesQueue.push(_this.buildMessage(key, message_types_1.default.GQL_START, _this.operations[key].options));\n });\n this.reconnecting = true;\n }\n this.clearTryReconnectTimeout();\n var delay = this.backoff.duration();\n this.tryReconnectTimeoutId = setTimeout(function () {\n _this.connect();\n }, delay);\n };\n SubscriptionClient.prototype.flushUnsentMessagesQueue = function () {\n var _this = this;\n this.unsentMessagesQueue.forEach(function (message) {\n _this.sendMessageRaw(message);\n });\n this.unsentMessagesQueue = [];\n };\n SubscriptionClient.prototype.checkConnection = function () {\n if (this.wasKeepAliveReceived) {\n this.wasKeepAliveReceived = false;\n return;\n }\n if (!this.reconnecting) {\n this.close(false, true);\n }\n };\n SubscriptionClient.prototype.checkMaxConnectTimeout = function () {\n var _this = this;\n this.clearMaxConnectTimeout();\n this.maxConnectTimeoutId = setTimeout(function () {\n if (_this.status !== _this.wsImpl.OPEN) {\n _this.reconnecting = true;\n _this.close(false, true);\n }\n }, this.maxConnectTimeGenerator.duration());\n };\n SubscriptionClient.prototype.connect = function () {\n var _a;\n var _this = this;\n this.client = new ((_a = this.wsImpl).bind.apply(_a, __spreadArray([void 0, this.url, this.wsProtocols], this.wsOptionArguments, false)))();\n this.checkMaxConnectTimeout();\n this.client.onopen = function () { return __awaiter(_this, void 0, void 0, function () {\n var connectionParams, error_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(this.status === this.wsImpl.OPEN)) return [3, 4];\n this.clearMaxConnectTimeout();\n this.closedByUser = false;\n this.eventEmitter.emit(this.reconnecting ? 'reconnecting' : 'connecting');\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4, this.connectionParams()];\n case 2:\n connectionParams = _a.sent();\n this.sendMessage(undefined, message_types_1.default.GQL_CONNECTION_INIT, connectionParams);\n this.flushUnsentMessagesQueue();\n return [3, 4];\n case 3:\n error_1 = _a.sent();\n this.sendMessage(undefined, message_types_1.default.GQL_CONNECTION_ERROR, error_1);\n this.flushUnsentMessagesQueue();\n return [3, 4];\n case 4: return [2];\n }\n });\n }); };\n this.client.onclose = function () {\n if (!_this.closedByUser) {\n _this.close(false, false);\n }\n };\n this.client.onerror = function (err) {\n _this.eventEmitter.emit('error', err);\n };\n this.client.onmessage = function (_a) {\n var data = _a.data;\n _this.processReceivedData(data.toString());\n };\n };\n SubscriptionClient.prototype.processReceivedData = function (receivedData) {\n var parsedMessage;\n var opId;\n try {\n parsedMessage = JSON.parse(receivedData);\n opId = parsedMessage.id;\n }\n catch (e) {\n throw new Error(\"Message must be JSON-parseable. Got: \".concat(receivedData));\n }\n if ([message_types_1.default.GQL_DATA,\n message_types_1.default.GQL_COMPLETE,\n message_types_1.default.GQL_ERROR,\n ].indexOf(parsedMessage.type) !== -1 && !this.operations[opId]) {\n this.unsubscribe(opId);\n return;\n }\n switch (parsedMessage.type) {\n case message_types_1.default.GQL_CONNECTION_ERROR:\n if (this.connectionCallback) {\n this.connectionCallback(parsedMessage.payload);\n }\n break;\n case message_types_1.default.GQL_CONNECTION_ACK:\n this.eventEmitter.emit(this.reconnecting ? 'reconnected' : 'connected', parsedMessage.payload);\n this.reconnecting = false;\n this.backoff.reset();\n this.maxConnectTimeGenerator.reset();\n if (this.connectionCallback) {\n this.connectionCallback();\n }\n break;\n case message_types_1.default.GQL_COMPLETE:\n var handler = this.operations[opId].handler;\n delete this.operations[opId];\n handler.call(this, null, null);\n break;\n case message_types_1.default.GQL_ERROR:\n this.operations[opId].handler(this.formatErrors(parsedMessage.payload), null);\n delete this.operations[opId];\n break;\n case message_types_1.default.GQL_DATA:\n var parsedPayload = !parsedMessage.payload.errors ?\n parsedMessage.payload : __assign(__assign({}, parsedMessage.payload), { errors: this.formatErrors(parsedMessage.payload.errors) });\n this.operations[opId].handler(null, parsedPayload);\n break;\n case message_types_1.default.GQL_CONNECTION_KEEP_ALIVE:\n var firstKA = typeof this.wasKeepAliveReceived === 'undefined';\n this.wasKeepAliveReceived = true;\n if (firstKA) {\n this.checkConnection();\n }\n if (this.checkConnectionIntervalId) {\n clearInterval(this.checkConnectionIntervalId);\n this.checkConnection();\n }\n this.checkConnectionIntervalId = setInterval(this.checkConnection.bind(this), this.wsTimeout);\n break;\n default:\n throw new Error('Invalid message type!');\n }\n };\n SubscriptionClient.prototype.unsubscribe = function (opId) {\n if (this.operations[opId]) {\n delete this.operations[opId];\n this.setInactivityTimeout();\n this.sendMessage(opId, message_types_1.default.GQL_STOP, undefined);\n }\n };\n return SubscriptionClient;\n}());\nexports.SubscriptionClient = SubscriptionClient;\n//# sourceMappingURL=client.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WS_TIMEOUT = exports.MIN_WS_TIMEOUT = void 0;\nvar MIN_WS_TIMEOUT = 1000;\nexports.MIN_WS_TIMEOUT = MIN_WS_TIMEOUT;\nvar WS_TIMEOUT = 30000;\nexports.WS_TIMEOUT = WS_TIMEOUT;\n//# sourceMappingURL=defaults.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar MessageTypes = (function () {\n function MessageTypes() {\n throw new Error('Static Class');\n }\n MessageTypes.GQL_CONNECTION_INIT = 'connection_init';\n MessageTypes.GQL_CONNECTION_ACK = 'connection_ack';\n MessageTypes.GQL_CONNECTION_ERROR = 'connection_error';\n MessageTypes.GQL_CONNECTION_KEEP_ALIVE = 'ka';\n MessageTypes.GQL_CONNECTION_TERMINATE = 'connection_terminate';\n MessageTypes.GQL_START = 'start';\n MessageTypes.GQL_DATA = 'data';\n MessageTypes.GQL_ERROR = 'error';\n MessageTypes.GQL_COMPLETE = 'complete';\n MessageTypes.GQL_STOP = 'stop';\n MessageTypes.SUBSCRIPTION_START = 'subscription_start';\n MessageTypes.SUBSCRIPTION_DATA = 'subscription_data';\n MessageTypes.SUBSCRIPTION_SUCCESS = 'subscription_success';\n MessageTypes.SUBSCRIPTION_FAIL = 'subscription_fail';\n MessageTypes.SUBSCRIPTION_END = 'subscription_end';\n MessageTypes.INIT = 'init';\n MessageTypes.INIT_SUCCESS = 'init_success';\n MessageTypes.INIT_FAIL = 'init_fail';\n MessageTypes.KEEP_ALIVE = 'keepalive';\n return MessageTypes;\n}());\nexports.default = MessageTypes;\n//# sourceMappingURL=message-types.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GRAPHQL_SUBSCRIPTIONS = exports.GRAPHQL_WS = void 0;\nvar GRAPHQL_WS = 'graphql-ws';\nexports.GRAPHQL_WS = GRAPHQL_WS;\nvar GRAPHQL_SUBSCRIPTIONS = 'graphql-subscriptions';\nexports.GRAPHQL_SUBSCRIPTIONS = GRAPHQL_SUBSCRIPTIONS;\n//# sourceMappingURL=protocol.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isObject(value) {\n return ((value !== null) && (typeof value === 'object'));\n}\nexports.default = isObject;\n//# sourceMappingURL=is-object.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isString(value) {\n return typeof value === 'string';\n}\nexports.default = isString;\n//# sourceMappingURL=is-string.js.map","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n(function(){\n \"use strict\";\n\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n // Use a lookup table to find the index.\n var lookup = new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n\n exports.encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer),\n i, len = bytes.length, base64 = \"\";\n\n for (i = 0; i < len; i+=3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n\n if ((len % 3) === 2) {\n base64 = base64.substring(0, base64.length - 1) + \"=\";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + \"==\";\n }\n\n return base64;\n };\n\n exports.decode = function(base64) {\n var bufferLength = base64.length * 0.75,\n len = base64.length, i, p = 0,\n encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === \"=\") {\n bufferLength--;\n if (base64[base64.length - 2] === \"=\") {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (i = 0; i < len; i+=4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i+1)];\n encoded3 = lookup[base64.charCodeAt(i+2)];\n encoded4 = lookup[base64.charCodeAt(i+3)];\n\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n\n return arraybuffer;\n };\n})();\n","export default '00000000-0000-0000-0000-000000000000';","import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n var v;\n var arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nvar getRandomValues;\nvar rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation. Also,\n // find the complete implementation of crypto (msCrypto) on IE11.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nvar byteToHex = [];\n\nfor (var i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr) {\n var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js'; // **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\n\nvar _clockseq; // Previous uuid creation time\n\n\nvar _lastMSecs = 0;\nvar _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || new Array(16);\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n var seedBytes = options.random || (options.rng || rng)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || stringify(b);\n}\n\nexport default v1;","/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (var i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n var output = [];\n var length32 = input.length * 32;\n var hexTab = '0123456789abcdef';\n\n for (var i = 0; i < length32; i += 8) {\n var x = input[i >> 5] >>> i % 32 & 0xff;\n var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n var length8 = input.length * 8;\n var output = new Uint32Array(getOutputLength(length8));\n\n for (var i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n var lsw = (x & 0xffff) + (y & 0xffff);\n var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nexport default md5;","import v35 from './v35.js';\nimport md5 from './md5.js';\nvar v3 = v35('v3', 0x30, md5);\nexport default v3;","import stringify from './stringify.js';\nimport parse from './parse.js';\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n var bytes = [];\n\n for (var i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nexport var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexport var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexport default function (name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = parse(namespace);\n }\n\n if (namespace.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n var bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return stringify(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (var i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (var i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n var l = bytes.length / 4 + 2;\n var N = Math.ceil(l / 16);\n var M = new Array(N);\n\n for (var _i = 0; _i < N; ++_i) {\n var arr = new Uint32Array(16);\n\n for (var j = 0; j < 16; ++j) {\n arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];\n }\n\n M[_i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (var _i2 = 0; _i2 < N; ++_i2) {\n var W = new Uint32Array(80);\n\n for (var t = 0; t < 16; ++t) {\n W[t] = M[_i2][t];\n }\n\n for (var _t = 16; _t < 80; ++_t) {\n W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);\n }\n\n var a = H[0];\n var b = H[1];\n var c = H[2];\n var d = H[3];\n var e = H[4];\n\n for (var _t2 = 0; _t2 < 80; ++_t2) {\n var s = Math.floor(_t2 / 20);\n var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nexport default sha1;","import v35 from './v35.js';\nimport sha1 from './sha1.js';\nvar v5 = v35('v5', 0x50, sha1);\nexport default v5;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n\nfunction version(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.substr(14, 1), 16);\n}\n\nexport default version;"],"names":["Object","defineProperty","exports","value","AdminClient","GraphQLError","RequestError","ConnectionError","resetAdminServer","async","options","serverUrl","adminServerUrl","types_1","DEFAULT_ADMIN_SERVER_PORT","requestFromAdminServer","requestOptions","method","_","events_1","DuplexPair","typed_error_1","CrossFetch","WebSocket","connectWebSocketStream","subscriptions_transport_ws_1","graphql_1","util_1","error_1","promise_1","schema_introspection_1","schema_introspection_2","admin_query_1","fetch","Headers","isNode","globalThis","TypedError","constructor","message","response","super","this","errors","length","status","map","e","join","mergeClientOptions","defaultOptions","headers","forEach","key","append","isObject","assign","path","url","isErrorLike","code","body","text","jsonBody","JSON","parse","error","json","EventEmitter","debug","running","enableDebug","queryMockServer","reset","adminClientOptions","defaults","adminStreamReconnectAttempts","attachStreamWebsocket","adminSessionBaseUrl","targetStream","adminSessionBaseWSUrl","replace","wsStream","streamConnected","on","pipe","end","console","warn","emit","closeEvent","unpipe","tryToReconnectStream","log","removeAllListeners","destroy","retries","newStream","Promise","resolve","reject","once","then","catch","err","retryAttempt","delay","Math","pow","openStreamToMockServer","socket1","wsTarget","socket2","exposedStream","setMaxListeners","prepareSubscriptionClientToAdminServer","subscriptionUrl","subscriptionClient","SubscriptionClient","lazy","reconnect","reconnectionAttempts","wsOptionArguments","onError","onReconnecting","requestFromMockServer","Error","query","variables","stringify","data","graphQLErrors","e2","start","pluginStartParams","startPromise","getDeferred","result","portConfig","port","undefined","adminServerResponse","plugins","http","isPluginAwareServer","sessionId","id","toString","adminServerStream","stop","adminServerSchema","SchemaIntrospector","introspectionQuery","__schema","serverMetadata","adminServerMetadata","pluginData","isRunning","metadata","schema","adminStream","stopPromise","close","requestServerStop","sendQuery","sendQueries","queries","results","transformResponse","print","adminClient","all","subscribe","callback","fieldName","getSingleSelectedFieldName","typeHasField","isConnected","client","request","next","onConnected","onDisconnected","getRuleParameterKeys","queryTypeDefined","ruleParameterKeys","isFieldSelection","selection","kind","selectedFieldNames","gqlQuery","definitions","selectionSet","getQuerySelectionNode","selections","filter","name","MockedEndpointClient","explanation","endpointDataGetter","getMockedEndpointData","mockedEndpointData","getSeenRequests","seenRequests","isPending","call","MockttpAdminRequestBuilder","graphql_tag_1","request_utils_1","header_utils_1","mocked_endpoint_client_1","rule_serialization_1","normalizeHttpMessage","event","timingEvents","rawHeaders","rawHeadersToObject","objectHeadersToRaw","rawTrailers","trailers","buildBodyReader","Buffer","from","tags","startsWith","tlsMetadata","getEndpointDataGetter","ruleId","mockedEndpoint","default","asOptionalField","req","buildAddRequestRulesQuery","rules","requestName","mutationName","serializedRules","rule","serializedRule","serializeRuleData","typeHasInputField","newRules","endpoints","buildAddWebSocketRulesQuery","buildMockedEndpointsQuery","mockedEndpoints","buildPendingEndpointsQuery","pendingEndpoints","buildSubscriptionRequest","abort","mapValues","v","content","eventData","rawBody","MockttpClient","mockttp_1","admin_client_1","mockttp_admin_request_builder_1","AbstractMockttp","cors","addRequestRules","_addRequestRules","setRequestRules","addWebSocketRules","_addWsRules","setWebSocketRules","requestBuilder","mockServerOptions","mockRoot","getMockedEndpoints","getPendingEndpoints","slice","subRequest","queryType","isTypeDefined","typeName","some","types","type","find","fields","firstAvailableName","Array","isArray","inputFields","MockttpPluggableAdmin","PluggableAdmin","enumerable","get","Method","matchers","requestHandlerDefinitions","webSocketHandlerDefinitions","completionCheckers","SimpleHandlerDefinition","CallbackHandlerDefinition","StreamHandlerDefinition","FileHandlerDefinition","PassThroughHandlerDefinition","CloseConnectionHandlerDefinition","TimeoutHandlerDefinition","HandlerDefinitionLookup","PassThroughWebSocketHandlerDefinition","WsHandlerDefinitionLookup","rule_parameters_1","MOCKTTP_PARAM_REF","common_tags_1","request_rule_builder_1","websocket_rule_builder_1","addRequestRule","addWebSocketRule","corsOptions","recordTraffic","suggestChanges","proxyEnv","HTTP_PROXY","HTTPS_PROXY","urlFor","forAnyRequest","RequestRuleBuilder","forUnmatchedRequest","asPriority","RulePriority","FALLBACK","forGet","GET","forPost","POST","forPut","PUT","forDelete","DELETE","forPatch","PATCH","forHead","HEAD","forOptions","stripIndent","OPTIONS","forJsonRpcRequest","match","withJsonBodyIncluding","jsonrpc","params","forAnyWebSocket","WebSocketRuleBuilder","Serialization","AdminServer","BaseRuleBuilder","lodash_1","completion_checkers_1","matchers_1","priority","DEFAULT","buildBaseRuleData","completionChecker","forHost","host","push","HostMatcher","forHostname","hostname","HostnameMatcher","forPort","PortMatcher","withHeaders","HeaderMatcher","withQuery","QueryMatcher","withExactQuery","ExactQueryMatcher","withForm","formData","FormDataMatcher","withMultipartForm","matchConditions","MultipartFormDataMatcher","withBody","isString","RawBodyMatcher","RegexBodyMatcher","withBodyIncluding","RawBodyIncludesMatcher","withJsonBody","JsonBodyMatcher","JsonBodyFlexibleMatcher","withCookie","cookie","CookieMatcher","withProtocol","protocol","ProtocolMatcher","withUrlMatching","pattern","RegexUrlMatcher","matching","CallbackMatcher","always","Always","Once","twice","Twice","thrice","Thrice","times","n","NTimes","CompletionCheckerLookup","serialization_1","Serializable","arguments","isComplete","explain","seenRequestCount","explainUntil","Infinity","count","seen","MatcherLookup","RegexPathMatcher","SimplePathMatcher","MethodMatcher","WildcardMatcher","matchesAll","resultsPromises","matcher","matches","maybePromiseResult","every","explainMatchers","m","multipart","url_1","body_serialization_1","unescapeRegexp","input","includes","parsedUrl","URL","endsWith","split","search","oneLine","normalizeUrl","expectedUrl","reqUrl","isRelativeUrl","getPathFromAbsoluteUrl","isAbsoluteUrl","getUrlWithoutProtocol","regex","regexSource","source","regexFlags","flags","absoluteUrl","urlPath","urlMatcher","RegExp","test","headersInput","mapKeys","_value","toLowerCase","isMatch","queryObjectInput","queryObject","av","contentType","indexOf","asFormData","boundary","parsedBody","asDecodedBuffer","condition","expectedContent","part","equals","filename","asText","regexString","receivedBody","asJson","isEqual","trim","element","completedRequest","waitForCompletedRequest","serialize","channel","onRequest","streamMsg","withDeserializedBodyReader","version","deserialize","rpcCallback","withSerializedBodyReader","JsonRpcResponseHandlerDefinition","ResetConnectionHandlerDefinition","SERIALIZED_OMIT","base64_arraybuffer_1","stream_1","fast_json_patch_1","buffer_utils_1","validateCustomHeaders","originalHeaders","modifiedHeaders","headerWhitelist","invalidHeaders","pickBy","keys","size","statusMessage","isEmpty","entries","args","buffer","callbackResult","withSerializedCallbackBuffers","stream","serializationStream","Transform","objectMode","transform","chunk","_encoding","serializedEventData","isBuffer","isArrayBuffer","isTypedArray","encode","isNil","flush","filePath","ignoreHostHttpsErrors","extraCACertificates","outgoingSockets","Set","forwarding","targetHost","suggestion","format","lookupOptions","proxyConfig","simulateConnectionErrors","additionalTrustedCAs","trustAdditionalCAs","clientCertificateHostMap","beforeRequest","transformRequest","updateHeaders","replaceHeaders","o","replaceBody","replaceBodyFromFile","updateJsonBody","patchJsonBody","matchReplaceBody","validationError","validate","beforeResponse","serializedResult","forwardToLocation","serializeProxyConfig","ignoreHostCertificateErrors","certObject","cert","pfx","passphrase","serializeBuffer","asBuffer","k","isRegExp","hasBeforeRequestCallback","hasBeforeResponseCallback","resultType","request_handler_definitions_1","base_rule_builder_1","methodOrAddRule","addRule","Function","thenReply","dataOrMessage","dataOrHeaders","headersOrTrailers","handler","thenJson","jsonData","merge","byteLength","thenCallback","thenStream","thenFromFile","pathOrMessage","pathOrHeaders","thenPassThrough","thenForwardTo","thenCloseConnection","thenResetConnection","thenTimeout","thenSendJsonRpcResult","thenSendJsonRpcError","isParamReference","dereferenceParam","paramRef","paramKey","assertParamDereferenced","maybeParamRef","Symbol","validateMockRuleData","RejectWebSocketHandlerDefinition","ListenWebSocketHandlerDefinition","EchoWebSocketHandlerDefinition","statusCode","websocket_handler_definitions_1","thenEcho","thenPassivelyListen","thenRejectConnection","deserializeBuffer","serializedBody","isMockttpBody","withDeserializedCallbackBuffers","ClientServerChannel","obj","topicId","ruleParams","lookup","deserialized","builtinDispose","dispose","ensureParamsDeferenced","isFunction","callbackId","uuid_1","v4","config","SERIALIZED_PARAM_REFERENCE","trustedCAs","caDefinition","deserializeProxyConfig","_channel","_ruleParams","create","prototype","DISPOSE_MESSAGE","disposeChannel","Duplex","rawStream","_onRawStreamError","_onRawStreamFinish","_readFromRawStream","rawData","d","rawDataLine","omit","reading","_write","encoding","write","_read","actionOrData","dataOrNothing","action","requestId","responseListener","stack","removeListener","cbOrAction","cbOrNothing","actionName","cb","writable","pick","getOwnPropertyNames","disposeReceived","isSerializedRuleParam","streamToBuffer","bufferToStream","bufferThenStream","splitBuffer","splitter","maxParts","parts","remainingBuffer","endOfPart","MAX_BUFFER_SIZE","inputStream","active","outputStream","PassThrough","read","failedWith","concat","currentChunks","readableEnded","readableAborted","events","chunks","maxSize","bufferPromise","failWithAbortError","currentSize","onData","findRawHeaders","findRawHeaderIndex","findRawHeader","pairFlatRawHeaders","flatRawHeaders","i","flattenPairedRawHeaders","flat","reduce","existingValue","rawHeadersToObjectPreservingCase","headerNameMap","lowerCaseKey","objectHeadersToFlat","flatHeaders","h2HeadersToH1","h2Headers","h1Headers","unshift","cookieHeaders","h1HeadersToH2","HTTP2_ILLEGAL_HEADERS","dropDefaultHeaders","defaultHeader","removeHeader","validateHeader","validateHeaderName","validateHeaderValue","targetKey","findIndex","array","testResults","objectAllPromise","zipObject","values","resolveCallback","rejectCallback","parseRequestBody","writeHead","shouldKeepAlive","isHttp2","encodeBodyBuffer","contentEncoding","encodeBuffer","level","decodeBodyBuffer","buildInitiatedRequest","waitForBody","trackResponse","trackedResponse","trackingStream","originalWriteHeader","originalWrite","originalEnd","originalAddTrailers","addTrailers","originalGetHeaders","getHeaders","writtenHeaders","writtenTrailers","getRawHeaders","headersArg","headersSentTimestamp","now","getHeaderPairsFromArgument","storedHeaders","apply","writtenHeaderKeys","storedHeaderKeys","reverse","getRawTrailers","trailersArg","trackingWrite","parseBodyStream","waitForCompletedResponse","responseSentTimestamp","completedResponse","valueOf","http2","Http2ServerResponse","tryToParseHttpRequest","socket","__lastHopEncrypted","tls_1","TLSSocket","servername","lines","requestLine","rawUri","httpProtocol","emptyLineIndex","line","headerParts","p","hostHeader","httpVersion","parseRawHttpResponse","responseLine","subarray","_httpVersion","rawStatusCode","restResponseLine","parseInt","querystring","decodeBuffer","bodyStream","completedBuffer","asStream","b","t","runAsyncOrUndefined","func","bufferBody","hasOwnProperty","completedBody","getDecodedBuffer","getText","getMultipartFormData","multipartBodyBuffer","multiPartBody","prevValue","getUrlEncodedFormData","getEffectivePort","isAbsoluteProtocollessUrl","pathIndex","nthIndexOf","memoize","urlInput","isProtocolless","queryIndex","hash","pathname","encoded","toUpperCase","unicodeChar","encodeURIComponent","normalizedUrl","makePropertyWritable","isWeb","isWorker","index","Blob","r","setTimeout","WorkerGlobalScope","self","Window","process","property","__assign","s","__awaiter","thisArg","_arguments","P","generator","fulfilled","step","rejected","done","__generator","f","y","g","label","sent","trys","ops","verb","iterator","op","TypeError","pop","__spreadArray","to","pack","ar","l","_global","window","NativeWebSocket","MozWebSocket","Backoff","eventemitter3_1","is_string_1","is_object_1","printer_1","getOperationAST_1","symbol_observable_1","protocol_1","defaults_1","message_types_1","webSocketImpl","webSocketProtocols","_a","_b","connectionCallback","_c","connectionParams","_d","minTimeout","MIN_WS_TIMEOUT","_e","timeout","WS_TIMEOUT","_f","_g","_h","_j","inactivityTimeout","_k","wsImpl","wsProtocols","GRAPHQL_WS","operations","nextOperationId","minWsTimeout","wsTimeout","unsentMessagesQueue","reconnecting","closedByUser","backoff","jitter","eventEmitter","middlewares","maxConnectTimeGenerator","createMaxConnectTimeGenerator","getConnectionParams","connect","CLOSED","readyState","configurable","isForced","clearInactivityTimeout","clearCheckConnectionInterval","clearMaxConnectTimeout","clearTryReconnectTimeout","unsubscribeAll","sendMessage","GQL_CONNECTION_TERMINATE","onopen","onclose","onmessage","onerror","tryReconnect","opId","getObserver","bind","executeOperation","unsubscribe","observerOrNext","onComplete","observer","complete","eventName","context","off","onConnecting","onReconnected","_this","subId","applyMiddlewares","funcs","scope","shift","applyMiddleware","use","middleware","generateOperationId","processedOptions","checkOperationOptions","GQL_START","formatErrors","minValue","maxValue","min","max","factor","checkConnectionIntervalId","clearInterval","maxConnectTimeoutId","clearTimeout","tryReconnectTimeoutId","inactivityTimeoutId","setInactivityTimeout","operationName","getOperationAST","buildMessage","payload","originalError","sendMessageRaw","OPEN","serializedMessage","send","CONNECTING","String","attempts","duration","flushUnsentMessagesQueue","checkConnection","wasKeepAliveReceived","checkMaxConnectTimeout","GQL_CONNECTION_INIT","GQL_CONNECTION_ERROR","processReceivedData","receivedData","parsedMessage","GQL_DATA","GQL_COMPLETE","GQL_ERROR","GQL_CONNECTION_ACK","parsedPayload","GQL_CONNECTION_KEEP_ALIVE","firstKA","setInterval","GQL_STOP","MessageTypes","SUBSCRIPTION_START","SUBSCRIPTION_DATA","SUBSCRIPTION_SUCCESS","SUBSCRIPTION_FAIL","SUBSCRIPTION_END","INIT","INIT_SUCCESS","INIT_FAIL","KEEP_ALIVE","GRAPHQL_SUBSCRIPTIONS","chars","Uint8Array","charCodeAt","arraybuffer","bytes","len","base64","substring","decode","encoded1","encoded2","encoded3","encoded4","bufferLength","ArrayBuffer","uuid","arr","getRandomValues","rnds8","rng","crypto","msCrypto","byteToHex","substr","offset","_nodeId","_clockseq","_lastMSecs","_lastNSecs","buf","node","clockseq","seedBytes","random","msecs","Date","nsecs","dt","tl","tmh","getOutputLength","inputLength8","safeAdd","x","lsw","md5cmn","q","a","num","cnt","md5ff","c","md5gg","md5hh","md5ii","msg","unescape","output","length32","hexTab","hex","charAt","md5ToHexEncodedArray","olda","oldb","oldc","oldd","wordsToMd5","length8","Uint32Array","bytesToWords","DNS","hashfunc","generateUUID","namespace","str","stringToBytes","set","rnds","z","ROTL","K","H","N","ceil","M","_i","j","floor","_i2","W","_t","_t2","T"],"sourceRoot":""}