@intuned/runtime-dev 0.1.0-test.4 → 0.1.0-test.41

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 (44) hide show
  1. package/InterfaceTemplate/index.playwright.ts +5 -0
  2. package/InterfaceTemplate/utils.ts +257 -0
  3. package/Intuned.json +1 -1
  4. package/WebTemplate/api.ts +90 -92
  5. package/WebTemplate/controllers/async.ts +52 -48
  6. package/WebTemplate/controllers/authSessions/check.ts +3 -4
  7. package/WebTemplate/controllers/authSessions/create.ts +5 -7
  8. package/WebTemplate/controllers/authSessions/resumeOperation.ts +1 -1
  9. package/WebTemplate/controllers/runApi/helpers.ts +12 -7
  10. package/WebTemplate/index.playwright.ts +32 -42
  11. package/WebTemplate/jobs.ts +13 -2
  12. package/WebTemplate/utils.ts +48 -1
  13. package/api/test2.ts +7 -5
  14. package/auth-sessions/check.ts +3 -1
  15. package/auth-sessions/create.ts +10 -10
  16. package/bin/intuned-ts-check +1 -1
  17. package/dist/commands/api/run.js +6 -4
  18. package/dist/commands/auth-sessions/run-check.js +8 -2
  19. package/dist/commands/auth-sessions/run-create.js +10 -5
  20. package/dist/commands/build.js +16 -13
  21. package/dist/commands/common/tsNodeImport.d.ts +1 -0
  22. package/dist/commands/common/{getDefaultExportFromFile.js → tsNodeImport.js} +6 -5
  23. package/dist/commands/common/utils/settings.js +5 -5
  24. package/dist/commands/common/utils/template.d.ts +2 -0
  25. package/dist/commands/common/utils/{webTemplate.js → template.js} +7 -7
  26. package/dist/commands/interface/run.d.ts +1 -1
  27. package/dist/commands/interface/run.js +131 -106
  28. package/dist/commands/ts-check.js +9 -7
  29. package/dist/common/formatZodError.d.ts +2 -0
  30. package/dist/common/formatZodError.js +18 -0
  31. package/dist/common/getPlaywrightConstructs.js +5 -1
  32. package/dist/common/runApi/errors.d.ts +8 -3
  33. package/dist/common/runApi/errors.js +26 -3
  34. package/dist/common/runApi/index.d.ts +1 -1
  35. package/dist/common/runApi/index.js +33 -55
  36. package/dist/common/runApi/types.d.ts +277 -61
  37. package/dist/common/runApi/types.js +26 -2
  38. package/dist/runtime/executionHelpers.test.js +6 -6
  39. package/package.json +5 -3
  40. package/tsconfig.json +1 -2
  41. package/InterfaceTemplate/index.ts +0 -1
  42. package/dist/commands/common/getDefaultExportFromFile.d.ts +0 -1
  43. package/dist/commands/common/utils/webTemplate.d.ts +0 -1
  44. package/testing +0 -0
@@ -1,15 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
 
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.runAutomationCLI = runAutomationCLI;
4
8
  var _commander = require("commander");
5
9
  var _dotenv = _interopRequireDefault(require("dotenv"));
6
10
  var _asyncLocalStorage = require("../../common/asyncLocalStorage");
7
11
  var net = _interopRequireWildcard(require("net"));
8
12
  var _zod = _interopRequireDefault(require("zod"));
9
13
  var _runApi = require("../../common/runApi");
10
- var _enums = require("src/runtime/enums");
14
+ var _enums = require("../../runtime/enums");
11
15
  var _unixSocket = require("../common/utils/unixSocket");
12
16
  var _promises = require("timers/promises");
17
+ var _jwtTokenManager = require("../../common/jwtTokenManager");
18
+ var _formatZodError = require("../../common/formatZodError");
13
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); }
14
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; }
15
21
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
@@ -17,6 +23,7 @@ const startRunApiSchema = _zod.default.object({
17
23
  type: _zod.default.literal("start"),
18
24
  parameters: _runApi.runApiParametersSchema.extend({
19
25
  retrieveSession: _zod.default.boolean(),
26
+ functionsToken: _zod.default.string().optional(),
20
27
  context: _zod.default.object({
21
28
  jobId: _zod.default.string().optional(),
22
29
  jobRunId: _zod.default.string().optional(),
@@ -35,121 +42,136 @@ const abortRunApiSchema = _zod.default.object({
35
42
  type: _zod.default.literal("abort"),
36
43
  parameters: _zod.default.object({}).optional()
37
44
  });
38
- const inputSchema = _zod.default.union([startRunApiSchema, nextRunApiSchema, abortRunApiSchema]);
45
+ const tokenUpdateSchema = _zod.default.object({
46
+ type: _zod.default.literal("tokenUpdate"),
47
+ parameters: _zod.default.object({
48
+ functionsToken: _zod.default.string()
49
+ })
50
+ });
51
+ const inputSchema = _zod.default.union([startRunApiSchema, nextRunApiSchema, abortRunApiSchema, tokenUpdateSchema]);
39
52
  _dotenv.default.config({
40
53
  path: `.env`
41
54
  });
42
- _commander.program.description("run user automation and communicate using unix socket").argument("<socket-path>", "path to unix socket").action(async socketPath => {
43
- let context;
44
- const throttleTime = 1_000;
45
- let timeoutTimestamp = Date.now();
46
- const client = net.createConnection(socketPath, () => {
47
- console.log("connected to server!");
48
- });
49
- let generator = null;
50
- const abortController = new AbortController();
51
- client.on("end", () => {
52
- console.log("Disconnected from socket");
53
- });
54
- client.on("error", err => {
55
- var _generator;
56
- console.error("Child connection error:", err);
57
- void ((_generator = generator) === null || _generator === void 0 ? void 0 : _generator.throw(err).catch(() => undefined));
58
- });
59
- process.on("SIGINT", () => {
60
- var _generator2;
61
- console.log("Received SIGINT");
62
- void ((_generator2 = generator) === null || _generator2 === void 0 ? void 0 : _generator2.throw(new Error("Interrupted")).catch(() => undefined));
63
- client.end();
64
- process.exit(1);
65
- });
66
- const jsonUnixSocket = new _unixSocket.JSONUnixSocket(client);
67
- async function runGeneratorAndSendResult(next) {
68
- if (!generator) return;
69
- const result = await (0, _asyncLocalStorage.runWithContext)(context, () => generator.next(next));
70
- if (result.done) {
71
- const resultToSend = result.value.isOk() ? result.value.value : result.value.error.json;
72
- const success = result.value.isOk();
73
- jsonUnixSocket.sendJSON({
74
- type: "done",
75
- result: resultToSend,
76
- success
77
- });
78
- return true;
79
- } else {
80
- jsonUnixSocket.sendJSON({
81
- type: "yield",
82
- result: result.value
83
- });
84
- return false;
85
- }
86
- }
87
- for await (const data of jsonUnixSocket.receiveJSON()) {
88
- const inputParseResult = inputSchema.safeParse(data);
89
- if (!inputParseResult.success) {
90
- console.error(inputParseResult.error.errors);
91
- jsonUnixSocket.sendJSON({
92
- type: "done",
93
- result: {
94
- error: "InvalidJSON",
95
- message: "Invalid input",
96
- details: {
97
- errors: inputParseResult.error.errors
98
- }
99
- },
100
- success: false
101
- });
102
- break;
103
- }
104
- const input = inputParseResult.data;
105
- if (input.type === "abort") {
106
- abortController.abort();
107
- await (0, _promises.setTimeout)(10);
108
- jsonUnixSocket.sendJSON({
109
- type: "done",
110
- result: null
111
- });
112
- break;
113
- }
114
- if (input.type === "start") {
115
- const gen = (0, _runApi.runApiGenerator)({
116
- ...input.parameters,
117
- abortSignal: abortController.signal
118
- });
119
- generator = gen;
120
- context = {
121
- extendedPayloads: [],
122
- runEnvironment: input.parameters.runOptions.environment === "deployed" ? _enums.RunEnvironment.DEPLOYED : _enums.RunEnvironment.IDE,
123
- timeoutInfo: {
124
- extendTimeoutCallback: async () => {
125
- if (Date.now() - timeoutTimestamp < throttleTime) return;
126
- timeoutTimestamp = Date.now();
127
- jsonUnixSocket.sendJSON({
128
- type: "extend"
129
- });
130
- }
131
- },
132
- ...(input.parameters.context ?? {}),
133
- proxy: getProxyUrlFromRunOptions(input.parameters.runOptions)
55
+ function runAutomationCLI(importFunction) {
56
+ _commander.program.description("run user automation and communicate using unix socket").argument("<socket-path>", "path to unix socket").action(async socketPath => {
57
+ let context;
58
+ const throttleTime = 1_000;
59
+ let timeoutTimestamp = Date.now();
60
+ const client = net.createConnection(socketPath);
61
+ let generator = null;
62
+ const abortController = new AbortController();
63
+ client.on("error", err => {
64
+ var _generator2;
65
+ void ((_generator2 = generator) === null || _generator2 === void 0 ? void 0 : _generator2.throw(err).catch(() => undefined));
66
+ });
67
+ process.on("SIGINT", () => {
68
+ var _generator3;
69
+ void ((_generator3 = generator) === null || _generator3 === void 0 ? void 0 : _generator3.throw(new Error("Interrupted")).catch(() => undefined));
70
+ client.end();
71
+ process.exit(1);
72
+ });
73
+ process.on("SIGTERM", () => {
74
+ var _generator4;
75
+ void ((_generator4 = generator) === null || _generator4 === void 0 ? void 0 : _generator4.throw(new Error("Interrupted")).catch(() => undefined));
76
+ client.end();
77
+ process.exit(1);
78
+ });
79
+ const jsonUnixSocket = new _unixSocket.JSONUnixSocket(client);
80
+ async function runGeneratorAndSendResult(next) {
81
+ const _generator = generator;
82
+ if (_generator == null) return {
83
+ done: true
134
84
  };
135
- if (await runGeneratorAndSendResult()) {
136
- break;
85
+ const result = await (0, _asyncLocalStorage.runWithContext)(context, () => _generator.next(next));
86
+ if (result.done) {
87
+ const resultToSend = result.value.isOk() ? result.value.value : result.value.error.json;
88
+ const success = result.value.isOk();
89
+ jsonUnixSocket.sendJSON({
90
+ type: "done",
91
+ result: resultToSend,
92
+ success
93
+ });
94
+ } else {
95
+ jsonUnixSocket.sendJSON({
96
+ type: "yield",
97
+ result: result.value
98
+ });
137
99
  }
138
- continue;
100
+ return {
101
+ done: result.done ?? false
102
+ };
139
103
  }
140
- if (input.type === "next") {
141
- if (!generator) {
142
- throw new Error("generator not started");
104
+ for await (const data of jsonUnixSocket.receiveJSON()) {
105
+ const inputParseResult = inputSchema.safeParse(data);
106
+ if (!inputParseResult.success) {
107
+ console.error("Validation error:", (0, _formatZodError.formatZodError)(inputParseResult.error));
108
+ jsonUnixSocket.sendJSON({
109
+ type: "done",
110
+ result: new _runApi.InternalInvalidInputError("Invalid input", (0, _formatZodError.formatZodError)(inputParseResult.error)).json,
111
+ success: false
112
+ });
113
+ break;
143
114
  }
144
- if (await runGeneratorAndSendResult(input.parameters.value)) {
115
+ const input = inputParseResult.data;
116
+ if (input.type === "abort") {
117
+ abortController.abort();
118
+ await (0, _promises.setTimeout)(10);
119
+ jsonUnixSocket.sendJSON({
120
+ type: "done",
121
+ result: null
122
+ });
145
123
  break;
146
124
  }
147
- continue;
125
+ if (input.type === "start") {
126
+ _jwtTokenManager.backendFunctionsTokenManager.token = input.parameters.functionsToken;
127
+ generator = (0, _runApi.runApiGenerator)({
128
+ ...input.parameters,
129
+ abortSignal: abortController.signal,
130
+ importFunction
131
+ });
132
+ context = {
133
+ extendedPayloads: [],
134
+ runEnvironment: input.parameters.runOptions.environment === "deployed" ? _enums.RunEnvironment.DEPLOYED : _enums.RunEnvironment.IDE,
135
+ timeoutInfo: {
136
+ extendTimeoutCallback: async () => {
137
+ if (Date.now() - timeoutTimestamp < throttleTime) return;
138
+ timeoutTimestamp = Date.now();
139
+ jsonUnixSocket.sendJSON({
140
+ type: "extend"
141
+ });
142
+ }
143
+ },
144
+ ...(input.parameters.context ?? {}),
145
+ proxy: getProxyUrlFromRunOptions(input.parameters.runOptions)
146
+ };
147
+ const {
148
+ done
149
+ } = await runGeneratorAndSendResult();
150
+ if (done) {
151
+ break;
152
+ }
153
+ continue;
154
+ }
155
+ if (input.type === "next") {
156
+ if (!generator) {
157
+ throw new Error("generator not started");
158
+ }
159
+ const {
160
+ done
161
+ } = await runGeneratorAndSendResult(input.parameters.value);
162
+ if (done) {
163
+ break;
164
+ }
165
+ continue;
166
+ }
167
+ if (input.type === "tokenUpdate") {
168
+ _jwtTokenManager.backendFunctionsTokenManager.token = input.parameters.functionsToken;
169
+ }
148
170
  }
149
- }
150
- process.exit(0);
151
- });
152
- _commander.program.parse(process.argv);
171
+ process.exit(0);
172
+ });
173
+ _commander.program.parse(process.argv);
174
+ }
153
175
  function getProxyUrlFromRunOptions(runOptions) {
154
176
  if ((runOptions === null || runOptions === void 0 ? void 0 : runOptions.environment) !== "deployed") return undefined;
155
177
  const proxy = runOptions.proxy;
@@ -158,4 +180,7 @@ function getProxyUrlFromRunOptions(runOptions) {
158
180
  url.username = proxy.username;
159
181
  url.password = proxy.password;
160
182
  return url.toString();
183
+ }
184
+ if (require.main === module) {
185
+ runAutomationCLI();
161
186
  }
@@ -5,17 +5,19 @@ var ts = _interopRequireWildcard(require("typescript"));
5
5
  var _commander = require("commander");
6
6
  var fs = _interopRequireWildcard(require("fs-extra"));
7
7
  var path = _interopRequireWildcard(require("path"));
8
- var _webTemplate = require("./common/utils/webTemplate");
8
+ var _template = require("./common/utils/template");
9
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
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
- _commander.program.description("Check TypeScript types in the project").allowUnknownOption().action(async () => {
12
- await (0, _webTemplate.moveWebTemplateFiles)();
11
+ _commander.program.description("Check TypeScript types in the project").option("-t, --template <type>", "template to use", "WebTemplate").allowUnknownOption().action(async ({
12
+ template
13
+ }) => {
14
+ await (0, _template.moveTemplateFiles)(template);
13
15
  const templateTsConfig = path.resolve(__dirname, "..", "..", "template.tsconfig.json");
14
- await fs.copy(templateTsConfig, "./intuned/WebTemplate/tsconfig.json");
15
- checkTypes();
16
+ await fs.copy(templateTsConfig, `./intuned/${template}/tsconfig.json`);
17
+ checkTypes(template);
16
18
  });
17
- function checkTypes() {
18
- const configPath = ts.findConfigFile("./intuned/WebTemplate", ts.sys.fileExists, "tsconfig.json");
19
+ function checkTypes(template) {
20
+ const configPath = ts.findConfigFile(`./intuned/${template}`, ts.sys.fileExists, "tsconfig.json");
19
21
  if (!configPath) {
20
22
  console.error("Could not find a valid 'tsconfig.json'.");
21
23
  process.exit(1);
@@ -0,0 +1,2 @@
1
+ import { ZodError } from "zod";
2
+ export declare function formatZodError(zodError: ZodError): string[];
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.formatZodError = formatZodError;
7
+ function formatZodError(zodError) {
8
+ const formattedErrors = zodError.errors.map(error => {
9
+ const path = error.path.map(segment => {
10
+ return typeof segment === "number" ? `[${segment}]` : segment;
11
+ }).join(".");
12
+ if (path) {
13
+ return `${path} is invalid - ${error.message}`;
14
+ }
15
+ return error.message;
16
+ });
17
+ return formattedErrors;
18
+ }
@@ -151,7 +151,11 @@ async function loadSessionToContext({
151
151
  }) {
152
152
  let sessionToLoad;
153
153
  if (session.type === "state") {
154
- sessionToLoad = session.state;
154
+ const state = session.state;
155
+ if (state === undefined || state === null) {
156
+ return;
157
+ }
158
+ sessionToLoad = state;
155
159
  } else {
156
160
  const fullPath = (0, _fileUtils.getFullPathInProject)(session.path);
157
161
  sessionToLoad = await fs.readJson(fullPath);
@@ -1,5 +1,5 @@
1
1
  import { RunAutomationResponse } from "./types";
2
- import { RunErrorOptions } from "src/runtime/export";
2
+ import { RunErrorOptions } from "../../runtime/export";
3
3
  export declare const apiNotFoundErrorCode = "APINotFoundError";
4
4
  export declare const invalidApiErrorCode = "InvalidAPIError";
5
5
  export declare const invalidCheckErrorCode = "InvalidCheckError";
@@ -9,7 +9,8 @@ export declare const authCheckNotFoundErrorCode = "AuthCheckNotFoundError";
9
9
  export declare const authCheckFailedErrorCode = "AuthCheckFailedError";
10
10
  export declare const maxLevelsExceededErrorCode = "MaxLevelsExceededError";
11
11
  export declare const automationError = "AutomationError";
12
- export declare const runAutomationErrorCodes: readonly ["APINotFoundError", "InvalidAPIError", "InvalidCheckError", "AbortedError", "AuthRequiredError", "AuthCheckNotFoundError", "AuthCheckFailedError", "MaxLevelsExceededError", "AutomationError"];
12
+ export declare const internalInvalidInputErrorCode = "InternalInvalidInputError";
13
+ export declare const runAutomationErrorCodes: readonly ["APINotFoundError", "InvalidAPIError", "InvalidCheckError", "AbortedError", "AuthRequiredError", "AuthCheckNotFoundError", "AuthCheckFailedError", "MaxLevelsExceededError", "AutomationError", "InternalInvalidInputError"];
13
14
  export type RunAutomationErrorCode = (typeof runAutomationErrorCodes)[number];
14
15
  export declare abstract class RunAutomationError<T = any> {
15
16
  code: RunAutomationErrorCode;
@@ -20,7 +21,7 @@ export declare abstract class RunAutomationError<T = any> {
20
21
  details?: T;
21
22
  get apiResponse(): RunAutomationResponse;
22
23
  get json(): {
23
- code: "APINotFoundError" | "InvalidAPIError" | "InvalidCheckError" | "AbortedError" | "AuthRequiredError" | "AuthCheckNotFoundError" | "AuthCheckFailedError" | "MaxLevelsExceededError" | "AutomationError";
24
+ code: "APINotFoundError" | "InvalidAPIError" | "InvalidCheckError" | "AbortedError" | "AuthRequiredError" | "AuthCheckNotFoundError" | "AuthCheckFailedError" | "MaxLevelsExceededError" | "AutomationError" | "InternalInvalidInputError";
24
25
  details: T | undefined;
25
26
  cause: any;
26
27
  };
@@ -69,3 +70,7 @@ export declare class AutomationError extends RunAutomationError<{
69
70
  error: any;
70
71
  constructor(error: any);
71
72
  }
73
+ export declare class InternalInvalidInputError extends RunAutomationError {
74
+ constructor(message: string, details?: any);
75
+ get apiResponse(): RunAutomationResponse;
76
+ }
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
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;
6
+ exports.runAutomationErrorCodes = exports.maxLevelsExceededErrorCode = exports.invalidCheckErrorCode = exports.invalidApiErrorCode = exports.internalInvalidInputErrorCode = exports.automationError = exports.authRequiredErrorCode = exports.authCheckNotFoundErrorCode = exports.authCheckFailedErrorCode = exports.apiNotFoundErrorCode = exports.abortedErrorCode = exports.RunAutomationError = exports.MaxLevelsExceededError = exports.InvalidCheckError = exports.InvalidApiError = exports.InternalInvalidInputError = exports.AutomationError = exports.AuthRequiredError = exports.AuthCheckNotFoundError = exports.AuthCheckFailedError = exports.ApiNotFoundError = exports.AbortedError = void 0;
7
7
  var _runtime = require("../../runtime");
8
8
  var playwright = _interopRequireWildcard(require("@intuned/playwright-core"));
9
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); }
@@ -17,7 +17,8 @@ const authCheckNotFoundErrorCode = exports.authCheckNotFoundErrorCode = "AuthChe
17
17
  const authCheckFailedErrorCode = exports.authCheckFailedErrorCode = "AuthCheckFailedError";
18
18
  const maxLevelsExceededErrorCode = exports.maxLevelsExceededErrorCode = "MaxLevelsExceededError";
19
19
  const automationError = exports.automationError = "AutomationError";
20
- const runAutomationErrorCodes = exports.runAutomationErrorCodes = [apiNotFoundErrorCode, invalidApiErrorCode, invalidCheckErrorCode, abortedErrorCode, authRequiredErrorCode, authCheckNotFoundErrorCode, authCheckFailedErrorCode, maxLevelsExceededErrorCode, automationError];
20
+ const internalInvalidInputErrorCode = exports.internalInvalidInputErrorCode = "InternalInvalidInputError";
21
+ const runAutomationErrorCodes = exports.runAutomationErrorCodes = [apiNotFoundErrorCode, invalidApiErrorCode, invalidCheckErrorCode, abortedErrorCode, authRequiredErrorCode, authCheckNotFoundErrorCode, authCheckFailedErrorCode, maxLevelsExceededErrorCode, automationError, internalInvalidInputErrorCode];
21
22
  class RunAutomationError {
22
23
  wrapped = false;
23
24
  get apiResponse() {
@@ -92,6 +93,7 @@ class AuthRequiredError extends RunAutomationError {
92
93
  this.code = authRequiredErrorCode;
93
94
  this.statusCode = 401;
94
95
  this.message = "Authentication is required";
96
+ this.wrapped = true;
95
97
  }
96
98
  }
97
99
  exports.AuthRequiredError = AuthRequiredError;
@@ -110,6 +112,7 @@ class AuthCheckFailedError extends RunAutomationError {
110
112
  this.code = authCheckFailedErrorCode;
111
113
  this.statusCode = 401;
112
114
  this.message = "auth session check failed";
115
+ this.wrapped = true;
113
116
  }
114
117
  get apiResponse() {
115
118
  return {
@@ -169,4 +172,24 @@ class AutomationError extends RunAutomationError {
169
172
  };
170
173
  }
171
174
  }
172
- exports.AutomationError = AutomationError;
175
+ exports.AutomationError = AutomationError;
176
+ class InternalInvalidInputError extends RunAutomationError {
177
+ constructor(message, details) {
178
+ super();
179
+ this.code = internalInvalidInputErrorCode;
180
+ this.statusCode = 500;
181
+ this.message = message;
182
+ this.details = details;
183
+ }
184
+ get apiResponse() {
185
+ return {
186
+ status: 500,
187
+ body: {
188
+ error: "InternalServerError",
189
+ message: `Internal error: ${this.message}. Please report this issue to the Intuned team.`,
190
+ details: this.details
191
+ }
192
+ };
193
+ }
194
+ }
195
+ exports.InternalInvalidInputError = InternalInvalidInputError;
@@ -9,4 +9,4 @@ export declare function runApiGenerator<ResultType = any, _YieldType = any, _Nex
9
9
  }): AsyncGenerator<_YieldType, RunApiResult<ResultType, RunApiResultWithSessionOk>, _NextType>;
10
10
  export declare function runApiGenerator<ResultType = any, _YieldType = any, _NextType = any>(params: ExtendedRunApiParameters): AsyncGenerator<_YieldType, RunApiResult<ResultType>, _NextType>;
11
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>>;
12
+ export declare function checkAuthSessionWithRetries(page: Page, context: BrowserContext, importFunction: ExtendedRunApiParameters["importFunction"], retries?: number): Promise<Result<boolean, RunAutomationError>>;
@@ -15,7 +15,6 @@ var _downloadDirectory = require("../../runtime/downloadDirectory");
15
15
  var _asyncLocalStorage = require("../asyncLocalStorage");
16
16
  var _fsExtra = _interopRequireWildcard(require("fs-extra"));
17
17
  var fs = _fsExtra;
18
- var _jwtTokenManager = require("../jwtTokenManager");
19
18
  var _contextStorageStateHelpers = require("../contextStorageStateHelpers");
20
19
  var _neverthrow = require("neverthrow");
21
20
  var _errors = require("./errors");
@@ -44,26 +43,32 @@ Object.keys(_types).forEach(function (key) {
44
43
  }
45
44
  });
46
45
  });
46
+ var _formatZodError = require("../formatZodError");
47
+ var _cleanEnvironmentVariables = require("../cleanEnvironmentVariables");
47
48
  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
49
  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
50
  async function* runApiGenerator({
50
51
  retrieveSession = false,
51
52
  abortSignal,
53
+ importFunction,
52
54
  ...input
53
55
  }) {
54
56
  let traceStarted = false;
57
+ const inputParseResult = _types.runApiParametersSchema.safeParse(input);
58
+ if (!inputParseResult.success) {
59
+ return (0, _neverthrow.err)(new _errors.InternalInvalidInputError("Input validation failed", (0, _formatZodError.formatZodError)(inputParseResult.error)));
60
+ }
55
61
  const {
56
62
  automationFunction,
57
63
  runOptions,
58
64
  tracing,
59
- auth,
60
- functionsToken
65
+ auth
61
66
  } = _types.runApiParametersSchema.parse(input);
62
- _jwtTokenManager.backendFunctionsTokenManager.token = functionsToken;
63
- const downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
64
67
  let page;
65
68
  let context;
69
+ let downloadsPath;
66
70
  if (runOptions.environment === "deployed") {
71
+ downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
67
72
  const {
68
73
  headless,
69
74
  proxy
@@ -87,10 +92,6 @@ async function* runApiGenerator({
87
92
  context
88
93
  } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, cdpAddress, auth === null || auth === void 0 ? void 0 : auth.session));
89
94
  }
90
- const executionContext = (0, _asyncLocalStorage.getExecutionContext)();
91
- if (!executionContext) {
92
- throw "";
93
- }
94
95
  async function saveTraceIfNeeded({
95
96
  errorMessage
96
97
  }) {
@@ -122,18 +123,20 @@ async function* runApiGenerator({
122
123
  });
123
124
  });
124
125
  if (auth && auth.session.type === "state") {
125
- await (0, _contextStorageStateHelpers.setContextStorageState)(context, auth.session.state);
126
+ const state = auth.session.state;
127
+ if (state === undefined || state === null) {
128
+ return (0, _neverthrow.err)(new _errors.AuthRequiredError());
129
+ }
130
+ await (0, _contextStorageStateHelpers.setContextStorageState)(context, state);
126
131
  }
127
132
  async function* runAutomation() {
128
133
  var _getExecutionContext;
129
134
  if (auth !== null && auth !== void 0 && auth.runCheck) {
130
135
  if (!auth.session) {
131
- return (0, _neverthrow.err)({
132
- code: "AuthRequiredError"
133
- });
136
+ return (0, _neverthrow.err)(new _errors.AuthRequiredError());
134
137
  }
135
138
  console.log("Running auth check");
136
- const authCheckResult = await checkAuthSessionWithRetries(page, context, 2);
139
+ const authCheckResult = await checkAuthSessionWithRetries(page, context, importFunction, 2);
137
140
  if (authCheckResult.isErr()) {
138
141
  const error = authCheckResult.error;
139
142
  if (["APINotFoundError", "InvalidAPIError"].includes(error.code)) {
@@ -142,20 +145,18 @@ async function* runApiGenerator({
142
145
  return authCheckResult;
143
146
  }
144
147
  if (!authCheckResult.value) {
145
- return (0, _neverthrow.err)({
146
- code: "AuthCheckFailedError"
147
- });
148
+ return (0, _neverthrow.err)(new _errors.AuthCheckFailedError());
148
149
  }
149
150
  }
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;
151
+ (0, _cleanEnvironmentVariables.cleanEnvironmentVariables)();
152
+ const args = [...(automationFunction.params !== undefined ? [automationFunction.params] : []), page, context];
153
+ const validatedModuleResult = await importUsingImportFunction(automationFunction.name, importFunction);
154
+ if (validatedModuleResult.isErr()) {
155
+ return validatedModuleResult;
155
156
  }
156
157
  let result;
157
- if (importResult.value.type === "async-generator") {
158
- const generator = importResult.value.generator(...args);
158
+ if (validatedModuleResult.value.type === "async-generator") {
159
+ const generator = validatedModuleResult.value.generator(...args);
159
160
  let next = undefined;
160
161
  while (true) {
161
162
  const generatorResult = await generator.next(...(next ? [next] : []));
@@ -167,7 +168,7 @@ async function* runApiGenerator({
167
168
  break;
168
169
  }
169
170
  } else {
170
- result = await importResult.value.func(...args);
171
+ result = await validatedModuleResult.value.func(...args);
171
172
  }
172
173
  return (0, _neverthrow.ok)({
173
174
  result,
@@ -190,14 +191,15 @@ async function* runApiGenerator({
190
191
  return result.value;
191
192
  }
192
193
  } catch (error) {
193
- console.log("run errored", error);
194
194
  return (0, _neverthrow.err)(new _errors.AutomationError(error));
195
195
  } finally {
196
196
  await saveTraceIfNeeded({
197
197
  errorMessage: "failed to save trace"
198
198
  });
199
199
  await context.close();
200
- await fs.remove(downloadsPath);
200
+ if (downloadsPath !== undefined) {
201
+ await fs.remove(downloadsPath);
202
+ }
201
203
  }
202
204
  }
203
205
  async function runApi(params) {
@@ -211,13 +213,13 @@ async function runApi(params) {
211
213
  }
212
214
  return (0, _neverthrow.err)(new _errors.InvalidApiError("Expected API to be async function, got async generator"));
213
215
  }
214
- async function checkAuthSessionWithRetries(page, context, retries = 3) {
216
+ async function checkAuthSessionWithRetries(page, context, importFunction, retries = 3) {
215
217
  if (retries === 0) {
216
218
  return (0, _neverthrow.ok)(false);
217
219
  }
218
220
  let tryNumber = 0;
219
221
  console.log("Checking auth session with retries", `${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
220
- const importResult = await importFunction(`${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
222
+ const importResult = await importUsingImportFunction(`${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`, importFunction);
221
223
  if (importResult.isErr()) {
222
224
  return (0, _neverthrow.err)(importResult.error);
223
225
  }
@@ -232,33 +234,9 @@ async function checkAuthSessionWithRetries(page, context, retries = 3) {
232
234
  }
233
235
  return (0, _neverthrow.ok)(false);
234
236
  }
235
- async function importFunction(path) {
236
- const functionNameParts = path.split("/");
237
- const functionNameDepth = functionNameParts.length;
237
+ async function importUsingImportFunction(path, importFunction) {
238
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
- }
239
+ const imported = importFunction ? await importFunction(path) : await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`./${path}.ts`);
262
240
  if (!imported || !imported.default || !imported.default.constructor) {
263
241
  return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default export"));
264
242
  }