@intuned/runtime-dev 1.3.1-api-token.5 → 1.3.3-fix.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/commands/api/run.js +5 -3
  2. package/dist/commands/auth-sessions/load.js +3 -3
  3. package/dist/commands/auth-sessions/run-check.js +1 -2
  4. package/dist/commands/auth-sessions/run-create.js +12 -35
  5. package/dist/commands/interface/run.d.ts +1 -1
  6. package/dist/commands/interface/run.js +14 -40
  7. package/dist/commands/intuned-cli/commands/run_authsession.command.d.ts +2 -1
  8. package/dist/commands/intuned-cli/commands/types.d.ts +1 -1
  9. package/dist/commands/intuned-cli/controller/__test__/api.test.js +1 -2
  10. package/dist/commands/intuned-cli/controller/api.js +1 -2
  11. package/dist/commands/intuned-cli/controller/authSession.js +3 -4
  12. package/dist/commands/intuned-cli/controller/save.js +28 -29
  13. package/dist/commands/intuned-cli/helpers/errors.d.ts +2 -2
  14. package/dist/commands/intuned-cli/helpers/errors.js +8 -4
  15. package/dist/commands/intuned-cli/main.js +2 -2
  16. package/dist/common/asyncLocalStorage/index.d.ts +1 -0
  17. package/dist/common/jwtTokenManager.d.ts +1 -1
  18. package/dist/common/jwtTokenManager.js +18 -13
  19. package/dist/common/playwrightContext.d.ts +54 -0
  20. package/dist/common/{getPlaywrightConstructs.js → playwrightContext.js} +148 -79
  21. package/dist/common/runApi/importUsingImportFunction.d.ts +9 -0
  22. package/dist/common/runApi/importUsingImportFunction.js +46 -0
  23. package/dist/common/runApi/index.d.ts +2 -7
  24. package/dist/common/runApi/index.js +92 -177
  25. package/dist/common/runApi/types.d.ts +3 -7
  26. package/dist/common/runApi/types.js +1 -2
  27. package/dist/common/setupContextHook.d.ts +17 -0
  28. package/dist/common/setupContextHook.js +22 -0
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +13 -19
  31. package/dist/runtime/attemptStore.d.ts +2 -0
  32. package/dist/runtime/attemptStore.js +23 -0
  33. package/dist/runtime/export.d.ts +51 -41
  34. package/dist/runtime/index.d.ts +1 -2
  35. package/dist/runtime/index.js +7 -13
  36. package/package.json +3 -1
  37. package/dist/common/getPlaywrightConstructs.d.ts +0 -30
  38. package/dist/runtime/requestMoreInfo.d.ts +0 -18
  39. package/dist/runtime/requestMoreInfo.js +0 -25
@@ -3,10 +3,11 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.getPlaywrightConstructsForMode = getPlaywrightConstructsForMode;
7
- exports.getProductionPlaywrightConstructs = getProductionPlaywrightConstructs;
6
+ exports.browserScriptsFile = void 0;
8
7
  exports.getRemotePlaywrightContext = getRemotePlaywrightContext;
8
+ exports.launchChromium = launchChromium;
9
9
  exports.loadSessionToContext = loadSessionToContext;
10
+ exports.withPlaywrightContext = withPlaywrightContext;
10
11
  var playwright = _interopRequireWildcard(require("playwright"));
11
12
  var _fsExtra = _interopRequireWildcard(require("fs-extra"));
12
13
  var fs = _fsExtra;
@@ -14,7 +15,10 @@ var _contextStorageStateHelpers = require("./contextStorageStateHelpers");
14
15
  var _path = _interopRequireWildcard(require("path"));
15
16
  var _fileUtils = require("../commands/common/utils/fileUtils");
16
17
  var _waitOn = _interopRequireDefault(require("wait-on"));
17
- var _runtime = require("../runtime");
18
+ var _errors = require("./runApi/errors");
19
+ var _neverthrow = require("neverthrow");
20
+ var _setupContextHook = require("./setupContextHook");
21
+ var _portfinder = require("portfinder");
18
22
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
19
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); }
20
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; }
@@ -33,22 +37,39 @@ async function createUserDirWithPreferences() {
33
37
  await (0, _fsExtra.writeFile)((0, _path.join)(defaultDir, "Preferences"), JSON.stringify(preferences));
34
38
  return userDir;
35
39
  }
36
- async function getProductionPlaywrightConstructs({
40
+ async function launchChromium({
37
41
  proxy,
38
42
  headless = true,
39
- storageState,
40
- downloadsPath
43
+ downloadsPath,
44
+ cdpAddress,
45
+ cdpPort
41
46
  }) {
42
- const extraArgs = ["--no-first-run", "--disable-sync", "--disable-translate", "--disable-features=TranslateUI", "--disable-features=NetworkService", "--lang=en"];
43
- if (headless) {
44
- extraArgs.push("--headless=new");
47
+ if (cdpAddress) {
48
+ const browser = await playwright.chromium.connectOverCDP(cdpAddress);
49
+ if (browser.contexts().length === 0) {
50
+ throw new Error("No browser contexts found in the connected browser");
51
+ }
52
+ const context = browser.contexts()[0];
53
+ let page = context.pages().at(0);
54
+ if (!page) {
55
+ page = await context.newPage();
56
+ }
57
+ return {
58
+ page,
59
+ context
60
+ };
45
61
  }
62
+ const extraArgs = [];
46
63
  const userDataDir = await createUserDirWithPreferences();
64
+ if (cdpPort) {
65
+ extraArgs.push(`--remote-debugging-port=${cdpPort}`);
66
+ }
47
67
  const context = await playwright.chromium.launchPersistentContext(userDataDir, {
48
68
  headless,
49
69
  viewport: null,
50
70
  proxy,
51
- downloadsPath
71
+ downloadsPath,
72
+ args: extraArgs
52
73
  });
53
74
  context.once("close", async () => {
54
75
  try {
@@ -62,80 +83,122 @@ async function getProductionPlaywrightConstructs({
62
83
  console.error("Failed to remove user data dir", error);
63
84
  }
64
85
  });
65
- if (storageState) {
66
- await loadSessionToContext({
67
- context,
68
- session: storageState
69
- });
70
- }
71
- const assetsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
72
- await context.addInitScript({
73
- path: assetsFile
74
- });
75
- let page = context.pages().at(0);
76
- if (page) {
77
- const scriptString = await (0, _fsExtra.readFile)(assetsFile, "utf8");
78
- await page.evaluate(scriptString);
79
- } else {
80
- page = await context.newPage();
86
+ if (cdpPort) {
87
+ const createdCdpAddress = getLocalCdpAddress(cdpPort);
88
+ await waitOnCdpAddress(createdCdpAddress);
81
89
  }
90
+ const page = context.pages().at(0) ?? (await context.newPage());
82
91
  return {
83
92
  page,
84
93
  context
85
94
  };
86
95
  }
87
- async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
88
- if (mode == "playwright-standalone") {
89
- if (!cdpAddress) {
90
- throw new Error("cdpAddress is required");
91
- }
92
- const {
93
- context
94
- } = await getRemotePlaywrightContext(cdpAddress);
95
- if (!context) {
96
- throw new Error("no context found");
96
+ const browserScriptsFile = exports.browserScriptsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
97
+ async function withPlaywrightContext({
98
+ cdpAddress,
99
+ proxy,
100
+ headless = true,
101
+ downloadsPath,
102
+ importFunction,
103
+ apiName,
104
+ apiParameters
105
+ }, fn) {
106
+ let context;
107
+ let page;
108
+ try {
109
+ const setupContextHookResult = importFunction ? await (0, _setupContextHook.loadSetupContextHook)({
110
+ importFunction
111
+ }) : (0, _neverthrow.ok)(null);
112
+ if (setupContextHookResult.isErr()) {
113
+ return setupContextHookResult;
97
114
  }
98
- const assetsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
99
- await context.addInitScript({
100
- path: assetsFile
101
- });
102
- const pages = await context.pages();
103
- let page = null;
104
- if (pages.length > 0) {
105
- page = pages[0];
106
- const scriptString = await fs.readFile(assetsFile, "utf8");
107
- await page.evaluate(scriptString);
108
- } else {
109
- page = await context.newPage();
115
+ const setupContextHook = setupContextHookResult.value;
116
+ if (setupContextHook === null) {
117
+ if (cdpAddress !== undefined) {
118
+ ({
119
+ page,
120
+ context
121
+ } = await launchChromium({
122
+ cdpAddress
123
+ }));
124
+ } else {
125
+ ({
126
+ page,
127
+ context
128
+ } = await launchChromium({
129
+ proxy,
130
+ headless,
131
+ downloadsPath
132
+ }));
133
+ }
134
+ return await fn(context, page);
110
135
  }
111
- if (authSession) {
112
- await loadSessionToContext({
136
+ let hookCdpUrl = null;
137
+ if (cdpAddress) {
138
+ hookCdpUrl = cdpAddress;
139
+ ({
113
140
  context,
114
- session: authSession
141
+ page
142
+ } = await launchChromium({
143
+ cdpAddress
144
+ }));
145
+ } else {
146
+ const port = await (0, _portfinder.getPort)({
147
+ port: 9222
115
148
  });
149
+ hookCdpUrl = getLocalCdpAddress(port);
150
+ ({
151
+ context,
152
+ page
153
+ } = await launchChromium({
154
+ proxy,
155
+ headless,
156
+ downloadsPath,
157
+ cdpPort: port
158
+ }));
116
159
  }
117
- return {
118
- page,
119
- context
120
- };
121
- }
122
- const downloadsPath = (0, _runtime.getDownloadDirectoryPath)();
123
- if (mode === "playwright" || mode === "playwright-headless") {
124
- const productionConstructs = await getProductionPlaywrightConstructs({
125
- headless: mode === "playwright-headless",
126
- downloadsPath
127
- });
128
- if (authSession) {
129
- await loadSessionToContext({
130
- context: productionConstructs.context,
131
- session: authSession
160
+ let hookResult;
161
+ try {
162
+ hookResult = await setupContextHook({
163
+ apiName: apiName,
164
+ apiParameters: apiParameters,
165
+ cdpUrl: hookCdpUrl
132
166
  });
167
+ } catch (error) {
168
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
133
169
  }
134
- return {
135
- ...productionConstructs
136
- };
170
+ if (!hookResult) {
171
+ return await fn(context, page);
172
+ }
173
+ const {
174
+ page: newPage,
175
+ context: newContext,
176
+ cleanup
177
+ } = hookResult;
178
+ let result;
179
+ try {
180
+ result = {
181
+ return: await fn(newContext, newPage ?? page)
182
+ };
183
+ } catch (e) {
184
+ result = {
185
+ throw: e
186
+ };
187
+ }
188
+ try {
189
+ await cleanup?.();
190
+ } catch (e) {
191
+ result = {
192
+ return: (0, _neverthrow.err)(new _errors.AutomationError(e))
193
+ };
194
+ }
195
+ if ("throw" in result) {
196
+ throw result.throw;
197
+ }
198
+ return result.return;
199
+ } finally {
200
+ await context?.close();
137
201
  }
138
- throw "invalid mode";
139
202
  }
140
203
  async function loadSessionToContext({
141
204
  context,
@@ -154,22 +217,28 @@ async function loadSessionToContext({
154
217
  }
155
218
  await (0, _contextStorageStateHelpers.setStorageState)(context, sessionToLoad);
156
219
  }
220
+ function getLocalCdpAddress(port) {
221
+ return `http://localhost:${port}`;
222
+ }
223
+ async function waitOnCdpAddress(cdpAddress) {
224
+ const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
225
+ await (0, _waitOn.default)({
226
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
227
+ delay: 100,
228
+ interval: 100,
229
+ timeout: 5000,
230
+ tcpTimeout: 1000,
231
+ window: 1000
232
+ });
233
+ }
157
234
  async function getRemotePlaywrightContext(cdpAddress) {
158
235
  const playwright = await Promise.resolve().then(() => _interopRequireWildcard(require("playwright")));
159
236
  let browser = null;
160
237
  if (!cdpAddress) {
161
238
  throw new Error("cdpAddress is required");
162
239
  }
163
- const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
164
240
  try {
165
- await (0, _waitOn.default)({
166
- resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
167
- delay: 100,
168
- interval: 100,
169
- timeout: 5000,
170
- tcpTimeout: 1000,
171
- window: 1000
172
- });
241
+ await waitOnCdpAddress(cdpAddress);
173
242
  } catch (error) {
174
243
  console.error("Failed to connect to the browser");
175
244
  process.exit(128 + 9);
@@ -0,0 +1,9 @@
1
+ import { Result } from "neverthrow";
2
+ import { RunAutomationError } from "./errors";
3
+ import { ExtendedRunApiParameters } from "./types";
4
+ export type ImportFunction = ExtendedRunApiParameters["importFunction"];
5
+ export declare function importUsingImportFunction<_ReturnType = any>({ path, allowGenerators, importFunction, }: {
6
+ path: string;
7
+ importFunction: ImportFunction;
8
+ allowGenerators?: boolean;
9
+ }): Promise<Result<(..._: any) => Promise<_ReturnType>, RunAutomationError>>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.importUsingImportFunction = importUsingImportFunction;
7
+ var _neverthrow = require("neverthrow");
8
+ var _errors = require("./errors");
9
+ async function importUsingImportFunction({
10
+ path,
11
+ allowGenerators = true,
12
+ importFunction
13
+ }) {
14
+ try {
15
+ const importedResult = await importFunction(path);
16
+ if (importedResult.isErr()) {
17
+ if (importedResult.error.type === "not_found") {
18
+ return (0, _neverthrow.err)(new _errors.ApiNotFoundError(path));
19
+ }
20
+ return (0, _neverthrow.err)(new _errors.AutomationError(importedResult.error.error));
21
+ }
22
+ const imported = importedResult.value;
23
+ if (!imported || !imported.default || !imported.default.constructor) {
24
+ return (0, _neverthrow.err)(new _errors.InvalidApiError(`${path} does not have a default export`));
25
+ }
26
+ if (imported.default.constructor.name === "AsyncGeneratorFunction") {
27
+ if (!allowGenerators) {
28
+ return (0, _neverthrow.err)(new _errors.InvalidApiError(`${path} default export must be an async function`));
29
+ }
30
+ return (0, _neverthrow.ok)(async (...args) => {
31
+ const generator = imported.default(...args);
32
+ const result = await generator.next();
33
+ if (!result.done) {
34
+ throw new Error("Yield is not supported");
35
+ }
36
+ return result.value;
37
+ });
38
+ }
39
+ if (imported.default.constructor.name === "AsyncFunction") {
40
+ return (0, _neverthrow.ok)(imported.default);
41
+ }
42
+ return (0, _neverthrow.err)(new _errors.InvalidApiError(`${path} default export must be an async function`));
43
+ } catch (error) {
44
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
45
+ }
46
+ }
@@ -4,13 +4,8 @@ import { Page, BrowserContext } from "playwright";
4
4
  import { ExtendedRunApiParameters, RunApiResult, RunApiResultWithSessionOk } from "./types";
5
5
  export * from "./types";
6
6
  export * from "./errors";
7
- export declare function runApiGenerator<ResultType = any, _YieldType = any, _NextType = any>(params: ExtendedRunApiParameters & {
8
- retrieveSession: true;
9
- }): AsyncGenerator<_YieldType, RunApiResult<ResultType, RunApiResultWithSessionOk>, _NextType>;
10
- export declare function runApiGenerator<ResultType = any, _YieldType = any, _NextType = any>(params: ExtendedRunApiParameters): AsyncGenerator<_YieldType, RunApiResult<ResultType>, _NextType>;
11
- export declare function runApi<ResultType = any>(params: ExtendedRunApiParameters & {
7
+ export declare function runApi<ResultType = any>(input: ExtendedRunApiParameters & {
12
8
  retrieveSession: true;
13
9
  }): Promise<RunApiResult<ResultType, RunApiResultWithSessionOk>>;
14
- export declare function runApi<ResultType = any>(params: ExtendedRunApiParameters): Promise<RunApiResult<ResultType>>;
10
+ export declare function runApi<ResultType = any>(input: ExtendedRunApiParameters): Promise<RunApiResult<ResultType>>;
15
11
  export declare function checkAuthSessionWithRetries(page: Page, context: BrowserContext, checkFn: (..._: any) => Promise<boolean>, retries?: number): Promise<Result<boolean, RunAutomationError>>;
16
- export type ImportFunction = ExtendedRunApiParameters["importFunction"];