@intuned/runtime 1.3.0 → 1.3.2

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 (51) hide show
  1. package/WebTemplate.zip +0 -0
  2. package/dist/commands/api/run.js +5 -3
  3. package/dist/commands/auth-sessions/load.js +3 -3
  4. package/dist/commands/auth-sessions/run-check.js +1 -2
  5. package/dist/commands/auth-sessions/run-create.js +12 -35
  6. package/dist/commands/interface/run.d.ts +1 -1
  7. package/dist/commands/interface/run.js +14 -40
  8. package/dist/commands/intuned-cli/commands/deploy.command.js +6 -9
  9. package/dist/commands/intuned-cli/commands/index.d.ts +1 -0
  10. package/dist/commands/intuned-cli/commands/index.js +11 -0
  11. package/dist/commands/intuned-cli/commands/run_authsession.command.d.ts +2 -1
  12. package/dist/commands/intuned-cli/commands/save.command.d.ts +12 -0
  13. package/dist/commands/intuned-cli/commands/save.command.js +46 -0
  14. package/dist/commands/intuned-cli/commands/types.d.ts +1 -1
  15. package/dist/commands/intuned-cli/controller/__test__/api.test.js +1 -2
  16. package/dist/commands/intuned-cli/controller/api.js +1 -2
  17. package/dist/commands/intuned-cli/controller/authSession.js +3 -4
  18. package/dist/commands/intuned-cli/controller/deploy.d.ts +1 -12
  19. package/dist/commands/intuned-cli/controller/deploy.js +9 -284
  20. package/dist/commands/intuned-cli/controller/save.d.ts +14 -0
  21. package/dist/commands/intuned-cli/controller/save.js +364 -0
  22. package/dist/commands/intuned-cli/helpers/backend.js +4 -3
  23. package/dist/commands/intuned-cli/helpers/errors.d.ts +2 -2
  24. package/dist/commands/intuned-cli/helpers/errors.js +8 -4
  25. package/dist/commands/intuned-cli/main.js +7 -0
  26. package/dist/common/asyncLocalStorage/index.d.ts +1 -0
  27. package/dist/common/constants.d.ts +6 -0
  28. package/dist/common/constants.js +8 -2
  29. package/dist/common/jwtTokenManager.d.ts +1 -0
  30. package/dist/common/jwtTokenManager.js +37 -7
  31. package/dist/common/playwrightContext.d.ts +54 -0
  32. package/dist/common/{getPlaywrightConstructs.js → playwrightContext.js} +148 -79
  33. package/dist/common/runApi/importUsingImportFunction.d.ts +9 -0
  34. package/dist/common/runApi/importUsingImportFunction.js +46 -0
  35. package/dist/common/runApi/index.d.ts +2 -7
  36. package/dist/common/runApi/index.js +93 -178
  37. package/dist/common/runApi/types.d.ts +3 -7
  38. package/dist/common/runApi/types.js +1 -2
  39. package/dist/common/setupContextHook.d.ts +17 -0
  40. package/dist/common/setupContextHook.js +22 -0
  41. package/dist/index.d.ts +2 -2
  42. package/dist/index.js +13 -19
  43. package/dist/runtime/attemptStore.d.ts +2 -0
  44. package/dist/runtime/attemptStore.js +23 -0
  45. package/dist/runtime/export.d.ts +51 -41
  46. package/dist/runtime/index.d.ts +1 -2
  47. package/dist/runtime/index.js +7 -13
  48. package/package.json +3 -1
  49. package/dist/common/getPlaywrightConstructs.d.ts +0 -30
  50. package/dist/runtime/requestMoreInfo.d.ts +0 -18
  51. package/dist/runtime/requestMoreInfo.js +0 -25
@@ -0,0 +1,364 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.projectNameSchema = void 0;
7
+ exports.runSaveProject = runSaveProject;
8
+ exports.validateProjectName = exports.validateIntunedProject = void 0;
9
+ var fs = _interopRequireWildcard(require("fs-extra"));
10
+ var path = _interopRequireWildcard(require("path"));
11
+ var _minimatch = require("minimatch");
12
+ var _zod = require("zod");
13
+ var _projectExclusions = _interopRequireDefault(require("../../common/projectExclusions"));
14
+ var _constants = require("../constants");
15
+ var _helpers = require("../helpers");
16
+ var _lodash = require("lodash");
17
+ var _uuid = require("uuid");
18
+ var _terminal = require("../helpers/terminal");
19
+ var _build = require("./build");
20
+ var dotenv = _interopRequireWildcard(require("dotenv"));
21
+ var _constants2 = require("../../../common/constants");
22
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
23
+ 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); }
24
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
25
+ const saveProjectApiResponseSchema = _zod.z.string().transform((val, ctx) => {
26
+ try {
27
+ return JSON.parse(val);
28
+ } catch (e) {
29
+ ctx.addIssue({
30
+ code: _zod.z.ZodIssueCode.custom,
31
+ message: "Response is not valid JSON"
32
+ });
33
+ return _zod.z.NEVER;
34
+ }
35
+ }).pipe(_zod.z.object({
36
+ id: _zod.z.string().uuid()
37
+ }));
38
+ async function runSaveProject(projectName, auth) {
39
+ const {
40
+ workspaceId,
41
+ apiKey
42
+ } = auth;
43
+ const baseUrl = (0, _helpers.getBaseUrl)();
44
+ const url = `${baseUrl}/api/v1/workspace/${workspaceId}/projects/${projectName}`;
45
+ const headers = {
46
+ [_constants2.API_KEY_HEADER_NAME]: apiKey,
47
+ "Content-Type": "application/json"
48
+ };
49
+ const projectPath = process.cwd();
50
+ const codeTree = await convertProjectToCodeTree(projectPath);
51
+ codeTree["tsconfig.json"] = {
52
+ file: {
53
+ contents: JSON.stringify(_constants.tsConfigCli, null, 2)
54
+ }
55
+ };
56
+ const saveProjectPayload = {
57
+ codeTree,
58
+ platformType: "CLI",
59
+ language: "typescript"
60
+ };
61
+ const response = await fetch(url, {
62
+ headers,
63
+ method: "PUT",
64
+ body: JSON.stringify(saveProjectPayload)
65
+ });
66
+ if (!response.ok) {
67
+ if (response.status === 401) {
68
+ throw new _helpers.CLIError(`Invalid API key. Please check your API key and try again.`);
69
+ }
70
+ throw new _helpers.CLIError(`^r^+Invalid response from server\n^:^R${response.status} ${await response.text()}^:\n^r^+Project save failed^:\n`, {
71
+ autoColor: false
72
+ });
73
+ }
74
+ (0, _terminal.terminal)("^g^+Project saved successfully!^:\n");
75
+ const body = await response.text();
76
+ const parseResult = saveProjectApiResponseSchema.safeParse(body);
77
+ if (!parseResult.success) {
78
+ (0, _terminal.terminal)(`^yWarning: Could not parse save project response:^:\n`);
79
+ (0, _terminal.terminal)(body + "\n");
80
+ return;
81
+ }
82
+ const {
83
+ id: projectId
84
+ } = parseResult.data;
85
+ const dotEnvPath = path.join(projectPath, ".env");
86
+ if (!(await fs.exists(dotEnvPath))) {
87
+ await fs.writeFile(dotEnvPath, `${_constants2.PROJECT_ID_ENV_VAR_KEY}=${projectId}
88
+ ${_constants2.WORKSPACE_ID_ENV_VAR_KEY}=${workspaceId}
89
+ ${_constants2.API_KEY_ENV_VAR_KEY}=${apiKey}`);
90
+ (0, _terminal.terminal)(`^g^+Created .env file with project credentials.^:\n`);
91
+ }
92
+ const envContent = await fs.readFile(dotEnvPath, "utf-8");
93
+ const dotenvContent = dotenv.parse(envContent);
94
+ let contentToAppend = "";
95
+ if (!dotenvContent[_constants2.PROJECT_ID_ENV_VAR_KEY] || dotenvContent[_constants2.PROJECT_ID_ENV_VAR_KEY] !== projectId) {
96
+ contentToAppend += `\n${_constants2.PROJECT_ID_ENV_VAR_KEY}=${projectId}`;
97
+ }
98
+ if (!dotenvContent[_constants2.WORKSPACE_ID_ENV_VAR_KEY]) {
99
+ contentToAppend += `\n${_constants2.WORKSPACE_ID_ENV_VAR_KEY}=${workspaceId}`;
100
+ }
101
+ if (!dotenvContent[_constants2.API_KEY_ENV_VAR_KEY]) {
102
+ contentToAppend += `\n${_constants2.API_KEY_ENV_VAR_KEY}=${apiKey}`;
103
+ }
104
+ if (contentToAppend) {
105
+ await fs.appendFile(dotEnvPath, contentToAppend + "\n");
106
+ (0, _terminal.terminal)(`^g^+Updated .env file with project credentials.^:\n`);
107
+ }
108
+ }
109
+ const projectNameSchema = exports.projectNameSchema = _zod.z.string().min(1, "Project Name is required").max(50, "Name must be 50 characters or less").regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/, "Name can only contain lowercase letters, numbers, hyphens, and underscores in between").refine(value => !_zod.z.string().uuid().safeParse(value).success, {
110
+ message: "Name cannot be a UUID"
111
+ });
112
+ const validateProjectName = projectName => {
113
+ const validation = projectNameSchema.safeParse(projectName);
114
+ if (!validation.success) {
115
+ return {
116
+ isValid: false,
117
+ errorMessage: validation.error.errors[0].message
118
+ };
119
+ }
120
+ return {
121
+ isValid: true
122
+ };
123
+ };
124
+ exports.validateProjectName = validateProjectName;
125
+ const validateIntunedProject = async () => {
126
+ const currentDirectoryToSave = process.cwd();
127
+ const validationSteps = [{
128
+ name: "build",
129
+ check: async () => {
130
+ try {
131
+ const buildResult = await (0, _build.runBuild)();
132
+ if (!buildResult) {
133
+ return {
134
+ isValid: false,
135
+ errorMessage: "Build failed"
136
+ };
137
+ }
138
+ return {
139
+ isValid: true
140
+ };
141
+ } catch (error) {
142
+ return {
143
+ isValid: false,
144
+ errorMessage: "Build failed"
145
+ };
146
+ }
147
+ }
148
+ }, {
149
+ name: "package.json",
150
+ check: async () => {
151
+ try {
152
+ const packageJsonPath = path.join(currentDirectoryToSave, "package.json");
153
+ await fs.exists(packageJsonPath);
154
+ const packageJson = JSON.parse(await fs.readFile(packageJsonPath, {
155
+ encoding: "utf-8"
156
+ }));
157
+ const userCodePlaywrightVersion = packageJson.dependencies?.playwright;
158
+ if (userCodePlaywrightVersion !== _constants.CURRENT_PLAYWRIGHT_VERSION) {
159
+ return {
160
+ isValid: false,
161
+ errorMessage: `Playwright version mismatch: expected ${_constants.CURRENT_PLAYWRIGHT_VERSION}, found ${userCodePlaywrightVersion || "none"}`
162
+ };
163
+ }
164
+ return {
165
+ isValid: true
166
+ };
167
+ } catch (error) {
168
+ return {
169
+ isValid: false,
170
+ errorMessage: "Package.json file not found or cannot be read"
171
+ };
172
+ }
173
+ }
174
+ }, {
175
+ name: "Intuned.json",
176
+ check: async () => {
177
+ try {
178
+ const intunedJsonPath = path.join(currentDirectoryToSave, "Intuned.json");
179
+ await fs.exists(intunedJsonPath);
180
+ return {
181
+ isValid: true
182
+ };
183
+ } catch (error) {
184
+ return {
185
+ isValid: false,
186
+ errorMessage: "Intuned.json file not found"
187
+ };
188
+ }
189
+ }
190
+ }, {
191
+ name: "api folder",
192
+ check: async () => {
193
+ try {
194
+ const apiFolderPath = path.join(currentDirectoryToSave, "api");
195
+ await fs.access(apiFolderPath);
196
+ return {
197
+ isValid: true
198
+ };
199
+ } catch (error) {
200
+ return {
201
+ isValid: false,
202
+ errorMessage: "API folder not found"
203
+ };
204
+ }
205
+ }
206
+ }];
207
+ for (const step of validationSteps) {
208
+ const result = await step.check();
209
+ if (!result.isValid) {
210
+ return result;
211
+ }
212
+ }
213
+ return {
214
+ isValid: true
215
+ };
216
+ };
217
+ exports.validateIntunedProject = validateIntunedProject;
218
+ function ignoreFilesByPattern(filePath, patterns, projectPath) {
219
+ const relativePath = path.relative(projectPath, filePath);
220
+ if (relativePath.startsWith("node_modules")) {
221
+ return true;
222
+ }
223
+ for (const pattern of patterns) {
224
+ if (!pattern || pattern.startsWith("#")) continue;
225
+ if (pattern.startsWith("!")) {
226
+ if ((0, _minimatch.minimatch)(relativePath, pattern.substring(1))) {
227
+ return false;
228
+ }
229
+ } else if ((0, _minimatch.minimatch)(relativePath, pattern)) {
230
+ return true;
231
+ }
232
+ }
233
+ return false;
234
+ }
235
+ function listFilesNotIgnored(projectPath, ignorePatterns) {
236
+ const results = [];
237
+ function traverseDirectory(dirPath) {
238
+ try {
239
+ const entries = fs.readdirSync(dirPath);
240
+ for (const entry of entries) {
241
+ const fullPath = path.join(dirPath, entry);
242
+ if (ignoreFilesByPattern(fullPath, ignorePatterns, projectPath)) {
243
+ continue;
244
+ }
245
+ try {
246
+ const stats = fs.statSync(fullPath);
247
+ if (stats.isDirectory()) {
248
+ traverseDirectory(fullPath);
249
+ } else if (stats.isFile()) {
250
+ results.push(path.relative(projectPath, fullPath));
251
+ }
252
+ } catch (error) {
253
+ (0, _terminal.terminal)(`^yWarning: Could not access ${fullPath}^:\n`);
254
+ }
255
+ }
256
+ } catch (error) {
257
+ (0, _terminal.terminal)(`^YWarning: Could not read directory ${dirPath}^:\n`);
258
+ }
259
+ }
260
+ traverseDirectory(projectPath);
261
+ return results;
262
+ }
263
+ async function convertProjectToCodeTree(projectPath) {
264
+ const filesToSave = listFilesNotIgnored(projectPath, _projectExclusions.default);
265
+ const filesToSaveText = " " + filesToSave.join("\n ");
266
+ (0, _terminal.terminal)("^CFiles to be saved:^:\n");
267
+ (0, _terminal.terminal)(filesToSaveText + "\n");
268
+ function readDirectory(dirPath) {
269
+ const tree = {};
270
+ try {
271
+ const entries = fs.readdirSync(dirPath);
272
+ for (const entry of entries) {
273
+ const entryPath = path.join(dirPath, entry);
274
+ if (ignoreFilesByPattern(entryPath, _projectExclusions.default, projectPath)) {
275
+ continue;
276
+ }
277
+ try {
278
+ const stats = fs.statSync(entryPath);
279
+ if (stats.isFile()) {
280
+ try {
281
+ const content = fs.readFileSync(entryPath, "utf-8");
282
+ tree[entry] = {
283
+ file: {
284
+ contents: content
285
+ }
286
+ };
287
+ } catch (error) {
288
+ (0, _terminal.terminal)(`^yWarning: Could not read file ${entryPath}^:\n`);
289
+ }
290
+ } else if (stats.isDirectory()) {
291
+ const subTree = readDirectory(entryPath);
292
+ if (Object.keys(subTree).length > 0) {
293
+ tree[entry] = {
294
+ directory: subTree
295
+ };
296
+ }
297
+ }
298
+ } catch (error) {
299
+ (0, _terminal.terminal)(`^yWarning: Could not access ${entryPath}^:\n`);
300
+ }
301
+ }
302
+ } catch (error) {
303
+ (0, _terminal.terminal)(`^YWarning: Could not read directory ${dirPath}^:\n`);
304
+ }
305
+ return tree;
306
+ }
307
+ const tree = readDirectory(projectPath);
308
+ mapToIDEParams(tree);
309
+ return tree;
310
+ }
311
+ function mapToIDEParams(tree) {
312
+ if (!tree) {
313
+ return;
314
+ }
315
+ if (!tree["parameters"] || "file" in tree["parameters"]) {
316
+ return;
317
+ }
318
+ const apiParametersMap = {};
319
+ const cliParameters = Object.keys(tree["parameters"].directory);
320
+ const ____testParameters = {
321
+ directory: {}
322
+ };
323
+ for (const parameterKey of cliParameters) {
324
+ const parameter = tree["parameters"].directory[parameterKey];
325
+ if ("directory" in parameter) {
326
+ continue;
327
+ }
328
+ if ((0, _lodash.isEmpty)(parameter.file.contents)) {
329
+ continue;
330
+ }
331
+ const parameterPayload = JSON.parse(parameter.file.contents);
332
+ if (!parameterPayload["__api-name"]) {
333
+ continue;
334
+ }
335
+ const api = parameterPayload["__api-name"];
336
+ const {
337
+ "__api-name": _,
338
+ ...parameterValue
339
+ } = parameterPayload;
340
+ const testParameter = {
341
+ name: parameterKey.replace(".json", ""),
342
+ lastUsed: false,
343
+ id: (0, _uuid.v4)(),
344
+ value: JSON.stringify(parameterValue)
345
+ };
346
+ if (!apiParametersMap[api]) {
347
+ apiParametersMap[api] = [];
348
+ }
349
+ apiParametersMap[api].push(testParameter);
350
+ }
351
+ for (const api in apiParametersMap) {
352
+ if (apiParametersMap[api].length > 0) {
353
+ apiParametersMap[api][apiParametersMap[api].length - 1].lastUsed = true;
354
+ }
355
+ ____testParameters.directory[`${api}.json`] = {
356
+ file: {
357
+ contents: JSON.stringify(apiParametersMap[api], null, 2)
358
+ }
359
+ };
360
+ }
361
+ delete tree["parameters"];
362
+ tree["____testParameters"] = ____testParameters;
363
+ return;
364
+ }
@@ -5,16 +5,17 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.getAuthCredentials = getAuthCredentials;
7
7
  exports.getBaseUrl = getBaseUrl;
8
+ var _constants = require("../../../common/constants");
8
9
  var _errors = require("./errors");
9
10
  var _intunedJson = require("./intunedJson");
10
11
  async function getAuthCredentials(options) {
11
12
  const workspaceId = options.workspaceId || (await (0, _intunedJson.getSettingIntunedJSON)("workspaceId"));
12
- const apiKey = options.apiKey || process.env.INTUNED_API_KEY;
13
+ const apiKey = options.apiKey || process.env[_constants.API_KEY_ENV_VAR_KEY];
13
14
  if (!workspaceId) {
14
15
  throw new _errors.CLIError("Workspace ID is required. Please provide it via command line options or Intuned.json");
15
16
  }
16
17
  if (!apiKey) {
17
- throw new _errors.CLIError("API key is required. Please provide it via command line options or INTUNED_API_KEY environment variable.");
18
+ throw new _errors.CLIError(`API key is required. Please provide it via command line options or ${_constants.API_KEY_ENV_VAR_KEY} environment variable.`);
18
19
  }
19
20
  return {
20
21
  workspaceId,
@@ -22,5 +23,5 @@ async function getAuthCredentials(options) {
22
23
  };
23
24
  }
24
25
  function getBaseUrl() {
25
- return process.env.INTUNED_API_BASE_URL || process.env.INTUNED_API_DOMAIN || `https://app.intuned.io`;
26
+ return process.env[_constants.API_BASE_URL_ENV_VAR_KEY] || process.env.INTUNED_API_DOMAIN || `https://app.intuned.io`;
26
27
  }
@@ -1,4 +1,4 @@
1
- import { AutomationError } from "../../../common/runApi";
1
+ import { RunAutomationError } from "../../../common/runApi";
2
2
  export declare class CLIError extends Error {
3
3
  autoColor: boolean;
4
4
  constructor(message: string, options?: {
@@ -10,5 +10,5 @@ export declare class CLIAssertionError extends CLIError {
10
10
  autoColor?: boolean;
11
11
  });
12
12
  }
13
- export declare function logAutomationError(error: AutomationError): void;
13
+ export declare function logAutomationError(error: RunAutomationError): void;
14
14
  export declare function withErrorLogging<T extends any[]>(fn: (...args: T) => Promise<unknown>): (...args: T) => Promise<never>;
@@ -25,11 +25,15 @@ class CLIAssertionError extends CLIError {
25
25
  exports.CLIAssertionError = CLIAssertionError;
26
26
  function logAutomationError(error) {
27
27
  (0, _terminal.terminal)(`^r^+An error occurred while running the API:^:\n`);
28
- if (error.error.stack) {
29
- const stackLines = error.error.stack.split("\n").filter(line => !line.includes("@intuned/runtime") && !line.includes("node:"));
30
- (0, _terminal.terminal)(`^r${stackLines.join("\n")}^:\n`);
28
+ if (error instanceof _runApi.AutomationError) {
29
+ if (error.error.stack) {
30
+ const stackLines = error.error.stack.split("\n").filter(line => !line.includes("@intuned/runtime") && !line.includes("node:"));
31
+ (0, _terminal.terminal)(`^r${stackLines.join("\n")}^:\n`);
32
+ } else {
33
+ (0, _terminal.terminal)(`^r${error.error.message}^:\n`);
34
+ }
31
35
  } else {
32
- (0, _terminal.terminal)(`^r${error.error.message}^:\n`);
36
+ (0, _terminal.terminal)(`^r${error.message}^:\n`);
33
37
  }
34
38
  }
35
39
  function withErrorLogging(fn) {
@@ -1,12 +1,19 @@
1
1
  "use strict";
2
2
 
3
3
  var _dotenv = _interopRequireDefault(require("dotenv"));
4
+ var _constants = require("../../common/constants");
5
+ var _backend = require("./helpers/backend");
4
6
  var _commands = require("./commands");
5
7
  var _helpers = require("./helpers");
6
8
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
7
9
  _dotenv.default.config({
8
10
  path: `.env`
9
11
  });
12
+ process.env[_constants.CLI_ENV_VAR_KEY] = "true";
13
+ process.env.RUN_ENVIRONMENT = "AUTHORING";
14
+ if (!process.env.FUNCTIONS_DOMAIN) {
15
+ process.env.FUNCTIONS_DOMAIN = (0, _backend.getBaseUrl)().replace(/\/$/, "");
16
+ }
10
17
  _commands.program.configureHelp({
11
18
  sortSubcommands: true
12
19
  });
@@ -9,6 +9,7 @@ interface TimeoutInfo {
9
9
  export interface InternalRunInfo extends RunInfo {
10
10
  extendedPayloads: Payload[];
11
11
  timeoutInfo?: TimeoutInfo;
12
+ store?: Record<string, any>;
12
13
  getAuthSessionParameters?: () => Promise<any>;
13
14
  }
14
15
  export declare function getExecutionContext(): InternalRunInfo | undefined;
@@ -1,3 +1,9 @@
1
1
  export declare const API_FOLDER_NAME = "api";
2
2
  export declare const AUTH_SESSIONS_FOLDER_NAME = "auth-sessions";
3
3
  export declare const AUTH_SESSIONS_INSTANCES_FOLDER_NAME = "auth-sessions-instances";
4
+ export declare const WORKSPACE_ID_ENV_VAR_KEY = "INTUNED_WORKSPACE_ID";
5
+ export declare const PROJECT_ID_ENV_VAR_KEY = "INTUNED_PROJECT_ID";
6
+ export declare const API_KEY_ENV_VAR_KEY = "INTUNED_API_KEY";
7
+ export declare const API_KEY_HEADER_NAME = "x-api-key";
8
+ export declare const API_BASE_URL_ENV_VAR_KEY = "INTUNED_API_BASE_URL";
9
+ export declare const CLI_ENV_VAR_KEY = "INTUNED_CLI";
@@ -3,7 +3,13 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.AUTH_SESSIONS_INSTANCES_FOLDER_NAME = exports.AUTH_SESSIONS_FOLDER_NAME = exports.API_FOLDER_NAME = void 0;
6
+ exports.WORKSPACE_ID_ENV_VAR_KEY = exports.PROJECT_ID_ENV_VAR_KEY = exports.CLI_ENV_VAR_KEY = exports.AUTH_SESSIONS_INSTANCES_FOLDER_NAME = exports.AUTH_SESSIONS_FOLDER_NAME = exports.API_KEY_HEADER_NAME = exports.API_KEY_ENV_VAR_KEY = exports.API_FOLDER_NAME = exports.API_BASE_URL_ENV_VAR_KEY = void 0;
7
7
  const API_FOLDER_NAME = exports.API_FOLDER_NAME = "api";
8
8
  const AUTH_SESSIONS_FOLDER_NAME = exports.AUTH_SESSIONS_FOLDER_NAME = "auth-sessions";
9
- const AUTH_SESSIONS_INSTANCES_FOLDER_NAME = exports.AUTH_SESSIONS_INSTANCES_FOLDER_NAME = "auth-sessions-instances";
9
+ const AUTH_SESSIONS_INSTANCES_FOLDER_NAME = exports.AUTH_SESSIONS_INSTANCES_FOLDER_NAME = "auth-sessions-instances";
10
+ const WORKSPACE_ID_ENV_VAR_KEY = exports.WORKSPACE_ID_ENV_VAR_KEY = "INTUNED_WORKSPACE_ID";
11
+ const PROJECT_ID_ENV_VAR_KEY = exports.PROJECT_ID_ENV_VAR_KEY = "INTUNED_PROJECT_ID";
12
+ const API_KEY_ENV_VAR_KEY = exports.API_KEY_ENV_VAR_KEY = "INTUNED_API_KEY";
13
+ const API_KEY_HEADER_NAME = exports.API_KEY_HEADER_NAME = "x-api-key";
14
+ const API_BASE_URL_ENV_VAR_KEY = exports.API_BASE_URL_ENV_VAR_KEY = "INTUNED_API_BASE_URL";
15
+ const CLI_ENV_VAR_KEY = exports.CLI_ENV_VAR_KEY = "INTUNED_CLI";
@@ -10,6 +10,7 @@ declare class JwtTokenManager {
10
10
  private scheduleTokenRefresh;
11
11
  private refreshToken;
12
12
  fetchWithToken(...[input, init]: Parameters<typeof fetch>): Promise<Response>;
13
+ get backendFunctionsBaseUrl(): string | undefined;
13
14
  }
14
15
  export declare const backendFunctionsTokenManager: JwtTokenManager;
15
16
  export declare function callBackendFunctionWithToken(path: string, init?: Parameters<typeof fetch>[1]): Promise<Response>;
@@ -8,6 +8,7 @@ exports.callBackendFunctionWithToken = callBackendFunctionWithToken;
8
8
  var _crossFetch = _interopRequireDefault(require("cross-fetch"));
9
9
  var jwt = _interopRequireWildcard(require("jsonwebtoken"));
10
10
  var _neverthrow = require("neverthrow");
11
+ var _constants = require("./constants");
11
12
  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
13
  function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
13
14
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
@@ -51,7 +52,7 @@ class JwtTokenManager {
51
52
  }
52
53
  async refreshToken() {
53
54
  if (process.env.RUN_ENVIRONMENT?.toLowerCase() !== "authoring") return;
54
- const res = await this.fetchWithToken(this.refreshTokenPath, {
55
+ const res = await this.fetchWithToken(`${this.backendFunctionsBaseUrl}/${this.refreshTokenPath}`, {
55
56
  method: "GET"
56
57
  });
57
58
  if (res.status === 401) {
@@ -62,18 +63,47 @@ class JwtTokenManager {
62
63
  const newToken = jsonResult.value.token;
63
64
  if (newToken) this._token = newToken;
64
65
  }
65
- fetchWithToken(...[input, init]) {
66
+ async fetchWithToken(...[input, init]) {
66
67
  const headers = new Headers(init?.headers);
67
- headers.set("Authorization", `Bearer ${this.token}`);
68
- return (0, _crossFetch.default)(input, {
68
+ if (process.env[_constants.API_KEY_ENV_VAR_KEY]) {
69
+ headers.set(_constants.API_KEY_HEADER_NAME, process.env[_constants.API_KEY_ENV_VAR_KEY]);
70
+ }
71
+ if (this.token !== undefined) {
72
+ headers.set("Authorization", `Bearer ${this.token}`);
73
+ }
74
+ const result = await (0, _crossFetch.default)(input, {
69
75
  ...init,
70
76
  headers
71
77
  });
78
+ if (result.status === 401 && process.env[_constants.CLI_ENV_VAR_KEY] === "true") {
79
+ console.warn("Unauthorized backend function call - make sure to save your project to Intuned to set up the correct API credentials");
80
+ }
81
+ return result;
82
+ }
83
+ get backendFunctionsBaseUrl() {
84
+ try {
85
+ if (!process.env.FUNCTIONS_DOMAIN) {
86
+ throw new Error(`Cannot call backend function - FUNCTIONS_DOMAIN not set`);
87
+ }
88
+ const domain = process.env.FUNCTIONS_DOMAIN;
89
+ if (!process.env[_constants.WORKSPACE_ID_ENV_VAR_KEY]) {
90
+ throw new Error(`Cannot call backend function - ${_constants.WORKSPACE_ID_ENV_VAR_KEY} not set`);
91
+ }
92
+ const workspaceId = process.env[_constants.WORKSPACE_ID_ENV_VAR_KEY];
93
+ if (!process.env[_constants.PROJECT_ID_ENV_VAR_KEY] && !process.env.INTUNED_INTEGRATION_ID) {
94
+ throw new Error(`Cannot call backend function - ${_constants.PROJECT_ID_ENV_VAR_KEY} or INTUNED_INTEGRATION_ID not set`);
95
+ }
96
+ const projectId = process.env.INTUNED_INTEGRATION_ID ?? process.env[_constants.PROJECT_ID_ENV_VAR_KEY];
97
+ return `${domain}/api/${workspaceId}/functions/${projectId}`;
98
+ } catch (e) {
99
+ if (process.env[_constants.CLI_ENV_VAR_KEY] === "true") {
100
+ throw new Error(`API credentials not set - make sure to save your project to Intuned to set up the correct API credentials.\nOriginal error: ${e.message}`);
101
+ }
102
+ }
72
103
  }
73
104
  }
74
- const backendFunctionsPath = `${process.env.FUNCTIONS_DOMAIN}/api/${process.env.INTUNED_WORKSPACE_ID}/functions/${process.env.INTUNED_INTEGRATION_ID}`;
75
- const backendFunctionsTokenManager = exports.backendFunctionsTokenManager = new JwtTokenManager(`${backendFunctionsPath}/refreshBackendFunctionsToken`);
105
+ const backendFunctionsTokenManager = exports.backendFunctionsTokenManager = new JwtTokenManager(`refreshBackendFunctionsToken`);
76
106
  backendFunctionsTokenManager.token = process.env.INTUNED_AUTHORING_SESSION_BACKEND_FUNCTIONS_TOKEN;
77
107
  function callBackendFunctionWithToken(path, init) {
78
- return backendFunctionsTokenManager.fetchWithToken(`${backendFunctionsPath}/${path}`, init);
108
+ return backendFunctionsTokenManager.fetchWithToken(`${backendFunctionsTokenManager.backendFunctionsBaseUrl}/${path}`, init);
79
109
  }
@@ -0,0 +1,54 @@
1
+ import * as playwright from "playwright";
2
+ import { RunAutomationError } from "./runApi/errors";
3
+ import type { RunApiSession } from "./runApi/types";
4
+ import { Err, Ok } from "neverthrow";
5
+ import { type ImportFunction } from "./runApi/importUsingImportFunction";
6
+ export interface Proxy {
7
+ server: string;
8
+ username: string;
9
+ password: string;
10
+ }
11
+ export declare function launchChromium(options: {
12
+ proxy?: Proxy;
13
+ headless: boolean;
14
+ downloadsPath?: string;
15
+ cdpPort?: number;
16
+ }): Promise<{
17
+ page: playwright.Page;
18
+ context: playwright.BrowserContext;
19
+ }>;
20
+ export declare function launchChromium(options: {
21
+ cdpAddress: string;
22
+ }): Promise<{
23
+ page: playwright.Page;
24
+ context: playwright.BrowserContext;
25
+ }>;
26
+ export declare const browserScriptsFile: string;
27
+ type WithPlaywrightContextParameters = {
28
+ importFunction: ImportFunction;
29
+ apiName: string;
30
+ apiParameters: any;
31
+ } | {
32
+ importFunction?: undefined;
33
+ apiName?: undefined;
34
+ apiParameters?: undefined;
35
+ };
36
+ type WithPlaywrightContextWrappedFunctionReturn<R> = Ok<R, any> | Err<any, RunAutomationError>;
37
+ export type WithPlaywrightContextWrappedFunction<R> = (context: playwright.BrowserContext, page: playwright.Page) => Promise<WithPlaywrightContextWrappedFunctionReturn<R>>;
38
+ export declare function withPlaywrightContext<R>(options: {
39
+ proxy?: Proxy;
40
+ headless: boolean;
41
+ downloadsPath: string;
42
+ } & WithPlaywrightContextParameters, fn: WithPlaywrightContextWrappedFunction<R>): Promise<Ok<R, any> | Err<any, RunAutomationError>>;
43
+ export declare function withPlaywrightContext<R>(options: {
44
+ cdpAddress: string;
45
+ } & WithPlaywrightContextParameters, fn: WithPlaywrightContextWrappedFunction<R>): Promise<Ok<R, any> | Err<any, RunAutomationError>>;
46
+ export declare function loadSessionToContext({ context, session, }: {
47
+ context: playwright.BrowserContext;
48
+ session: RunApiSession;
49
+ }): Promise<void>;
50
+ export declare function getRemotePlaywrightContext(cdpAddress: string): Promise<{
51
+ browser: playwright.Browser;
52
+ context: playwright.BrowserContext;
53
+ }>;
54
+ export {};