Best JavaScript code snippet using playwright-internal
network.js
Source:network.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.validateHeaders = validateHeaders;6exports.WebSocket = exports.Response = exports.Route = exports.InterceptedResponse = exports.Request = void 0;7var _url = require("url");8var _channelOwner = require("./channelOwner");9var _frame = require("./frame");10var _fs = _interopRequireDefault(require("fs"));11var mime = _interopRequireWildcard(require("mime"));12var _utils = require("../utils/utils");13var _events = require("./events");14var _waiter = require("./waiter");15function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }16function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }17function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }18/**19 * Copyright (c) Microsoft Corporation.20 *21 * Licensed under the Apache License, Version 2.0 (the "License");22 * you may not use this file except in compliance with the License.23 * You may obtain a copy of the License at24 *25 * http://www.apache.org/licenses/LICENSE-2.026 *27 * Unless required by applicable law or agreed to in writing, software28 * distributed under the License is distributed on an "AS IS" BASIS,29 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.30 * See the License for the specific language governing permissions and31 * limitations under the License.32 */33class Request extends _channelOwner.ChannelOwner {34 static from(request) {35 return request._object;36 }37 static fromNullable(request) {38 return request ? Request.from(request) : null;39 }40 constructor(parent, type, guid, initializer) {41 super(parent, type, guid, initializer);42 this._redirectedFrom = null;43 this._redirectedTo = null;44 this._failureText = null;45 this._headers = void 0;46 this._postData = void 0;47 this._timing = void 0;48 this._redirectedFrom = Request.fromNullable(initializer.redirectedFrom);49 if (this._redirectedFrom) this._redirectedFrom._redirectedTo = this;50 this._headers = (0, _utils.headersArrayToObject)(initializer.headers, true51 /* lowerCase */52 );53 this._postData = initializer.postData ? Buffer.from(initializer.postData, 'base64') : null;54 this._timing = {55 startTime: 0,56 domainLookupStart: -1,57 domainLookupEnd: -1,58 connectStart: -1,59 secureConnectionStart: -1,60 connectEnd: -1,61 requestStart: -1,62 responseStart: -1,63 responseEnd: -164 };65 }66 url() {67 return this._initializer.url;68 }69 resourceType() {70 return this._initializer.resourceType;71 }72 method() {73 return this._initializer.method;74 }75 postData() {76 return this._postData ? this._postData.toString('utf8') : null;77 }78 postDataBuffer() {79 return this._postData;80 }81 postDataJSON() {82 const postData = this.postData();83 if (!postData) return null;84 const contentType = this.headers()['content-type'];85 if (contentType === 'application/x-www-form-urlencoded') {86 const entries = {};87 const parsed = new _url.URLSearchParams(postData);88 for (const [k, v] of parsed.entries()) entries[k] = v;89 return entries;90 }91 try {92 return JSON.parse(postData);93 } catch (e) {94 throw new Error('POST data is not a valid JSON object: ' + postData);95 }96 }97 headers() {98 return { ...this._headers99 };100 }101 async response() {102 return this._wrapApiCall(async channel => {103 return Response.fromNullable((await channel.response()).response);104 });105 }106 frame() {107 return _frame.Frame.from(this._initializer.frame);108 }109 isNavigationRequest() {110 return this._initializer.isNavigationRequest;111 }112 redirectedFrom() {113 return this._redirectedFrom;114 }115 redirectedTo() {116 return this._redirectedTo;117 }118 failure() {119 if (this._failureText === null) return null;120 return {121 errorText: this._failureText122 };123 }124 timing() {125 return this._timing;126 }127 _finalRequest() {128 return this._redirectedTo ? this._redirectedTo._finalRequest() : this;129 }130}131exports.Request = Request;132class InterceptedResponse {133 constructor(route, initializer) {134 this._route = void 0;135 this._initializer = void 0;136 this._request = void 0;137 this._headers = void 0;138 this._route = route;139 this._initializer = initializer;140 this._headers = (0, _utils.headersArrayToObject)(initializer.headers, true141 /* lowerCase */142 );143 this._request = Request.from(initializer.request);144 }145 async securityDetails() {146 return null;147 }148 async serverAddr() {149 return null;150 }151 async finished() {152 const response = await this._request.response();153 if (!response) return null;154 return await response.finished();155 }156 frame() {157 return this._request.frame();158 }159 ok() {160 return this._initializer.status === 0 || this._initializer.status >= 200 && this._initializer.status <= 299;161 }162 url() {163 return this._request.url();164 }165 status() {166 return this._initializer.status;167 }168 statusText() {169 return this._initializer.statusText;170 }171 headers() {172 return { ...this._headers173 };174 }175 async body() {176 return this._route._responseBody();177 }178 async text() {179 const content = await this.body();180 return content.toString('utf8');181 }182 async json() {183 const content = await this.text();184 return JSON.parse(content);185 }186 request() {187 return this._request;188 }189}190exports.InterceptedResponse = InterceptedResponse;191class Route extends _channelOwner.ChannelOwner {192 static from(route) {193 return route._object;194 }195 constructor(parent, type, guid, initializer) {196 super(parent, type, guid, initializer);197 }198 request() {199 return Request.from(this._initializer.request);200 }201 async abort(errorCode) {202 return this._wrapApiCall(async channel => {203 await channel.abort({204 errorCode205 });206 });207 }208 async fulfill(options = {}) {209 return this._wrapApiCall(async channel => {210 let body = '';211 let isBase64 = false;212 let length = 0;213 if (options.path) {214 const buffer = await _fs.default.promises.readFile(options.path);215 body = buffer.toString('base64');216 isBase64 = true;217 length = buffer.length;218 } else if ((0, _utils.isString)(options.body)) {219 body = options.body;220 isBase64 = false;221 length = Buffer.byteLength(body);222 } else if (options.body) {223 body = options.body.toString('base64');224 isBase64 = true;225 length = options.body.length;226 }227 const headers = {};228 for (const header of Object.keys(options.headers || {})) headers[header.toLowerCase()] = String(options.headers[header]);229 if (options.contentType) headers['content-type'] = String(options.contentType);else if (options.path) headers['content-type'] = mime.getType(options.path) || 'application/octet-stream';230 if (length && !('content-length' in headers)) headers['content-length'] = String(length);231 await channel.fulfill({232 status: options.status || 200,233 headers: (0, _utils.headersObjectToArray)(headers),234 body,235 isBase64236 });237 });238 }239 async _intercept(options = {}) {240 return await this._continue(options, true);241 }242 async continue(options = {}) {243 await this._continue(options, false);244 }245 async _continue(options, interceptResponse) {246 return await this._wrapApiCall(async channel => {247 const postDataBuffer = (0, _utils.isString)(options.postData) ? Buffer.from(options.postData, 'utf8') : options.postData;248 const result = await channel.continue({249 url: options.url,250 method: options.method,251 headers: options.headers ? (0, _utils.headersObjectToArray)(options.headers) : undefined,252 postData: postDataBuffer ? postDataBuffer.toString('base64') : undefined,253 interceptResponse254 });255 if (result.response) return new InterceptedResponse(this, result.response);256 return null;257 });258 }259 async _responseBody() {260 return this._wrapApiCall(async channel => {261 return Buffer.from((await channel.responseBody()).binary, 'base64');262 });263 }264}265exports.Route = Route;266class Response extends _channelOwner.ChannelOwner {267 static from(response) {268 return response._object;269 }270 static fromNullable(response) {271 return response ? Response.from(response) : null;272 }273 constructor(parent, type, guid, initializer) {274 super(parent, type, guid, initializer);275 this._headers = void 0;276 this._request = void 0;277 this._headers = (0, _utils.headersArrayToObject)(initializer.headers, true278 /* lowerCase */279 );280 this._request = Request.from(this._initializer.request);281 this._request._headers = (0, _utils.headersArrayToObject)(initializer.requestHeaders, true282 /* lowerCase */283 );284 Object.assign(this._request._timing, this._initializer.timing);285 }286 url() {287 return this._initializer.url;288 }289 ok() {290 return this._initializer.status === 0 || this._initializer.status >= 200 && this._initializer.status <= 299;291 }292 status() {293 return this._initializer.status;294 }295 statusText() {296 return this._initializer.statusText;297 }298 headers() {299 return { ...this._headers300 };301 }302 async finished() {303 return this._wrapApiCall(async channel => {304 const result = await channel.finished();305 if (result.error) return new Error(result.error);306 return null;307 });308 }309 async body() {310 return this._wrapApiCall(async channel => {311 return Buffer.from((await channel.body()).binary, 'base64');312 });313 }314 async text() {315 const content = await this.body();316 return content.toString('utf8');317 }318 async json() {319 const content = await this.text();320 return JSON.parse(content);321 }322 request() {323 return this._request;324 }325 frame() {326 return this._request.frame();327 }328 async serverAddr() {329 return this._wrapApiCall(async channel => {330 return (await channel.serverAddr()).value || null;331 });332 }333 async securityDetails() {334 return this._wrapApiCall(async channel => {335 return (await channel.securityDetails()).value || null;336 });337 }338}339exports.Response = Response;340class WebSocket extends _channelOwner.ChannelOwner {341 static from(webSocket) {342 return webSocket._object;343 }344 constructor(parent, type, guid, initializer) {345 super(parent, type, guid, initializer);346 this._page = void 0;347 this._isClosed = void 0;348 this._isClosed = false;349 this._page = parent;350 this._channel.on('frameSent', event => {351 if (event.opcode === 1) this.emit(_events.Events.WebSocket.FrameSent, {352 payload: event.data353 });else if (event.opcode === 2) this.emit(_events.Events.WebSocket.FrameSent, {354 payload: Buffer.from(event.data, 'base64')355 });356 });357 this._channel.on('frameReceived', event => {358 if (event.opcode === 1) this.emit(_events.Events.WebSocket.FrameReceived, {359 payload: event.data360 });else if (event.opcode === 2) this.emit(_events.Events.WebSocket.FrameReceived, {361 payload: Buffer.from(event.data, 'base64')362 });363 });364 this._channel.on('socketError', ({365 error366 }) => this.emit(_events.Events.WebSocket.Error, error));367 this._channel.on('close', () => {368 this._isClosed = true;369 this.emit(_events.Events.WebSocket.Close, this);370 });371 }372 url() {373 return this._initializer.url;374 }375 isClosed() {376 return this._isClosed;377 }378 async waitForEvent(event, optionsOrPredicate = {}) {379 return this._wrapApiCall(async channel => {380 const timeout = this._page._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);381 const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;382 const waiter = _waiter.Waiter.createForEvent(this, event);383 waiter.rejectOnTimeout(timeout, `Timeout while waiting for event "${event}"`);384 if (event !== _events.Events.WebSocket.Error) waiter.rejectOnEvent(this, _events.Events.WebSocket.Error, new Error('Socket error'));385 if (event !== _events.Events.WebSocket.Close) waiter.rejectOnEvent(this, _events.Events.WebSocket.Close, new Error('Socket closed'));386 waiter.rejectOnEvent(this._page, _events.Events.Page.Close, new Error('Page closed'));387 const result = await waiter.waitForEvent(this, event, predicate);388 waiter.dispose();389 return result;390 });391 }392}393exports.WebSocket = WebSocket;394function validateHeaders(headers) {395 for (const key of Object.keys(headers)) {396 const value = headers[key];397 if (!Object.is(value, undefined) && !(0, _utils.isString)(value)) throw new Error(`Expected value of header "${key}" to be String, but "${typeof value}" is found.`);398 }...
common.js
Source:common.js
1'use strict';2var _ = require('lodash');3var debug = require('debug')('nock.common');4var semver = require('semver')5/**6 * Normalizes the request options so that it always has `host` property.7 *8 * @param {Object} options - a parsed options object of the request9 */10var normalizeRequestOptions = function(options) {11 options.proto = options.proto || (options._https_ ? 'https': 'http');12 options.port = options.port || ((options.proto === 'http') ? 80 : 443);13 if (options.host) {14 debug('options.host:', options.host);15 if (! options.hostname) {16 if (options.host.split(':').length == 2) {17 options.hostname = options.host.split(':')[0];18 } else {19 options.hostname = options.host;20 }21 }22 }23 debug('options.hostname in the end: %j', options.hostname);24 options.host = (options.hostname || 'localhost') + ':' + options.port;25 debug('options.host in the end: %j', options.host);26 /// lowercase host names27 ['hostname', 'host'].forEach(function(attr) {28 if (options[attr]) {29 options[attr] = options[attr].toLowerCase();30 }31 });32 return options;33};34/**35 * Returns true if the data contained in buffer is binary which in this case means36 * that it cannot be reconstructed from its utf8 representation.37 *38 * @param {Object} buffer - a Buffer object39 */40var isBinaryBuffer = function(buffer) {41 if(!Buffer.isBuffer(buffer)) {42 return false;43 }44 // Test if the buffer can be reconstructed verbatim from its utf8 encoding.45 var utfEncodedBuffer = buffer.toString('utf8');46 var reconstructedBuffer = new Buffer(utfEncodedBuffer, 'utf8');47 var compareBuffers = function(lhs, rhs) {48 if(lhs.length !== rhs.length) {49 return false;50 }51 for(var i = 0; i < lhs.length; ++i) {52 if(lhs[i] !== rhs[i]) {53 return false;54 }55 }56 return true;57 };58 // If the buffers are *not* equal then this is a "binary buffer"59 // meaning that it cannot be faitfully represented in utf8.60 return !compareBuffers(buffer, reconstructedBuffer);61};62/**63 * If the chunks are Buffer objects then it returns a single Buffer object with the data from all the chunks.64 * If the chunks are strings then it returns a single string value with data from all the chunks.65 *66 * @param {Array} chunks - an array of Buffer objects or strings67 */68var mergeChunks = function(chunks) {69 if(_.isEmpty(chunks)) {70 return new Buffer(0);71 }72 // We assume that all chunks are Buffer objects if the first is buffer object.73 var areBuffers = Buffer.isBuffer(_.first(chunks));74 if(!areBuffers) {75 // When the chunks are not buffers we assume that they are strings.76 return chunks.join('');77 }78 // Merge all the buffers into a single Buffer object.79 return Buffer.concat(chunks);80};81// Array where all information about all the overridden requests are held.82var requestOverride = [];83/**84 * Overrides the current `request` function of `http` and `https` modules with85 * our own version which intercepts issues HTTP/HTTPS requests and forwards them86 * to the given `newRequest` function.87 *88 * @param {Function} newRequest - a function handling requests; it accepts four arguments:89 * - proto - a string with the overridden module's protocol name (either `http` or `https`)90 * - overriddenRequest - the overridden module's request function already bound to module's object91 * - options - the options of the issued request92 * - callback - the callback of the issued request93 */94var overrideRequests = function(newRequest) {95 debug('overriding requests');96 ['http', 'https'].forEach(function(proto) {97 debug('- overriding request for', proto);98 var moduleName = proto, // 1 to 1 match of protocol and module is fortunate :)99 module = {100 http: require('http'),101 https: require('https')102 }[moduleName],103 overriddenRequest = module.request,104 overriddenGet = module.get;105 if(requestOverride[moduleName]) {106 throw new Error('Module\'s request already overridden for ' + moduleName + ' protocol.');107 }108 // Store the properties of the overridden request so that it can be restored later on.109 requestOverride[moduleName] = {110 module: module,111 request: overriddenRequest,112 get: overriddenGet113 };114 module.request = function(options, callback) {115 // debug('request options:', options);116 return newRequest(proto, overriddenRequest.bind(module), options, callback);117 };118 if (semver.satisfies(process.version, '>=8')) {119 module.get = function(options, callback) {120 var req = newRequest(proto, overriddenRequest.bind(module), options, callback);121 req.end();122 return req;123 }124 }125 debug('- overridden request for', proto);126 });127};128/**129 * Restores `request` function of `http` and `https` modules to values they130 * held before they were overridden by us.131 */132var restoreOverriddenRequests = function() {133 debug('restoring requests');134 // Restore any overridden requests.135 _(requestOverride).keys().each(function(proto) {136 debug('- restoring request for', proto);137 var override = requestOverride[proto];138 if(override) {139 override.module.request = override.request;140 override.module.get = override.get;141 debug('- restored request for', proto);142 }143 });144 requestOverride = [];145};146/**147 * Get high level information about request as string148 * @param {Object} options149 * @param {string} options.method150 * @param {string} options.port151 * @param {string} options.proto152 * @param {string} options.hostname153 * @param {string} options.path154 * @param {Object} options.headers155 * @param {string|object} body156 * @return {string}157 */158function stringifyRequest(options, body) {159 var method = options.method || 'GET';160 var port = options.port;161 if (! port) port = (options.proto == 'https' ? '443' : '80');162 if (options.proto == 'https' && port == '443' ||163 options.proto == 'http' && port == '80') {164 port = '';165 }166 if (port) port = ':' + port;167 var path = options.path ? options.path : '';168 var log = {169 method: method,170 url: options.proto + '://' + options.hostname + port + path,171 headers: options.headers172 };173 if (body) {174 log.body = body;175 }176 return JSON.stringify(log, null, 2);177}178function isContentEncoded(headers) {179 var contentEncoding = _.get(headers, 'content-encoding');180 return _.isString(contentEncoding) && contentEncoding !== '';181}182function contentEncoding(headers, encoder) {183 var contentEncoding = _.get(headers, 'content-encoding');184 return contentEncoding === encoder;185}186function isJSONContent(headers) {187 var contentType = _.get(headers, 'content-type');188 if (Array.isArray(contentType)) {189 contentType = contentType[0];190 }191 contentType = (contentType || '').toLocaleLowerCase();192 return contentType === 'application/json';193}194var headersFieldNamesToLowerCase = function(headers) {195 if(!_.isObject(headers)) {196 return headers;197 }198 // For each key in the headers, delete its value and reinsert it with lower-case key.199 // Keys represent headers field names.200 var lowerCaseHeaders = {};201 _.forOwn(headers, function(fieldVal, fieldName) {202 var lowerCaseFieldName = fieldName.toLowerCase();203 if(!_.isUndefined(lowerCaseHeaders[lowerCaseFieldName])) {204 throw new Error('Failed to convert header keys to lower case due to field name conflict: ' + lowerCaseFieldName);205 }206 lowerCaseHeaders[lowerCaseFieldName] = fieldVal;207 });208 return lowerCaseHeaders;209};210var headersFieldsArrayToLowerCase = function (headers) {211 return _.uniq(_.map(headers, function (fieldName) {212 return fieldName.toLowerCase();213 }));214};215var headersArrayToObject = function (rawHeaders) {216 if(!_.isArray(rawHeaders)) {217 return rawHeaders;218 }219 var headers = {};220 for (var i=0, len=rawHeaders.length; i<len; i=i+2) {221 var key = rawHeaders[i];222 var value = rawHeaders[i+1];223 if (headers[key]) {224 headers[key] = _.isArray(headers[key]) ? headers[key] : [headers[key]];225 headers[key].push(value);226 } else {227 headers[key] = value;228 }229 }230 return headers;231};232/**233 * Deletes the given `fieldName` property from `headers` object by performing234 * case-insensitive search through keys.235 *236 * @headers {Object} headers - object of header field names and values237 * @fieldName {String} field name - string with the case-insensitive field name238 */239var deleteHeadersField = function(headers, fieldNameToDelete) {240 if(!_.isObject(headers) || !_.isString(fieldNameToDelete)) {241 return;242 }243 var lowerCaseFieldNameToDelete = fieldNameToDelete.toLowerCase();244 // Search through the headers and delete all values whose field name matches the given field name.245 _(headers).keys().each(function(fieldName) {246 var lowerCaseFieldName = fieldName.toLowerCase();247 if(lowerCaseFieldName === lowerCaseFieldNameToDelete) {248 delete headers[fieldName];249 // We don't stop here but continue in order to remove *all* matching field names250 // (even though if seen regorously there shouldn't be any)251 }252 });253};254function percentDecode (str) {255 try {256 return decodeURIComponent(str.replace(/\+/g, ' '));257 } catch (e) {258 return str;259 }260}261function percentEncode(str) {262 return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {263 return '%' + c.charCodeAt(0).toString(16).toUpperCase();264 });265}266function matchStringOrRegexp(target, pattern) {267 var str = (!_.isUndefined(target) && target.toString && target.toString()) || '';268 return pattern instanceof RegExp ? str.match(pattern) : str === String(pattern);269}270/**271 * Formats a query parameter.272 *273 * @param key The key of the query parameter to format.274 * @param value The value of the query parameter to format.275 * @param stringFormattingFn The function used to format string values. Can276 * be used to encode or decode the query value.277 *278 * @returns the formatted [key, value] pair.279 */280function formatQueryValue(key, value, stringFormattingFn) {281 switch (true) {282 case _.isNumber(value): // fall-through283 case _.isBoolean(value):284 value = value.toString();285 break;286 case _.isUndefined(value): // fall-through287 case _.isNull(value):288 value = '';289 break;290 case _.isString(value):291 if(stringFormattingFn) {292 value = stringFormattingFn(value);293 }294 break;295 case (value instanceof RegExp):296 break;297 case _.isArray(value):298 var tmpArray = new Array(value.length);299 for (var i = 0; i < value.length; ++i) {300 tmpArray[i] = formatQueryValue(i, value[i], stringFormattingFn)[1];301 }302 value = tmpArray;303 break;304 case _.isObject(value):305 var tmpObj = {};306 _.forOwn(value, function(subVal, subKey){307 var subPair = formatQueryValue(subKey, subVal, stringFormattingFn);308 tmpObj[subPair[0]] = subPair[1];309 });310 value = tmpObj;311 break;312 }313 if (stringFormattingFn) key = stringFormattingFn(key);314 return [key, value];315}316function isStream(obj) {317 return obj &&318 (typeof a !== 'string') &&319 (! Buffer.isBuffer(obj)) &&320 _.isFunction(obj.setEncoding);321}322exports.normalizeRequestOptions = normalizeRequestOptions;323exports.isBinaryBuffer = isBinaryBuffer;324exports.mergeChunks = mergeChunks;325exports.overrideRequests = overrideRequests;326exports.restoreOverriddenRequests = restoreOverriddenRequests;327exports.stringifyRequest = stringifyRequest;328exports.isContentEncoded = isContentEncoded;329exports.contentEncoding = contentEncoding;330exports.isJSONContent = isJSONContent;331exports.headersFieldNamesToLowerCase = headersFieldNamesToLowerCase;332exports.headersFieldsArrayToLowerCase = headersFieldsArrayToLowerCase;333exports.headersArrayToObject = headersArrayToObject;334exports.deleteHeadersField = deleteHeadersField;335exports.percentEncode = percentEncode;336exports.percentDecode = percentDecode;337exports.matchStringOrRegexp = matchStringOrRegexp;338exports.formatQueryValue = formatQueryValue;...
test_common.js
Source:test_common.js
...356 'foobar',357 'Expires',358 'fizbuzz',359 ]360 t.deepEqual(common.headersArrayToObject(headers), {361 'content-type': 'application/json; charset=utf-8',362 'last-modified': 'foobar',363 expires: 'fizbuzz',364 })365 const headersMultipleSetCookies = headers.concat([366 'Set-Cookie',367 'foo=bar; Domain=.github.com; Path=/',368 'Set-Cookie',369 'fiz=baz; Domain=.github.com; Path=/',370 'set-cookie',371 'foo=baz; Domain=.github.com; Path=/',372 ])373 t.deepEqual(common.headersArrayToObject(headersMultipleSetCookies), {374 'content-type': 'application/json; charset=utf-8',375 'last-modified': 'foobar',376 expires: 'fizbuzz',377 'set-cookie': [378 'foo=bar; Domain=.github.com; Path=/',379 'fiz=baz; Domain=.github.com; Path=/',380 'foo=baz; Domain=.github.com; Path=/',381 ],382 })383 t.throws(() => common.headersArrayToObject(123), {384 message: 'Expected a header array',385 })386 t.end()387})388test('percentEncode encodes extra reserved characters', t => {389 t.equal(common.percentEncode('foo+(*)!'), 'foo%2B%28%2A%29%21')390 t.done()391})392test('normalizeClientRequestArgs throws for invalid URL', async t => {393 // no schema394 t.throws(() => http.get('example.test'), {395 input: 'example.test',396 name: /TypeError/,397 })...
index.js
Source:index.js
...140 }141 }142 return result;143}144function headersArrayToObject(headers, lowerCase) {145 const result = {};146 for (const {147 name,148 value149 } of headers) result[lowerCase ? name.toLowerCase() : name] = value;150 return result;151}152function monotonicTime() {153 const [seconds, nanoseconds] = process.hrtime();154 return seconds * 1000 + (nanoseconds / 1000 | 0) / 1000;155}156function objectToArray(map) {157 if (!map) return undefined;158 const result = [];...
wkInterceptableRequest.js
Source:wkInterceptableRequest.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.WKRouteImpl = exports.WKInterceptableRequest = void 0;6var network = _interopRequireWildcard(require("../network"));7var _utils = require("../../utils/utils");8var _async = require("../../utils/async");9function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }10function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }11/**12 * Copyright 2017 Google Inc. All rights reserved.13 * Modifications copyright (c) Microsoft Corporation.14 *15 * Licensed under the Apache License, Version 2.0 (the "License");16 * you may not use this file except in compliance with the License.17 * You may obtain a copy of the License at18 *19 * http://www.apache.org/licenses/LICENSE-2.020 *21 * Unless required by applicable law or agreed to in writing, software22 * distributed under the License is distributed on an "AS IS" BASIS,23 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.24 * See the License for the specific language governing permissions and25 * limitations under the License.26 */27const errorReasons = {28 'aborted': 'Cancellation',29 'accessdenied': 'AccessControl',30 'addressunreachable': 'General',31 'blockedbyclient': 'Cancellation',32 'blockedbyresponse': 'General',33 'connectionaborted': 'General',34 'connectionclosed': 'General',35 'connectionfailed': 'General',36 'connectionrefused': 'General',37 'connectionreset': 'General',38 'internetdisconnected': 'General',39 'namenotresolved': 'General',40 'timedout': 'Timeout',41 'failed': 'General'42};43class WKInterceptableRequest {44 constructor(session, route, frame, event, redirectedFrom, documentId) {45 this._session = void 0;46 this.request = void 0;47 this._requestId = void 0;48 this._timestamp = void 0;49 this._wallTime = void 0;50 this._route = void 0;51 this._redirectedFrom = void 0;52 this._session = session;53 this._requestId = event.requestId;54 this._route = route;55 this._redirectedFrom = redirectedFrom;56 const resourceType = event.type ? event.type.toLowerCase() : redirectedFrom ? redirectedFrom.request.resourceType() : 'other';57 let postDataBuffer = null;58 this._timestamp = event.timestamp;59 this._wallTime = event.walltime * 1000;60 if (event.request.postData) postDataBuffer = Buffer.from(event.request.postData, 'base64');61 this.request = new network.Request(frame, (redirectedFrom === null || redirectedFrom === void 0 ? void 0 : redirectedFrom.request) || null, documentId, event.request.url, resourceType, event.request.method, postDataBuffer, (0, _utils.headersObjectToArray)(event.request.headers));62 }63 _routeForRedirectChain() {64 let request = this;65 while (request._redirectedFrom) request = request._redirectedFrom;66 return request._route;67 }68 createResponse(responsePayload) {69 const getResponseBody = async () => {70 const response = await this._session.send('Network.getResponseBody', {71 requestId: this._requestId72 });73 return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');74 };75 const timingPayload = responsePayload.timing;76 const timing = {77 startTime: this._wallTime,78 domainLookupStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.domainLookupStart) : -1,79 domainLookupEnd: timingPayload ? wkMillisToRoundishMillis(timingPayload.domainLookupEnd) : -1,80 connectStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.connectStart) : -1,81 secureConnectionStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.secureConnectionStart) : -1,82 connectEnd: timingPayload ? wkMillisToRoundishMillis(timingPayload.connectEnd) : -1,83 requestStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.requestStart) : -1,84 responseStart: timingPayload ? wkMillisToRoundishMillis(timingPayload.responseStart) : -185 };86 const setCookieSeparator = process.platform === 'darwin' ? ',' : '\n';87 return new network.Response(this.request, responsePayload.status, responsePayload.statusText, (0, _utils.headersObjectToArray)(responsePayload.headers, ',', setCookieSeparator), timing, getResponseBody);88 }89}90exports.WKInterceptableRequest = WKInterceptableRequest;91class WKRouteImpl {92 constructor(session, requestId) {93 this._session = void 0;94 this._requestId = void 0;95 this._requestInterceptedPromise = new _async.ManualPromise();96 this._session = session;97 this._requestId = requestId;98 }99 async abort(errorCode) {100 const errorType = errorReasons[errorCode];101 (0, _utils.assert)(errorType, 'Unknown error code: ' + errorCode);102 await this._requestInterceptedPromise; // In certain cases, protocol will return error if the request was already canceled103 // or the page was closed. We should tolerate these errors.104 await this._session.sendMayFail('Network.interceptRequestWithError', {105 requestId: this._requestId,106 errorType107 });108 }109 async fulfill(response) {110 if (300 <= response.status && response.status < 400) throw new Error('Cannot fulfill with redirect status: ' + response.status);111 await this._requestInterceptedPromise; // In certain cases, protocol will return error if the request was already canceled112 // or the page was closed. We should tolerate these errors.113 let mimeType = response.isBase64 ? 'application/octet-stream' : 'text/plain';114 const headers = (0, _utils.headersArrayToObject)(response.headers, true115 /* lowerCase */116 );117 const contentType = headers['content-type'];118 if (contentType) mimeType = contentType.split(';')[0].trim();119 await this._session.sendMayFail('Network.interceptRequestWithResponse', {120 requestId: this._requestId,121 status: response.status,122 statusText: network.STATUS_TEXTS[String(response.status)],123 mimeType,124 headers,125 base64Encoded: response.isBase64,126 content: response.body127 });128 }129 async continue(request, overrides) {130 await this._requestInterceptedPromise; // In certain cases, protocol will return error if the request was already canceled131 // or the page was closed. We should tolerate these errors.132 await this._session.sendMayFail('Network.interceptWithRequest', {133 requestId: this._requestId,134 url: overrides.url,135 method: overrides.method,136 headers: overrides.headers ? (0, _utils.headersArrayToObject)(overrides.headers, false137 /* lowerCase */138 ) : undefined,139 postData: overrides.postData ? Buffer.from(overrides.postData).toString('base64') : undefined140 });141 }142}143exports.WKRouteImpl = WKRouteImpl;144function wkMillisToRoundishMillis(value) {145 // WebKit uses -1000 for unavailable.146 if (value === -1000) return -1; // WebKit has a bug, instead of -1 it sends -1000 to be in ms.147 if (value <= 0) {148 // DNS can start before request start on Mac Network Stack149 return -1;150 }151 return (value * 1000 | 0) / 1000;...
utils.js
Source:utils.js
...110 result.push({ name, value: headers[name] })111 }112 return result113}114export function headersArrayToObject(headers, lowerCase) {115 const result = {}116 for (const { name, value } of headers)117 result[lowerCase ? name.toLowerCase() : name] = value118 return result119}120export function monotonicTime() {121 const [seconds, nanoseconds] = process.hrtime()122 return seconds * 1000 + ((nanoseconds / 1000) | 0) / 1000123}124export function calculateSha1(buffer) {125 const hash = crypto.createHash('sha1')126 hash.update(buffer)127 return hash.digest('hex')128}...
util.js
Source:util.js
...79 * @return {object[]}80 */81function ungzipFixtureDefinitionResponse (defs) {82 return defs.map(def => {83 const headers = headersArrayToObject(def.rawHeaders);84 if (headers['content-encoding'] !== 'gzip') return def;85 const rawHeaders = headersInputToRawArray({ ...headers, 'content-encoding': '' });86 const data = def.response.join ? def.response.join('') : def.response;87 const binary = Buffer.from(data, 'hex');88 const buffer = zlib.gunzipSync(binary);89 const response = headers['content-type'] === 'application/json'90 ? JSON.parse(buffer)91 : buffer.toString();92 return { ...def, response, rawHeaders };93 });94}95module.exports = {96 getCredentials,97 nockBack...
stubCassette.js
Source:stubCassette.js
...3const getCassette = require('./getCassette');4function stubCassette(cassetteName, times = 1) {5 const cassette = getCassette(cassetteName);6 const { scope, path, method, body, status, response, reqHeaders = {} } = cassette;7 const responseHeaders = headersArrayToObject(cassette.rawHeaders);8 stub(scope, path, method, reqHeaders, body, status, responseHeaders, response, times);9}...
Using AI Code Generation
1const { headersArrayToObject } = require('@playwright/test/lib/utils/utils');2];3const headersObject = headersArrayToObject(headers);4console.log(headersObject);5 ✓ should return headers object (2ms)6 1 passed (3ms)7[MIT](LICENSE)
Using AI Code Generation
1const { headersArrayToObject } = require('playwright/lib/utils/utils');2];3const headersObject = headersArrayToObject(headers);4const { headersObjectToArray } = require('playwright/lib/utils/utils');5const headers = {6};7const headersArray = headersObjectToArray(headers);8const { isString } = require('playwright/lib/utils/utils');9const value = 'test';10const isString = isString(value);11const { isNumber } = require('playwright/lib/utils/utils');12const value = 10;13const isNumber = isNumber(value);14const { isBoolean } = require('playwright/lib/utils/utils');15const value = true;16const isBoolean = isBoolean(value);17const { isRegExp } = require('playwright/lib/utils/utils');18const value = /test/;
Using AI Code Generation
1const { headersArrayToObject } = require('playwright/lib/utils/utils');2 'application/json; charset=utf-8',3];4const headersObject = headersArrayToObject(headers);5console.log(headersObject);6{7 'content-type': 'application/json; charset=utf-8',8}9[MIT](LICENSE)
Using AI Code Generation
1const { headersArrayToObject } = require('playwright-core/lib/utils/utils');2];3const headersObject = headersArrayToObject(headers);4console.log(headersObject);5const { headersObjectToArray } = require('playwright-core/lib/utils/utils');6const headersObject = {7};8const headers = headersObjectToArray(headersObject);9console.log(headers);10const { isString } = require('playwright-core/lib/utils/utils');11const string = 'Hello World';12const isStringResult = isString(string);13console.log(isStringResult);14const { isSafeCloseError } = require('playwright-core/lib/utils/utils');15const error = new Error('Connection closed');16const isSafeCloseErrorResult = isSafeCloseError(error);17console.log(isSafeCloseErrorResult);18const { isUnderTest } = require('playwright-core/lib/utils/utils');19const isUnderTestResult = isUnderTest();20console.log(isUnderTestResult);21const { isObject } = require('playwright-core/lib/utils/utils');22const object = { name: 'John', age: 30 };23const isObjectResult = isObject(object);24console.log(isObjectResult);25const { isNumber } = require('playwright-core/lib/utils/utils');26const number = 123;27const isNumberResult = isNumber(number);28console.log(isNumberResult);29const { isRegExp } = require('playwright
Using AI Code Generation
1const { headersArrayToObject } = require('@playwright/test/lib/utils/utils');2];3const headersObject = headersArrayToObject(headers);4console.log(headersObject);5const { headersObjectToArray } = require('@playwright/test/lib/utils/utils');6const headers = {7};8const headersArray = headersObjectToArray(headers);9console.log(headersArray);10const { isLocalIpAddress } = require('@playwright/test/lib/utils/utils');
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!