@intuned/runtime-dev 0.1.0-test.11 → 0.1.0-test.13

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 (100) hide show
  1. package/.babelrc +0 -1
  2. package/dist/commands/api/run.js +156 -83
  3. package/dist/commands/api/run.ts +105 -0
  4. package/dist/commands/auth-sessions/load.js +20 -20
  5. package/dist/commands/auth-sessions/load.ts +30 -0
  6. package/dist/commands/auth-sessions/run-check.js +45 -39
  7. package/dist/commands/auth-sessions/run-check.ts +51 -0
  8. package/dist/commands/auth-sessions/run-create.js +84 -74
  9. package/dist/commands/auth-sessions/run-create.ts +91 -0
  10. package/dist/commands/browser/save-state.js +12 -7
  11. package/dist/commands/browser/save-state.ts +14 -0
  12. package/dist/commands/browser/start-browser.js +7 -4
  13. package/dist/commands/browser/start-browser.ts +11 -0
  14. package/dist/commands/build.js +97 -61
  15. package/dist/commands/build.ts +78 -0
  16. package/dist/commands/common/browserUtils.js +42 -31
  17. package/dist/commands/common/browserUtils.ts +45 -0
  18. package/dist/commands/common/getDefaultExportFromFile.js +11 -10
  19. package/dist/commands/common/getDefaultExportFromFile.ts +11 -0
  20. package/dist/commands/common/getFirstLineNumber.js +90 -83
  21. package/dist/commands/common/{getFirstLineNumber.test.js → getFirstLineNumber.test.ts} +2 -2
  22. package/dist/commands/common/getFirstLineNumber.ts +96 -0
  23. package/dist/commands/common/sendMessageToClient.js +4 -2
  24. package/dist/commands/common/sendMessageToClient.ts +3 -0
  25. package/dist/commands/common/utils/fileUtils.js +16 -16
  26. package/dist/commands/common/utils/fileUtils.ts +23 -0
  27. package/dist/commands/common/utils/settings.js +17 -19
  28. package/dist/commands/common/utils/settings.ts +22 -0
  29. package/dist/commands/common/utils/unixSocket.js +43 -36
  30. package/dist/commands/common/utils/unixSocket.ts +38 -0
  31. package/dist/commands/common/utils/webTemplate.js +25 -18
  32. package/dist/commands/common/utils/webTemplate.ts +22 -0
  33. package/dist/commands/interface/run.js +139 -133
  34. package/dist/commands/interface/run.ts +156 -0
  35. package/dist/commands/ts-check.js +45 -41
  36. package/dist/commands/ts-check.ts +50 -0
  37. package/dist/common/Logger/Logger/index.d.ts +1 -1
  38. package/dist/common/Logger/Logger/index.js +40 -46
  39. package/dist/common/Logger/Logger/index.ts +53 -0
  40. package/dist/common/Logger/Logger/types.js +1 -1
  41. package/dist/common/Logger/index.d.ts +1 -1
  42. package/dist/common/Logger/index.js +40 -46
  43. package/dist/common/Logger/index.ts +53 -0
  44. package/dist/common/Logger/types.js +1 -1
  45. package/dist/common/asyncLocalStorage/index.js +4 -4
  46. package/dist/common/asyncLocalStorage/index.ts +9 -0
  47. package/dist/common/cleanEnvironmentVariables.js +11 -9
  48. package/dist/common/cleanEnvironmentVariables.ts +10 -0
  49. package/dist/common/constants.js +1 -1
  50. package/dist/common/constants.ts +1 -0
  51. package/dist/common/contextStorageStateHelpers.js +36 -38
  52. package/dist/common/contextStorageStateHelpers.ts +43 -0
  53. package/dist/common/getPlaywrightConstructs.d.ts +1 -1
  54. package/dist/common/getPlaywrightConstructs.js +187 -157
  55. package/dist/common/getPlaywrightConstructs.ts +181 -0
  56. package/dist/common/jwtTokenManager.js +74 -61
  57. package/dist/common/jwtTokenManager.ts +71 -0
  58. package/dist/common/runApi/errors.d.ts +1 -1
  59. package/dist/common/runApi/errors.js +130 -121
  60. package/dist/common/runApi/errors.ts +154 -0
  61. package/dist/common/runApi/index.d.ts +4 -4
  62. package/dist/common/runApi/index.js +219 -233
  63. package/dist/common/runApi/index.ts +253 -0
  64. package/dist/common/runApi/types.d.ts +1 -1
  65. package/dist/common/runApi/types.js +55 -41
  66. package/dist/common/runApi/types.ts +43 -0
  67. package/dist/common/settingsSchema.js +9 -6
  68. package/dist/common/settingsSchema.ts +9 -0
  69. package/dist/common/telemetry.js +27 -16
  70. package/dist/common/telemetry.ts +23 -0
  71. package/dist/index.d.ts +4 -4
  72. package/dist/index.js +4 -4
  73. package/dist/index.ts +4 -0
  74. package/dist/runtime/RunError.d.ts +1 -1
  75. package/dist/runtime/RunError.js +10 -10
  76. package/dist/runtime/RunError.ts +12 -0
  77. package/dist/runtime/downloadDirectory.js +10 -10
  78. package/dist/runtime/downloadDirectory.ts +13 -0
  79. package/dist/runtime/enums.d.ts +1 -11
  80. package/dist/runtime/enums.js +12 -12
  81. package/dist/runtime/enums.ts +12 -0
  82. package/dist/runtime/{executionHelpers.test.js → executionHelpers.test.ts} +2 -2
  83. package/dist/runtime/export.d.ts +1 -202
  84. package/dist/runtime/extendPayload.d.ts +1 -1
  85. package/dist/runtime/extendPayload.js +13 -13
  86. package/dist/runtime/extendPayload.ts +15 -0
  87. package/dist/runtime/extendTimeout.js +19 -20
  88. package/dist/runtime/extendTimeout.ts +24 -0
  89. package/dist/runtime/index.d.ts +7 -7
  90. package/dist/runtime/index.js +6 -6
  91. package/dist/runtime/index.ts +6 -0
  92. package/dist/runtime/requestMoreInfo.js +14 -14
  93. package/dist/runtime/requestMoreInfo.ts +18 -0
  94. package/dist/runtime/runInfo.d.ts +1 -1
  95. package/dist/runtime/runInfo.js +12 -13
  96. package/dist/runtime/runInfo.ts +15 -0
  97. package/package.json +3 -2
  98. package/tsconfig.json +1 -1
  99. /package/dist/{runtime/enums.d.js → common/Logger/Logger/types.ts} +0 -0
  100. /package/dist/{runtime/export.d.js → common/Logger/types.ts} +0 -0
@@ -1,38 +1,45 @@
1
1
  export class JSONUnixSocket {
2
- static LENGTH_HEADER_LENGTH = 4;
3
- constructor(socket) {
4
- this.socket = socket;
5
- }
6
- sendJSON(data) {
7
- const dataToSend = JSON.stringify(data);
8
- const length = Buffer.byteLength(dataToSend);
9
- const buffer = Buffer.alloc(JSONUnixSocket.LENGTH_HEADER_LENGTH + length);
10
- buffer.writeUInt32BE(length, 0);
11
- buffer.write(dataToSend, JSONUnixSocket.LENGTH_HEADER_LENGTH);
12
- this.socket.write(buffer);
13
- }
14
- async *receiveJSON() {
15
- let buffer = Buffer.alloc(0);
16
- const endPromise = new Promise((resolve, reject) => {
17
- this.socket.once("end", () => {
18
- console.log("end");
19
- resolve();
20
- });
21
- this.socket.once("error", reject);
22
- });
23
- while (true) {
24
- const chunk = await Promise.race([new Promise(resolve => this.socket.once("data", data => resolve(data))), endPromise]);
25
- if (!(chunk instanceof Buffer)) {
26
- break;
27
- }
28
- buffer = Buffer.concat([buffer, chunk]);
29
- const length = buffer.readUInt32BE(0);
30
- if (buffer.length < length + JSONUnixSocket.LENGTH_HEADER_LENGTH) {
31
- continue;
32
- }
33
- const data = buffer.subarray(JSONUnixSocket.LENGTH_HEADER_LENGTH, length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
34
- buffer = buffer.subarray(length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
35
- yield JSON.parse(data.toString());
2
+ constructor(socket) {
3
+ this.socket = socket;
36
4
  }
37
- }
38
- }
5
+ sendJSON(data) {
6
+ const dataToSend = JSON.stringify(data);
7
+ // calculate length
8
+ const length = Buffer.byteLength(dataToSend);
9
+ // create buffer
10
+ const buffer = Buffer.alloc(JSONUnixSocket.LENGTH_HEADER_LENGTH + length);
11
+ // write length in big endian
12
+ buffer.writeUInt32BE(length, 0);
13
+ // write data
14
+ buffer.write(dataToSend, JSONUnixSocket.LENGTH_HEADER_LENGTH);
15
+ this.socket.write(buffer);
16
+ }
17
+ async *receiveJSON() {
18
+ let buffer = Buffer.alloc(0);
19
+ const endPromise = new Promise((resolve, reject) => {
20
+ this.socket.once("end", () => {
21
+ console.log("end");
22
+ resolve();
23
+ });
24
+ this.socket.once("error", reject);
25
+ });
26
+ while (true) {
27
+ const chunk = await Promise.race([
28
+ new Promise((resolve) => this.socket.once("data", (data) => resolve(data))),
29
+ endPromise,
30
+ ]);
31
+ if (!(chunk instanceof Buffer)) {
32
+ break;
33
+ }
34
+ buffer = Buffer.concat([buffer, chunk]);
35
+ const length = buffer.readUInt32BE(0);
36
+ if (buffer.length < length + JSONUnixSocket.LENGTH_HEADER_LENGTH) {
37
+ continue;
38
+ }
39
+ const data = buffer.subarray(JSONUnixSocket.LENGTH_HEADER_LENGTH, length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
40
+ buffer = buffer.subarray(length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
41
+ yield JSON.parse(data.toString());
42
+ }
43
+ }
44
+ }
45
+ JSONUnixSocket.LENGTH_HEADER_LENGTH = 4;
@@ -0,0 +1,38 @@
1
+ export class JSONUnixSocket {
2
+ static LENGTH_HEADER_LENGTH = 4;
3
+ constructor(socket) {
4
+ this.socket = socket;
5
+ }
6
+ sendJSON(data) {
7
+ const dataToSend = JSON.stringify(data);
8
+ const length = Buffer.byteLength(dataToSend);
9
+ const buffer = Buffer.alloc(JSONUnixSocket.LENGTH_HEADER_LENGTH + length);
10
+ buffer.writeUInt32BE(length, 0);
11
+ buffer.write(dataToSend, JSONUnixSocket.LENGTH_HEADER_LENGTH);
12
+ this.socket.write(buffer);
13
+ }
14
+ async *receiveJSON() {
15
+ let buffer = Buffer.alloc(0);
16
+ const endPromise = new Promise((resolve, reject) => {
17
+ this.socket.once("end", () => {
18
+ console.log("end");
19
+ resolve();
20
+ });
21
+ this.socket.once("error", reject);
22
+ });
23
+ while (true) {
24
+ const chunk = await Promise.race([new Promise(resolve => this.socket.once("data", data => resolve(data))), endPromise]);
25
+ if (!(chunk instanceof Buffer)) {
26
+ break;
27
+ }
28
+ buffer = Buffer.concat([buffer, chunk]);
29
+ const length = buffer.readUInt32BE(0);
30
+ if (buffer.length < length + JSONUnixSocket.LENGTH_HEADER_LENGTH) {
31
+ continue;
32
+ }
33
+ const data = buffer.subarray(JSONUnixSocket.LENGTH_HEADER_LENGTH, length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
34
+ buffer = buffer.subarray(length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
35
+ yield JSON.parse(data.toString());
36
+ }
37
+ }
38
+ }
@@ -1,22 +1,29 @@
1
1
  import * as fs from "fs-extra";
2
2
  import * as path from "path";
3
- import { getFullPathInProject, listProjectFilesAndFolders } from "./fileUtils";
3
+ import { getFullPathInProject, listProjectFilesAndFolders, } from "./fileUtils.js";
4
4
  export const moveWebTemplateFiles = async () => {
5
- await fs.remove("./intuned");
6
- await fs.ensureDir("./intuned");
7
- const currentFileLocation = path.resolve(__dirname, "..", "..", "..", "..", "WebTemplate");
8
- await fs.copy(`${currentFileLocation}`, "./intuned/WebTemplate", {
9
- filter: (src, dest) => {
10
- if (src.includes(".d.ts")) {
11
- return false;
12
- }
13
- return true;
5
+ await fs.remove("./intuned");
6
+ await fs.ensureDir("./intuned");
7
+ const currentFileLocation = path.resolve(path.dirname(import.meta.url), "..", "..", "..", "..", "WebTemplate");
8
+ // copy WebTemplate to ./intuned
9
+ await fs.copy(`${currentFileLocation}`, "./intuned/WebTemplate", {
10
+ filter: (src, dest) => {
11
+ if (src.includes(".d.ts")) {
12
+ return false;
13
+ }
14
+ return true;
15
+ },
16
+ });
17
+ const filesAndFolders = await listProjectFilesAndFolders();
18
+ const pathsIgnoreList = [
19
+ getFullPathInProject("intuned"),
20
+ getFullPathInProject("node_modules"),
21
+ getFullPathInProject("package.json"),
22
+ getFullPathInProject("yarn.lock"),
23
+ getFullPathInProject(".env"),
24
+ ];
25
+ const filesToCopy = filesAndFolders.filter((file) => !pathsIgnoreList.includes(file.fullPath));
26
+ for (const file of filesToCopy) {
27
+ await fs.copy(file.fullPath, `./intuned/WebTemplate/${file.name}`);
14
28
  }
15
- });
16
- const filesAndFolders = await listProjectFilesAndFolders();
17
- const pathsIgnoreList = [getFullPathInProject("intuned"), getFullPathInProject("node_modules"), getFullPathInProject("package.json"), getFullPathInProject("yarn.lock"), getFullPathInProject(".env")];
18
- const filesToCopy = filesAndFolders.filter(file => !pathsIgnoreList.includes(file.fullPath));
19
- for (const file of filesToCopy) {
20
- await fs.copy(file.fullPath, `./intuned/WebTemplate/${file.name}`);
21
- }
22
- };
29
+ };
@@ -0,0 +1,22 @@
1
+ import * as fs from "fs-extra";
2
+ import * as path from "path";
3
+ import { getFullPathInProject, listProjectFilesAndFolders } from "./fileUtils.js";
4
+ export const moveWebTemplateFiles = async () => {
5
+ await fs.remove("./intuned");
6
+ await fs.ensureDir("./intuned");
7
+ const currentFileLocation = path.resolve(path.dirname(import.meta.url), "..", "..", "..", "..", "WebTemplate");
8
+ await fs.copy(`${currentFileLocation}`, "./intuned/WebTemplate", {
9
+ filter: (src, dest) => {
10
+ if (src.includes(".d.ts")) {
11
+ return false;
12
+ }
13
+ return true;
14
+ }
15
+ });
16
+ const filesAndFolders = await listProjectFilesAndFolders();
17
+ const pathsIgnoreList = [getFullPathInProject("intuned"), getFullPathInProject("node_modules"), getFullPathInProject("package.json"), getFullPathInProject("yarn.lock"), getFullPathInProject(".env")];
18
+ const filesToCopy = filesAndFolders.filter(file => !pathsIgnoreList.includes(file.fullPath));
19
+ for (const file of filesToCopy) {
20
+ await fs.copy(file.fullPath, `./intuned/WebTemplate/${file.name}`);
21
+ }
22
+ };
@@ -1,156 +1,162 @@
1
1
  #!/usr/bin/env node
2
2
  import { program } from "commander";
3
3
  import dotenv from "dotenv";
4
- import { runWithContext } from "../../common/asyncLocalStorage";
4
+ import { runWithContext, } from "../../common/asyncLocalStorage";
5
5
  import * as net from "net";
6
6
  import z from "zod";
7
- import { runApiGenerator, runApiParametersSchema } from "../../common/runApi";
7
+ import { runApiGenerator, runApiParametersSchema, } from "../../common/runApi";
8
8
  import { RunEnvironment } from "src/runtime/enums";
9
9
  import { JSONUnixSocket } from "../common/utils/unixSocket";
10
10
  import { setTimeout } from "timers/promises";
11
11
  const startRunApiSchema = z.object({
12
- type: z.literal("start"),
13
- parameters: runApiParametersSchema.extend({
14
- retrieveSession: z.boolean(),
15
- context: z.object({
16
- jobId: z.string().optional(),
17
- jobRunId: z.string().optional(),
18
- runId: z.string().optional(),
19
- queueId: z.string().optional()
20
- }).optional()
21
- })
12
+ type: z.literal("start"),
13
+ parameters: runApiParametersSchema.extend({
14
+ retrieveSession: z.boolean(),
15
+ context: z
16
+ .object({
17
+ jobId: z.string().optional(),
18
+ jobRunId: z.string().optional(),
19
+ runId: z.string().optional(),
20
+ queueId: z.string().optional(),
21
+ })
22
+ .optional(),
23
+ }),
22
24
  });
23
25
  const nextRunApiSchema = z.object({
24
- type: z.literal("next"),
25
- parameters: z.object({
26
- value: z.string()
27
- })
26
+ type: z.literal("next"),
27
+ parameters: z.object({ value: z.string() }),
28
28
  });
29
29
  const abortRunApiSchema = z.object({
30
- type: z.literal("abort"),
31
- parameters: z.object({}).optional()
30
+ type: z.literal("abort"),
31
+ parameters: z.object({}).optional(),
32
32
  });
33
- const inputSchema = z.union([startRunApiSchema, nextRunApiSchema, abortRunApiSchema]);
33
+ const inputSchema = z.union([
34
+ startRunApiSchema,
35
+ nextRunApiSchema,
36
+ abortRunApiSchema,
37
+ ]);
34
38
  dotenv.config({
35
- path: `.env`
39
+ path: `.env`,
36
40
  });
37
- program.description("run user automation and communicate using unix socket").argument("<socket-path>", "path to unix socket").action(async socketPath => {
38
- let context;
39
- const throttleTime = 1_000;
40
- let timeoutTimestamp = Date.now();
41
- const client = net.createConnection(socketPath, () => {
42
- console.log("connected to server!");
43
- });
44
- let generator = null;
45
- const abortController = new AbortController();
46
- client.on("end", () => {
47
- console.log("Disconnected from socket");
48
- });
49
- client.on("error", err => {
50
- var _generator;
51
- console.error("Child connection error:", err);
52
- void ((_generator = generator) === null || _generator === void 0 ? void 0 : _generator.throw(err).catch(() => undefined));
53
- });
54
- process.on("SIGINT", () => {
55
- var _generator2;
56
- console.log("Received SIGINT");
57
- void ((_generator2 = generator) === null || _generator2 === void 0 ? void 0 : _generator2.throw(new Error("Interrupted")).catch(() => undefined));
58
- client.end();
59
- process.exit(1);
60
- });
61
- const jsonUnixSocket = new JSONUnixSocket(client);
62
- async function runGeneratorAndSendResult(next) {
63
- if (!generator) return;
64
- const result = await runWithContext(context, () => generator.next(next));
65
- if (result.done) {
66
- const resultToSend = result.value.isOk() ? result.value.value : result.value.error.json;
67
- const success = result.value.isOk();
68
- jsonUnixSocket.sendJSON({
69
- type: "done",
70
- result: resultToSend,
71
- success
72
- });
73
- return true;
74
- } else {
75
- jsonUnixSocket.sendJSON({
76
- type: "yield",
77
- result: result.value
78
- });
79
- return false;
80
- }
81
- }
82
- for await (const data of jsonUnixSocket.receiveJSON()) {
83
- const inputParseResult = inputSchema.safeParse(data);
84
- if (!inputParseResult.success) {
85
- console.error(inputParseResult.error.errors);
86
- jsonUnixSocket.sendJSON({
87
- type: "done",
88
- result: {
89
- error: "InvalidJSON",
90
- message: "Invalid input",
91
- details: {
92
- errors: inputParseResult.error.errors
93
- }
94
- },
95
- success: false
96
- });
97
- break;
98
- }
99
- const input = inputParseResult.data;
100
- if (input.type === "abort") {
101
- abortController.abort();
102
- await setTimeout(10);
103
- jsonUnixSocket.sendJSON({
104
- type: "done",
105
- result: null
106
- });
107
- break;
108
- }
109
- if (input.type === "start") {
110
- const gen = runApiGenerator({
111
- ...input.parameters,
112
- abortSignal: abortController.signal
113
- });
114
- generator = gen;
115
- context = {
116
- extendedPayloads: [],
117
- runEnvironment: input.parameters.runOptions.environment === "deployed" ? RunEnvironment.DEPLOYED : RunEnvironment.IDE,
118
- timeoutInfo: {
119
- extendTimeoutCallback: async () => {
120
- if (Date.now() - timeoutTimestamp < throttleTime) return;
121
- timeoutTimestamp = Date.now();
41
+ program
42
+ .description("run user automation and communicate using unix socket")
43
+ .argument("<socket-path>", "path to unix socket")
44
+ .action(async (socketPath) => {
45
+ let context;
46
+ const throttleTime = 1_000;
47
+ let timeoutTimestamp = Date.now();
48
+ const client = net.createConnection(socketPath, () => {
49
+ console.log("connected to server!");
50
+ });
51
+ let generator = null;
52
+ const abortController = new AbortController();
53
+ client.on("end", () => {
54
+ console.log("Disconnected from socket");
55
+ });
56
+ client.on("error", (err) => {
57
+ console.error("Child connection error:", err);
58
+ void generator?.throw(err).catch(() => undefined);
59
+ });
60
+ process.on("SIGINT", () => {
61
+ console.log("Received SIGINT");
62
+ void generator?.throw(new Error("Interrupted")).catch(() => undefined);
63
+ client.end();
64
+ process.exit(1);
65
+ });
66
+ const jsonUnixSocket = new JSONUnixSocket(client);
67
+ async function runGeneratorAndSendResult(next) {
68
+ if (!generator)
69
+ return;
70
+ const result = await runWithContext(context, () => generator.next(next));
71
+ if (result.done) {
72
+ const resultToSend = result.value.isOk()
73
+ ? result.value.value
74
+ : result.value.error.json;
75
+ const success = result.value.isOk();
122
76
  jsonUnixSocket.sendJSON({
123
- type: "extend"
77
+ type: "done",
78
+ result: resultToSend,
79
+ success,
124
80
  });
125
- }
126
- },
127
- ...(input.parameters.context ?? {}),
128
- proxy: getProxyUrlFromRunOptions(input.parameters.runOptions)
129
- };
130
- if (await runGeneratorAndSendResult()) {
131
- break;
132
- }
133
- continue;
81
+ return true;
82
+ }
83
+ else {
84
+ jsonUnixSocket.sendJSON({ type: "yield", result: result.value });
85
+ return false;
86
+ }
134
87
  }
135
- if (input.type === "next") {
136
- if (!generator) {
137
- throw new Error("generator not started");
138
- }
139
- if (await runGeneratorAndSendResult(input.parameters.value)) {
140
- break;
141
- }
142
- continue;
88
+ for await (const data of jsonUnixSocket.receiveJSON()) {
89
+ const inputParseResult = inputSchema.safeParse(data);
90
+ if (!inputParseResult.success) {
91
+ console.error(inputParseResult.error.errors);
92
+ jsonUnixSocket.sendJSON({
93
+ type: "done",
94
+ result: {
95
+ error: "InvalidJSON",
96
+ message: "Invalid input",
97
+ details: {
98
+ errors: inputParseResult.error.errors,
99
+ },
100
+ },
101
+ success: false,
102
+ });
103
+ break;
104
+ }
105
+ const input = inputParseResult.data;
106
+ if (input.type === "abort") {
107
+ abortController.abort();
108
+ await setTimeout(10);
109
+ jsonUnixSocket.sendJSON({ type: "done", result: null });
110
+ break;
111
+ }
112
+ if (input.type === "start") {
113
+ const gen = runApiGenerator({
114
+ ...input.parameters,
115
+ abortSignal: abortController.signal,
116
+ });
117
+ generator = gen;
118
+ context = {
119
+ extendedPayloads: [],
120
+ runEnvironment: input.parameters.runOptions.environment === "deployed"
121
+ ? RunEnvironment.DEPLOYED
122
+ : RunEnvironment.IDE,
123
+ timeoutInfo: {
124
+ extendTimeoutCallback: async () => {
125
+ if (Date.now() - timeoutTimestamp < throttleTime)
126
+ return;
127
+ timeoutTimestamp = Date.now();
128
+ jsonUnixSocket.sendJSON({ type: "extend" });
129
+ },
130
+ },
131
+ ...(input.parameters.context ?? {}),
132
+ proxy: getProxyUrlFromRunOptions(input.parameters.runOptions),
133
+ };
134
+ if (await runGeneratorAndSendResult()) {
135
+ break;
136
+ }
137
+ continue;
138
+ }
139
+ if (input.type === "next") {
140
+ if (!generator) {
141
+ throw new Error("generator not started");
142
+ }
143
+ if (await runGeneratorAndSendResult(input.parameters.value)) {
144
+ break;
145
+ }
146
+ continue;
147
+ }
143
148
  }
144
- }
145
- process.exit(0);
149
+ process.exit(0);
146
150
  });
147
151
  program.parse(process.argv);
148
152
  function getProxyUrlFromRunOptions(runOptions) {
149
- if ((runOptions === null || runOptions === void 0 ? void 0 : runOptions.environment) !== "deployed") return undefined;
150
- const proxy = runOptions.proxy;
151
- if (!proxy) return undefined;
152
- const url = new URL(proxy.server);
153
- url.username = proxy.username;
154
- url.password = proxy.password;
155
- return url.toString();
156
- }
153
+ if (runOptions?.environment !== "deployed")
154
+ return undefined;
155
+ const proxy = runOptions.proxy;
156
+ if (!proxy)
157
+ return undefined;
158
+ const url = new URL(proxy.server);
159
+ url.username = proxy.username;
160
+ url.password = proxy.password;
161
+ return url.toString();
162
+ }
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ import { program } from "commander";
3
+ import dotenv from "dotenv";
4
+ import { runWithContext } from "../../common/asyncLocalStorage";
5
+ import * as net from "net";
6
+ import z from "zod";
7
+ import { runApiGenerator, runApiParametersSchema } from "../../common/runApi";
8
+ import { RunEnvironment } from "src/runtime/enums";
9
+ import { JSONUnixSocket } from "../common/utils/unixSocket";
10
+ import { setTimeout } from "timers/promises";
11
+ const startRunApiSchema = z.object({
12
+ type: z.literal("start"),
13
+ parameters: runApiParametersSchema.extend({
14
+ retrieveSession: z.boolean(),
15
+ context: z.object({
16
+ jobId: z.string().optional(),
17
+ jobRunId: z.string().optional(),
18
+ runId: z.string().optional(),
19
+ queueId: z.string().optional()
20
+ }).optional()
21
+ })
22
+ });
23
+ const nextRunApiSchema = z.object({
24
+ type: z.literal("next"),
25
+ parameters: z.object({
26
+ value: z.string()
27
+ })
28
+ });
29
+ const abortRunApiSchema = z.object({
30
+ type: z.literal("abort"),
31
+ parameters: z.object({}).optional()
32
+ });
33
+ const inputSchema = z.union([startRunApiSchema, nextRunApiSchema, abortRunApiSchema]);
34
+ dotenv.config({
35
+ path: `.env`
36
+ });
37
+ program.description("run user automation and communicate using unix socket").argument("<socket-path>", "path to unix socket").action(async socketPath => {
38
+ let context;
39
+ const throttleTime = 1_000;
40
+ let timeoutTimestamp = Date.now();
41
+ const client = net.createConnection(socketPath, () => {
42
+ console.log("connected to server!");
43
+ });
44
+ let generator = null;
45
+ const abortController = new AbortController();
46
+ client.on("end", () => {
47
+ console.log("Disconnected from socket");
48
+ });
49
+ client.on("error", err => {
50
+ var _generator;
51
+ console.error("Child connection error:", err);
52
+ void ((_generator = generator) === null || _generator === void 0 ? void 0 : _generator.throw(err).catch(() => undefined));
53
+ });
54
+ process.on("SIGINT", () => {
55
+ var _generator2;
56
+ console.log("Received SIGINT");
57
+ void ((_generator2 = generator) === null || _generator2 === void 0 ? void 0 : _generator2.throw(new Error("Interrupted")).catch(() => undefined));
58
+ client.end();
59
+ process.exit(1);
60
+ });
61
+ const jsonUnixSocket = new JSONUnixSocket(client);
62
+ async function runGeneratorAndSendResult(next) {
63
+ if (!generator) return;
64
+ const result = await runWithContext(context, () => generator.next(next));
65
+ if (result.done) {
66
+ const resultToSend = result.value.isOk() ? result.value.value : result.value.error.json;
67
+ const success = result.value.isOk();
68
+ jsonUnixSocket.sendJSON({
69
+ type: "done",
70
+ result: resultToSend,
71
+ success
72
+ });
73
+ return true;
74
+ } else {
75
+ jsonUnixSocket.sendJSON({
76
+ type: "yield",
77
+ result: result.value
78
+ });
79
+ return false;
80
+ }
81
+ }
82
+ for await (const data of jsonUnixSocket.receiveJSON()) {
83
+ const inputParseResult = inputSchema.safeParse(data);
84
+ if (!inputParseResult.success) {
85
+ console.error(inputParseResult.error.errors);
86
+ jsonUnixSocket.sendJSON({
87
+ type: "done",
88
+ result: {
89
+ error: "InvalidJSON",
90
+ message: "Invalid input",
91
+ details: {
92
+ errors: inputParseResult.error.errors
93
+ }
94
+ },
95
+ success: false
96
+ });
97
+ break;
98
+ }
99
+ const input = inputParseResult.data;
100
+ if (input.type === "abort") {
101
+ abortController.abort();
102
+ await setTimeout(10);
103
+ jsonUnixSocket.sendJSON({
104
+ type: "done",
105
+ result: null
106
+ });
107
+ break;
108
+ }
109
+ if (input.type === "start") {
110
+ const gen = runApiGenerator({
111
+ ...input.parameters,
112
+ abortSignal: abortController.signal
113
+ });
114
+ generator = gen;
115
+ context = {
116
+ extendedPayloads: [],
117
+ runEnvironment: input.parameters.runOptions.environment === "deployed" ? RunEnvironment.DEPLOYED : RunEnvironment.IDE,
118
+ timeoutInfo: {
119
+ extendTimeoutCallback: async () => {
120
+ if (Date.now() - timeoutTimestamp < throttleTime) return;
121
+ timeoutTimestamp = Date.now();
122
+ jsonUnixSocket.sendJSON({
123
+ type: "extend"
124
+ });
125
+ }
126
+ },
127
+ ...(input.parameters.context ?? {}),
128
+ proxy: getProxyUrlFromRunOptions(input.parameters.runOptions)
129
+ };
130
+ if (await runGeneratorAndSendResult()) {
131
+ break;
132
+ }
133
+ continue;
134
+ }
135
+ if (input.type === "next") {
136
+ if (!generator) {
137
+ throw new Error("generator not started");
138
+ }
139
+ if (await runGeneratorAndSendResult(input.parameters.value)) {
140
+ break;
141
+ }
142
+ continue;
143
+ }
144
+ }
145
+ process.exit(0);
146
+ });
147
+ program.parse(process.argv);
148
+ function getProxyUrlFromRunOptions(runOptions) {
149
+ if ((runOptions === null || runOptions === void 0 ? void 0 : runOptions.environment) !== "deployed") return undefined;
150
+ const proxy = runOptions.proxy;
151
+ if (!proxy) return undefined;
152
+ const url = new URL(proxy.server);
153
+ url.username = proxy.username;
154
+ url.password = proxy.password;
155
+ return url.toString();
156
+ }