Best JavaScript code snippet using playwright-internal
socksProxy.js
Source:socksProxy.js
1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.SocksProxyHandler = exports.SocksProxy = void 0;6var _dns = _interopRequireDefault(require("dns"));7var _events = _interopRequireDefault(require("events"));8var _net = _interopRequireDefault(require("net"));9var _util = _interopRequireDefault(require("util"));10var _debugLogger = require("./debugLogger");11var _netUtils = require("./netUtils");12var _utils = require("./utils");13function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }14/**15 * Copyright (c) Microsoft Corporation.16 *17 * Licensed under the Apache License, Version 2.0 (the "License");18 * you may not use this file except in compliance with the License.19 * You may obtain a copy of the License at20 *21 * http://www.apache.org/licenses/LICENSE-2.022 *23 * Unless required by applicable law or agreed to in writing, software24 * distributed under the License is distributed on an "AS IS" BASIS,25 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.26 * See the License for the specific language governing permissions and27 * limitations under the License.28 */29const dnsLookupAsync = _util.default.promisify(_dns.default.lookup); // https://tools.ietf.org/html/rfc192830var SocksAuth;31(function (SocksAuth) {32 SocksAuth[SocksAuth["NO_AUTHENTICATION_REQUIRED"] = 0] = "NO_AUTHENTICATION_REQUIRED";33 SocksAuth[SocksAuth["GSSAPI"] = 1] = "GSSAPI";34 SocksAuth[SocksAuth["USERNAME_PASSWORD"] = 2] = "USERNAME_PASSWORD";35 SocksAuth[SocksAuth["NO_ACCEPTABLE_METHODS"] = 255] = "NO_ACCEPTABLE_METHODS";36})(SocksAuth || (SocksAuth = {}));37var SocksAddressType;38(function (SocksAddressType) {39 SocksAddressType[SocksAddressType["IPv4"] = 1] = "IPv4";40 SocksAddressType[SocksAddressType["FqName"] = 3] = "FqName";41 SocksAddressType[SocksAddressType["IPv6"] = 4] = "IPv6";42})(SocksAddressType || (SocksAddressType = {}));43var SocksCommand;44(function (SocksCommand) {45 SocksCommand[SocksCommand["CONNECT"] = 1] = "CONNECT";46 SocksCommand[SocksCommand["BIND"] = 2] = "BIND";47 SocksCommand[SocksCommand["UDP_ASSOCIATE"] = 3] = "UDP_ASSOCIATE";48})(SocksCommand || (SocksCommand = {}));49var SocksReply;50(function (SocksReply) {51 SocksReply[SocksReply["Succeeded"] = 0] = "Succeeded";52 SocksReply[SocksReply["GeneralServerFailure"] = 1] = "GeneralServerFailure";53 SocksReply[SocksReply["NotAllowedByRuleSet"] = 2] = "NotAllowedByRuleSet";54 SocksReply[SocksReply["NetworkUnreachable"] = 3] = "NetworkUnreachable";55 SocksReply[SocksReply["HostUnreachable"] = 4] = "HostUnreachable";56 SocksReply[SocksReply["ConnectionRefused"] = 5] = "ConnectionRefused";57 SocksReply[SocksReply["TtlExpired"] = 6] = "TtlExpired";58 SocksReply[SocksReply["CommandNotSupported"] = 7] = "CommandNotSupported";59 SocksReply[SocksReply["AddressTypeNotSupported"] = 8] = "AddressTypeNotSupported";60})(SocksReply || (SocksReply = {}));61class SocksConnection {62 constructor(uid, socket, client) {63 this._buffer = Buffer.from([]);64 this._offset = 0;65 this._fence = 0;66 this._fenceCallback = void 0;67 this._socket = void 0;68 this._boundOnData = void 0;69 this._uid = void 0;70 this._client = void 0;71 this._uid = uid;72 this._socket = socket;73 this._client = client;74 this._boundOnData = this._onData.bind(this);75 socket.on('data', this._boundOnData);76 socket.on('close', () => this._onClose());77 socket.on('end', () => this._onClose());78 socket.on('error', () => this._onClose());79 this._run().catch(() => this._socket.end());80 }81 async _run() {82 (0, _utils.assert)(await this._authenticate());83 const {84 command,85 host,86 port87 } = await this._parseRequest();88 if (command !== SocksCommand.CONNECT) {89 this._writeBytes(Buffer.from([0x05, SocksReply.CommandNotSupported, 0x00, // RSV90 0x01, // IPv491 0x00, 0x00, 0x00, 0x00, // Address92 0x00, 0x00 // Port93 ]));94 return;95 }96 this._socket.off('data', this._boundOnData);97 this._client.onSocketRequested({98 uid: this._uid,99 host,100 port101 });102 }103 async _authenticate() {104 // Request:105 // +----+----------+----------+106 // |VER | NMETHODS | METHODS |107 // +----+----------+----------+108 // | 1 | 1 | 1 to 255 |109 // +----+----------+----------+110 // Response:111 // +----+--------+112 // |VER | METHOD |113 // +----+--------+114 // | 1 | 1 |115 // +----+--------+116 const version = await this._readByte();117 (0, _utils.assert)(version === 0x05, 'The VER field must be set to x05 for this version of the protocol, was ' + version);118 const nMethods = await this._readByte();119 (0, _utils.assert)(nMethods, 'No authentication methods specified');120 const methods = await this._readBytes(nMethods);121 for (const method of methods) {122 if (method === 0) {123 this._writeBytes(Buffer.from([version, method]));124 return true;125 }126 }127 this._writeBytes(Buffer.from([version, SocksAuth.NO_ACCEPTABLE_METHODS]));128 return false;129 }130 async _parseRequest() {131 // Request.132 // +----+-----+-------+------+----------+----------+133 // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |134 // +----+-----+-------+------+----------+----------+135 // | 1 | 1 | X'00' | 1 | Variable | 2 |136 // +----+-----+-------+------+----------+----------+137 // Response.138 // +----+-----+-------+------+----------+----------+139 // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |140 // +----+-----+-------+------+----------+----------+141 // | 1 | 1 | X'00' | 1 | Variable | 2 |142 // +----+-----+-------+------+----------+----------+143 const version = await this._readByte();144 (0, _utils.assert)(version === 0x05, 'The VER field must be set to x05 for this version of the protocol, was ' + version);145 const command = await this._readByte();146 await this._readByte(); // skip reserved.147 const addressType = await this._readByte();148 let host = '';149 switch (addressType) {150 case SocksAddressType.IPv4:151 host = (await this._readBytes(4)).join('.');152 break;153 case SocksAddressType.FqName:154 const length = await this._readByte();155 host = (await this._readBytes(length)).toString();156 break;157 case SocksAddressType.IPv6:158 const bytes = await this._readBytes(16);159 const tokens = [];160 for (let i = 0; i < 8; ++i) tokens.push(bytes.readUInt16BE(i * 2));161 host = tokens.join(':');162 break;163 }164 const port = (await this._readBytes(2)).readUInt16BE(0);165 this._buffer = Buffer.from([]);166 this._offset = 0;167 this._fence = 0;168 return {169 command,170 host,171 port172 };173 }174 async _readByte() {175 const buffer = await this._readBytes(1);176 return buffer[0];177 }178 async _readBytes(length) {179 this._fence = this._offset + length;180 if (!this._buffer || this._buffer.length < this._fence) await new Promise(f => this._fenceCallback = f);181 this._offset += length;182 return this._buffer.slice(this._offset - length, this._offset);183 }184 _writeBytes(buffer) {185 if (this._socket.writable) this._socket.write(buffer);186 }187 _onClose() {188 this._client.onSocketClosed({189 uid: this._uid190 });191 }192 _onData(buffer) {193 this._buffer = Buffer.concat([this._buffer, buffer]);194 if (this._fenceCallback && this._buffer.length >= this._fence) {195 const callback = this._fenceCallback;196 this._fenceCallback = undefined;197 callback();198 }199 }200 socketConnected(host, port) {201 this._writeBytes(Buffer.from([0x05, SocksReply.Succeeded, 0x00, // RSV202 0x01, // IPv4203 ...parseIP(host), // Address204 port << 8, port & 0xFF // Port205 ]));206 this._socket.on('data', data => this._client.onSocketData({207 uid: this._uid,208 data209 }));210 }211 socketFailed(errorCode) {212 const buffer = Buffer.from([0x05, 0, 0x00, // RSV213 0x01, // IPv4214 ...parseIP('0.0.0.0'), // Address215 0, 0 // Port216 ]);217 switch (errorCode) {218 case 'ENOENT':219 case 'ENOTFOUND':220 case 'ETIMEDOUT':221 case 'EHOSTUNREACH':222 buffer[1] = SocksReply.HostUnreachable;223 break;224 case 'ENETUNREACH':225 buffer[1] = SocksReply.NetworkUnreachable;226 break;227 case 'ECONNREFUSED':228 buffer[1] = SocksReply.ConnectionRefused;229 break;230 }231 this._writeBytes(buffer);232 this._socket.end();233 }234 sendData(data) {235 this._socket.write(data);236 }237 end() {238 this._socket.end();239 }240 error(error) {241 this._socket.destroy(new Error(error));242 }243}244function parseIP(address) {245 if (!_net.default.isIPv4(address)) throw new Error('IPv6 is not supported');246 return address.split('.', 4).map(t => +t);247}248class SocksProxy extends _events.default {249 constructor() {250 super();251 this._server = void 0;252 this._connections = new Map();253 this._server = new _net.default.Server(socket => {254 const uid = (0, _utils.createGuid)();255 const connection = new SocksConnection(uid, socket, this);256 this._connections.set(uid, connection);257 });258 }259 async listen(port) {260 return new Promise(f => {261 this._server.listen(port, () => {262 const port = this._server.address().port;263 _debugLogger.debugLogger.log('proxy', `Starting socks proxy server on port ${port}`);264 f(port);265 });266 });267 }268 async close() {269 await new Promise(f => this._server.close(f));270 }271 onSocketRequested(payload) {272 this.emit(SocksProxy.Events.SocksRequested, payload);273 }274 onSocketData(payload) {275 this.emit(SocksProxy.Events.SocksData, payload);276 }277 onSocketClosed(payload) {278 this.emit(SocksProxy.Events.SocksClosed, payload);279 }280 socketConnected({281 uid,282 host,283 port284 }) {285 var _this$_connections$ge;286 (_this$_connections$ge = this._connections.get(uid)) === null || _this$_connections$ge === void 0 ? void 0 : _this$_connections$ge.socketConnected(host, port);287 }288 socketFailed({289 uid,290 errorCode291 }) {292 var _this$_connections$ge2;293 (_this$_connections$ge2 = this._connections.get(uid)) === null || _this$_connections$ge2 === void 0 ? void 0 : _this$_connections$ge2.socketFailed(errorCode);294 }295 sendSocketData({296 uid,297 data298 }) {299 var _this$_connections$ge3;300 (_this$_connections$ge3 = this._connections.get(uid)) === null || _this$_connections$ge3 === void 0 ? void 0 : _this$_connections$ge3.sendData(data);301 }302 sendSocketEnd({303 uid304 }) {305 var _this$_connections$ge4;306 (_this$_connections$ge4 = this._connections.get(uid)) === null || _this$_connections$ge4 === void 0 ? void 0 : _this$_connections$ge4.end();307 }308 sendSocketError({309 uid,310 error311 }) {312 var _this$_connections$ge5;313 (_this$_connections$ge5 = this._connections.get(uid)) === null || _this$_connections$ge5 === void 0 ? void 0 : _this$_connections$ge5.error(error);314 }315}316exports.SocksProxy = SocksProxy;317SocksProxy.Events = {318 SocksRequested: 'socksRequested',319 SocksData: 'socksData',320 SocksClosed: 'socksClosed'321};322class SocksProxyHandler extends _events.default {323 constructor(redirectPortForTest) {324 super();325 this._sockets = new Map();326 this._redirectPortForTest = void 0;327 this._redirectPortForTest = redirectPortForTest;328 }329 cleanup() {330 for (const uid of this._sockets.keys()) this.socketClosed({331 uid332 });333 }334 async socketRequested({335 uid,336 host,337 port338 }) {339 if (host === 'local.playwright') host = 'localhost';340 try {341 if (this._redirectPortForTest) port = this._redirectPortForTest;342 const {343 address344 } = await dnsLookupAsync(host);345 const socket = await (0, _netUtils.createSocket)(address, port);346 socket.on('data', data => {347 const payload = {348 uid,349 data350 };351 this.emit(SocksProxyHandler.Events.SocksData, payload);352 });353 socket.on('error', error => {354 const payload = {355 uid,356 error: error.message357 };358 this.emit(SocksProxyHandler.Events.SocksError, payload);359 this._sockets.delete(uid);360 });361 socket.on('end', () => {362 const payload = {363 uid364 };365 this.emit(SocksProxyHandler.Events.SocksEnd, payload);366 this._sockets.delete(uid);367 });368 const localAddress = socket.localAddress;369 const localPort = socket.localPort;370 this._sockets.set(uid, socket);371 const payload = {372 uid,373 host: localAddress,374 port: localPort375 };376 this.emit(SocksProxyHandler.Events.SocksConnected, payload);377 } catch (error) {378 const payload = {379 uid,380 errorCode: error.code381 };382 this.emit(SocksProxyHandler.Events.SocksFailed, payload);383 }384 }385 sendSocketData({386 uid,387 data388 }) {389 var _this$_sockets$get;390 (_this$_sockets$get = this._sockets.get(uid)) === null || _this$_sockets$get === void 0 ? void 0 : _this$_sockets$get.write(data);391 }392 socketClosed({393 uid394 }) {395 var _this$_sockets$get2;396 (_this$_sockets$get2 = this._sockets.get(uid)) === null || _this$_sockets$get2 === void 0 ? void 0 : _this$_sockets$get2.destroy();397 this._sockets.delete(uid);398 }399}400exports.SocksProxyHandler = SocksProxyHandler;401SocksProxyHandler.Events = {402 SocksConnected: 'socksConnected',403 SocksData: 'socksData',404 SocksError: 'socksError',405 SocksFailed: 'socksFailed',406 SocksEnd: 'socksEnd'...
browserTypeDispatcher.js
Source:browserTypeDispatcher.js
...132 this._handler.on(socks.SocksProxyHandler.Events.SocksData, payload => this._channel.socksData({133 uid: payload.uid,134 data: payload.data.toString('base64')135 }));136 this._handler.on(socks.SocksProxyHandler.Events.SocksError, payload => this._channel.socksError(payload));137 this._handler.on(socks.SocksProxyHandler.Events.SocksFailed, payload => this._channel.socksFailed(payload));138 this._handler.on(socks.SocksProxyHandler.Events.SocksEnd, payload => this._channel.socksEnd(payload));139 this._channel.on('socksRequested', payload => this._handler.socketRequested(payload));140 this._channel.on('socksClosed', payload => this._handler.socketClosed(payload));141 this._channel.on('socksData', payload => this._handler.sendSocketData({142 uid: payload.uid,143 data: Buffer.from(payload.data, 'base64')144 }));145 }146 cleanup() {147 this._handler.cleanup();148 }149 interceptMessage(message) {150 if (this._ids.has(message.id)) {...
playwright.js
Source:playwright.js
...89 handler.on(socks.SocksProxyHandler.Events.SocksData, payload => socksSupport.socksData({90 uid: payload.uid,91 data: payload.data.toString('base64')92 }).catch(() => {}));93 handler.on(socks.SocksProxyHandler.Events.SocksError, payload => socksSupport.socksError(payload).catch(() => {}));94 handler.on(socks.SocksProxyHandler.Events.SocksFailed, payload => socksSupport.socksFailed(payload).catch(() => {}));95 handler.on(socks.SocksProxyHandler.Events.SocksEnd, payload => socksSupport.socksEnd(payload).catch(() => {}));96 socksSupport.on('socksRequested', payload => handler.socketRequested(payload));97 socksSupport.on('socksClosed', payload => handler.socketClosed(payload));98 socksSupport.on('socksData', payload => handler.sendSocketData({99 uid: payload.uid,100 data: Buffer.from(payload.data, 'base64')101 }));102 }103 static from(channel) {104 return channel._object;105 }106}107exports.Playwright = Playwright;
playwrightDispatcher.js
Source:playwrightDispatcher.js
...100 uid: params.uid,101 data: Buffer.from(params.data, 'base64')102 });103 }104 async socksError(params) {105 var _this$_socksProxy4;106 (_this$_socksProxy4 = this._socksProxy) === null || _this$_socksProxy4 === void 0 ? void 0 : _this$_socksProxy4.sendSocketError(params);107 }108 async socksEnd(params) {109 var _this$_socksProxy5;110 (_this$_socksProxy5 = this._socksProxy) === null || _this$_socksProxy5 === void 0 ? void 0 : _this$_socksProxy5.sendSocketEnd(params);111 }...
DispatchInterface.js
Source:DispatchInterface.js
1'use strict'2var SocksProxy, crypto, inspect, os, program, 3 splice = [].splice4os = require('os')5inspect = require('util')6crypto = require('crypto')7program = require('commander')8SocksProxy = require('../../lib/dispatch-proxy/lib/proxy/socks')9/*10 Wrapper for https://github.com/Morhaus/dispatch-proxy11*/12module.exports = class DispatchInterface {13 constructor() {14 const signals = os.constants.signals15 this.socksProxy = null16 this.running = false17 }18 getNetworkAdapters() {19 var address, addrs, family, i, interfaces, len, name, opts, results; 20 interfaces = os.networkInterfaces(); 21 results = []; 22 for (name in interfaces) {23 addrs = interfaces[name]; 24 let internal = false25 let adapter = {26 'name':name,27 'priority': 128 }29 for (i = 0, len = addrs.length; i < len && addrs; i ++) {30 ( {address, family, internal} = addrs[i]);31 adapter.address = address32 }33 if (!internal)34 results.push(adapter); 35 }36 return results; 37 }38 startSocks() {39 this.running = true40 const port = 108041 const host = 'localhost'42 const addresses = this.getNetworkAdapters()43 this.socksProxy = new SocksProxy(addresses, port, host)44 45 let ins = this46 this.socksProxy.on('request', function({serverConnection, clientConnection, host, port, localAddress}) {47 48 //stop service if it's not longer enabled49 if (ins.running !== true) {50 this.socksProxy.stop()51 this.socksProxy = null52 return53 }54 var id;55 id = (crypto.randomBytes(3)).toString('hex')56 console.log('request', `[${id}] <a>${host}</><b>:${port}</>`)57 console.log('dispatch', `[${id}] <a>${localAddress}</>`)58 serverConnection59 .on('connect', function() {60 return console.log('connect', `[${id}] <a>${host}</><b>:${port}</>`)61 })62 .on('error', function(err) {63 return console.log('error', `[${id}] serverConnection\n${escape(err.stack)}`)64 })65 .on('end', function() {66 return console.log('end', `[${id}] serverConnection`)67 })68 return clientConnection69 .on('error', function(err) {70 console.log('error', `[${id}] clientConnection\n${escape(err.stack)}`)71 return err72 })73 .on('end', function() {74 console.log('end', `[${id}] clientConnection`)75 return76 })77 })78 .on('error', function(err) {79 console.log('error', `server\n${escape(err.stack)}`)80 return 'error'81 })82 .on('socksError', function(err) {83 console.log('stackerror', `socks\n${escape(err.message)}`)84 return 'stackerror'85 })86 }87 stop() {88 this.running = false89 }...
Using AI Code Generation
1const socksError = require('playwright/internal/socks').socksError;2const socksAgent = require('playwright/internal/socks').socksAgent;3const socksConnection = require('playwright/internal/socks').socksConnection;4const socksSocket = require('playwright/internal/socks').socksSocket;5const socksSocket = require('playwright/internal/socks').socksSocket;6const socksSocket = require('playwright/internal/socks').socksSocket;7const socksSocket = require('playwright/internal/socks').socksSocket;8const socksSocket = require('playwright/internal/socks').socksSocket;9const socksSocket = require('playwright/internal/socks').socksSocket;10const socksSocket = require('playwright/internal/socks').socksSocket;11const socksSocket = require('playwright/internal/socks').socksSocket;12const socksSocket = require('playwright/internal/socks').socksSocket;13const socksSocket = require('playwright/internal/socks').socksSocket;14const socksSocket = require('playwright/internal/socks').socksSocket;15const socksSocket = require('playwright/internal/socks').socksSocket;16const socksSocket = require('playwright/internal/socks').socksSocket;17const socksSocket = require('playwright/internal/socks').socksSocket;
Using AI Code Generation
1const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');2const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');3const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');4const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');5const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');6const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');7const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');8const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');9const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');10const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');11const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');12const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');13const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');14const {socksError} = require('playwright/lib/server/supplements/recorder/recorderApp');
Using AI Code Generation
1const { socksError } = require('playwright/lib/utils/stackTrace');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({5 proxy: {6 },7 });8 const context = await browser.newContext();9 const page = await context.newPage();10 await browser.close();11})();12const { socksError } = require('playwright/lib/utils/stackTrace');13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch({16 proxy: {17 },18 });19 const context = await browser.newContext();20 const page = await context.newPage();21 await browser.close();22})();23const { socksError } = require('playwright/lib/utils/stackTrace');24const { chromium } = require('playwright');25(async () => {26 const browser = await chromium.launch({27 proxy: {28 },29 });30 const context = await browser.newContext();31 const page = await context.newPage();32 await browser.close();33})();34const { socksError } = require('playwright/lib/utils/stackTrace');35const { chromium } = require('playwright');36(async () => {37 const browser = await chromium.launch({38 proxy: {
Using AI Code Generation
1const socksError = require('@playwright/test/lib/utils/socksError');2const socksProxy = require('@playwright/test/lib/utils/socksProxy');3const socksProxyAgent = require('@playwright/test/lib/utils/socksProxyAgent');4const socksProxyServer = require('@playwright/test/lib/utils/socksProxyServer');5const socksSocket = require('@playwright/test/lib/utils/socksSocket');6const socksSocketServer = require('@playwright/test/lib/utils/socksSocketServer');7const socksError = require('@playwright/test/lib/utils/socksError');8const socksProxy = require('@playwright/test/lib/utils/socksProxy');9const socksProxyAgent = require('@playwright/test/lib/utils/socksProxyAgent');10const socksProxyServer = require('@playwright/test/lib/utils/socksProxyServer');11const socksSocket = require('@playwright/test/lib/utils/socksSocket');12const socksSocketServer = require('@playwright/test/lib/utils/socksSocketServer');13const socksError = require('@playwright/test/lib/utils/socksError');14const socksProxy = require('@playwright/test/lib/utils/socksProxy');15const socksProxyAgent = require('@playwright/test/lib/utils/socksProxyAgent');16const socksProxyServer = require('@playwright/test/lib/utils/socksProxyServer');17const socksSocket = require('@playwright/test
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!!