@intuned/runtime-dev 0.1.0-test.15 → 0.1.0-test.17

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 (61) hide show
  1. package/.babelrc +1 -2
  2. package/WebTemplate/api.ts +90 -92
  3. package/WebTemplate/controllers/authSessions/create.ts +2 -2
  4. package/WebTemplate/controllers/authSessions/store.ts +1 -1
  5. package/WebTemplate/controllers/runApi/helpers.ts +14 -12
  6. package/WebTemplate/index.playwright.ts +32 -42
  7. package/WebTemplate/jobs.ts +13 -2
  8. package/WebTemplate/utils.ts +53 -1
  9. package/api/test2.ts +6 -1
  10. package/auth-sessions/check.ts +3 -1
  11. package/auth-sessions/create.ts +10 -10
  12. package/dist/commands/api/run.js +41 -29
  13. package/dist/commands/auth-sessions/load.js +13 -11
  14. package/dist/commands/auth-sessions/run-check.js +21 -14
  15. package/dist/commands/auth-sessions/run-create.js +32 -25
  16. package/dist/commands/browser/save-state.js +10 -7
  17. package/dist/commands/browser/start-browser.js +10 -7
  18. package/dist/commands/build.js +30 -27
  19. package/dist/commands/common/browserUtils.js +28 -15
  20. package/dist/commands/common/getFirstLineNumber.js +20 -13
  21. package/dist/commands/common/getFirstLineNumber.test.js +52 -48
  22. package/dist/commands/common/sendMessageToClient.js +9 -2
  23. package/dist/commands/common/tsNodeImport.d.ts +1 -0
  24. package/dist/commands/common/tsNodeImport.js +18 -0
  25. package/dist/commands/common/utils/fileUtils.js +16 -6
  26. package/dist/commands/common/utils/settings.js +13 -7
  27. package/dist/commands/common/utils/unixSocket.js +9 -2
  28. package/dist/commands/common/utils/webTemplate.js +17 -9
  29. package/dist/commands/interface/run.js +163 -134
  30. package/dist/commands/ts-check.js +13 -10
  31. package/dist/common/Logger/Logger/index.js +16 -9
  32. package/dist/common/Logger/Logger/types.js +5 -1
  33. package/dist/common/Logger/index.js +16 -9
  34. package/dist/common/Logger/types.js +5 -1
  35. package/dist/common/asyncLocalStorage/index.js +12 -4
  36. package/dist/common/cleanEnvironmentVariables.js +7 -1
  37. package/dist/common/constants.js +7 -1
  38. package/dist/common/contextStorageStateHelpers.js +9 -2
  39. package/dist/common/getPlaywrightConstructs.js +39 -29
  40. package/dist/common/jwtTokenManager.js +18 -8
  41. package/dist/common/runApi/errors.js +42 -24
  42. package/dist/common/runApi/index.js +97 -103
  43. package/dist/common/runApi/types.d.ts +19 -5
  44. package/dist/common/runApi/types.js +42 -31
  45. package/dist/common/settingsSchema.js +10 -2
  46. package/dist/common/telemetry.js +12 -3
  47. package/dist/index.js +69 -4
  48. package/dist/runtime/RunError.js +8 -1
  49. package/dist/runtime/downloadDirectory.js +11 -5
  50. package/dist/runtime/enums.d.js +5 -1
  51. package/dist/runtime/enums.js +8 -2
  52. package/dist/runtime/executionHelpers.test.js +22 -20
  53. package/dist/runtime/export.d.js +5 -1
  54. package/dist/runtime/extendPayload.js +11 -5
  55. package/dist/runtime/extendTimeout.js +9 -3
  56. package/dist/runtime/index.js +53 -6
  57. package/dist/runtime/requestMoreInfo.js +9 -2
  58. package/dist/runtime/runInfo.js +11 -5
  59. package/package.json +3 -5
  60. package/dist/commands/common/getDefaultExportFromFile.d.ts +0 -0
  61. package/dist/commands/common/getDefaultExportFromFile.js +0 -0
@@ -1,18 +1,28 @@
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
- import { fileURLToPath } from "url";
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getPlaywrightConstructsForMode = getPlaywrightConstructsForMode;
7
+ exports.getProductionPlaywrightConstructs = getProductionPlaywrightConstructs;
8
+ exports.getRemotePlaywrightContext = getRemotePlaywrightContext;
9
+ exports.loadSessionToContext = loadSessionToContext;
10
+ var playwright = _interopRequireWildcard(require("@intuned/playwright-core"));
11
+ var _fsExtra = _interopRequireWildcard(require("fs-extra"));
12
+ var fs = _fsExtra;
13
+ var _contextStorageStateHelpers = require("./contextStorageStateHelpers.js");
14
+ var _path = _interopRequireWildcard(require("path"));
15
+ var _fileUtils = require("../commands/common/utils/fileUtils");
16
+ var _waitOn = _interopRequireDefault(require("wait-on"));
17
+ var _runtime = require("../runtime");
18
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
+ 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); }
20
+ 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
21
  async function createUserDirWithPreferences() {
12
- const playwrightTempDir = await mkdtemp("/tmp/pw-");
13
- const userDir = join(playwrightTempDir, "userdir");
14
- const defaultDir = join(userDir, "Default");
15
- await mkdir(defaultDir, {
22
+ const playwrightTempDir = await (0, _fsExtra.mkdtemp)("/tmp/pw-");
23
+ const userDir = (0, _path.join)(playwrightTempDir, "userdir");
24
+ const defaultDir = (0, _path.join)(userDir, "Default");
25
+ await (0, _fsExtra.mkdir)(defaultDir, {
16
26
  recursive: true
17
27
  });
18
28
  const preferences = {
@@ -20,10 +30,10 @@ async function createUserDirWithPreferences() {
20
30
  always_open_pdf_externally: true
21
31
  }
22
32
  };
23
- await writeFile(join(defaultDir, "Preferences"), JSON.stringify(preferences));
33
+ await (0, _fsExtra.writeFile)((0, _path.join)(defaultDir, "Preferences"), JSON.stringify(preferences));
24
34
  return userDir;
25
35
  }
26
- export async function getProductionPlaywrightConstructs({
36
+ async function getProductionPlaywrightConstructs({
27
37
  proxy,
28
38
  headless = true,
29
39
  storageState,
@@ -35,7 +45,7 @@ export async function getProductionPlaywrightConstructs({
35
45
  }
36
46
  const executablePath = playwright.chromium.executablePath();
37
47
  const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
38
- const isChrome127There = existsSync(chromium127Path);
48
+ const isChrome127There = (0, _fsExtra.existsSync)(chromium127Path);
39
49
  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`;
40
50
  const userDataDir = await createUserDirWithPreferences();
41
51
  const context = await playwright.chromium.launchPersistentContext(userDataDir, {
@@ -49,7 +59,7 @@ export async function getProductionPlaywrightConstructs({
49
59
  });
50
60
  context.once("close", async () => {
51
61
  try {
52
- await rm(userDataDir, {
62
+ await (0, _fsExtra.rm)(userDataDir, {
53
63
  recursive: true,
54
64
  force: true,
55
65
  retryDelay: 1000,
@@ -65,13 +75,13 @@ export async function getProductionPlaywrightConstructs({
65
75
  session: storageState
66
76
  });
67
77
  }
68
- const assetsFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "./assets/browser_scripts.js");
78
+ const assetsFile = _path.default.join(_path.default.dirname(__filename), "./assets/browser_scripts.js");
69
79
  await context.addInitScript({
70
80
  path: assetsFile
71
81
  });
72
82
  let page = context.pages().at(0);
73
83
  if (page) {
74
- const scriptString = await readFile(assetsFile, "utf8");
84
+ const scriptString = await (0, _fsExtra.readFile)(assetsFile, "utf8");
75
85
  await page.evaluate(scriptString);
76
86
  } else {
77
87
  page = await context.newPage();
@@ -82,7 +92,7 @@ export async function getProductionPlaywrightConstructs({
82
92
  };
83
93
  }
84
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"];
85
- export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
95
+ async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
86
96
  if (mode == "playwright-standalone") {
87
97
  if (!cdpAddress) {
88
98
  throw new Error("cdpAddress is required");
@@ -93,7 +103,7 @@ export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSessi
93
103
  if (!context) {
94
104
  throw new Error("no context found");
95
105
  }
96
- const assetsFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "./assets/browser_scripts.js");
106
+ const assetsFile = _path.default.join(_path.default.dirname(__filename), "./assets/browser_scripts.js");
97
107
  await context.addInitScript({
98
108
  path: assetsFile
99
109
  });
@@ -117,7 +127,7 @@ export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSessi
117
127
  context
118
128
  };
119
129
  }
120
- const downloadsPath = getDownloadDirectoryPath();
130
+ const downloadsPath = (0, _runtime.getDownloadDirectoryPath)();
121
131
  if (mode === "playwright" || mode === "playwright-headless") {
122
132
  const productionConstructs = await getProductionPlaywrightConstructs({
123
133
  headless: mode === "playwright-headless",
@@ -135,7 +145,7 @@ export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSessi
135
145
  }
136
146
  throw "invalid mode";
137
147
  }
138
- export async function loadSessionToContext({
148
+ async function loadSessionToContext({
139
149
  context,
140
150
  session
141
151
  }) {
@@ -143,20 +153,20 @@ export async function loadSessionToContext({
143
153
  if (session.type === "state") {
144
154
  sessionToLoad = session.state;
145
155
  } else {
146
- const fullPath = getFullPathInProject(session.path);
156
+ const fullPath = (0, _fileUtils.getFullPathInProject)(session.path);
147
157
  sessionToLoad = await fs.readJson(fullPath);
148
158
  }
149
- await setContextStorageState(context, sessionToLoad);
159
+ await (0, _contextStorageStateHelpers.setContextStorageState)(context, sessionToLoad);
150
160
  }
151
- export async function getRemotePlaywrightContext(cdpAddress) {
152
- const playwright = await import("@intuned/playwright-core");
161
+ async function getRemotePlaywrightContext(cdpAddress) {
162
+ const playwright = await Promise.resolve().then(() => _interopRequireWildcard(require("@intuned/playwright-core")));
153
163
  let browser = null;
154
164
  if (!cdpAddress) {
155
165
  throw new Error("cdpAddress is required");
156
166
  }
157
167
  const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
158
168
  try {
159
- await waitOn({
169
+ await (0, _waitOn.default)({
160
170
  resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
161
171
  delay: 100,
162
172
  interval: 100,
@@ -1,6 +1,16 @@
1
- import fetch from "cross-fetch";
2
- import * as jwt from "jsonwebtoken";
3
- import { err, ResultAsync } from "neverthrow";
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.backendFunctionsTokenManager = void 0;
7
+ exports.callBackendFunctionWithToken = callBackendFunctionWithToken;
8
+ var _crossFetch = _interopRequireDefault(require("cross-fetch"));
9
+ var jwt = _interopRequireWildcard(require("jsonwebtoken"));
10
+ var _neverthrow = require("neverthrow");
11
+ 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); }
12
+ 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; }
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
4
14
  class JwtTokenManager {
5
15
  constructor(refreshTokenPath) {
6
16
  this.refreshTokenPath = refreshTokenPath;
@@ -47,9 +57,9 @@ class JwtTokenManager {
47
57
  method: "GET"
48
58
  });
49
59
  if (res.status === 401) {
50
- return err("Unauthorized");
60
+ return (0, _neverthrow.err)("Unauthorized");
51
61
  }
52
- const jsonResult = await ResultAsync.fromPromise(res.json(), () => "not json");
62
+ const jsonResult = await _neverthrow.ResultAsync.fromPromise(res.json(), () => "not json");
53
63
  if (jsonResult.isErr()) return;
54
64
  const newToken = jsonResult.value.token;
55
65
  if (newToken) this._token = newToken;
@@ -57,15 +67,15 @@ class JwtTokenManager {
57
67
  fetchWithToken(...[input, init]) {
58
68
  const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
59
69
  headers.set("Authorization", `Bearer ${this.token}`);
60
- return fetch(input, {
70
+ return (0, _crossFetch.default)(input, {
61
71
  ...init,
62
72
  headers
63
73
  });
64
74
  }
65
75
  }
66
76
  const backendFunctionsPath = `${process.env.FUNCTIONS_DOMAIN}/api/${process.env.INTUNED_WORKSPACE_ID}/functions/${process.env.INTUNED_INTEGRATION_ID}`;
67
- export const backendFunctionsTokenManager = new JwtTokenManager(`${backendFunctionsPath}/refreshBackendFunctionsToken`);
77
+ const backendFunctionsTokenManager = exports.backendFunctionsTokenManager = new JwtTokenManager(`${backendFunctionsPath}/refreshBackendFunctionsToken`);
68
78
  backendFunctionsTokenManager.token = process.env.INTUNED_AUTHORING_SESSION_BACKEND_FUNCTIONS_TOKEN;
69
- export function callBackendFunctionWithToken(path, init) {
79
+ function callBackendFunctionWithToken(path, init) {
70
80
  return backendFunctionsTokenManager.fetchWithToken(`${backendFunctionsPath}/${path}`, init);
71
81
  }
@@ -1,16 +1,24 @@
1
- import { RunError } from "../../runtime";
2
- import * as playwright from "@intuned/playwright-core";
3
- export const apiNotFoundErrorCode = "APINotFoundError";
4
- export const invalidApiErrorCode = "InvalidAPIError";
5
- export const invalidCheckErrorCode = "InvalidCheckError";
6
- export const abortedErrorCode = "AbortedError";
7
- export const authRequiredErrorCode = "AuthRequiredError";
8
- export const authCheckNotFoundErrorCode = "AuthCheckNotFoundError";
9
- export const authCheckFailedErrorCode = "AuthCheckFailedError";
10
- export const maxLevelsExceededErrorCode = "MaxLevelsExceededError";
11
- export const automationError = "AutomationError";
12
- export const runAutomationErrorCodes = [apiNotFoundErrorCode, invalidApiErrorCode, invalidCheckErrorCode, abortedErrorCode, authRequiredErrorCode, authCheckNotFoundErrorCode, authCheckFailedErrorCode, maxLevelsExceededErrorCode, automationError];
13
- export class RunAutomationError {
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 {
14
22
  wrapped = false;
15
23
  get apiResponse() {
16
24
  if (this.wrapped) {
@@ -40,7 +48,8 @@ export class RunAutomationError {
40
48
  };
41
49
  }
42
50
  }
43
- export class ApiNotFoundError extends RunAutomationError {
51
+ exports.RunAutomationError = RunAutomationError;
52
+ class ApiNotFoundError extends RunAutomationError {
44
53
  constructor(apiName) {
45
54
  super();
46
55
  this.code = apiNotFoundErrorCode;
@@ -48,7 +57,8 @@ export class ApiNotFoundError extends RunAutomationError {
48
57
  this.message = `API ${apiName} not found`;
49
58
  }
50
59
  }
51
- export class InvalidApiError extends RunAutomationError {
60
+ exports.ApiNotFoundError = ApiNotFoundError;
61
+ class InvalidApiError extends RunAutomationError {
52
62
  constructor(message) {
53
63
  super();
54
64
  this.code = invalidApiErrorCode;
@@ -56,7 +66,8 @@ export class InvalidApiError extends RunAutomationError {
56
66
  this.message = `API is invalid: ${message}`;
57
67
  }
58
68
  }
59
- export class InvalidCheckError extends RunAutomationError {
69
+ exports.InvalidApiError = InvalidApiError;
70
+ class InvalidCheckError extends RunAutomationError {
60
71
  constructor(message, cause) {
61
72
  super();
62
73
  this.code = invalidCheckErrorCode;
@@ -65,7 +76,8 @@ export class InvalidCheckError extends RunAutomationError {
65
76
  this.cause = cause;
66
77
  }
67
78
  }
68
- export class AbortedError extends RunAutomationError {
79
+ exports.InvalidCheckError = InvalidCheckError;
80
+ class AbortedError extends RunAutomationError {
69
81
  constructor() {
70
82
  super();
71
83
  this.code = abortedErrorCode;
@@ -73,7 +85,8 @@ export class AbortedError extends RunAutomationError {
73
85
  this.message = "Operation was aborted";
74
86
  }
75
87
  }
76
- export class AuthRequiredError extends RunAutomationError {
88
+ exports.AbortedError = AbortedError;
89
+ class AuthRequiredError extends RunAutomationError {
77
90
  constructor() {
78
91
  super();
79
92
  this.code = authRequiredErrorCode;
@@ -81,7 +94,8 @@ export class AuthRequiredError extends RunAutomationError {
81
94
  this.message = "Authentication is required";
82
95
  }
83
96
  }
84
- export class AuthCheckNotFoundError extends RunAutomationError {
97
+ exports.AuthRequiredError = AuthRequiredError;
98
+ class AuthCheckNotFoundError extends RunAutomationError {
85
99
  constructor() {
86
100
  super();
87
101
  this.code = authCheckNotFoundErrorCode;
@@ -89,7 +103,8 @@ export class AuthCheckNotFoundError extends RunAutomationError {
89
103
  this.message = "Auth check not found";
90
104
  }
91
105
  }
92
- export class AuthCheckFailedError extends RunAutomationError {
106
+ exports.AuthCheckNotFoundError = AuthCheckNotFoundError;
107
+ class AuthCheckFailedError extends RunAutomationError {
93
108
  constructor() {
94
109
  super();
95
110
  this.code = authCheckFailedErrorCode;
@@ -107,7 +122,8 @@ export class AuthCheckFailedError extends RunAutomationError {
107
122
  };
108
123
  }
109
124
  }
110
- export class MaxLevelsExceededError extends RunAutomationError {
125
+ exports.AuthCheckFailedError = AuthCheckFailedError;
126
+ class MaxLevelsExceededError extends RunAutomationError {
111
127
  constructor(levels) {
112
128
  super();
113
129
  this.code = maxLevelsExceededErrorCode;
@@ -118,7 +134,8 @@ export class MaxLevelsExceededError extends RunAutomationError {
118
134
  };
119
135
  }
120
136
  }
121
- export class AutomationError extends RunAutomationError {
137
+ exports.MaxLevelsExceededError = MaxLevelsExceededError;
138
+ class AutomationError extends RunAutomationError {
122
139
  constructor(error) {
123
140
  super();
124
141
  this.error = error;
@@ -132,7 +149,7 @@ export class AutomationError extends RunAutomationError {
132
149
  };
133
150
  return;
134
151
  }
135
- if (error instanceof RunError) {
152
+ if (error instanceof _runtime.RunError) {
136
153
  this.wrapped = true;
137
154
  this.statusCode = error.options.status_code ?? 500;
138
155
  this.message = `[${error.options.error_code ?? error.name}] ${error.message}`;
@@ -151,4 +168,5 @@ export class AutomationError extends RunAutomationError {
151
168
  message: error === null || error === void 0 ? void 0 : error.message
152
169
  };
153
170
  }
154
- }
171
+ }
172
+ exports.AutomationError = AutomationError;
@@ -1,17 +1,52 @@
1
- import { getDownloadDirectoryPath } from "../../runtime/downloadDirectory";
2
- import { getExecutionContext } from "../asyncLocalStorage";
3
- import * as fs from "fs-extra";
4
- import { backendFunctionsTokenManager } from "../jwtTokenManager";
5
- import { getContextStorageState, setContextStorageState } from "../contextStorageStateHelpers";
6
- import { remove } from "fs-extra";
7
- import { ok, err } from "neverthrow";
8
- import { AbortedError, ApiNotFoundError, AutomationError, InvalidApiError, InvalidCheckError, MaxLevelsExceededError } from "./errors.js";
9
- import { AUTH_SESSIONS_FOLDER_NAME } from "../constants";
10
- import { getPlaywrightConstructsForMode, getProductionPlaywrightConstructs } from "../getPlaywrightConstructs";
11
- import { runApiParametersSchema } from "./types.js";
12
- export * from "./types.js";
13
- export * from "./errors.js";
14
- export async function* runApiGenerator({
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.js");
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.js");
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({
15
50
  retrieveSession = false,
16
51
  abortSignal,
17
52
  ...input
@@ -23,9 +58,9 @@ export async function* runApiGenerator({
23
58
  tracing,
24
59
  auth,
25
60
  functionsToken
26
- } = runApiParametersSchema.parse(input);
27
- backendFunctionsTokenManager.token = functionsToken;
28
- const downloadsPath = getDownloadDirectoryPath();
61
+ } = _types.runApiParametersSchema.parse(input);
62
+ _jwtTokenManager.backendFunctionsTokenManager.token = functionsToken;
63
+ const downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
29
64
  let page;
30
65
  let context;
31
66
  if (runOptions.environment === "deployed") {
@@ -36,7 +71,7 @@ export async function* runApiGenerator({
36
71
  ({
37
72
  page,
38
73
  context
39
- } = await getProductionPlaywrightConstructs({
74
+ } = await (0, _getPlaywrightConstructs.getProductionPlaywrightConstructs)({
40
75
  headless,
41
76
  proxy,
42
77
  downloadsPath,
@@ -50,9 +85,9 @@ export async function* runApiGenerator({
50
85
  ({
51
86
  page,
52
87
  context
53
- } = await getPlaywrightConstructsForMode(mode, cdpAddress, auth === null || auth === void 0 ? void 0 : auth.session));
88
+ } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, cdpAddress, auth === null || auth === void 0 ? void 0 : auth.session));
54
89
  }
55
- const executionContext = getExecutionContext();
90
+ const executionContext = (0, _asyncLocalStorage.getExecutionContext)();
56
91
  if (!executionContext) {
57
92
  throw "";
58
93
  }
@@ -68,7 +103,7 @@ export async function* runApiGenerator({
68
103
  });
69
104
  } catch (error) {
70
105
  console.log(errorMessage, error === null || error === void 0 ? void 0 : error.message);
71
- await remove(tracing.filePath);
106
+ await (0, _fsExtra.remove)(tracing.filePath);
72
107
  }
73
108
  }
74
109
  if (tracing.enabled) {
@@ -87,40 +122,35 @@ export async function* runApiGenerator({
87
122
  });
88
123
  });
89
124
  if (auth && auth.session.type === "state") {
90
- await setContextStorageState(context, auth.session.state);
125
+ await (0, _contextStorageStateHelpers.setContextStorageState)(context, auth.session.state);
91
126
  }
92
127
  async function* runAutomation() {
93
128
  var _getExecutionContext;
94
129
  if (auth !== null && auth !== void 0 && auth.runCheck) {
95
130
  if (!auth.session) {
96
- return err({
97
- code: "AuthRequiredError"
98
- });
131
+ return (0, _neverthrow.err)(new _errors.AuthRequiredError());
99
132
  }
100
133
  console.log("Running auth check");
101
134
  const authCheckResult = await checkAuthSessionWithRetries(page, context, 2);
102
135
  if (authCheckResult.isErr()) {
103
136
  const error = authCheckResult.error;
104
137
  if (["APINotFoundError", "InvalidAPIError"].includes(error.code)) {
105
- return err(new InvalidCheckError(`Auth session check function failed`, error));
138
+ return (0, _neverthrow.err)(new _errors.InvalidCheckError(`Auth session check function failed`, error));
106
139
  }
107
140
  return authCheckResult;
108
141
  }
109
142
  if (!authCheckResult.value) {
110
- return err({
111
- code: "AuthCheckFailedError"
112
- });
143
+ return (0, _neverthrow.err)(new _errors.AuthCheckFailedError());
113
144
  }
114
145
  }
115
- console.log("Running function", automationFunction.name);
116
146
  const args = [...(automationFunction.params ? [automationFunction.params] : []), page, context];
117
- const importResult = await importFunction(automationFunction.name);
118
- if (importResult.isErr()) {
119
- return importResult;
147
+ const validatedModuleResult = await validateModule(automationFunction.module);
148
+ if (validatedModuleResult.isErr()) {
149
+ return validatedModuleResult;
120
150
  }
121
151
  let result;
122
- if (importResult.value.type === "async-generator") {
123
- const generator = importResult.value.generator(...args);
152
+ if (validatedModuleResult.value.type === "async-generator") {
153
+ const generator = validatedModuleResult.value.generator(...args);
124
154
  let next = undefined;
125
155
  while (true) {
126
156
  const generatorResult = await generator.next(...(next ? [next] : []));
@@ -132,12 +162,12 @@ export async function* runApiGenerator({
132
162
  break;
133
163
  }
134
164
  } else {
135
- result = await importResult.value.func(...args);
165
+ result = await validatedModuleResult.value.func(...args);
136
166
  }
137
- return ok({
167
+ return (0, _neverthrow.ok)({
138
168
  result,
139
- extendedPayloads: (_getExecutionContext = getExecutionContext()) === null || _getExecutionContext === void 0 ? void 0 : _getExecutionContext.extendedPayloads,
140
- session: retrieveSession ? await getContextStorageState(context) : undefined
169
+ extendedPayloads: (_getExecutionContext = (0, _asyncLocalStorage.getExecutionContext)()) === null || _getExecutionContext === void 0 ? void 0 : _getExecutionContext.extendedPayloads,
170
+ session: retrieveSession ? await (0, _contextStorageStateHelpers.getContextStorageState)(context) : undefined
141
171
  });
142
172
  }
143
173
  try {
@@ -146,7 +176,7 @@ export async function* runApiGenerator({
146
176
  while (true) {
147
177
  const result = await Promise.race([generator.next(await next), abortPromise]);
148
178
  if (result === abortSymbol) {
149
- return err(new AbortedError());
179
+ return (0, _neverthrow.err)(new _errors.AbortedError());
150
180
  }
151
181
  if (!result.done) {
152
182
  next = yield result.value;
@@ -156,7 +186,7 @@ export async function* runApiGenerator({
156
186
  }
157
187
  } catch (error) {
158
188
  console.log("run errored", error);
159
- return err(new AutomationError(error));
189
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
160
190
  } finally {
161
191
  await saveTraceIfNeeded({
162
192
  errorMessage: "failed to save trace"
@@ -165,7 +195,7 @@ export async function* runApiGenerator({
165
195
  await fs.remove(downloadsPath);
166
196
  }
167
197
  }
168
- export async function runApi(params) {
198
+ async function runApi(params) {
169
199
  const generator = runApiGenerator(params);
170
200
  const {
171
201
  value,
@@ -174,80 +204,44 @@ export async function runApi(params) {
174
204
  if (done) {
175
205
  return value;
176
206
  }
177
- return err(new InvalidApiError("Expected API to be async function, got async generator"));
207
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("Expected API to be async function, got async generator"));
178
208
  }
179
- export async function checkAuthSessionWithRetries(page, context, retries = 3) {
209
+ async function checkAuthSessionWithRetries(page, context, retries = 3) {
180
210
  if (retries === 0) {
181
- return ok(false);
211
+ return (0, _neverthrow.ok)(false);
182
212
  }
183
213
  let tryNumber = 0;
184
- console.log("Checking auth session with retries", `${AUTH_SESSIONS_FOLDER_NAME}/check`);
185
- const importResult = await importFunction(`${AUTH_SESSIONS_FOLDER_NAME}/check`);
214
+ console.log("Checking auth session with retries", `${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
215
+ const importResult = await validateModule(`${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
186
216
  if (importResult.isErr()) {
187
- return err(importResult.error);
217
+ return (0, _neverthrow.err)(importResult.error);
188
218
  }
189
219
  if (importResult.value.type !== "async") {
190
- return err(new InvalidCheckError("Check function is not an async function"));
220
+ return (0, _neverthrow.err)(new _errors.InvalidCheckError("Check function is not an async function"));
191
221
  }
192
222
  const check = importResult.value.func;
193
223
  while (retries > tryNumber) {
194
224
  const result = await check(page, context);
195
- if (result) return ok(true);
225
+ if (result) return (0, _neverthrow.ok)(true);
196
226
  tryNumber++;
197
227
  }
198
- return ok(false);
228
+ return (0, _neverthrow.ok)(false);
199
229
  }
200
- async function importFunction(path) {
201
- const functionNameParts = path.split("/");
202
- const functionNameDepth = functionNameParts.length;
203
- try {
204
- let imported = undefined;
205
- switch (functionNameDepth) {
206
- case 1:
207
- imported = await import(`../../../${functionNameParts[0]}.ts`);
208
- break;
209
- case 2:
210
- imported = await import(`../../../${functionNameParts[0]}/${functionNameParts[1]}.ts`);
211
- break;
212
- case 3:
213
- imported = await import(`../../../${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}.ts`);
214
- break;
215
- case 4:
216
- imported = await import(`../../../${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}.ts`);
217
- break;
218
- case 5:
219
- imported = await import(`../../../${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}/${functionNameParts[4]}.ts`);
220
- break;
221
- case 6:
222
- imported = await import(`../../../${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}/${functionNameParts[4]}/${functionNameParts[5]}.ts`);
223
- break;
224
- default:
225
- return err(new MaxLevelsExceededError(5));
226
- }
227
- if (!imported || !imported.default || !imported.default.constructor) {
228
- return err(new InvalidApiError("API file path does not have a default export"));
229
- }
230
- if (imported.default.constructor.name === "AsyncGeneratorFunction") {
231
- return ok({
232
- type: "async-generator",
233
- generator: imported.default
234
- });
235
- }
236
- if (imported.default.constructor.name === "AsyncFunction") {
237
- return ok({
238
- type: "async",
239
- func: imported.default
240
- });
241
- }
242
- return err(new InvalidApiError("API file path does not have a default async function/generator export"));
243
- } catch (error) {
244
- if (error.message.includes("Unknown variable dynamic import")) {
245
- return err(new ApiNotFoundError(path));
246
- }
247
- if ((error === null || error === void 0 ? void 0 : error.code) === "ERR_MODULE_NOT_FOUND") {
248
- console.log("API not found", error);
249
- return err(new ApiNotFoundError(path));
250
- }
251
- throw error;
230
+ async function validateModule(module) {
231
+ if (!module || !module.default || !module.default.constructor) {
232
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default export"));
233
+ }
234
+ if (module.default.constructor.name === "AsyncGeneratorFunction") {
235
+ return (0, _neverthrow.ok)({
236
+ type: "async-generator",
237
+ generator: module.default
238
+ });
239
+ }
240
+ if (module.default.constructor.name === "AsyncFunction") {
241
+ return (0, _neverthrow.ok)({
242
+ type: "async",
243
+ func: module.default
244
+ });
252
245
  }
246
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default async function/generator export"));
253
247
  }