@intuned/runtime-dev 1.3.1-api-token.6 → 1.3.4-dev.0

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 (43) hide show
  1. package/dist/commands/api/run.js +5 -3
  2. package/dist/commands/auth-sessions/load.js +3 -3
  3. package/dist/commands/auth-sessions/run-check.js +1 -2
  4. package/dist/commands/auth-sessions/run-create.js +12 -35
  5. package/dist/commands/interface/run.d.ts +1 -1
  6. package/dist/commands/interface/run.js +14 -40
  7. package/dist/commands/intuned-cli/controller/__test__/api.test.js +1 -2
  8. package/dist/commands/intuned-cli/controller/api.js +1 -2
  9. package/dist/commands/intuned-cli/controller/authSession.js +3 -4
  10. package/dist/commands/intuned-cli/controller/save.js +27 -28
  11. package/dist/commands/intuned-cli/helpers/errors.d.ts +2 -2
  12. package/dist/commands/intuned-cli/helpers/errors.js +8 -4
  13. package/dist/commands/intuned-cli/main.js +2 -2
  14. package/dist/common/asyncLocalStorage/index.d.ts +1 -0
  15. package/dist/common/constants.d.ts +1 -0
  16. package/dist/common/constants.js +2 -1
  17. package/dist/common/extensionsHelpers.d.ts +15 -0
  18. package/dist/common/extensionsHelpers.js +81 -0
  19. package/dist/common/playwrightContext.d.ts +54 -0
  20. package/dist/common/playwrightContext.js +274 -0
  21. package/dist/common/runApi/importUsingImportFunction.d.ts +9 -0
  22. package/dist/common/runApi/importUsingImportFunction.js +46 -0
  23. package/dist/common/runApi/index.d.ts +2 -7
  24. package/dist/common/runApi/index.js +92 -177
  25. package/dist/common/runApi/types.d.ts +1 -5
  26. package/dist/common/runApi/types.js +1 -2
  27. package/dist/common/settingsSchema.d.ts +513 -0
  28. package/dist/common/settingsSchema.js +40 -2
  29. package/dist/common/setupContextHook.d.ts +17 -0
  30. package/dist/common/setupContextHook.js +22 -0
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +13 -19
  33. package/dist/runtime/attemptStore.d.ts +2 -0
  34. package/dist/runtime/attemptStore.js +23 -0
  35. package/dist/runtime/export.d.ts +51 -41
  36. package/dist/runtime/index.d.ts +1 -2
  37. package/dist/runtime/index.js +7 -13
  38. package/package.json +3 -1
  39. package/WebTemplate.zip +0 -0
  40. package/dist/common/getPlaywrightConstructs.d.ts +0 -30
  41. package/dist/common/getPlaywrightConstructs.js +0 -188
  42. package/dist/runtime/requestMoreInfo.d.ts +0 -18
  43. package/dist/runtime/requestMoreInfo.js +0 -25
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.browserScriptsFile = void 0;
7
+ exports.getRemotePlaywrightContext = getRemotePlaywrightContext;
8
+ exports.launchChromium = launchChromium;
9
+ exports.loadSessionToContext = loadSessionToContext;
10
+ exports.withPlaywrightContext = withPlaywrightContext;
11
+ var playwright = _interopRequireWildcard(require("playwright"));
12
+ var _fsExtra = _interopRequireWildcard(require("fs-extra"));
13
+ var fs = _fsExtra;
14
+ var _contextStorageStateHelpers = require("./contextStorageStateHelpers");
15
+ var _path = _interopRequireWildcard(require("path"));
16
+ var _fileUtils = require("../commands/common/utils/fileUtils");
17
+ var _waitOn = _interopRequireDefault(require("wait-on"));
18
+ var _errors = require("./runApi/errors");
19
+ var _neverthrow = require("neverthrow");
20
+ var _setupContextHook = require("./setupContextHook");
21
+ var _portfinder = require("portfinder");
22
+ var _extensionsHelpers = require("./extensionsHelpers");
23
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
24
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
25
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
26
+ async function createUserDirWithPreferences() {
27
+ const playwrightTempDir = await (0, _fsExtra.mkdtemp)("/tmp/pw-");
28
+ const userDir = (0, _path.join)(playwrightTempDir, "userdir");
29
+ const defaultDir = (0, _path.join)(userDir, "Default");
30
+ await (0, _fsExtra.mkdir)(defaultDir, {
31
+ recursive: true
32
+ });
33
+ const preferences = {
34
+ plugins: {
35
+ always_open_pdf_externally: true
36
+ }
37
+ };
38
+ await (0, _fsExtra.writeFile)((0, _path.join)(defaultDir, "Preferences"), JSON.stringify(preferences));
39
+ return userDir;
40
+ }
41
+ async function launchChromium({
42
+ proxy,
43
+ headless = true,
44
+ downloadsPath,
45
+ cdpAddress,
46
+ cdpPort
47
+ }) {
48
+ if (cdpAddress) {
49
+ const browser = await playwright.chromium.connectOverCDP(cdpAddress);
50
+ if (browser.contexts().length === 0) {
51
+ throw new Error("No browser contexts found in the connected browser");
52
+ }
53
+ const context = browser.contexts()[0];
54
+ let page = context.pages().at(0);
55
+ if (!page) {
56
+ page = await context.newPage();
57
+ }
58
+ return {
59
+ page,
60
+ context
61
+ };
62
+ }
63
+ const defaultArgsToIgnore = ["--disable-extensions", "--disable-component-extensions-with-background-pages", "--disable-background-networking", "--disable-backgrounding-occluded-windows", "--disable-background-timer-throttling"];
64
+ const extraArgs = [];
65
+ const userDataDir = await createUserDirWithPreferences();
66
+ if ((0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
67
+ const extensionsList = (0, _extensionsHelpers.buildExtensionsList)();
68
+ const extensions = extensionsList.join(",");
69
+ extraArgs.push(`--disable-extensions-except=${extensions}`);
70
+ extraArgs.push(`--load-extension=${extensions}`);
71
+ await (0, _extensionsHelpers.setupIntunedExtension)();
72
+ }
73
+ if (cdpPort) {
74
+ extraArgs.push(`--remote-debugging-port=${cdpPort}`);
75
+ }
76
+ if (headless) {
77
+ defaultArgsToIgnore.push("--headless=old");
78
+ extraArgs.push("--headless=new");
79
+ }
80
+ const context = await playwright.chromium.launchPersistentContext(userDataDir, {
81
+ headless,
82
+ viewport: null,
83
+ proxy,
84
+ downloadsPath,
85
+ args: extraArgs,
86
+ ignoreDefaultArgs: defaultArgsToIgnore
87
+ });
88
+ context.once("close", async () => {
89
+ try {
90
+ await (0, _fsExtra.rm)(userDataDir, {
91
+ recursive: true,
92
+ force: true,
93
+ retryDelay: 1000,
94
+ maxRetries: 5
95
+ });
96
+ } catch (error) {
97
+ console.error("Failed to remove user data dir", error);
98
+ }
99
+ });
100
+ if ((0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
101
+ await (0, _extensionsHelpers.getIntunedExtensionWorker)(context);
102
+ }
103
+ if (cdpPort) {
104
+ const createdCdpAddress = getLocalCdpAddress(cdpPort);
105
+ await waitOnCdpAddress(createdCdpAddress);
106
+ }
107
+ const page = context.pages().at(0) ?? (await context.newPage());
108
+ return {
109
+ page,
110
+ context
111
+ };
112
+ }
113
+ const browserScriptsFile = exports.browserScriptsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
114
+ async function withPlaywrightContext({
115
+ cdpAddress,
116
+ proxy,
117
+ headless = true,
118
+ downloadsPath,
119
+ importFunction,
120
+ apiName,
121
+ apiParameters
122
+ }, fn) {
123
+ let context;
124
+ let page;
125
+ try {
126
+ const setupContextHookResult = importFunction ? await (0, _setupContextHook.loadSetupContextHook)({
127
+ importFunction
128
+ }) : (0, _neverthrow.ok)(null);
129
+ if (setupContextHookResult.isErr()) {
130
+ return setupContextHookResult;
131
+ }
132
+ const setupContextHook = setupContextHookResult.value;
133
+ if (setupContextHook === null) {
134
+ if (cdpAddress !== undefined) {
135
+ ({
136
+ page,
137
+ context
138
+ } = await launchChromium({
139
+ cdpAddress
140
+ }));
141
+ } else {
142
+ ({
143
+ page,
144
+ context
145
+ } = await launchChromium({
146
+ proxy,
147
+ headless,
148
+ downloadsPath
149
+ }));
150
+ }
151
+ return await fn(context, page);
152
+ }
153
+ let hookCdpUrl = null;
154
+ if (cdpAddress) {
155
+ hookCdpUrl = cdpAddress;
156
+ ({
157
+ context,
158
+ page
159
+ } = await launchChromium({
160
+ cdpAddress
161
+ }));
162
+ } else {
163
+ const port = await (0, _portfinder.getPort)({
164
+ port: 9222
165
+ });
166
+ hookCdpUrl = getLocalCdpAddress(port);
167
+ ({
168
+ context,
169
+ page
170
+ } = await launchChromium({
171
+ proxy,
172
+ headless,
173
+ downloadsPath,
174
+ cdpPort: port
175
+ }));
176
+ }
177
+ let hookResult;
178
+ try {
179
+ hookResult = await setupContextHook({
180
+ apiName: apiName,
181
+ apiParameters: apiParameters,
182
+ cdpUrl: hookCdpUrl
183
+ });
184
+ } catch (error) {
185
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
186
+ }
187
+ if (!hookResult) {
188
+ return await fn(context, page);
189
+ }
190
+ const {
191
+ page: newPage,
192
+ context: newContext,
193
+ cleanup
194
+ } = hookResult;
195
+ let result;
196
+ try {
197
+ result = {
198
+ return: await fn(newContext, newPage ?? page)
199
+ };
200
+ } catch (e) {
201
+ result = {
202
+ throw: e
203
+ };
204
+ }
205
+ try {
206
+ await cleanup?.();
207
+ } catch (e) {
208
+ result = {
209
+ return: (0, _neverthrow.err)(new _errors.AutomationError(e))
210
+ };
211
+ }
212
+ if ("throw" in result) {
213
+ throw result.throw;
214
+ }
215
+ return result.return;
216
+ } finally {
217
+ await context?.close();
218
+ }
219
+ }
220
+ async function loadSessionToContext({
221
+ context,
222
+ session
223
+ }) {
224
+ let sessionToLoad;
225
+ if (session.type === "state") {
226
+ const state = session.state;
227
+ if (state === undefined || state === null) {
228
+ return;
229
+ }
230
+ sessionToLoad = state;
231
+ } else {
232
+ const fullPath = (0, _fileUtils.getFullPathInProject)(session.path);
233
+ sessionToLoad = await fs.readJson(fullPath);
234
+ }
235
+ await (0, _contextStorageStateHelpers.setStorageState)(context, sessionToLoad);
236
+ }
237
+ function getLocalCdpAddress(port) {
238
+ return `http://localhost:${port}`;
239
+ }
240
+ async function waitOnCdpAddress(cdpAddress) {
241
+ const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
242
+ await (0, _waitOn.default)({
243
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
244
+ delay: 100,
245
+ interval: 100,
246
+ timeout: 5000,
247
+ tcpTimeout: 1000,
248
+ window: 1000
249
+ });
250
+ }
251
+ async function getRemotePlaywrightContext(cdpAddress) {
252
+ const playwright = await Promise.resolve().then(() => _interopRequireWildcard(require("playwright")));
253
+ let browser = null;
254
+ if (!cdpAddress) {
255
+ throw new Error("cdpAddress is required");
256
+ }
257
+ try {
258
+ await waitOnCdpAddress(cdpAddress);
259
+ } catch (error) {
260
+ console.error("Failed to connect to the browser");
261
+ process.exit(128 + 9);
262
+ }
263
+ try {
264
+ browser = await playwright.chromium.connectOverCDP(cdpAddress);
265
+ } catch (e) {
266
+ console.log(e);
267
+ throw new Error("failed to connect to the browser");
268
+ }
269
+ const context = browser.contexts()[0];
270
+ return {
271
+ browser,
272
+ context
273
+ };
274
+ }
@@ -0,0 +1,9 @@
1
+ import { Result } from "neverthrow";
2
+ import { RunAutomationError } from "./errors";
3
+ import { ExtendedRunApiParameters } from "./types";
4
+ export type ImportFunction = ExtendedRunApiParameters["importFunction"];
5
+ export declare function importUsingImportFunction<_ReturnType = any>({ path, allowGenerators, importFunction, }: {
6
+ path: string;
7
+ importFunction: ImportFunction;
8
+ allowGenerators?: boolean;
9
+ }): Promise<Result<(..._: any) => Promise<_ReturnType>, RunAutomationError>>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.importUsingImportFunction = importUsingImportFunction;
7
+ var _neverthrow = require("neverthrow");
8
+ var _errors = require("./errors");
9
+ async function importUsingImportFunction({
10
+ path,
11
+ allowGenerators = true,
12
+ importFunction
13
+ }) {
14
+ try {
15
+ const importedResult = await importFunction(path);
16
+ if (importedResult.isErr()) {
17
+ if (importedResult.error.type === "not_found") {
18
+ return (0, _neverthrow.err)(new _errors.ApiNotFoundError(path));
19
+ }
20
+ return (0, _neverthrow.err)(new _errors.AutomationError(importedResult.error.error));
21
+ }
22
+ const imported = importedResult.value;
23
+ if (!imported || !imported.default || !imported.default.constructor) {
24
+ return (0, _neverthrow.err)(new _errors.InvalidApiError(`${path} does not have a default export`));
25
+ }
26
+ if (imported.default.constructor.name === "AsyncGeneratorFunction") {
27
+ if (!allowGenerators) {
28
+ return (0, _neverthrow.err)(new _errors.InvalidApiError(`${path} default export must be an async function`));
29
+ }
30
+ return (0, _neverthrow.ok)(async (...args) => {
31
+ const generator = imported.default(...args);
32
+ const result = await generator.next();
33
+ if (!result.done) {
34
+ throw new Error("Yield is not supported");
35
+ }
36
+ return result.value;
37
+ });
38
+ }
39
+ if (imported.default.constructor.name === "AsyncFunction") {
40
+ return (0, _neverthrow.ok)(imported.default);
41
+ }
42
+ return (0, _neverthrow.err)(new _errors.InvalidApiError(`${path} default export must be an async function`));
43
+ } catch (error) {
44
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
45
+ }
46
+ }
@@ -4,13 +4,8 @@ import { Page, BrowserContext } from "playwright";
4
4
  import { ExtendedRunApiParameters, RunApiResult, RunApiResultWithSessionOk } from "./types";
5
5
  export * from "./types";
6
6
  export * from "./errors";
7
- export declare function runApiGenerator<ResultType = any, _YieldType = any, _NextType = any>(params: ExtendedRunApiParameters & {
8
- retrieveSession: true;
9
- }): AsyncGenerator<_YieldType, RunApiResult<ResultType, RunApiResultWithSessionOk>, _NextType>;
10
- export declare function runApiGenerator<ResultType = any, _YieldType = any, _NextType = any>(params: ExtendedRunApiParameters): AsyncGenerator<_YieldType, RunApiResult<ResultType>, _NextType>;
11
- export declare function runApi<ResultType = any>(params: ExtendedRunApiParameters & {
7
+ export declare function runApi<ResultType = any>(input: ExtendedRunApiParameters & {
12
8
  retrieveSession: true;
13
9
  }): Promise<RunApiResult<ResultType, RunApiResultWithSessionOk>>;
14
- export declare function runApi<ResultType = any>(params: ExtendedRunApiParameters): Promise<RunApiResult<ResultType>>;
10
+ export declare function runApi<ResultType = any>(input: ExtendedRunApiParameters): Promise<RunApiResult<ResultType>>;
15
11
  export declare function checkAuthSessionWithRetries(page: Page, context: BrowserContext, checkFn: (..._: any) => Promise<boolean>, retries?: number): Promise<Result<boolean, RunAutomationError>>;
16
- export type ImportFunction = ExtendedRunApiParameters["importFunction"];
@@ -4,13 +4,11 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  var _exportNames = {
7
- runApiGenerator: true,
8
7
  runApi: true,
9
8
  checkAuthSessionWithRetries: true
10
9
  };
11
10
  exports.checkAuthSessionWithRetries = checkAuthSessionWithRetries;
12
11
  exports.runApi = runApi;
13
- exports.runApiGenerator = runApiGenerator;
14
12
  var _downloadDirectory = require("../../runtime/downloadDirectory");
15
13
  var _asyncLocalStorage = require("../asyncLocalStorage");
16
14
  var _fsExtra = _interopRequireWildcard(require("fs-extra"));
@@ -30,7 +28,7 @@ Object.keys(_errors).forEach(function (key) {
30
28
  });
31
29
  });
32
30
  var _constants = require("../constants");
33
- var _getPlaywrightConstructs = require("../getPlaywrightConstructs");
31
+ var _playwrightContext = require("../playwrightContext");
34
32
  var _types = require("./types");
35
33
  Object.keys(_types).forEach(function (key) {
36
34
  if (key === "default" || key === "__esModule") return;
@@ -45,6 +43,7 @@ Object.keys(_types).forEach(function (key) {
45
43
  });
46
44
  var _formatZodError = require("../formatZodError");
47
45
  var _cleanEnvironmentVariables = require("../cleanEnvironmentVariables");
46
+ var _importUsingImportFunction = require("./importUsingImportFunction");
48
47
  function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
49
48
  function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
50
49
  function getObjectSizeInBytes(obj) {
@@ -54,10 +53,10 @@ function getObjectSizeInBytes(obj) {
54
53
  return new TextEncoder().encode(String(obj)).length;
55
54
  }
56
55
  }
57
- async function* runApiGenerator({
58
- retrieveSession = false,
56
+ async function runApi({
59
57
  abortSignal,
60
58
  importFunction,
59
+ retrieveSession = false,
61
60
  ...input
62
61
  }) {
63
62
  let traceStarted = false;
@@ -66,7 +65,10 @@ async function* runApiGenerator({
66
65
  return (0, _neverthrow.err)(new _errors.InternalInvalidInputError("Input validation failed", (0, _formatZodError.formatZodError)(inputParseResult.error)));
67
66
  }
68
67
  const {
69
- automationFunction,
68
+ automationFunction: {
69
+ name,
70
+ params
71
+ },
70
72
  runOptions,
71
73
  tracing,
72
74
  auth
@@ -78,166 +80,109 @@ async function* runApiGenerator({
78
80
  resolve(abortSymbol);
79
81
  });
80
82
  });
81
- let context;
82
- let downloadsPath;
83
- async function saveTraceIfNeeded({
84
- errorMessage
85
- }) {
86
- if (!tracing.enabled || !traceStarted) {
87
- return;
88
- }
89
- try {
90
- await context?.tracing.stop({
91
- path: tracing.filePath
92
- });
93
- } catch (error) {
94
- console.log(errorMessage, error?.message);
95
- await (0, _fsExtra.remove)(tracing.filePath);
96
- }
97
- }
98
- async function* runAutomation() {
99
- let page;
100
- const validatedModuleResult = await importUsingImportFunction(automationFunction.name, importFunction);
83
+ async function runAutomation() {
84
+ const validatedModuleResult = await (0, _importUsingImportFunction.importUsingImportFunction)({
85
+ path: name,
86
+ importFunction
87
+ });
101
88
  if (validatedModuleResult.isErr()) {
102
89
  return (0, _neverthrow.err)(validatedModuleResult.error);
103
90
  }
104
- const importedModule = validatedModuleResult.value;
105
- let checkFn;
106
- if (auth?.runCheck) {
107
- if (!auth.session) {
108
- return (0, _neverthrow.err)(new _errors.AuthRequiredError());
109
- }
110
- const checkImportResult = await importUsingImportFunction(`${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`, importFunction);
111
- if (checkImportResult.isErr()) {
112
- return (0, _neverthrow.err)(checkImportResult.error);
113
- }
114
- if (checkImportResult.value.type !== "async") {
115
- return (0, _neverthrow.err)(new _errors.InvalidCheckError("Check function is not an async function"));
116
- }
117
- checkFn = checkImportResult.value.func;
118
- }
91
+ const automationFunction = validatedModuleResult.value;
119
92
  if (auth && auth.session.type === "state") {
120
93
  const state = auth.session.state;
121
94
  if (state === undefined || state === null) {
122
95
  return (0, _neverthrow.err)(new _errors.AuthRequiredError());
123
96
  }
124
97
  }
125
- if (runOptions.environment === "standalone") {
126
- downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
127
- const {
128
- headless,
129
- proxy
130
- } = runOptions;
131
- ({
132
- page,
133
- context
134
- } = await (0, _getPlaywrightConstructs.getProductionPlaywrightConstructs)({
135
- headless,
136
- proxy,
137
- downloadsPath,
138
- storageState: auth?.session
139
- }));
140
- } else {
141
- const {
142
- mode,
143
- cdpAddress
144
- } = runOptions;
145
- ({
146
- page,
147
- context
148
- } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, cdpAddress, auth?.session));
149
- }
150
- if (tracing.enabled) {
151
- await context.tracing.start({
152
- screenshots: true,
153
- snapshots: true,
154
- sources: true
98
+ const playwrightContextParameters = {
99
+ apiName: name,
100
+ apiParameters: params,
101
+ importFunction
102
+ };
103
+ const runAutomationWithContext = async (context, page) => {
104
+ async function saveTraceIfNeeded({
105
+ errorMessage
106
+ }) {
107
+ if (!tracing.enabled || !traceStarted) {
108
+ return;
109
+ }
110
+ try {
111
+ await context?.tracing.stop({
112
+ path: tracing.filePath
113
+ });
114
+ } catch (error) {
115
+ console.log(errorMessage, error?.message);
116
+ await (0, _fsExtra.remove)(tracing.filePath);
117
+ }
118
+ }
119
+ if (auth) {
120
+ await (0, _playwrightContext.loadSessionToContext)({
121
+ context,
122
+ session: auth.session
123
+ });
124
+ }
125
+ const scriptContent = await fs.readFile(_playwrightContext.browserScriptsFile, "utf-8");
126
+ await context.addInitScript({
127
+ content: scriptContent
155
128
  });
156
- traceStarted = true;
157
- }
158
- (0, _cleanEnvironmentVariables.cleanEnvironmentVariables)();
159
- if (checkFn !== undefined) {
129
+ for (const page of context.pages()) {
130
+ await page.evaluate(scriptContent);
131
+ }
132
+ if (tracing.enabled) {
133
+ await context.tracing.start({
134
+ screenshots: true,
135
+ snapshots: true,
136
+ sources: true
137
+ });
138
+ traceStarted = true;
139
+ }
140
+ (0, _cleanEnvironmentVariables.cleanEnvironmentVariables)();
141
+ const automationFunctionParameters = [...(params !== undefined ? [params] : []), page, context];
160
142
  try {
161
- console.log("Running auth check");
162
- const authCheckResult = await checkAuthSessionWithRetries(page, context, checkFn, 2);
163
- if (authCheckResult.isErr()) {
164
- const error = authCheckResult.error;
165
- if (["APINotFoundError", "InvalidAPIError"].includes(error.code)) {
166
- return (0, _neverthrow.err)(new _errors.InvalidCheckError(`Auth session check function failed`, error));
167
- }
168
- return authCheckResult;
169
- }
170
- if (!authCheckResult.value) {
171
- return (0, _neverthrow.err)(new _errors.AuthCheckFailedError());
143
+ const automationFunctionResult = await automationFunction(...automationFunctionParameters);
144
+ const MAX_RESULT_SIZE_BYTES = 2 * 1024 * 1024;
145
+ const resultSizeInBytes = getObjectSizeInBytes(automationFunctionResult);
146
+ if (resultSizeInBytes > MAX_RESULT_SIZE_BYTES) {
147
+ return (0, _neverthrow.err)(new _errors.ResultTooBigError(resultSizeInBytes, MAX_RESULT_SIZE_BYTES));
172
148
  }
149
+ return (0, _neverthrow.ok)({
150
+ result: automationFunctionResult,
151
+ extendedPayloads: (0, _asyncLocalStorage.getExecutionContext)()?.extendedPayloads,
152
+ session: retrieveSession ? await (0, _contextStorageStateHelpers.getStorageState)(context) : undefined
153
+ });
173
154
  } catch (error) {
174
- return (0, _neverthrow.err)(new _errors.AuthCheckFailedError());
155
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
156
+ } finally {
157
+ await saveTraceIfNeeded({
158
+ errorMessage: "failed to save trace"
159
+ });
175
160
  }
176
- }
177
- const automationFunctionParameters = [...(automationFunction.params !== undefined ? [automationFunction.params] : []), page, context];
178
- let result;
179
- if (importedModule.type === "async-generator") {
180
- const generator = importedModule.generator(...automationFunctionParameters);
181
- let next = undefined;
182
- while (true) {
183
- const generatorResult = await generator.next(...(next ? [next] : []));
184
- if (!generatorResult.done) {
185
- next = yield generatorResult.value;
186
- continue;
187
- }
188
- result = generatorResult.value;
189
- break;
161
+ };
162
+ if (runOptions.environment === "standalone") {
163
+ const downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
164
+ try {
165
+ return await (0, _playwrightContext.withPlaywrightContext)({
166
+ headless: runOptions.headless,
167
+ proxy: runOptions.proxy,
168
+ downloadsPath,
169
+ ...playwrightContextParameters
170
+ }, runAutomationWithContext);
171
+ } finally {
172
+ await fs.remove(downloadsPath);
190
173
  }
191
174
  } else {
192
- result = await importedModule.func(...automationFunctionParameters);
175
+ return await (0, _playwrightContext.withPlaywrightContext)({
176
+ cdpAddress: runOptions.cdpAddress,
177
+ ...playwrightContextParameters
178
+ }, runAutomationWithContext);
193
179
  }
194
- const MAX_RESULT_SIZE_BYTES = 2 * 1024 * 1024;
195
- const resultSizeInBytes = getObjectSizeInBytes(result);
196
- if (resultSizeInBytes > MAX_RESULT_SIZE_BYTES) {
197
- return (0, _neverthrow.err)(new _errors.ResultTooBigError(resultSizeInBytes, MAX_RESULT_SIZE_BYTES));
198
- }
199
- return (0, _neverthrow.ok)({
200
- result,
201
- extendedPayloads: (0, _asyncLocalStorage.getExecutionContext)()?.extendedPayloads,
202
- session: retrieveSession ? await (0, _contextStorageStateHelpers.getStorageState)(context) : undefined
203
- });
204
180
  }
205
- try {
206
- const generator = runAutomation();
207
- let next = undefined;
208
- while (true) {
209
- const result = await Promise.race([generator.next(await next), abortPromise]);
210
- if (result === abortSymbol) {
211
- return (0, _neverthrow.err)(new _errors.AbortedError());
212
- }
213
- if (!result.done) {
214
- next = yield result.value;
215
- continue;
216
- }
217
- return result.value;
218
- }
219
- } catch (error) {
220
- return (0, _neverthrow.err)(new _errors.AutomationError(error));
221
- } finally {
222
- await saveTraceIfNeeded({
223
- errorMessage: "failed to save trace"
224
- });
225
- await context?.close();
226
- if (downloadsPath !== undefined) {
227
- await fs.remove(downloadsPath);
228
- }
181
+ const result = await Promise.race([await runAutomation(), abortPromise]);
182
+ if (result === abortSymbol) {
183
+ return (0, _neverthrow.err)(new _errors.AbortedError());
229
184
  }
230
- }
231
- async function runApi(params) {
232
- const generator = runApiGenerator(params);
233
- const {
234
- value,
235
- done
236
- } = await generator.next();
237
- if (done) {
238
- return value;
239
- }
240
- return (0, _neverthrow.err)(new _errors.InvalidApiError("Expected API to be async function, got async generator"));
185
+ return result;
241
186
  }
242
187
  async function checkAuthSessionWithRetries(page, context, checkFn, retries = 3) {
243
188
  if (retries === 0) {
@@ -251,34 +196,4 @@ async function checkAuthSessionWithRetries(page, context, checkFn, retries = 3)
251
196
  tryNumber++;
252
197
  }
253
198
  return (0, _neverthrow.ok)(false);
254
- }
255
- async function importUsingImportFunction(path, importFunction) {
256
- try {
257
- const importedResult = await importFunction(path);
258
- if (importedResult.isErr()) {
259
- if (importedResult.error.type === "not_found") {
260
- return (0, _neverthrow.err)(new _errors.ApiNotFoundError(path));
261
- }
262
- return (0, _neverthrow.err)(new _errors.AutomationError(importedResult.error.error));
263
- }
264
- const imported = importedResult.value;
265
- if (!imported || !imported.default || !imported.default.constructor) {
266
- return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default export"));
267
- }
268
- if (imported.default.constructor.name === "AsyncGeneratorFunction") {
269
- return (0, _neverthrow.ok)({
270
- type: "async-generator",
271
- generator: imported.default
272
- });
273
- }
274
- if (imported.default.constructor.name === "AsyncFunction") {
275
- return (0, _neverthrow.ok)({
276
- type: "async",
277
- func: imported.default
278
- });
279
- }
280
- return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default async function/generator export"));
281
- } catch (error) {
282
- return (0, _neverthrow.err)(new _errors.AutomationError(error));
283
- }
284
199
  }