@intuned/runtime-dev 0.1.0-test.11 → 0.1.0-test.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/.babelrc +0 -1
  2. package/dist/commands/api/run.js +156 -83
  3. package/dist/commands/api/run.ts +105 -0
  4. package/dist/commands/auth-sessions/load.js +20 -20
  5. package/dist/commands/auth-sessions/load.ts +30 -0
  6. package/dist/commands/auth-sessions/run-check.js +45 -39
  7. package/dist/commands/auth-sessions/run-check.ts +51 -0
  8. package/dist/commands/auth-sessions/run-create.js +84 -74
  9. package/dist/commands/auth-sessions/run-create.ts +91 -0
  10. package/dist/commands/browser/save-state.js +12 -7
  11. package/dist/commands/browser/save-state.ts +14 -0
  12. package/dist/commands/browser/start-browser.js +7 -4
  13. package/dist/commands/browser/start-browser.ts +11 -0
  14. package/dist/commands/build.js +97 -61
  15. package/dist/commands/build.ts +78 -0
  16. package/dist/commands/common/browserUtils.js +42 -31
  17. package/dist/commands/common/browserUtils.ts +45 -0
  18. package/dist/commands/common/getDefaultExportFromFile.js +11 -10
  19. package/dist/commands/common/getDefaultExportFromFile.ts +11 -0
  20. package/dist/commands/common/getFirstLineNumber.js +90 -83
  21. package/dist/commands/common/{getFirstLineNumber.test.js → getFirstLineNumber.test.ts} +2 -2
  22. package/dist/commands/common/getFirstLineNumber.ts +96 -0
  23. package/dist/commands/common/sendMessageToClient.js +4 -2
  24. package/dist/commands/common/sendMessageToClient.ts +3 -0
  25. package/dist/commands/common/utils/fileUtils.js +16 -16
  26. package/dist/commands/common/utils/fileUtils.ts +23 -0
  27. package/dist/commands/common/utils/settings.js +17 -19
  28. package/dist/commands/common/utils/settings.ts +22 -0
  29. package/dist/commands/common/utils/unixSocket.js +43 -36
  30. package/dist/commands/common/utils/unixSocket.ts +38 -0
  31. package/dist/commands/common/utils/webTemplate.js +25 -18
  32. package/dist/commands/common/utils/webTemplate.ts +22 -0
  33. package/dist/commands/interface/run.js +139 -133
  34. package/dist/commands/interface/run.ts +156 -0
  35. package/dist/commands/ts-check.js +45 -41
  36. package/dist/commands/ts-check.ts +50 -0
  37. package/dist/common/Logger/Logger/index.d.ts +1 -1
  38. package/dist/common/Logger/Logger/index.js +40 -46
  39. package/dist/common/Logger/Logger/index.ts +53 -0
  40. package/dist/common/Logger/Logger/types.js +1 -1
  41. package/dist/common/Logger/index.d.ts +1 -1
  42. package/dist/common/Logger/index.js +40 -46
  43. package/dist/common/Logger/index.ts +53 -0
  44. package/dist/common/Logger/types.js +1 -1
  45. package/dist/common/asyncLocalStorage/index.js +4 -4
  46. package/dist/common/asyncLocalStorage/index.ts +9 -0
  47. package/dist/common/cleanEnvironmentVariables.js +11 -9
  48. package/dist/common/cleanEnvironmentVariables.ts +10 -0
  49. package/dist/common/constants.js +1 -1
  50. package/dist/common/constants.ts +1 -0
  51. package/dist/common/contextStorageStateHelpers.js +36 -38
  52. package/dist/common/contextStorageStateHelpers.ts +43 -0
  53. package/dist/common/getPlaywrightConstructs.d.ts +1 -1
  54. package/dist/common/getPlaywrightConstructs.js +187 -157
  55. package/dist/common/getPlaywrightConstructs.ts +181 -0
  56. package/dist/common/jwtTokenManager.js +74 -61
  57. package/dist/common/jwtTokenManager.ts +71 -0
  58. package/dist/common/runApi/errors.d.ts +1 -1
  59. package/dist/common/runApi/errors.js +130 -121
  60. package/dist/common/runApi/errors.ts +154 -0
  61. package/dist/common/runApi/index.d.ts +4 -4
  62. package/dist/common/runApi/index.js +219 -233
  63. package/dist/common/runApi/index.ts +253 -0
  64. package/dist/common/runApi/types.d.ts +1 -1
  65. package/dist/common/runApi/types.js +55 -41
  66. package/dist/common/runApi/types.ts +43 -0
  67. package/dist/common/settingsSchema.js +9 -6
  68. package/dist/common/settingsSchema.ts +9 -0
  69. package/dist/common/telemetry.js +27 -16
  70. package/dist/common/telemetry.ts +23 -0
  71. package/dist/index.d.ts +4 -4
  72. package/dist/index.js +4 -4
  73. package/dist/index.ts +4 -0
  74. package/dist/runtime/RunError.d.ts +1 -1
  75. package/dist/runtime/RunError.js +10 -10
  76. package/dist/runtime/RunError.ts +12 -0
  77. package/dist/runtime/downloadDirectory.js +10 -10
  78. package/dist/runtime/downloadDirectory.ts +13 -0
  79. package/dist/runtime/enums.d.ts +1 -11
  80. package/dist/runtime/enums.js +12 -12
  81. package/dist/runtime/enums.ts +12 -0
  82. package/dist/runtime/{executionHelpers.test.js → executionHelpers.test.ts} +2 -2
  83. package/dist/runtime/export.d.ts +1 -202
  84. package/dist/runtime/extendPayload.d.ts +1 -1
  85. package/dist/runtime/extendPayload.js +13 -13
  86. package/dist/runtime/extendPayload.ts +15 -0
  87. package/dist/runtime/extendTimeout.js +19 -20
  88. package/dist/runtime/extendTimeout.ts +24 -0
  89. package/dist/runtime/index.d.ts +7 -7
  90. package/dist/runtime/index.js +6 -6
  91. package/dist/runtime/index.ts +6 -0
  92. package/dist/runtime/requestMoreInfo.js +14 -14
  93. package/dist/runtime/requestMoreInfo.ts +18 -0
  94. package/dist/runtime/runInfo.d.ts +1 -1
  95. package/dist/runtime/runInfo.js +12 -13
  96. package/dist/runtime/runInfo.ts +15 -0
  97. package/package.json +3 -2
  98. package/tsconfig.json +1 -1
  99. /package/dist/{runtime/enums.d.js → common/Logger/Logger/types.ts} +0 -0
  100. /package/dist/{runtime/export.d.js → common/Logger/types.ts} +0 -0
@@ -1,6 +1,6 @@
1
1
  import * as playwright from "@intuned/playwright-core";
2
2
  import { existsSync, mkdir, mkdtemp, rm, writeFile, readFile } from "fs-extra";
3
- import { setContextStorageState } from "./contextStorageStateHelpers";
3
+ import { setContextStorageState, } from "./contextStorageStateHelpers.js";
4
4
  import { join } from "path";
5
5
  import path from "path";
6
6
  import * as fs from "fs-extra";
@@ -8,174 +8,204 @@ import { getFullPathInProject } from "../commands/common/utils/fileUtils";
8
8
  import waitOn from "wait-on";
9
9
  import { getDownloadDirectoryPath } from "../runtime";
10
10
  async function createUserDirWithPreferences() {
11
- const playwrightTempDir = await mkdtemp("/tmp/pw-");
12
- const userDir = join(playwrightTempDir, "userdir");
13
- const defaultDir = join(userDir, "Default");
14
- await mkdir(defaultDir, {
15
- recursive: true
16
- });
17
- const preferences = {
18
- plugins: {
19
- always_open_pdf_externally: true
20
- }
21
- };
22
- await writeFile(join(defaultDir, "Preferences"), JSON.stringify(preferences));
23
- return userDir;
24
- }
25
- export async function getProductionPlaywrightConstructs({
26
- proxy,
27
- headless = true,
28
- storageState,
29
- downloadsPath
30
- }) {
31
- const extraArgs = ["--no-first-run", "--disable-sync", "--disable-translate", "--disable-features=TranslateUI", "--disable-features=NetworkService", "--lang=en"];
32
- if (headless) {
33
- extraArgs.push("--headless=new");
34
- }
35
- const executablePath = playwright.chromium.executablePath();
36
- const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
37
- const isChrome127There = existsSync(chromium127Path);
38
- const userAgent = `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${isChrome127There ? 127 : 125}.0.0.0 Safari/537.36`;
39
- const userDataDir = await createUserDirWithPreferences();
40
- const context = await playwright.chromium.launchPersistentContext(userDataDir, {
41
- headless,
42
- ignoreDefaultArgs: [...getChromiumLaunchArgsToIgnore(), "--headless"],
43
- proxy,
44
- executablePath: isChrome127There ? chromium127Path : executablePath,
45
- args: extraArgs,
46
- downloadsPath,
47
- userAgent
48
- });
49
- context.once("close", async () => {
50
- try {
51
- await rm(userDataDir, {
11
+ const playwrightTempDir = await mkdtemp("/tmp/pw-");
12
+ const userDir = join(playwrightTempDir, "userdir");
13
+ const defaultDir = join(userDir, "Default");
14
+ await mkdir(defaultDir, {
52
15
  recursive: true,
53
- force: true,
54
- retryDelay: 1000,
55
- maxRetries: 5
56
- });
57
- } catch (error) {
58
- console.error("Failed to remove user data dir", error);
59
- }
60
- });
61
- if (storageState) {
62
- await loadSessionToContext({
63
- context,
64
- session: storageState
65
16
  });
66
- }
67
- const assetsFile = path.join(__dirname, "./assets/browser_scripts.js");
68
- await context.addInitScript({
69
- path: assetsFile
70
- });
71
- let page = context.pages().at(0);
72
- if (page) {
73
- const scriptString = await readFile(assetsFile, "utf8");
74
- await page.evaluate(scriptString);
75
- } else {
76
- page = await context.newPage();
77
- }
78
- return {
79
- page,
80
- context
81
- };
17
+ const preferences = {
18
+ plugins: {
19
+ always_open_pdf_externally: true,
20
+ },
21
+ };
22
+ await writeFile(join(defaultDir, "Preferences"), JSON.stringify(preferences));
23
+ return userDir;
82
24
  }
83
- const getChromiumLaunchArgsToIgnore = () => ["--disable-field-trial-config", "--disable-background-networking", "--enable-features=NetworkService,NetworkServiceInProcess", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "--disable-back-forward-cache", "--disable-breakpad", "--disable-client-side-phishing-detection", "--disable-component-extensions-with-background-pages", "--disable-component-update", "--no-default-browser-check", "--disable-default-apps", "--disable-dev-shm-usage", "--disable-extensions", "--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,TranslateUI", "--allow-pre-commit-input", "--disable-hang-monitor", "--disable-ipc-flooding-protection", "--disable-prompt-on-repost", "--disable-renderer-backgrounding", "--force-color-profile=srgb", "--metrics-recording-only", "--no-first-run", "--enable-automation", "--password-store=basic", "--use-mock-keychain", "--no-service-autorun", "--export-tagged-pdf", "--enable-use-zoom-for-dsf=false"];
84
- export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
85
- if (mode == "playwright-standalone") {
86
- if (!cdpAddress) {
87
- throw new Error("cdpAddress is required");
25
+ export async function getProductionPlaywrightConstructs({ proxy, headless = true, storageState, downloadsPath, }) {
26
+ const extraArgs = [
27
+ "--no-first-run",
28
+ "--disable-sync",
29
+ "--disable-translate",
30
+ "--disable-features=TranslateUI",
31
+ "--disable-features=NetworkService",
32
+ "--lang=en",
33
+ ];
34
+ if (headless) {
35
+ extraArgs.push("--headless=new");
88
36
  }
89
- const {
90
- context
91
- } = await getRemotePlaywrightContext(cdpAddress);
92
- if (!context) {
93
- throw new Error("no context found");
37
+ const executablePath = playwright.chromium.executablePath();
38
+ // use chromium 127 instead of 125, this depends on the docker image playwright version.
39
+ const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
40
+ const isChrome127There = existsSync(chromium127Path);
41
+ const userAgent = `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${isChrome127There ? 127 : 125}.0.0.0 Safari/537.36`;
42
+ const userDataDir = await createUserDirWithPreferences();
43
+ const context = await playwright.chromium.launchPersistentContext(userDataDir, {
44
+ headless,
45
+ ignoreDefaultArgs: [...getChromiumLaunchArgsToIgnore(), "--headless"],
46
+ proxy,
47
+ executablePath: isChrome127There ? chromium127Path : executablePath,
48
+ args: extraArgs,
49
+ downloadsPath,
50
+ userAgent,
51
+ });
52
+ context.once("close", async () => {
53
+ try {
54
+ await rm(userDataDir, {
55
+ recursive: true,
56
+ force: true,
57
+ retryDelay: 1000,
58
+ maxRetries: 5,
59
+ });
60
+ }
61
+ catch (error) {
62
+ console.error("Failed to remove user data dir", error);
63
+ }
64
+ });
65
+ if (storageState) {
66
+ await loadSessionToContext({ context, session: storageState });
94
67
  }
95
- const assetsFile = path.join(__dirname, "./assets/browser_scripts.js");
68
+ const assetsFile = path.join(path.dirname(import.meta.url), "./assets/browser_scripts.js");
96
69
  await context.addInitScript({
97
- path: assetsFile
70
+ path: assetsFile,
98
71
  });
99
- const pages = await context.pages();
100
- let page = null;
101
- if (pages.length > 0) {
102
- page = pages[0];
103
- const scriptString = await fs.readFile(assetsFile, "utf8");
104
- await page.evaluate(scriptString);
105
- } else {
106
- page = await context.newPage();
72
+ let page = context.pages().at(0);
73
+ if (page) {
74
+ const scriptString = await readFile(assetsFile, "utf8");
75
+ await page.evaluate(scriptString);
107
76
  }
108
- if (authSession) {
109
- await loadSessionToContext({
110
- context,
111
- session: authSession
112
- });
77
+ else {
78
+ page = await context.newPage();
113
79
  }
114
80
  return {
115
- page,
116
- context
81
+ page,
82
+ context,
117
83
  };
118
- }
119
- const downloadsPath = getDownloadDirectoryPath();
120
- if (mode === "playwright" || mode === "playwright-headless") {
121
- const productionConstructs = await getProductionPlaywrightConstructs({
122
- headless: mode === "playwright-headless",
123
- downloadsPath
124
- });
125
- if (authSession) {
126
- await loadSessionToContext({
127
- context: productionConstructs.context,
128
- session: authSession
129
- });
84
+ }
85
+ const getChromiumLaunchArgsToIgnore = () => [
86
+ "--disable-field-trial-config",
87
+ "--disable-background-networking",
88
+ "--enable-features=NetworkService,NetworkServiceInProcess",
89
+ "--disable-background-timer-throttling",
90
+ "--disable-backgrounding-occluded-windows",
91
+ "--disable-back-forward-cache",
92
+ "--disable-breakpad",
93
+ "--disable-client-side-phishing-detection",
94
+ "--disable-component-extensions-with-background-pages",
95
+ "--disable-component-update",
96
+ "--no-default-browser-check",
97
+ "--disable-default-apps",
98
+ "--disable-dev-shm-usage",
99
+ "--disable-extensions",
100
+ "--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,TranslateUI",
101
+ "--allow-pre-commit-input",
102
+ "--disable-hang-monitor",
103
+ "--disable-ipc-flooding-protection",
104
+ "--disable-prompt-on-repost",
105
+ "--disable-renderer-backgrounding",
106
+ "--force-color-profile=srgb",
107
+ "--metrics-recording-only",
108
+ "--no-first-run",
109
+ "--enable-automation",
110
+ "--password-store=basic",
111
+ "--use-mock-keychain",
112
+ "--no-service-autorun",
113
+ "--export-tagged-pdf",
114
+ "--enable-use-zoom-for-dsf=false",
115
+ ];
116
+ export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
117
+ if (mode == "playwright-standalone") {
118
+ if (!cdpAddress) {
119
+ throw new Error("cdpAddress is required");
120
+ }
121
+ const { context } = await getRemotePlaywrightContext(cdpAddress);
122
+ if (!context) {
123
+ throw new Error("no context found");
124
+ }
125
+ const assetsFile = path.join(path.dirname(import.meta.url), "./assets/browser_scripts.js");
126
+ await context.addInitScript({
127
+ path: assetsFile,
128
+ });
129
+ const pages = await context.pages();
130
+ let page = null;
131
+ if (pages.length > 0) {
132
+ page = pages[0];
133
+ const scriptString = await fs.readFile(assetsFile, "utf8");
134
+ await page.evaluate(scriptString);
135
+ }
136
+ else {
137
+ page = await context.newPage();
138
+ }
139
+ if (authSession) {
140
+ await loadSessionToContext({ context, session: authSession });
141
+ }
142
+ return {
143
+ page,
144
+ context,
145
+ };
130
146
  }
131
- return {
132
- ...productionConstructs
133
- };
134
- }
135
- throw "invalid mode";
147
+ const downloadsPath = getDownloadDirectoryPath();
148
+ if (mode === "playwright" || mode === "playwright-headless") {
149
+ const productionConstructs = await getProductionPlaywrightConstructs({
150
+ headless: mode === "playwright-headless",
151
+ downloadsPath,
152
+ });
153
+ if (authSession) {
154
+ await loadSessionToContext({
155
+ context: productionConstructs.context,
156
+ session: authSession,
157
+ });
158
+ }
159
+ return {
160
+ ...productionConstructs,
161
+ };
162
+ }
163
+ throw "invalid mode";
136
164
  }
137
- export async function loadSessionToContext({
138
- context,
139
- session
140
- }) {
141
- let sessionToLoad;
142
- if (session.type === "state") {
143
- sessionToLoad = session.state;
144
- } else {
145
- const fullPath = getFullPathInProject(session.path);
146
- sessionToLoad = await fs.readJson(fullPath);
147
- }
148
- await setContextStorageState(context, sessionToLoad);
165
+ export async function loadSessionToContext({ context, session, }) {
166
+ let sessionToLoad;
167
+ if (session.type === "state") {
168
+ sessionToLoad = session.state;
169
+ }
170
+ else {
171
+ const fullPath = getFullPathInProject(session.path);
172
+ sessionToLoad = await fs.readJson(fullPath);
173
+ }
174
+ await setContextStorageState(context, sessionToLoad);
149
175
  }
150
176
  export async function getRemotePlaywrightContext(cdpAddress) {
151
- const playwright = await import("@intuned/playwright-core");
152
- let browser = null;
153
- if (!cdpAddress) {
154
- throw new Error("cdpAddress is required");
155
- }
156
- const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
157
- try {
158
- await waitOn({
159
- resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
160
- delay: 100,
161
- interval: 100,
162
- timeout: 5000,
163
- tcpTimeout: 1000,
164
- window: 1000
165
- });
166
- } catch (error) {
167
- console.error("Failed to connect to the browser");
168
- process.exit(128 + 9);
169
- }
170
- try {
171
- browser = await playwright.chromium.connectOverCDP(cdpAddress);
172
- } catch (e) {
173
- console.log(e);
174
- throw new Error("failed to connect to the browser");
175
- }
176
- const context = browser.contexts()[0];
177
- return {
178
- browser,
179
- context
180
- };
181
- }
177
+ const playwright = await import("@intuned/playwright-core");
178
+ let browser = null;
179
+ if (!cdpAddress) {
180
+ throw new Error("cdpAddress is required");
181
+ }
182
+ const cdpAddressWithoutProtocol = cdpAddress
183
+ .replace("http://", "")
184
+ .replace("https://", "")
185
+ .replace("localhost", "127.0.0.1");
186
+ try {
187
+ await waitOn({
188
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
189
+ delay: 100,
190
+ interval: 100,
191
+ timeout: 5000,
192
+ tcpTimeout: 1000,
193
+ window: 1000,
194
+ });
195
+ }
196
+ catch (error) {
197
+ console.error("Failed to connect to the browser");
198
+ // 128 is the exit code for SIGINT https://tldp.org/LDP/abs/html/exitcodes.html
199
+ // 9 is the SIGKILL signal
200
+ process.exit(128 + 9);
201
+ }
202
+ try {
203
+ browser = await playwright.chromium.connectOverCDP(cdpAddress);
204
+ }
205
+ catch (e) {
206
+ console.log(e);
207
+ throw new Error("failed to connect to the browser");
208
+ }
209
+ const context = browser.contexts()[0];
210
+ return { browser, context };
211
+ }
@@ -0,0 +1,181 @@
1
+ import * as playwright from "@intuned/playwright-core";
2
+ import { existsSync, mkdir, mkdtemp, rm, writeFile, readFile } from "fs-extra";
3
+ import { setContextStorageState } from "./contextStorageStateHelpers.js";
4
+ import { join } from "path";
5
+ import path from "path";
6
+ import * as fs from "fs-extra";
7
+ import { getFullPathInProject } from "../commands/common/utils/fileUtils";
8
+ import waitOn from "wait-on";
9
+ import { getDownloadDirectoryPath } from "../runtime";
10
+ async function createUserDirWithPreferences() {
11
+ const playwrightTempDir = await mkdtemp("/tmp/pw-");
12
+ const userDir = join(playwrightTempDir, "userdir");
13
+ const defaultDir = join(userDir, "Default");
14
+ await mkdir(defaultDir, {
15
+ recursive: true
16
+ });
17
+ const preferences = {
18
+ plugins: {
19
+ always_open_pdf_externally: true
20
+ }
21
+ };
22
+ await writeFile(join(defaultDir, "Preferences"), JSON.stringify(preferences));
23
+ return userDir;
24
+ }
25
+ export async function getProductionPlaywrightConstructs({
26
+ proxy,
27
+ headless = true,
28
+ storageState,
29
+ downloadsPath
30
+ }) {
31
+ const extraArgs = ["--no-first-run", "--disable-sync", "--disable-translate", "--disable-features=TranslateUI", "--disable-features=NetworkService", "--lang=en"];
32
+ if (headless) {
33
+ extraArgs.push("--headless=new");
34
+ }
35
+ const executablePath = playwright.chromium.executablePath();
36
+ const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
37
+ const isChrome127There = existsSync(chromium127Path);
38
+ const userAgent = `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${isChrome127There ? 127 : 125}.0.0.0 Safari/537.36`;
39
+ const userDataDir = await createUserDirWithPreferences();
40
+ const context = await playwright.chromium.launchPersistentContext(userDataDir, {
41
+ headless,
42
+ ignoreDefaultArgs: [...getChromiumLaunchArgsToIgnore(), "--headless"],
43
+ proxy,
44
+ executablePath: isChrome127There ? chromium127Path : executablePath,
45
+ args: extraArgs,
46
+ downloadsPath,
47
+ userAgent
48
+ });
49
+ context.once("close", async () => {
50
+ try {
51
+ await rm(userDataDir, {
52
+ recursive: true,
53
+ force: true,
54
+ retryDelay: 1000,
55
+ maxRetries: 5
56
+ });
57
+ } catch (error) {
58
+ console.error("Failed to remove user data dir", error);
59
+ }
60
+ });
61
+ if (storageState) {
62
+ await loadSessionToContext({
63
+ context,
64
+ session: storageState
65
+ });
66
+ }
67
+ const assetsFile = path.join(path.dirname(import.meta.url), "./assets/browser_scripts.js");
68
+ await context.addInitScript({
69
+ path: assetsFile
70
+ });
71
+ let page = context.pages().at(0);
72
+ if (page) {
73
+ const scriptString = await readFile(assetsFile, "utf8");
74
+ await page.evaluate(scriptString);
75
+ } else {
76
+ page = await context.newPage();
77
+ }
78
+ return {
79
+ page,
80
+ context
81
+ };
82
+ }
83
+ const getChromiumLaunchArgsToIgnore = () => ["--disable-field-trial-config", "--disable-background-networking", "--enable-features=NetworkService,NetworkServiceInProcess", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "--disable-back-forward-cache", "--disable-breakpad", "--disable-client-side-phishing-detection", "--disable-component-extensions-with-background-pages", "--disable-component-update", "--no-default-browser-check", "--disable-default-apps", "--disable-dev-shm-usage", "--disable-extensions", "--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,TranslateUI", "--allow-pre-commit-input", "--disable-hang-monitor", "--disable-ipc-flooding-protection", "--disable-prompt-on-repost", "--disable-renderer-backgrounding", "--force-color-profile=srgb", "--metrics-recording-only", "--no-first-run", "--enable-automation", "--password-store=basic", "--use-mock-keychain", "--no-service-autorun", "--export-tagged-pdf", "--enable-use-zoom-for-dsf=false"];
84
+ export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
85
+ if (mode == "playwright-standalone") {
86
+ if (!cdpAddress) {
87
+ throw new Error("cdpAddress is required");
88
+ }
89
+ const {
90
+ context
91
+ } = await getRemotePlaywrightContext(cdpAddress);
92
+ if (!context) {
93
+ throw new Error("no context found");
94
+ }
95
+ const assetsFile = path.join(path.dirname(import.meta.url), "./assets/browser_scripts.js");
96
+ await context.addInitScript({
97
+ path: assetsFile
98
+ });
99
+ const pages = await context.pages();
100
+ let page = null;
101
+ if (pages.length > 0) {
102
+ page = pages[0];
103
+ const scriptString = await fs.readFile(assetsFile, "utf8");
104
+ await page.evaluate(scriptString);
105
+ } else {
106
+ page = await context.newPage();
107
+ }
108
+ if (authSession) {
109
+ await loadSessionToContext({
110
+ context,
111
+ session: authSession
112
+ });
113
+ }
114
+ return {
115
+ page,
116
+ context
117
+ };
118
+ }
119
+ const downloadsPath = getDownloadDirectoryPath();
120
+ if (mode === "playwright" || mode === "playwright-headless") {
121
+ const productionConstructs = await getProductionPlaywrightConstructs({
122
+ headless: mode === "playwright-headless",
123
+ downloadsPath
124
+ });
125
+ if (authSession) {
126
+ await loadSessionToContext({
127
+ context: productionConstructs.context,
128
+ session: authSession
129
+ });
130
+ }
131
+ return {
132
+ ...productionConstructs
133
+ };
134
+ }
135
+ throw "invalid mode";
136
+ }
137
+ export async function loadSessionToContext({
138
+ context,
139
+ session
140
+ }) {
141
+ let sessionToLoad;
142
+ if (session.type === "state") {
143
+ sessionToLoad = session.state;
144
+ } else {
145
+ const fullPath = getFullPathInProject(session.path);
146
+ sessionToLoad = await fs.readJson(fullPath);
147
+ }
148
+ await setContextStorageState(context, sessionToLoad);
149
+ }
150
+ export async function getRemotePlaywrightContext(cdpAddress) {
151
+ const playwright = await import("@intuned/playwright-core");
152
+ let browser = null;
153
+ if (!cdpAddress) {
154
+ throw new Error("cdpAddress is required");
155
+ }
156
+ const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
157
+ try {
158
+ await waitOn({
159
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
160
+ delay: 100,
161
+ interval: 100,
162
+ timeout: 5000,
163
+ tcpTimeout: 1000,
164
+ window: 1000
165
+ });
166
+ } catch (error) {
167
+ console.error("Failed to connect to the browser");
168
+ process.exit(128 + 9);
169
+ }
170
+ try {
171
+ browser = await playwright.chromium.connectOverCDP(cdpAddress);
172
+ } catch (e) {
173
+ console.log(e);
174
+ throw new Error("failed to connect to the browser");
175
+ }
176
+ const context = browser.contexts()[0];
177
+ return {
178
+ browser,
179
+ context
180
+ };
181
+ }