How to use resContentTypeIsJavaScript method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

proxy.js

Source: proxy.js Github

copy
1(function() {
2  var NO_BODY_STATUS_CODES, Promise, REDIRECT_STATUS_CODES, _, accept, blacklist, buffers, charset, concat, conditional, cors, cwd, debug, getNodeCharsetFromResponse, iconv, isGzipError, passthruStream, reqNeedsBasicAuthHeaders, responseMustHaveEmptyBody, rewriter, setCookie, zlib, zlibOptions,
3    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
4
5  _ = require("lodash");
6
7  zlib = require("zlib");
8
9  charset = require("charset");
10
11  concat = require("concat-stream");
12
13  iconv = require("iconv-lite");
14
15  Promise = require("bluebird");
16
17  accept = require("http-accept");
18
19  debug = require("debug")("cypress:server:proxy");
20
21  cwd = require("../cwd");
22
23  cors = require("../util/cors");
24
25  buffers = require("../util/buffers");
26
27  rewriter = require("../util/rewriter");
28
29  blacklist = require("../util/blacklist");
30
31  conditional = require("../util/conditional_stream");
32
33  passthruStream = require("../util/passthru_stream").passthruStream;
34
35  REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308];
36
37  NO_BODY_STATUS_CODES = [204, 304];
38
39  zlib = Promise.promisifyAll(zlib);
40
41  zlibOptions = {
42    flush: zlib.Z_SYNC_FLUSH,
43    finishFlush: zlib.Z_SYNC_FLUSH
44  };
45
46  getNodeCharsetFromResponse = function(headers, body) {
47    var httpCharset;
48    httpCharset = (charset(headers, body, 1024) || '').toLowerCase();
49    debug("inferred charset from response %o", {
50      httpCharset: httpCharset
51    });
52    if (iconv.encodingExists(httpCharset)) {
53      return httpCharset;
54    }
55    return "latin1";
56  };
57
58  isGzipError = function(err) {
59    return Object.prototype.hasOwnProperty.call(zlib.constants, err.code);
60  };
61
62  responseMustHaveEmptyBody = function(method, statusCode) {
63    return _.some([_.includes(NO_BODY_STATUS_CODES, statusCode), _.invoke(method, 'toLowerCase') === 'head']);
64  };
65
66  setCookie = function(res, key, val, domainName) {
67    var options;
68    options = {
69      domain: domainName
70    };
71    if (!val) {
72      val = "";
73      options.expires = new Date(0);
74    }
75    return res.cookie(key, val, options);
76  };
77
78  reqNeedsBasicAuthHeaders = function(req, remoteState) {
79    var auth, origin;
80    auth = remoteState.auth, origin = remoteState.origin;
81    return auth && !req.headers["authorization"] && cors.urlMatchesOriginProtectionSpace(req.proxiedUrl, origin);
82  };
83
84  module.exports = {
85    handle: function(req, res, config, getRemoteState, request, nodeProxy) {
86      var blh, matched, remoteState, thr;
87      remoteState = getRemoteState();
88      debug("handling proxied request %o", {
89        url: req.url,
90        proxiedUrl: req.proxiedUrl,
91        headers: req.headers,
92        remoteState: remoteState
93      });
94      if (req.cookies["__cypress.unload"]) {
95        return res.redirect(config.clientRoute);
96      }
97      if (req.url === req.proxiedUrl && !remoteState.visiting) {
98        return res.redirect(config.clientRoute);
99      }
100      if (blh = config.blacklistHosts) {
101        if (matched = blacklist.matches(req.proxiedUrl, blh)) {
102          res.set("x-cypress-matched-blacklisted-host", matched);
103          debug("blacklisting request %o", {
104            url: req.proxiedUrl,
105            matched: matched
106          });
107          return res.status(503).end();
108        }
109      }
110      thr = passthruStream();
111      return this.getHttpContent(thr, req, res, remoteState, config, request).pipe(res);
112    },
113    getHttpContent: function(thr, req, res, remoteState, config, request) {
114      var auth, base64, encodings, endWithNetworkErr, isInitial, obj, onResponse, opts, ref, reqAcceptsHtml, resContentTypeIs, resContentTypeIsJavaScript, resMatchesOriginPolicy, rq, setBody, setCookies, wantsInjection, wantsSecurityRemoved;
115      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
116      isInitial = req.cookies["__cypress.initial"] === "true";
117      wantsInjection = null;
118      wantsSecurityRemoved = null;
119      resContentTypeIs = function(respHeaders, str) {
120        var contentType;
121        contentType = respHeaders["content-type"];
122        return contentType && contentType.includes(str);
123      };
124      resContentTypeIsJavaScript = function(respHeaders) {
125        return _.some(['application/javascript', 'application/x-javascript', 'text/javascript'].map(_.partial(resContentTypeIs, respHeaders)));
126      };
127      reqAcceptsHtml = function() {
128        var find, ref, types;
129        if (req.headers["x-requested-with"]) {
130          return;
131        }
132        types = (ref = accept.parser(req.headers.accept)) != null ? ref : [];
133        find = function(type) {
134          return indexOf.call(types, type) >= 0;
135        };
136        return find("text/html") && find("application/xhtml+xml");
137      };
138      resMatchesOriginPolicy = function(respHeaders) {
139        switch (remoteState.strategy) {
140          case "http":
141            return cors.urlMatchesOriginPolicyProps(req.proxiedUrl, remoteState.props);
142          case "file":
143            return req.proxiedUrl.startsWith(remoteState.origin);
144        }
145      };
146      setCookies = function(value) {
147        if ((!value) && (!wantsInjection)) {
148          return;
149        }
150        if (!isInitial) {
151          return;
152        }
153        return setCookie(res, "__cypress.initial", value, remoteState.domainName);
154      };
155      setBody = function(str, statusCode, headers) {
156        var encoding, gunzip, injection, isGzipped, onError, rewrite;
157        res.status(statusCode);
158        setCookies(false, wantsInjection);
159        encoding = headers["content-encoding"];
160        isGzipped = encoding && encoding.includes("gzip");
161        debug("received response for %o", {
162          url: req.proxiedUrl,
163          headers: headers,
164          statusCode: statusCode,
165          isGzipped: isGzipped,
166          wantsInjection: wantsInjection,
167          wantsSecurityRemoved: wantsSecurityRemoved
168        });
169        if (responseMustHaveEmptyBody(req.method, statusCode)) {
170          return res.end();
171        }
172        if (wantsInjection) {
173          rewrite = function(body) {
174            var decodedBody, nodeCharset, rewrittenBody;
175            nodeCharset = getNodeCharsetFromResponse(headers, body);
176            decodedBody = iconv.decode(body, nodeCharset);
177            rewrittenBody = rewriter.html(decodedBody, remoteState.domainName, wantsInjection, wantsSecurityRemoved);
178            return iconv.encode(rewrittenBody, nodeCharset);
179          };
180          injection = concat(function(body) {
181            if (_.isEqual(body, [])) {
182              body = Buffer.from('');
183            }
184            if (isGzipped) {
185              return zlib.gunzipAsync(body, zlibOptions).then(rewrite).then(zlib.gzipAsync).then(thr.end)["catch"](endWithNetworkErr);
186            } else {
187              return thr.end(rewrite(body));
188            }
189          });
190          return str.pipe(injection);
191        } else {
192          if (wantsSecurityRemoved) {
193            gunzip = zlib.createGunzip(zlibOptions);
194            gunzip.setEncoding("utf8");
195            onError = function(err) {
196              var gzipError;
197              gzipError = isGzipError(err);
198              debug("failed to proxy response %o", {
199                url: req.proxiedUrl,
200                headers: headers,
201                statusCode: statusCode,
202                isGzipped: isGzipped,
203                gzipError: gzipError,
204                wantsInjection: wantsInjection,
205                wantsSecurityRemoved: wantsSecurityRemoved,
206                err: err
207              });
208              return endWithNetworkErr(err);
209            };
210            return str.pipe(conditional(isGzipped, gunzip)).on("error", onError).pipe(rewriter.security()).on("error", onError).pipe(conditional(isGzipped, zlib.createGzip())).on("error", onError).pipe(thr).on("error", onError);
211          }
212          return str.pipe(thr);
213        }
214      };
215      endWithNetworkErr = function(err) {
216        debug('request failed in proxy layer %o', {
217          res: _.pick(res, 'headersSent', 'statusCode', 'headers'),
218          req: _.pick(req, 'url', 'proxiedUrl', 'headers', 'method'),
219          err: err
220        });
221        return req.socket.destroy();
222      };
223      onResponse = (function(_this) {
224        return function(str, incomingRes) {
225          var c, cookies, err, headers, i, len, newUrl, originalSetHeader, ref, statusCode;
226          headers = incomingRes.headers, statusCode = incomingRes.statusCode;
227          originalSetHeader = res.setHeader;
228          res.setHeader = function(k, v) {
229            if (k === 'content-type') {
230              v = incomingRes.headers['content-type'];
231            }
232            return originalSetHeader.call(res, k, v);
233          };
234          if (wantsInjection == null) {
235            wantsInjection = (function() {
236              if (!resContentTypeIs(headers, "text/html")) {
237                return false;
238              }
239              if (!resMatchesOriginPolicy(headers)) {
240                return false;
241              }
242              if (isInitial) {
243                return "full";
244              }
245              if (!reqAcceptsHtml()) {
246                return false;
247              }
248              return "partial";
249            })();
250          }
251          wantsSecurityRemoved = (function() {
252            return config.modifyObstructiveCode && ((wantsInjection === "full") || resContentTypeIsJavaScript(headers));
253          })();
254          _this.setResHeaders(req, res, incomingRes, wantsInjection);
255          if (cookies = headers["set-cookie"]) {
256            ref = [].concat(cookies);
257            for (i = 0, len = ref.length; i < len; i++) {
258              c = ref[i];
259              try {
260                res.append("Set-Cookie", c);
261              } catch (error) {
262                err = error;
263              }
264            }
265          }
266          if (REDIRECT_STATUS_CODES.includes(statusCode)) {
267            newUrl = headers.location;
268            setCookies(true);
269            debug("redirecting to new url %o", {
270              status: statusCode,
271              url: newUrl
272            });
273            return res.redirect(statusCode, newUrl);
274          }
275          if (headers["x-cypress-file-server-error"]) {
276            wantsInjection || (wantsInjection = "partial");
277          }
278          return setBody(str, statusCode, headers);
279        };
280      })(this);
281      if (obj = buffers.take(req.proxiedUrl)) {
282        wantsInjection = "full";
283        onResponse(obj.stream, obj.response);
284      } else {
285        opts = {
286          timeout: null,
287          strictSSL: false,
288          followRedirect: false,
289          retryIntervals: [0, 100, 200, 200]
290        };
291        encodings = (ref = accept.parser(req.headers["accept-encoding"])) != null ? ref : [];
292        if (indexOf.call(encodings, "gzip") >= 0) {
293          req.headers["accept-encoding"] = "gzip";
294        } else {
295          delete req.headers["accept-encoding"];
296        }
297        if (remoteState.strategy === "file" && req.proxiedUrl.startsWith(remoteState.origin)) {
298          opts.url = req.proxiedUrl.replace(remoteState.origin, remoteState.fileServer);
299        } else {
300          opts.url = req.proxiedUrl;
301        }
302        if (reqNeedsBasicAuthHeaders(req, remoteState)) {
303          auth = remoteState.auth;
304          base64 = Buffer.from(auth.username + ":" + auth.password).toString("base64");
305          req.headers["authorization"] = "Basic " + base64;
306        }
307        rq = request.create(opts);
308        rq.on("error", endWithNetworkErr);
309        rq.on("response", function(incomingRes) {
310          return onResponse(rq, incomingRes);
311        });
312        req.on("aborted", function() {
313          return rq.abort();
314        });
315        req.pipe(rq);
316      }
317      return thr;
318    },
319    setResHeaders: function(req, res, incomingRes, wantsInjection) {
320      var headers;
321      if (res.headersSent) {
322        return;
323      }
324      headers = _.omit(incomingRes.headers, "set-cookie", "x-frame-options", "content-length", "content-security-policy", "connection");
325      if (wantsInjection) {
326        headers["cache-control"] = "no-cache, no-store, must-revalidate";
327      }
328      return res.set(headers);
329    }
330  };
331
332}).call(this);
333
Full Screen

response-middleware.js

Source: response-middleware.js Github

copy
1"use strict";
2var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3    if (k2 === undefined) k2 = k;
4    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5}) : (function(o, m, k, k2) {
6    if (k2 === undefined) k2 = k;
7    o[k2] = m[k];
8}));
9var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10    Object.defineProperty(o, "default", { enumerable: true, value: v });
11}) : function(o, v) {
12    o["default"] = v;
13});
14var __importStar = (this && this.__importStar) || function (mod) {
15    if (mod && mod.__esModule) return mod;
16    var result = {};
17    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18    __setModuleDefault(result, mod);
19    return result;
20};
21var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23    return new (P || (P = Promise))(function (resolve, reject) {
24        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27        step((generator = generator.apply(thisArg, _arguments || [])).next());
28    });
29};
30var __importDefault = (this && this.__importDefault) || function (mod) {
31    return (mod && mod.__esModule) ? mod : { "default": mod };
32};
33Object.defineProperty(exports, "__esModule", { value: true });
34const lodash_1 = __importDefault(require("lodash"));
35const charset_1 = __importDefault(require("charset"));
36const network_1 = require("../../../network");
37const debug_1 = __importDefault(require("debug"));
38const iconv_lite_1 = __importDefault(require("iconv-lite"));
39const net_stubbing_1 = require("../../../net-stubbing");
40const stream_1 = require("stream");
41const rewriter = __importStar(require("./util/rewriter"));
42const zlib_1 = __importDefault(require("zlib"));
43const debug = (0, debug_1.default)('cypress:proxy:http:response-middleware');
44// https://github.com/cypress-io/cypress/issues/1756
45const zlibOptions = {
46    flush: zlib_1.default.Z_SYNC_FLUSH,
47    finishFlush: zlib_1.default.Z_SYNC_FLUSH,
48};
49// https://github.com/cypress-io/cypress/issues/1543
50function getNodeCharsetFromResponse(headers, body) {
51    const httpCharset = ((0, charset_1.default)(headers, body, 1024) || '').toLowerCase();
52    debug('inferred charset from response %o', { httpCharset });
53    if (iconv_lite_1.default.encodingExists(httpCharset)) {
54        return httpCharset;
55    }
56    // browsers default to latin1
57    return 'latin1';
58}
59function reqMatchesOriginPolicy(req, remoteState) {
60    if (remoteState.strategy === 'http') {
61        return network_1.cors.urlMatchesOriginPolicyProps(req.proxiedUrl, remoteState.props);
62    }
63    if (remoteState.strategy === 'file') {
64        return req.proxiedUrl.startsWith(remoteState.origin);
65    }
66    return false;
67}
68function reqWillRenderHtml(req) {
69    // will this request be rendered in the browser, necessitating injection?
70    // https://github.com/cypress-io/cypress/issues/288
71    // don't inject if this is an XHR from jquery
72    if (req.headers['x-requested-with']) {
73        return;
74    }
75    // don't inject if we didn't find both text/html and application/xhtml+xml,
76    const accept = req.headers['accept'];
77    return accept && accept.includes('text/html') && accept.includes('application/xhtml+xml');
78}
79function resContentTypeIs(res, contentType) {
80    return (res.headers['content-type'] || '').includes(contentType);
81}
82function resContentTypeIsJavaScript(res) {
83    return lodash_1.default.some(['application/javascript', 'application/x-javascript', 'text/javascript']
84        .map(lodash_1.default.partial(resContentTypeIs, res)));
85}
86function isHtml(res) {
87    return !resContentTypeIsJavaScript(res);
88}
89function resIsGzipped(res) {
90    return (res.headers['content-encoding'] || '').includes('gzip');
91}
92function setCookie(res, k, v, domain) {
93    let opts = { domain };
94    if (!v) {
95        v = '';
96        opts.expires = new Date(0);
97    }
98    return res.cookie(k, v, opts);
99}
100function setInitialCookie(res, remoteState, value) {
101    // dont modify any cookies if we're trying to clear the initial cookie and we're not injecting anything
102    // dont set the cookies if we're not on the initial request
103    if ((!value && !res.wantsInjection) || !res.isInitial) {
104        return;
105    }
106    return setCookie(res, '__cypress.initial', value, remoteState.domainName);
107}
108// "autoplay *; document-domain 'none'" => { autoplay: "*", "document-domain": "'none'" }
109const parseFeaturePolicy = (policy) => {
110    const pairs = policy.split('; ').map((directive) => directive.split(' '));
111    return lodash_1.default.fromPairs(pairs);
112};
113// { autoplay: "*", "document-domain": "'none'" } => "autoplay *; document-domain 'none'"
114const stringifyFeaturePolicy = (policy) => {
115    const pairs = lodash_1.default.toPairs(policy);
116    return pairs.map((directive) => directive.join(' ')).join('; ');
117};
118const LogResponse = function () {
119    debug('received response %o', {
120        req: lodash_1.default.pick(this.req, 'method', 'proxiedUrl', 'headers'),
121        incomingRes: lodash_1.default.pick(this.incomingRes, 'headers', 'statusCode'),
122    });
123    this.next();
124};
125const AttachPlainTextStreamFn = function () {
126    this.makeResStreamPlainText = function () {
127        debug('ensuring resStream is plaintext');
128        if (!this.isGunzipped && resIsGzipped(this.incomingRes)) {
129            debug('gunzipping response body');
130            const gunzip = zlib_1.default.createGunzip(zlibOptions);
131            this.incomingResStream = this.incomingResStream.pipe(gunzip).on('error', this.onError);
132            this.isGunzipped = true;
133        }
134    };
135    this.next();
136};
137const PatchExpressSetHeader = function () {
138    const { incomingRes } = this;
139    const originalSetHeader = this.res.setHeader;
140    // Node uses their own Symbol object, so use this to get the internal kOutHeaders
141    // symbol - Symbol.for('kOutHeaders') will not work
142    const getKOutHeadersSymbol = () => {
143        const findKOutHeadersSymbol = () => {
144            return lodash_1.default.find(Object.getOwnPropertySymbols(this.res), (sym) => {
145                return sym.toString() === 'Symbol(kOutHeaders)';
146            });
147        };
148        let sym = findKOutHeadersSymbol();
149        if (sym) {
150            return sym;
151        }
152        // force creation of a new header field so the kOutHeaders key is available
153        this.res.setHeader('X-Cypress-HTTP-Response', 'X');
154        this.res.removeHeader('X-Cypress-HTTP-Response');
155        sym = findKOutHeadersSymbol();
156        if (!sym) {
157            throw new Error('unable to find kOutHeaders symbol');
158        }
159        return sym;
160    };
161    let kOutHeaders;
162    this.res.setHeader = function (name, value) {
163        // express.Response.setHeader does all kinds of silly/nasty stuff to the content-type...
164        // but we don't want to change it at all!
165        if (name === 'content-type') {
166            value = incomingRes.headers['content-type'] || value;
167        }
168        // run the original function - if an "invalid header char" error is raised,
169        // set the header manually. this way we can retain Node's original error behavior
170        try {
171            return originalSetHeader.call(this, name, value);
172        }
173        catch (err) {
174            if (err.code !== 'ERR_INVALID_CHAR') {
175                throw err;
176            }
177            debug('setHeader error ignored %o', { name, value, code: err.code, err });
178            if (!kOutHeaders) {
179                kOutHeaders = getKOutHeadersSymbol();
180            }
181            // https://github.com/nodejs/node/blob/42cce5a9d0fd905bf4ad7a2528c36572dfb8b5ad/lib/_http_outgoing.js#L483-L495
182            let headers = this[kOutHeaders];
183            if (!headers) {
184                this[kOutHeaders] = headers = Object.create(null);
185            }
186            headers[name.toLowerCase()] = [name, value];
187        }
188    };
189    this.next();
190};
191const SetInjectionLevel = function () {
192    this.res.isInitial = this.req.cookies['__cypress.initial'] === 'true';
193    const isRenderedHTML = reqWillRenderHtml(this.req);
194    if (isRenderedHTML) {
195        const origin = new URL(this.req.proxiedUrl).origin;
196        this.getRenderedHTMLOrigins()[origin] = true;
197    }
198    const isReqMatchOriginPolicy = reqMatchesOriginPolicy(this.req, this.getRemoteState());
199    const getInjectionLevel = () => {
200        if (this.incomingRes.headers['x-cypress-file-server-error'] && !this.res.isInitial) {
201            return 'partial';
202        }
203        if (!resContentTypeIs(this.incomingRes, 'text/html') || !isReqMatchOriginPolicy) {
204            return false;
205        }
206        if (this.res.isInitial) {
207            return 'full';
208        }
209        if (!isRenderedHTML) {
210            return false;
211        }
212        return 'partial';
213    };
214    if (!this.res.wantsInjection) {
215        this.res.wantsInjection = getInjectionLevel();
216    }
217    this.res.wantsSecurityRemoved = this.config.modifyObstructiveCode && isReqMatchOriginPolicy && ((this.res.wantsInjection === 'full')
218        || resContentTypeIsJavaScript(this.incomingRes));
219    debug('injection levels: %o', lodash_1.default.pick(this.res, 'isInitial', 'wantsInjection', 'wantsSecurityRemoved'));
220    this.next();
221};
222// https://github.com/cypress-io/cypress/issues/6480
223const MaybeStripDocumentDomainFeaturePolicy = function () {
224    const { 'feature-policy': featurePolicy } = this.incomingRes.headers;
225    if (featurePolicy) {
226        const directives = parseFeaturePolicy(featurePolicy);
227        if (directives['document-domain']) {
228            delete directives['document-domain'];
229            const policy = stringifyFeaturePolicy(directives);
230            if (policy) {
231                this.res.set('feature-policy', policy);
232            }
233            else {
234                this.res.removeHeader('feature-policy');
235            }
236        }
237    }
238    this.next();
239};
240const OmitProblematicHeaders = function () {
241    const headers = lodash_1.default.omit(this.incomingRes.headers, [
242        'set-cookie',
243        'x-frame-options',
244        'content-length',
245        'transfer-encoding',
246        'content-security-policy',
247        'content-security-policy-report-only',
248        'connection',
249    ]);
250    this.res.set(headers);
251    this.next();
252};
253const MaybePreventCaching = function () {
254    // do not cache injected responses
255    // TODO: consider implementing etag system so even injected content can be cached
256    if (this.res.wantsInjection) {
257        this.res.setHeader('cache-control', 'no-cache, no-store, must-revalidate');
258    }
259    this.next();
260};
261const CopyCookiesFromIncomingRes = function () {
262    const cookies = this.incomingRes.headers['set-cookie'];
263    if (cookies) {
264        [].concat(cookies).forEach((cookie) => {
265            try {
266                this.res.append('Set-Cookie', cookie);
267            }
268            catch (err) {
269                debug('failed to Set-Cookie, continuing %o', { err, cookie });
270            }
271        });
272    }
273    this.next();
274};
275const REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308];
276// TODO: this shouldn't really even be necessary?
277const MaybeSendRedirectToClient = function () {
278    const { statusCode, headers } = this.incomingRes;
279    const newUrl = headers['location'];
280    if (!REDIRECT_STATUS_CODES.includes(statusCode) || !newUrl) {
281        return this.next();
282    }
283    setInitialCookie(this.res, this.getRemoteState(), true);
284    debug('redirecting to new url %o', { statusCode, newUrl });
285    this.res.redirect(Number(statusCode), newUrl);
286    return this.end();
287};
288const CopyResponseStatusCode = function () {
289    this.res.status(Number(this.incomingRes.statusCode));
290    this.next();
291};
292const ClearCyInitialCookie = function () {
293    setInitialCookie(this.res, this.getRemoteState(), false);
294    this.next();
295};
296const MaybeEndWithEmptyBody = function () {
297    if (network_1.httpUtils.responseMustHaveEmptyBody(this.req, this.incomingRes)) {
298        this.res.end();
299        return this.end();
300    }
301    this.next();
302};
303const MaybeInjectHtml = function () {
304    if (!this.res.wantsInjection) {
305        return this.next();
306    }
307    this.skipMiddleware('MaybeRemoveSecurity'); // we only want to do one or the other
308    debug('injecting into HTML');
309    this.makeResStreamPlainText();
310    this.incomingResStream.pipe((0, network_1.concatStream)((body) => __awaiter(this, void 0, void 0, function* () {
311        const nodeCharset = getNodeCharsetFromResponse(this.incomingRes.headers, body);
312        const decodedBody = iconv_lite_1.default.decode(body, nodeCharset);
313        const injectedBody = yield rewriter.html(decodedBody, {
314            domainName: this.getRemoteState().domainName,
315            wantsInjection: this.res.wantsInjection,
316            wantsSecurityRemoved: this.res.wantsSecurityRemoved,
317            isHtml: isHtml(this.incomingRes),
318            useAstSourceRewriting: this.config.experimentalSourceRewriting,
319            url: this.req.proxiedUrl,
320            deferSourceMapRewrite: this.deferSourceMapRewrite,
321        });
322        const encodedBody = iconv_lite_1.default.encode(injectedBody, nodeCharset);
323        const pt = new stream_1.PassThrough;
324        pt.write(encodedBody);
325        pt.end();
326        this.incomingResStream = pt;
327        this.next();
328    }))).on('error', this.onError);
329};
330const MaybeRemoveSecurity = function () {
331    if (!this.res.wantsSecurityRemoved) {
332        return this.next();
333    }
334    debug('removing JS framebusting code');
335    this.makeResStreamPlainText();
336    this.incomingResStream.setEncoding('utf8');
337    this.incomingResStream = this.incomingResStream.pipe(rewriter.security({
338        isHtml: isHtml(this.incomingRes),
339        useAstSourceRewriting: this.config.experimentalSourceRewriting,
340        url: this.req.proxiedUrl,
341        deferSourceMapRewrite: this.deferSourceMapRewrite,
342    })).on('error', this.onError);
343    this.next();
344};
345const GzipBody = function () {
346    if (this.isGunzipped) {
347        debug('regzipping response body');
348        this.incomingResStream = this.incomingResStream.pipe(zlib_1.default.createGzip(zlibOptions)).on('error', this.onError);
349    }
350    this.next();
351};
352const SendResponseBodyToClient = function () {
353    this.incomingResStream.pipe(this.res).on('error', this.onError);
354    this.res.on('end', () => this.end());
355};
356exports.default = {
357    LogResponse,
358    AttachPlainTextStreamFn,
359    InterceptResponse: net_stubbing_1.InterceptResponse,
360    PatchExpressSetHeader,
361    SetInjectionLevel,
362    OmitProblematicHeaders,
363    MaybePreventCaching,
364    MaybeStripDocumentDomainFeaturePolicy,
365    CopyCookiesFromIncomingRes,
366    MaybeSendRedirectToClient,
367    CopyResponseStatusCode,
368    ClearCyInitialCookie,
369    MaybeEndWithEmptyBody,
370    MaybeInjectHtml,
371    MaybeRemoveSecurity,
372    GzipBody,
373    SendResponseBodyToClient,
374};
375
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)