@intuned/runtime-dev 0.0.1-testing.0 → 0.1.0-test.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 (50) hide show
  1. package/InterfaceTemplate/index.ts +1 -0
  2. package/Intuned.json +5 -0
  3. package/WebTemplate/api.ts +92 -90
  4. package/WebTemplate/controllers/authSessions/check.ts +23 -29
  5. package/WebTemplate/controllers/authSessions/create.ts +46 -71
  6. package/WebTemplate/controllers/authSessions/index.ts +4 -4
  7. package/WebTemplate/controllers/authSessions/killOperation.ts +1 -1
  8. package/WebTemplate/controllers/authSessions/resumeOperation.ts +28 -52
  9. package/WebTemplate/controllers/authSessions/store.ts +11 -6
  10. package/WebTemplate/controllers/runApi/helpers.ts +47 -144
  11. package/WebTemplate/index.playwright.ts +42 -32
  12. package/WebTemplate/index.vanilla.ts +2 -20
  13. package/WebTemplate/jobs.ts +2 -13
  14. package/WebTemplate/utils.ts +1 -85
  15. package/WebTemplate.zip +0 -0
  16. package/api/authed.ts +12 -0
  17. package/api/test.ts +3 -0
  18. package/api/test2.ts +25 -0
  19. package/auth-sessions/check.ts +9 -0
  20. package/auth-sessions/create.ts +32 -0
  21. package/authSessions +1 -0
  22. package/dist/commands/api/run.d.ts +1 -1
  23. package/dist/commands/api/run.js +28 -50
  24. package/dist/commands/auth-sessions/load.js +7 -1
  25. package/dist/commands/auth-sessions/run-check.js +23 -9
  26. package/dist/commands/auth-sessions/run-create.js +51 -30
  27. package/dist/commands/build.js +5 -2
  28. package/dist/commands/common/utils/settings.js +5 -5
  29. package/dist/commands/common/utils/unixSocket.d.ts +9 -0
  30. package/dist/commands/common/utils/unixSocket.js +45 -0
  31. package/dist/commands/interface/run.d.ts +2 -0
  32. package/dist/commands/interface/run.js +161 -0
  33. package/dist/common/asyncLocalStorage/index.d.ts +1 -1
  34. package/dist/common/contextStorageStateHelpers.d.ts +1 -2
  35. package/dist/common/contextStorageStateHelpers.js +9 -7
  36. package/dist/common/getPlaywrightConstructs.d.ts +7 -5
  37. package/dist/common/getPlaywrightConstructs.js +28 -11
  38. package/dist/common/runApi/errors.d.ts +71 -0
  39. package/dist/common/runApi/errors.js +172 -0
  40. package/dist/common/runApi/index.d.ts +12 -0
  41. package/dist/common/runApi/index.js +288 -0
  42. package/dist/common/runApi/types.d.ts +486 -0
  43. package/dist/common/runApi/types.js +50 -0
  44. package/dist/runtime/extendTimeout.js +10 -6
  45. package/dist/runtime/index.d.ts +1 -0
  46. package/dist/runtime/requestMoreInfo.d.ts +1 -0
  47. package/output.txt +39 -0
  48. package/package.json +7 -5
  49. package/testing +0 -0
  50. package/tsconfig.json +2 -1
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.getPlaywrightConstructsForMode = getPlaywrightConstructsForMode;
7
7
  exports.getProductionPlaywrightConstructs = getProductionPlaywrightConstructs;
8
8
  exports.getRemotePlaywrightContext = getRemotePlaywrightContext;
9
- exports.loadAuthSessionToContext = loadAuthSessionToContext;
9
+ exports.loadSessionToContext = loadSessionToContext;
10
10
  var playwright = _interopRequireWildcard(require("@intuned/playwright-core"));
11
11
  var _fsExtra = _interopRequireWildcard(require("fs-extra"));
12
12
  var fs = _fsExtra;
@@ -70,7 +70,10 @@ async function getProductionPlaywrightConstructs({
70
70
  }
71
71
  });
72
72
  if (storageState) {
73
- await (0, _contextStorageStateHelpers.setContextStorageState)(context, storageState);
73
+ await loadSessionToContext({
74
+ context,
75
+ session: storageState
76
+ });
74
77
  }
75
78
  const assetsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
76
79
  await context.addInitScript({
@@ -89,7 +92,7 @@ async function getProductionPlaywrightConstructs({
89
92
  };
90
93
  }
91
94
  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"];
92
- async function getPlaywrightConstructsForMode(mode, cdpAddress, authSessionPath) {
95
+ async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
93
96
  if (mode == "playwright-standalone") {
94
97
  if (!cdpAddress) {
95
98
  throw new Error("cdpAddress is required");
@@ -113,8 +116,11 @@ async function getPlaywrightConstructsForMode(mode, cdpAddress, authSessionPath)
113
116
  } else {
114
117
  page = await context.newPage();
115
118
  }
116
- if (authSessionPath) {
117
- await loadAuthSessionToContext(context, authSessionPath);
119
+ if (authSession) {
120
+ await loadSessionToContext({
121
+ context,
122
+ session: authSession
123
+ });
118
124
  }
119
125
  return {
120
126
  page,
@@ -127,8 +133,11 @@ async function getPlaywrightConstructsForMode(mode, cdpAddress, authSessionPath)
127
133
  headless: mode === "playwright-headless",
128
134
  downloadsPath
129
135
  });
130
- if (authSessionPath) {
131
- await loadAuthSessionToContext(productionConstructs.context, authSessionPath);
136
+ if (authSession) {
137
+ await loadSessionToContext({
138
+ context: productionConstructs.context,
139
+ session: authSession
140
+ });
132
141
  }
133
142
  return {
134
143
  ...productionConstructs
@@ -136,10 +145,18 @@ async function getPlaywrightConstructsForMode(mode, cdpAddress, authSessionPath)
136
145
  }
137
146
  throw "invalid mode";
138
147
  }
139
- async function loadAuthSessionToContext(context, authSessionPath) {
140
- const fullPath = (0, _fileUtils.getFullPathInProject)(authSessionPath);
141
- const data = await fs.readJson(fullPath);
142
- await (0, _contextStorageStateHelpers.setContextStorageState)(context, data);
148
+ async function loadSessionToContext({
149
+ context,
150
+ session
151
+ }) {
152
+ let sessionToLoad;
153
+ if (session.type === "state") {
154
+ sessionToLoad = session.state;
155
+ } else {
156
+ const fullPath = (0, _fileUtils.getFullPathInProject)(session.path);
157
+ sessionToLoad = await fs.readJson(fullPath);
158
+ }
159
+ await (0, _contextStorageStateHelpers.setContextStorageState)(context, sessionToLoad);
143
160
  }
144
161
  async function getRemotePlaywrightContext(cdpAddress) {
145
162
  const playwright = await Promise.resolve().then(() => _interopRequireWildcard(require("@intuned/playwright-core")));
@@ -0,0 +1,71 @@
1
+ import { RunAutomationResponse } from "./types";
2
+ import { RunErrorOptions } from "src/runtime/export";
3
+ export declare const apiNotFoundErrorCode = "APINotFoundError";
4
+ export declare const invalidApiErrorCode = "InvalidAPIError";
5
+ export declare const invalidCheckErrorCode = "InvalidCheckError";
6
+ export declare const abortedErrorCode = "AbortedError";
7
+ export declare const authRequiredErrorCode = "AuthRequiredError";
8
+ export declare const authCheckNotFoundErrorCode = "AuthCheckNotFoundError";
9
+ export declare const authCheckFailedErrorCode = "AuthCheckFailedError";
10
+ export declare const maxLevelsExceededErrorCode = "MaxLevelsExceededError";
11
+ export declare const automationError = "AutomationError";
12
+ export declare const runAutomationErrorCodes: readonly ["APINotFoundError", "InvalidAPIError", "InvalidCheckError", "AbortedError", "AuthRequiredError", "AuthCheckNotFoundError", "AuthCheckFailedError", "MaxLevelsExceededError", "AutomationError"];
13
+ export type RunAutomationErrorCode = (typeof runAutomationErrorCodes)[number];
14
+ export declare abstract class RunAutomationError<T = any> {
15
+ code: RunAutomationErrorCode;
16
+ statusCode: number;
17
+ wrapped: boolean;
18
+ message: string;
19
+ cause?: RunAutomationError;
20
+ details?: T;
21
+ get apiResponse(): RunAutomationResponse;
22
+ get json(): {
23
+ code: "APINotFoundError" | "InvalidAPIError" | "InvalidCheckError" | "AbortedError" | "AuthRequiredError" | "AuthCheckNotFoundError" | "AuthCheckFailedError" | "MaxLevelsExceededError" | "AutomationError";
24
+ details: T | undefined;
25
+ cause: any;
26
+ };
27
+ }
28
+ export declare class ApiNotFoundError extends RunAutomationError {
29
+ constructor(apiName: string);
30
+ }
31
+ export declare class InvalidApiError extends RunAutomationError {
32
+ constructor(message: string);
33
+ }
34
+ export declare class InvalidCheckError extends RunAutomationError {
35
+ constructor(message: string, cause?: RunAutomationError);
36
+ }
37
+ export declare class AbortedError extends RunAutomationError {
38
+ constructor();
39
+ }
40
+ export declare class AuthRequiredError extends RunAutomationError {
41
+ constructor();
42
+ }
43
+ export declare class AuthCheckNotFoundError extends RunAutomationError {
44
+ constructor();
45
+ }
46
+ export declare class AuthCheckFailedError extends RunAutomationError {
47
+ constructor();
48
+ get apiResponse(): {
49
+ status: number;
50
+ body: {
51
+ status: number;
52
+ error: string;
53
+ message: string;
54
+ };
55
+ };
56
+ }
57
+ export declare class MaxLevelsExceededError extends RunAutomationError<{
58
+ levels: number;
59
+ }> {
60
+ constructor(levels: number);
61
+ }
62
+ export declare class AutomationError extends RunAutomationError<{
63
+ name?: string;
64
+ message?: string;
65
+ statusCode?: number;
66
+ errorCode?: string;
67
+ options?: RunErrorOptions;
68
+ }> {
69
+ error: any;
70
+ constructor(error: any);
71
+ }
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.runAutomationErrorCodes = exports.maxLevelsExceededErrorCode = exports.invalidCheckErrorCode = exports.invalidApiErrorCode = exports.automationError = exports.authRequiredErrorCode = exports.authCheckNotFoundErrorCode = exports.authCheckFailedErrorCode = exports.apiNotFoundErrorCode = exports.abortedErrorCode = exports.RunAutomationError = exports.MaxLevelsExceededError = exports.InvalidCheckError = exports.InvalidApiError = exports.AutomationError = exports.AuthRequiredError = exports.AuthCheckNotFoundError = exports.AuthCheckFailedError = exports.ApiNotFoundError = exports.AbortedError = void 0;
7
+ var _runtime = require("../../runtime");
8
+ var playwright = _interopRequireWildcard(require("@intuned/playwright-core"));
9
+ 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); }
10
+ 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 && Object.prototype.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; }
11
+ const apiNotFoundErrorCode = exports.apiNotFoundErrorCode = "APINotFoundError";
12
+ const invalidApiErrorCode = exports.invalidApiErrorCode = "InvalidAPIError";
13
+ const invalidCheckErrorCode = exports.invalidCheckErrorCode = "InvalidCheckError";
14
+ const abortedErrorCode = exports.abortedErrorCode = "AbortedError";
15
+ const authRequiredErrorCode = exports.authRequiredErrorCode = "AuthRequiredError";
16
+ const authCheckNotFoundErrorCode = exports.authCheckNotFoundErrorCode = "AuthCheckNotFoundError";
17
+ const authCheckFailedErrorCode = exports.authCheckFailedErrorCode = "AuthCheckFailedError";
18
+ const maxLevelsExceededErrorCode = exports.maxLevelsExceededErrorCode = "MaxLevelsExceededError";
19
+ const automationError = exports.automationError = "AutomationError";
20
+ const runAutomationErrorCodes = exports.runAutomationErrorCodes = [apiNotFoundErrorCode, invalidApiErrorCode, invalidCheckErrorCode, abortedErrorCode, authRequiredErrorCode, authCheckNotFoundErrorCode, authCheckFailedErrorCode, maxLevelsExceededErrorCode, automationError];
21
+ class RunAutomationError {
22
+ wrapped = false;
23
+ get apiResponse() {
24
+ if (this.wrapped) {
25
+ return {
26
+ status: 200,
27
+ body: {
28
+ status: this.statusCode,
29
+ error: this.code,
30
+ message: this.message
31
+ }
32
+ };
33
+ }
34
+ return {
35
+ status: this.statusCode,
36
+ body: {
37
+ error: this.code,
38
+ message: this.message
39
+ }
40
+ };
41
+ }
42
+ get json() {
43
+ var _this$cause;
44
+ return {
45
+ code: this.code,
46
+ details: this.details,
47
+ cause: (_this$cause = this.cause) === null || _this$cause === void 0 ? void 0 : _this$cause.json
48
+ };
49
+ }
50
+ }
51
+ exports.RunAutomationError = RunAutomationError;
52
+ class ApiNotFoundError extends RunAutomationError {
53
+ constructor(apiName) {
54
+ super();
55
+ this.code = apiNotFoundErrorCode;
56
+ this.statusCode = 404;
57
+ this.message = `API ${apiName} not found`;
58
+ }
59
+ }
60
+ exports.ApiNotFoundError = ApiNotFoundError;
61
+ class InvalidApiError extends RunAutomationError {
62
+ constructor(message) {
63
+ super();
64
+ this.code = invalidApiErrorCode;
65
+ this.statusCode = 400;
66
+ this.message = `API is invalid: ${message}`;
67
+ }
68
+ }
69
+ exports.InvalidApiError = InvalidApiError;
70
+ class InvalidCheckError extends RunAutomationError {
71
+ constructor(message, cause) {
72
+ super();
73
+ this.code = invalidCheckErrorCode;
74
+ this.statusCode = 400;
75
+ this.message = message;
76
+ this.cause = cause;
77
+ }
78
+ }
79
+ exports.InvalidCheckError = InvalidCheckError;
80
+ class AbortedError extends RunAutomationError {
81
+ constructor() {
82
+ super();
83
+ this.code = abortedErrorCode;
84
+ this.statusCode = 200;
85
+ this.message = "Operation was aborted";
86
+ }
87
+ }
88
+ exports.AbortedError = AbortedError;
89
+ class AuthRequiredError extends RunAutomationError {
90
+ constructor() {
91
+ super();
92
+ this.code = authRequiredErrorCode;
93
+ this.statusCode = 401;
94
+ this.message = "Authentication is required";
95
+ }
96
+ }
97
+ exports.AuthRequiredError = AuthRequiredError;
98
+ class AuthCheckNotFoundError extends RunAutomationError {
99
+ constructor() {
100
+ super();
101
+ this.code = authCheckNotFoundErrorCode;
102
+ this.statusCode = 404;
103
+ this.message = "Auth check not found";
104
+ }
105
+ }
106
+ exports.AuthCheckNotFoundError = AuthCheckNotFoundError;
107
+ class AuthCheckFailedError extends RunAutomationError {
108
+ constructor() {
109
+ super();
110
+ this.code = authCheckFailedErrorCode;
111
+ this.statusCode = 401;
112
+ this.message = "auth session check failed";
113
+ }
114
+ get apiResponse() {
115
+ return {
116
+ status: 200,
117
+ body: {
118
+ status: this.statusCode,
119
+ error: "AUTH_SESSION_CHECK_FAILED",
120
+ message: this.message
121
+ }
122
+ };
123
+ }
124
+ }
125
+ exports.AuthCheckFailedError = AuthCheckFailedError;
126
+ class MaxLevelsExceededError extends RunAutomationError {
127
+ constructor(levels) {
128
+ super();
129
+ this.code = maxLevelsExceededErrorCode;
130
+ this.statusCode = 400;
131
+ this.message = `Max levels exceeded. Only ${levels} levels are supported`;
132
+ this.details = {
133
+ levels
134
+ };
135
+ }
136
+ }
137
+ exports.MaxLevelsExceededError = MaxLevelsExceededError;
138
+ class AutomationError extends RunAutomationError {
139
+ constructor(error) {
140
+ super();
141
+ this.error = error;
142
+ this.code = automationError;
143
+ if (error instanceof playwright.errors.TimeoutError) {
144
+ this.statusCode = 500;
145
+ this.message = `[${error.name}] ${error.message}`;
146
+ this.details = {
147
+ name: error.name,
148
+ message: error.message
149
+ };
150
+ return;
151
+ }
152
+ if (error instanceof _runtime.RunError) {
153
+ this.wrapped = true;
154
+ this.statusCode = error.options.status_code ?? 500;
155
+ this.message = `[${error.options.error_code ?? error.name}] ${error.message}`;
156
+ this.details = {
157
+ name: error.name,
158
+ statusCode: error.options.status_code,
159
+ errorCode: error.options.error_code,
160
+ message: error.message,
161
+ options: error.options
162
+ };
163
+ }
164
+ this.statusCode = 500;
165
+ this.message = `[${(error === null || error === void 0 ? void 0 : error.name) ?? error}] ${error === null || error === void 0 ? void 0 : error.message}`;
166
+ this.details = {
167
+ name: error === null || error === void 0 ? void 0 : error.name,
168
+ message: error === null || error === void 0 ? void 0 : error.message
169
+ };
170
+ }
171
+ }
172
+ exports.AutomationError = AutomationError;
@@ -0,0 +1,12 @@
1
+ import { Result } from "neverthrow";
2
+ import { RunAutomationError } from "./errors";
3
+ import { Page, BrowserContext } from "@intuned/playwright-core";
4
+ import { ExtendedRunApiParameters, RunApiResult, RunApiResultWithSessionOk } from "./types";
5
+ export * from "./types";
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): Promise<RunApiResult<ResultType>>;
12
+ export declare function checkAuthSessionWithRetries(page: Page, context: BrowserContext, retries?: number): Promise<Result<boolean, RunAutomationError>>;
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ runApiGenerator: true,
8
+ runApi: true,
9
+ checkAuthSessionWithRetries: true
10
+ };
11
+ exports.checkAuthSessionWithRetries = checkAuthSessionWithRetries;
12
+ exports.runApi = runApi;
13
+ exports.runApiGenerator = runApiGenerator;
14
+ var _downloadDirectory = require("../../runtime/downloadDirectory");
15
+ var _asyncLocalStorage = require("../asyncLocalStorage");
16
+ var _fsExtra = _interopRequireWildcard(require("fs-extra"));
17
+ var fs = _fsExtra;
18
+ var _jwtTokenManager = require("../jwtTokenManager");
19
+ var _contextStorageStateHelpers = require("../contextStorageStateHelpers");
20
+ var _neverthrow = require("neverthrow");
21
+ var _errors = require("./errors");
22
+ Object.keys(_errors).forEach(function (key) {
23
+ if (key === "default" || key === "__esModule") return;
24
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
25
+ if (key in exports && exports[key] === _errors[key]) return;
26
+ Object.defineProperty(exports, key, {
27
+ enumerable: true,
28
+ get: function () {
29
+ return _errors[key];
30
+ }
31
+ });
32
+ });
33
+ var _constants = require("../constants");
34
+ var _getPlaywrightConstructs = require("../getPlaywrightConstructs");
35
+ var _types = require("./types");
36
+ Object.keys(_types).forEach(function (key) {
37
+ if (key === "default" || key === "__esModule") return;
38
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
39
+ if (key in exports && exports[key] === _types[key]) return;
40
+ Object.defineProperty(exports, key, {
41
+ enumerable: true,
42
+ get: function () {
43
+ return _types[key];
44
+ }
45
+ });
46
+ });
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); }
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 && Object.prototype.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; }
49
+ async function* runApiGenerator({
50
+ retrieveSession = false,
51
+ abortSignal,
52
+ ...input
53
+ }) {
54
+ let traceStarted = false;
55
+ const {
56
+ automationFunction,
57
+ runOptions,
58
+ tracing,
59
+ auth,
60
+ functionsToken
61
+ } = _types.runApiParametersSchema.parse(input);
62
+ _jwtTokenManager.backendFunctionsTokenManager.token = functionsToken;
63
+ const downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
64
+ let page;
65
+ let context;
66
+ if (runOptions.environment === "deployed") {
67
+ const {
68
+ headless,
69
+ proxy
70
+ } = runOptions;
71
+ ({
72
+ page,
73
+ context
74
+ } = await (0, _getPlaywrightConstructs.getProductionPlaywrightConstructs)({
75
+ headless,
76
+ proxy,
77
+ downloadsPath,
78
+ storageState: auth === null || auth === void 0 ? void 0 : auth.session
79
+ }));
80
+ } else {
81
+ const {
82
+ mode,
83
+ cdpAddress
84
+ } = runOptions;
85
+ ({
86
+ page,
87
+ context
88
+ } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, cdpAddress, auth === null || auth === void 0 ? void 0 : auth.session));
89
+ }
90
+ const executionContext = (0, _asyncLocalStorage.getExecutionContext)();
91
+ if (!executionContext) {
92
+ throw "";
93
+ }
94
+ async function saveTraceIfNeeded({
95
+ errorMessage
96
+ }) {
97
+ if (!tracing.enabled || !traceStarted) {
98
+ return;
99
+ }
100
+ try {
101
+ await context.tracing.stop({
102
+ path: tracing.filePath
103
+ });
104
+ } catch (error) {
105
+ console.log(errorMessage, error === null || error === void 0 ? void 0 : error.message);
106
+ await (0, _fsExtra.remove)(tracing.filePath);
107
+ }
108
+ }
109
+ if (tracing.enabled) {
110
+ await context.tracing.start({
111
+ screenshots: true,
112
+ snapshots: true,
113
+ sources: true
114
+ });
115
+ traceStarted = true;
116
+ }
117
+ const abortSymbol = Symbol("abort");
118
+ const abortPromise = new Promise(resolve => {
119
+ if (!abortSignal) return;
120
+ abortSignal.addEventListener("abort", () => {
121
+ resolve(abortSymbol);
122
+ });
123
+ });
124
+ if (auth && auth.session.type === "state") {
125
+ await (0, _contextStorageStateHelpers.setContextStorageState)(context, auth.session.state);
126
+ }
127
+ async function* runAutomation() {
128
+ var _getExecutionContext;
129
+ if (auth !== null && auth !== void 0 && auth.runCheck) {
130
+ if (!auth.session) {
131
+ return (0, _neverthrow.err)({
132
+ code: "AuthRequiredError"
133
+ });
134
+ }
135
+ console.log("Running auth check");
136
+ const authCheckResult = await checkAuthSessionWithRetries(page, context, 2);
137
+ if (authCheckResult.isErr()) {
138
+ const error = authCheckResult.error;
139
+ if (["APINotFoundError", "InvalidAPIError"].includes(error.code)) {
140
+ return (0, _neverthrow.err)(new _errors.InvalidCheckError(`Auth session check function failed`, error));
141
+ }
142
+ return authCheckResult;
143
+ }
144
+ if (!authCheckResult.value) {
145
+ return (0, _neverthrow.err)({
146
+ code: "AuthCheckFailedError"
147
+ });
148
+ }
149
+ }
150
+ console.log("Running function", automationFunction.name);
151
+ const args = [...(automationFunction.params ? [automationFunction.params] : []), page, context];
152
+ const importResult = await importFunction(automationFunction.name);
153
+ if (importResult.isErr()) {
154
+ return importResult;
155
+ }
156
+ let result;
157
+ if (importResult.value.type === "async-generator") {
158
+ const generator = importResult.value.generator(...args);
159
+ let next = undefined;
160
+ while (true) {
161
+ const generatorResult = await generator.next(...(next ? [next] : []));
162
+ if (!generatorResult.done) {
163
+ next = yield generatorResult.value;
164
+ continue;
165
+ }
166
+ result = generatorResult.value;
167
+ break;
168
+ }
169
+ } else {
170
+ result = await importResult.value.func(...args);
171
+ }
172
+ return (0, _neverthrow.ok)({
173
+ result,
174
+ extendedPayloads: (_getExecutionContext = (0, _asyncLocalStorage.getExecutionContext)()) === null || _getExecutionContext === void 0 ? void 0 : _getExecutionContext.extendedPayloads,
175
+ session: retrieveSession ? await (0, _contextStorageStateHelpers.getContextStorageState)(context) : undefined
176
+ });
177
+ }
178
+ try {
179
+ const generator = runAutomation();
180
+ let next = undefined;
181
+ while (true) {
182
+ const result = await Promise.race([generator.next(await next), abortPromise]);
183
+ if (result === abortSymbol) {
184
+ return (0, _neverthrow.err)(new _errors.AbortedError());
185
+ }
186
+ if (!result.done) {
187
+ next = yield result.value;
188
+ continue;
189
+ }
190
+ return result.value;
191
+ }
192
+ } catch (error) {
193
+ console.log("run errored", error);
194
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
195
+ } finally {
196
+ await saveTraceIfNeeded({
197
+ errorMessage: "failed to save trace"
198
+ });
199
+ await context.close();
200
+ await fs.remove(downloadsPath);
201
+ }
202
+ }
203
+ async function runApi(params) {
204
+ const generator = runApiGenerator(params);
205
+ const {
206
+ value,
207
+ done
208
+ } = await generator.next();
209
+ if (done) {
210
+ return value;
211
+ }
212
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("Expected API to be async function, got async generator"));
213
+ }
214
+ async function checkAuthSessionWithRetries(page, context, retries = 3) {
215
+ if (retries === 0) {
216
+ return (0, _neverthrow.ok)(false);
217
+ }
218
+ let tryNumber = 0;
219
+ console.log("Checking auth session with retries", `${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
220
+ const importResult = await importFunction(`${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
221
+ if (importResult.isErr()) {
222
+ return (0, _neverthrow.err)(importResult.error);
223
+ }
224
+ if (importResult.value.type !== "async") {
225
+ return (0, _neverthrow.err)(new _errors.InvalidCheckError("Check function is not an async function"));
226
+ }
227
+ const check = importResult.value.func;
228
+ while (retries > tryNumber) {
229
+ const result = await check(page, context);
230
+ if (result) return (0, _neverthrow.ok)(true);
231
+ tryNumber++;
232
+ }
233
+ return (0, _neverthrow.ok)(false);
234
+ }
235
+ async function importFunction(path) {
236
+ const functionNameParts = path.split("/");
237
+ const functionNameDepth = functionNameParts.length;
238
+ try {
239
+ let imported = undefined;
240
+ switch (functionNameDepth) {
241
+ case 1:
242
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}.ts`);
243
+ break;
244
+ case 2:
245
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}.ts`);
246
+ break;
247
+ case 3:
248
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}.ts`);
249
+ break;
250
+ case 4:
251
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}.ts`);
252
+ break;
253
+ case 5:
254
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}/${functionNameParts[4]}.ts`);
255
+ break;
256
+ case 6:
257
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}/${functionNameParts[4]}/${functionNameParts[5]}.ts`);
258
+ break;
259
+ default:
260
+ return (0, _neverthrow.err)(new _errors.MaxLevelsExceededError(5));
261
+ }
262
+ if (!imported || !imported.default || !imported.default.constructor) {
263
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default export"));
264
+ }
265
+ if (imported.default.constructor.name === "AsyncGeneratorFunction") {
266
+ return (0, _neverthrow.ok)({
267
+ type: "async-generator",
268
+ generator: imported.default
269
+ });
270
+ }
271
+ if (imported.default.constructor.name === "AsyncFunction") {
272
+ return (0, _neverthrow.ok)({
273
+ type: "async",
274
+ func: imported.default
275
+ });
276
+ }
277
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default async function/generator export"));
278
+ } catch (error) {
279
+ if (error.message.includes("Unknown variable dynamic import")) {
280
+ return (0, _neverthrow.err)(new _errors.ApiNotFoundError(path));
281
+ }
282
+ if ((error === null || error === void 0 ? void 0 : error.code) === "ERR_MODULE_NOT_FOUND") {
283
+ console.log("API not found", error);
284
+ return (0, _neverthrow.err)(new _errors.ApiNotFoundError(path));
285
+ }
286
+ throw error;
287
+ }
288
+ }