playwrightServer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 (isExtension) {
  90. const connectFilter = url.searchParams.get("connect");
  91. if (connectFilter) {
  92. if (connectFilter !== "first")
  93. throw new Error(`Unknown connect filter: ${connectFilter}`);
  94. return new import_playwrightConnection.PlaywrightConnection(
  95. browserSemaphore,
  96. ws,
  97. false,
  98. this._playwright,
  99. () => this._initConnectMode(id, connectFilter, browserName, launchOptions),
  100. id
  101. );
  102. }
  103. if (url.searchParams.has("debug-controller")) {
  104. return new import_playwrightConnection.PlaywrightConnection(
  105. controllerSemaphore,
  106. ws,
  107. true,
  108. this._playwright,
  109. async () => {
  110. throw new Error("shouldnt be used");
  111. },
  112. id
  113. );
  114. }
  115. return new import_playwrightConnection.PlaywrightConnection(
  116. reuseBrowserSemaphore,
  117. ws,
  118. false,
  119. this._playwright,
  120. () => this._initReuseBrowsersMode(browserName, launchOptions, id),
  121. id
  122. );
  123. }
  124. if (this._options.mode === "launchServer" || this._options.mode === "launchServerShared") {
  125. if (this._options.preLaunchedBrowser) {
  126. return new import_playwrightConnection.PlaywrightConnection(
  127. browserSemaphore,
  128. ws,
  129. false,
  130. this._playwright,
  131. () => this._initPreLaunchedBrowserMode(id),
  132. id
  133. );
  134. }
  135. return new import_playwrightConnection.PlaywrightConnection(
  136. browserSemaphore,
  137. ws,
  138. false,
  139. this._playwright,
  140. () => this._initPreLaunchedAndroidMode(id),
  141. id
  142. );
  143. }
  144. return new import_playwrightConnection.PlaywrightConnection(
  145. browserSemaphore,
  146. ws,
  147. false,
  148. this._playwright,
  149. () => this._initLaunchBrowserMode(browserName, proxyValue, launchOptions, id),
  150. id
  151. );
  152. }
  153. });
  154. }
  155. async _initReuseBrowsersMode(browserName, launchOptions, id) {
  156. import_utils.debugLogger.log("server", `[${id}] engaged reuse browsers mode for ${browserName}`);
  157. const requestedOptions = launchOptionsHash(launchOptions);
  158. let browser = this._playwright.allBrowsers().find((b) => {
  159. if (b.options.name !== browserName)
  160. return false;
  161. if (this._dontReuseBrowsers.has(b))
  162. return false;
  163. const existingOptions = launchOptionsHash({ ...b.options.originalLaunchOptions, timeout: import_time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT });
  164. return existingOptions === requestedOptions;
  165. });
  166. for (const b of this._playwright.allBrowsers()) {
  167. if (b === browser)
  168. continue;
  169. if (this._dontReuseBrowsers.has(b))
  170. continue;
  171. if (b.options.name === browserName && b.options.channel === launchOptions.channel)
  172. await b.close({ reason: "Connection terminated" });
  173. }
  174. if (!browser) {
  175. const browserType = this._playwright[browserName || "chromium"];
  176. const controller = new import_progress.ProgressController();
  177. browser = await controller.run((progress) => browserType.launch(progress, {
  178. ...launchOptions,
  179. headless: !!process.env.PW_DEBUG_CONTROLLER_HEADLESS
  180. }), launchOptions.timeout);
  181. }
  182. return {
  183. preLaunchedBrowser: browser,
  184. denyLaunch: true,
  185. dispose: async () => {
  186. for (const context of browser.contexts()) {
  187. if (!context.pages().length)
  188. await context.close({ reason: "Connection terminated" });
  189. }
  190. }
  191. };
  192. }
  193. async _initConnectMode(id, filter, browserName, launchOptions) {
  194. browserName ??= "chromium";
  195. import_utils.debugLogger.log("server", `[${id}] engaged connect mode`);
  196. let browser = this._playwright.allBrowsers().find((b) => b.options.name === browserName);
  197. if (!browser) {
  198. const browserType = this._playwright[browserName];
  199. const controller = new import_progress.ProgressController();
  200. browser = await controller.run((progress) => browserType.launch(progress, launchOptions), launchOptions.timeout);
  201. this._dontReuse(browser);
  202. }
  203. return {
  204. preLaunchedBrowser: browser,
  205. denyLaunch: true,
  206. sharedBrowser: true
  207. };
  208. }
  209. async _initPreLaunchedBrowserMode(id) {
  210. import_utils.debugLogger.log("server", `[${id}] engaged pre-launched (browser) mode`);
  211. const browser = this._options.preLaunchedBrowser;
  212. for (const b of this._playwright.allBrowsers()) {
  213. if (b !== browser)
  214. await b.close({ reason: "Connection terminated" });
  215. }
  216. return {
  217. preLaunchedBrowser: browser,
  218. socksProxy: this._options.preLaunchedSocksProxy,
  219. sharedBrowser: this._options.mode === "launchServerShared",
  220. denyLaunch: true
  221. };
  222. }
  223. async _initPreLaunchedAndroidMode(id) {
  224. import_utils.debugLogger.log("server", `[${id}] engaged pre-launched (Android) mode`);
  225. const androidDevice = this._options.preLaunchedAndroidDevice;
  226. return {
  227. preLaunchedAndroidDevice: androidDevice,
  228. denyLaunch: true
  229. };
  230. }
  231. async _initLaunchBrowserMode(browserName, proxyValue, launchOptions, id) {
  232. import_utils.debugLogger.log("server", `[${id}] engaged launch mode for "${browserName}"`);
  233. let socksProxy;
  234. if (proxyValue) {
  235. socksProxy = new import_socksProxy.SocksProxy();
  236. socksProxy.setPattern(proxyValue);
  237. launchOptions.socksProxyPort = await socksProxy.listen(0);
  238. import_utils.debugLogger.log("server", `[${id}] started socks proxy on port ${launchOptions.socksProxyPort}`);
  239. } else {
  240. launchOptions.socksProxyPort = void 0;
  241. }
  242. const browserType = this._playwright[browserName];
  243. const controller = new import_progress.ProgressController();
  244. const browser = await controller.run((progress) => browserType.launch(progress, launchOptions), launchOptions.timeout);
  245. this._dontReuseBrowsers.add(browser);
  246. return {
  247. preLaunchedBrowser: browser,
  248. socksProxy,
  249. denyLaunch: true,
  250. dispose: async () => {
  251. await browser.close({ reason: "Connection terminated" });
  252. socksProxy?.close();
  253. }
  254. };
  255. }
  256. _dontReuse(browser) {
  257. this._dontReuseBrowsers.add(browser);
  258. browser.on(import_browser.Browser.Events.Disconnected, () => {
  259. this._dontReuseBrowsers.delete(browser);
  260. });
  261. }
  262. async listen(port = 0, hostname) {
  263. return this._wsServer.listen(port, hostname, this._options.path);
  264. }
  265. async close() {
  266. await this._wsServer.close();
  267. }
  268. }
  269. function userAgentVersionMatchesErrorMessage(userAgent) {
  270. const match = userAgent.match(/^Playwright\/(\d+\.\d+\.\d+)/);
  271. if (!match) {
  272. return;
  273. }
  274. const received = match[1].split(".").slice(0, 2).join(".");
  275. const expected = (0, import_userAgent.getPlaywrightVersion)(true);
  276. if (received !== expected) {
  277. return (0, import_ascii.wrapInASCIIBox)([
  278. `Playwright version mismatch:`,
  279. ` - server version: v${expected}`,
  280. ` - client version: v${received}`,
  281. ``,
  282. `If you are using VSCode extension, restart VSCode.`,
  283. ``,
  284. `If you are connecting to a remote service,`,
  285. `keep your local Playwright version in sync`,
  286. `with the remote service version.`,
  287. ``,
  288. `<3 Playwright Team`
  289. ].join("\n"), 1);
  290. }
  291. }
  292. function launchOptionsHash(options) {
  293. const copy = { ...options };
  294. for (const k of Object.keys(copy)) {
  295. const key = k;
  296. if (copy[key] === defaultLaunchOptions[key])
  297. delete copy[key];
  298. }
  299. for (const key of optionsThatAllowBrowserReuse)
  300. delete copy[key];
  301. return JSON.stringify(copy);
  302. }
  303. function filterLaunchOptions(options, allowFSPaths) {
  304. return {
  305. channel: options.channel,
  306. args: options.args,
  307. ignoreAllDefaultArgs: options.ignoreAllDefaultArgs,
  308. ignoreDefaultArgs: options.ignoreDefaultArgs,
  309. timeout: options.timeout,
  310. headless: options.headless,
  311. proxy: options.proxy,
  312. chromiumSandbox: options.chromiumSandbox,
  313. firefoxUserPrefs: options.firefoxUserPrefs,
  314. slowMo: options.slowMo,
  315. executablePath: (0, import_utils.isUnderTest)() || allowFSPaths ? options.executablePath : void 0,
  316. downloadsPath: allowFSPaths ? options.downloadsPath : void 0
  317. };
  318. }
  319. const defaultLaunchOptions = {
  320. ignoreAllDefaultArgs: false,
  321. handleSIGINT: false,
  322. handleSIGTERM: false,
  323. handleSIGHUP: false,
  324. headless: true
  325. };
  326. const optionsThatAllowBrowserReuse = [
  327. "headless",
  328. "timeout",
  329. "tracesDir"
  330. ];
  331. // Annotate the CommonJS export names for ESM import in node:
  332. 0 && (module.exports = {
  333. PlaywrightServer
  334. });