playwrightServer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var playwrightServer_exports = {};
  20. __export(playwrightServer_exports, {
  21. PlaywrightServer: () => PlaywrightServer
  22. });
  23. module.exports = __toCommonJS(playwrightServer_exports);
  24. var import_playwrightConnection = require("./playwrightConnection");
  25. var import_playwright = require("../server/playwright");
  26. var import_semaphore = require("../utils/isomorphic/semaphore");
  27. var import_time = require("../utils/isomorphic/time");
  28. var import_wsServer = require("../server/utils/wsServer");
  29. var import_ascii = require("../server/utils/ascii");
  30. var import_userAgent = require("../server/utils/userAgent");
  31. var import_utils = require("../utils");
  32. var import_socksProxy = require("../server/utils/socksProxy");
  33. var import_browser = require("../server/browser");
  34. var import_progress = require("../server/progress");
  35. class PlaywrightServer {
  36. constructor(options) {
  37. this._dontReuseBrowsers = /* @__PURE__ */ new Set();
  38. this._options = options;
  39. if (options.preLaunchedBrowser) {
  40. this._playwright = options.preLaunchedBrowser.attribution.playwright;
  41. this._dontReuse(options.preLaunchedBrowser);
  42. }
  43. if (options.preLaunchedAndroidDevice)
  44. this._playwright = options.preLaunchedAndroidDevice._android.attribution.playwright;
  45. this._playwright ??= (0, import_playwright.createPlaywright)({ sdkLanguage: "javascript", isServer: true });
  46. const browserSemaphore = new import_semaphore.Semaphore(this._options.maxConnections);
  47. const controllerSemaphore = new import_semaphore.Semaphore(1);
  48. const reuseBrowserSemaphore = new import_semaphore.Semaphore(1);
  49. this._wsServer = new import_wsServer.WSServer({
  50. onRequest: (request, response) => {
  51. if (request.method === "GET" && request.url === "/json") {
  52. response.setHeader("Content-Type", "application/json");
  53. response.end(JSON.stringify({
  54. wsEndpointPath: this._options.path
  55. }));
  56. return;
  57. }
  58. response.end("Running");
  59. },
  60. onUpgrade: (request, socket) => {
  61. const uaError = userAgentVersionMatchesErrorMessage(request.headers["user-agent"] || "");
  62. if (uaError)
  63. return { error: `HTTP/${request.httpVersion} 428 Precondition Required\r
  64. \r
  65. ${uaError}` };
  66. },
  67. onHeaders: (headers) => {
  68. if (process.env.PWTEST_SERVER_WS_HEADERS)
  69. headers.push(process.env.PWTEST_SERVER_WS_HEADERS);
  70. },
  71. onConnection: (request, url, ws, id) => {
  72. const browserHeader = request.headers["x-playwright-browser"];
  73. const browserName = url.searchParams.get("browser") || (Array.isArray(browserHeader) ? browserHeader[0] : browserHeader) || null;
  74. const proxyHeader = request.headers["x-playwright-proxy"];
  75. const proxyValue = url.searchParams.get("proxy") || (Array.isArray(proxyHeader) ? proxyHeader[0] : proxyHeader);
  76. const launchOptionsHeader = request.headers["x-playwright-launch-options"] || "";
  77. const launchOptionsHeaderValue = Array.isArray(launchOptionsHeader) ? launchOptionsHeader[0] : launchOptionsHeader;
  78. const launchOptionsParam = url.searchParams.get("launch-options");
  79. let launchOptions = { timeout: import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT };
  80. try {
  81. launchOptions = JSON.parse(launchOptionsParam || launchOptionsHeaderValue);
  82. if (!launchOptions.timeout)
  83. launchOptions.timeout = import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT;
  84. } catch (e) {
  85. }
  86. const isExtension = this._options.mode === "extension";
  87. const allowFSPaths = isExtension;
  88. launchOptions = filterLaunchOptions(launchOptions, allowFSPaths);
  89. if (url.searchParams.has("debug-controller")) {
  90. if (!(this._options.debugController || isExtension))
  91. throw new Error("Debug controller is not enabled");
  92. return new import_playwrightConnection.PlaywrightConnection(
  93. controllerSemaphore,
  94. ws,
  95. true,
  96. this._playwright,
  97. async () => {
  98. throw new Error("shouldnt be used");
  99. },
  100. id
  101. );
  102. }
  103. if (isExtension) {
  104. const connectFilter = url.searchParams.get("connect");
  105. if (connectFilter) {
  106. if (connectFilter !== "first")
  107. throw new Error(`Unknown connect filter: ${connectFilter}`);
  108. return new import_playwrightConnection.PlaywrightConnection(
  109. browserSemaphore,
  110. ws,
  111. false,
  112. this._playwright,
  113. () => this._initConnectMode(id, connectFilter, browserName, launchOptions),
  114. id
  115. );
  116. }
  117. return new import_playwrightConnection.PlaywrightConnection(
  118. reuseBrowserSemaphore,
  119. ws,
  120. false,
  121. this._playwright,
  122. () => this._initReuseBrowsersMode(browserName, launchOptions, id),
  123. id
  124. );
  125. }
  126. if (this._options.mode === "launchServer" || this._options.mode === "launchServerShared") {
  127. if (this._options.preLaunchedBrowser) {
  128. return new import_playwrightConnection.PlaywrightConnection(
  129. browserSemaphore,
  130. ws,
  131. false,
  132. this._playwright,
  133. () => this._initPreLaunchedBrowserMode(id),
  134. id
  135. );
  136. }
  137. return new import_playwrightConnection.PlaywrightConnection(
  138. browserSemaphore,
  139. ws,
  140. false,
  141. this._playwright,
  142. () => this._initPreLaunchedAndroidMode(id),
  143. id
  144. );
  145. }
  146. return new import_playwrightConnection.PlaywrightConnection(
  147. browserSemaphore,
  148. ws,
  149. false,
  150. this._playwright,
  151. () => this._initLaunchBrowserMode(browserName, proxyValue, launchOptions, id),
  152. id
  153. );
  154. }
  155. });
  156. }
  157. async _initReuseBrowsersMode(browserName, launchOptions, id) {
  158. import_utils.debugLogger.log("server", `[${id}] engaged reuse browsers mode for ${browserName}`);
  159. const requestedOptions = launchOptionsHash(launchOptions);
  160. let browser = this._playwright.allBrowsers().find((b) => {
  161. if (b.options.name !== browserName)
  162. return false;
  163. if (this._dontReuseBrowsers.has(b))
  164. return false;
  165. const existingOptions = launchOptionsHash({ ...b.options.originalLaunchOptions, timeout: import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT });
  166. return existingOptions === requestedOptions;
  167. });
  168. for (const b of this._playwright.allBrowsers()) {
  169. if (b === browser)
  170. continue;
  171. if (this._dontReuseBrowsers.has(b))
  172. continue;
  173. if (b.options.name === browserName && b.options.channel === launchOptions.channel)
  174. await b.close({ reason: "Connection terminated" });
  175. }
  176. if (!browser) {
  177. const browserType = this._playwright[browserName || "chromium"];
  178. const controller = new import_progress.ProgressController();
  179. browser = await controller.run((progress) => browserType.launch(progress, {
  180. ...launchOptions,
  181. headless: !!process.env.PW_DEBUG_CONTROLLER_HEADLESS
  182. }), launchOptions.timeout);
  183. }
  184. return {
  185. preLaunchedBrowser: browser,
  186. denyLaunch: true,
  187. dispose: async () => {
  188. for (const context of browser.contexts()) {
  189. if (!context.pages().length)
  190. await context.close({ reason: "Connection terminated" });
  191. }
  192. }
  193. };
  194. }
  195. async _initConnectMode(id, filter, browserName, launchOptions) {
  196. browserName ??= "chromium";
  197. import_utils.debugLogger.log("server", `[${id}] engaged connect mode`);
  198. let browser = this._playwright.allBrowsers().find((b) => b.options.name === browserName);
  199. if (!browser) {
  200. const browserType = this._playwright[browserName];
  201. const controller = new import_progress.ProgressController();
  202. browser = await controller.run((progress) => browserType.launch(progress, launchOptions), launchOptions.timeout);
  203. this._dontReuse(browser);
  204. }
  205. return {
  206. preLaunchedBrowser: browser,
  207. denyLaunch: true,
  208. sharedBrowser: true
  209. };
  210. }
  211. async _initPreLaunchedBrowserMode(id) {
  212. import_utils.debugLogger.log("server", `[${id}] engaged pre-launched (browser) mode`);
  213. const browser = this._options.preLaunchedBrowser;
  214. for (const b of this._playwright.allBrowsers()) {
  215. if (b !== browser)
  216. await b.close({ reason: "Connection terminated" });
  217. }
  218. return {
  219. preLaunchedBrowser: browser,
  220. socksProxy: this._options.preLaunchedSocksProxy,
  221. sharedBrowser: this._options.mode === "launchServerShared",
  222. denyLaunch: true
  223. };
  224. }
  225. async _initPreLaunchedAndroidMode(id) {
  226. import_utils.debugLogger.log("server", `[${id}] engaged pre-launched (Android) mode`);
  227. const androidDevice = this._options.preLaunchedAndroidDevice;
  228. return {
  229. preLaunchedAndroidDevice: androidDevice,
  230. denyLaunch: true
  231. };
  232. }
  233. async _initLaunchBrowserMode(browserName, proxyValue, launchOptions, id) {
  234. import_utils.debugLogger.log("server", `[${id}] engaged launch mode for "${browserName}"`);
  235. let socksProxy;
  236. if (proxyValue) {
  237. socksProxy = new import_socksProxy.SocksProxy();
  238. socksProxy.setPattern(proxyValue);
  239. launchOptions.socksProxyPort = await socksProxy.listen(0);
  240. import_utils.debugLogger.log("server", `[${id}] started socks proxy on port ${launchOptions.socksProxyPort}`);
  241. } else {
  242. launchOptions.socksProxyPort = void 0;
  243. }
  244. const browserType = this._playwright[browserName];
  245. const controller = new import_progress.ProgressController();
  246. const browser = await controller.run((progress) => browserType.launch(progress, launchOptions), launchOptions.timeout);
  247. this._dontReuseBrowsers.add(browser);
  248. return {
  249. preLaunchedBrowser: browser,
  250. socksProxy,
  251. denyLaunch: true,
  252. dispose: async () => {
  253. await browser.close({ reason: "Connection terminated" });
  254. socksProxy?.close();
  255. }
  256. };
  257. }
  258. _dontReuse(browser) {
  259. this._dontReuseBrowsers.add(browser);
  260. browser.on(import_browser.Browser.Events.Disconnected, () => {
  261. this._dontReuseBrowsers.delete(browser);
  262. });
  263. }
  264. async listen(port = 0, hostname) {
  265. return this._wsServer.listen(port, hostname, this._options.path);
  266. }
  267. async close() {
  268. await this._wsServer.close();
  269. }
  270. }
  271. function userAgentVersionMatchesErrorMessage(userAgent) {
  272. const match = userAgent.match(/^Playwright\/(\d+\.\d+\.\d+)/);
  273. if (!match) {
  274. return;
  275. }
  276. const received = match[1].split(".").slice(0, 2).join(".");
  277. const expected = (0, import_userAgent.getPlaywrightVersion)(true);
  278. if (received !== expected) {
  279. return (0, import_ascii.wrapInASCIIBox)([
  280. `Playwright version mismatch:`,
  281. ` - server version: v${expected}`,
  282. ` - client version: v${received}`,
  283. ``,
  284. `If you are using VSCode extension, restart VSCode.`,
  285. ``,
  286. `If you are connecting to a remote service,`,
  287. `keep your local Playwright version in sync`,
  288. `with the remote service version.`,
  289. ``,
  290. `<3 Playwright Team`
  291. ].join("\n"), 1);
  292. }
  293. }
  294. function launchOptionsHash(options) {
  295. const copy = { ...options };
  296. for (const k of Object.keys(copy)) {
  297. const key = k;
  298. if (copy[key] === defaultLaunchOptions[key])
  299. delete copy[key];
  300. }
  301. for (const key of optionsThatAllowBrowserReuse)
  302. delete copy[key];
  303. return JSON.stringify(copy);
  304. }
  305. function filterLaunchOptions(options, allowFSPaths) {
  306. return {
  307. channel: options.channel,
  308. args: options.args,
  309. ignoreAllDefaultArgs: options.ignoreAllDefaultArgs,
  310. ignoreDefaultArgs: options.ignoreDefaultArgs,
  311. timeout: options.timeout,
  312. headless: options.headless,
  313. proxy: options.proxy,
  314. chromiumSandbox: options.chromiumSandbox,
  315. firefoxUserPrefs: options.firefoxUserPrefs,
  316. slowMo: options.slowMo,
  317. executablePath: (0, import_utils.isUnderTest)() || allowFSPaths ? options.executablePath : void 0,
  318. downloadsPath: allowFSPaths ? options.downloadsPath : void 0
  319. };
  320. }
  321. const defaultLaunchOptions = {
  322. ignoreAllDefaultArgs: false,
  323. handleSIGINT: false,
  324. handleSIGTERM: false,
  325. handleSIGHUP: false,
  326. headless: true,
  327. devtools: false
  328. };
  329. const optionsThatAllowBrowserReuse = [
  330. "headless",
  331. "timeout",
  332. "tracesDir"
  333. ];
  334. // Annotate the CommonJS export names for ESM import in node:
  335. 0 && (module.exports = {
  336. PlaywrightServer
  337. });