@intuned/runtime 1.3.15 → 1.3.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/InterfaceTemplate/index.playwright.ts +1 -1
  2. package/WebTemplate.zip +0 -0
  3. package/dist/commands/api/run.js +4 -8
  4. package/dist/commands/auth-sessions/load.js +2 -2
  5. package/dist/commands/auth-sessions/run-check.js +5 -5
  6. package/dist/commands/auth-sessions/run-create.js +3 -3
  7. package/dist/commands/build.js +1 -1
  8. package/dist/commands/common/projectExclusions.js +1 -1
  9. package/dist/commands/common/tsNodeImport.js +9 -0
  10. package/dist/commands/interface/run.js +1 -1
  11. package/dist/commands/intuned-cli/commands/attempt_api.command.js +1 -1
  12. package/dist/commands/intuned-cli/commands/attempt_authsession.command.js +1 -1
  13. package/dist/commands/intuned-cli/commands/attempt_authsession_check.command.js +2 -2
  14. package/dist/commands/intuned-cli/commands/attempt_authsession_create.command.js +1 -1
  15. package/dist/commands/intuned-cli/commands/authsession.command.js +1 -1
  16. package/dist/commands/intuned-cli/commands/authsession_record.command.js +1 -1
  17. package/dist/commands/intuned-cli/commands/authsession_scaffold.command.d.ts +1 -0
  18. package/dist/commands/intuned-cli/commands/authsession_scaffold.command.js +16 -0
  19. package/dist/commands/intuned-cli/commands/deploy.command.js +13 -9
  20. package/dist/commands/intuned-cli/commands/index.d.ts +2 -2
  21. package/dist/commands/intuned-cli/commands/index.js +15 -15
  22. package/dist/commands/intuned-cli/commands/{save.command.d.ts → provision.command.d.ts} +1 -1
  23. package/dist/commands/intuned-cli/commands/provision.command.js +50 -0
  24. package/dist/commands/intuned-cli/commands/run_api.command.js +1 -1
  25. package/dist/commands/intuned-cli/commands/run_authsession.command.d.ts +3 -3
  26. package/dist/commands/intuned-cli/commands/run_authsession.command.js +2 -2
  27. package/dist/commands/intuned-cli/commands/run_authsession_create.command.js +1 -1
  28. package/dist/commands/intuned-cli/commands/run_authsession_update.command.js +2 -2
  29. package/dist/commands/intuned-cli/commands/run_authsession_validate.command.js +2 -2
  30. package/dist/commands/intuned-cli/commands/types.d.ts +1 -1
  31. package/dist/commands/intuned-cli/commands/types.js +2 -2
  32. package/dist/commands/intuned-cli/controller/__test__/api.test.js +6 -5
  33. package/dist/commands/intuned-cli/controller/__test__/authSession.test.js +12 -11
  34. package/dist/commands/intuned-cli/controller/api.js +4 -1
  35. package/dist/commands/intuned-cli/controller/authSession.js +28 -28
  36. package/dist/commands/intuned-cli/controller/deploy.js +52 -10
  37. package/dist/commands/intuned-cli/controller/index.js +1 -1
  38. package/dist/commands/intuned-cli/controller/{save.d.ts → provision.d.ts} +5 -1
  39. package/dist/commands/intuned-cli/controller/provision.js +300 -0
  40. package/dist/commands/intuned-cli/controller/scaffold.d.ts +1 -0
  41. package/dist/commands/intuned-cli/controller/scaffold.js +77 -0
  42. package/dist/commands/intuned-cli/helpers/__test__/browser.test.js +1 -0
  43. package/dist/commands/intuned-cli/helpers/__test__/tracing.test.js +1 -0
  44. package/dist/commands/intuned-cli/helpers/api.js +4 -7
  45. package/dist/commands/intuned-cli/helpers/auth.js +22 -19
  46. package/dist/commands/intuned-cli/helpers/backend.js +12 -4
  47. package/dist/commands/intuned-cli/helpers/context.js +2 -2
  48. package/dist/commands/intuned-cli/helpers/prompts.d.ts +3 -0
  49. package/dist/commands/intuned-cli/helpers/prompts.js +71 -0
  50. package/dist/commands/intuned-cli/helpers/wrapper.js +12 -2
  51. package/dist/commands/intuned-cli/main.js +21 -8
  52. package/dist/commands/intuned-cli/types.d.ts +42 -13
  53. package/dist/commands/intuned-cli/types.js +12 -2
  54. package/dist/common/backendFunctions/getAuthSessionParameters.js +1 -1
  55. package/dist/common/extension/extensionsHelpers.d.ts +6 -3
  56. package/dist/common/extension/extensionsHelpers.js +45 -19
  57. package/dist/common/extension/intunedExtensionServer.d.ts +2 -5
  58. package/dist/common/extension/intunedExtensionServer.js +6 -9
  59. package/dist/common/intunedJson.js +2 -2
  60. package/dist/common/jwtTokenManager.js +2 -2
  61. package/dist/common/launchBrowser.d.ts +2 -0
  62. package/dist/common/launchBrowser.js +41 -3
  63. package/dist/common/playwrightContext.js +7 -1
  64. package/dist/common/runApi/errors.js +1 -1
  65. package/dist/common/runApi/index.js +2 -2
  66. package/dist/common/settingsSchema.d.ts +2 -1
  67. package/dist/runtime/captcha.js +25 -11
  68. package/package.json +5 -3
  69. package/dist/commands/intuned-cli/commands/init.command.d.ts +0 -1
  70. package/dist/commands/intuned-cli/commands/init.command.js +0 -13
  71. package/dist/commands/intuned-cli/commands/save.command.js +0 -42
  72. package/dist/commands/intuned-cli/controller/save.js +0 -351
  73. /package/InterfaceTemplate/{utils.ts → __utils.ts} +0 -0
@@ -20,6 +20,7 @@ async function withWaitForCaptchaSolve(callback, options) {
20
20
  settleDurationMs = 5_000,
21
21
  waitForNetworkSettled = true
22
22
  } = options;
23
+ console.error(`Starting captcha solve wait (timeout=${timeoutInMs}ms, settleDuration=${settleDurationMs}ms, waitForNetworkSettled=${waitForNetworkSettled})`);
23
24
  const extensionServer = (0, _intunedExtensionServer.getIntunedExtensionServer)();
24
25
  let settledResolve = null;
25
26
  let settledPromise = new Promise(resolve => {
@@ -39,21 +40,35 @@ async function withWaitForCaptchaSolve(callback, options) {
39
40
  const onCaptchaUpdate = async _captcha => {
40
41
  const solvingCaptchas = await extensionServer.getCaptchas(page, "solving");
41
42
  const errorCaptchas = await extensionServer.getCaptchas(page, "error");
43
+ console.error(`Captcha update received: solving=${solvingCaptchas.length}, errors=${errorCaptchas.length}`);
42
44
  if (solvingCaptchas.length > 0) {
43
45
  captchasAppeared = true;
46
+ console.error(`Captchas detected: ${solvingCaptchas.map(c => c.id).join(", ")}`);
44
47
  }
45
48
  if (errorCaptchas.length > 0) {
46
49
  error = errorCaptchas[0].error;
50
+ console.error(`Captcha error detected: ${error?.code}`);
47
51
  await maybeSettle();
48
52
  return;
49
53
  }
50
54
  if (solvingCaptchas.length === 0) {
55
+ console.error("No pending captchas, settling");
51
56
  await maybeSettle();
52
57
  }
53
58
  };
59
+ const result = await callback(page);
60
+ actionDone = true;
61
+ if (waitForNetworkSettled) {
62
+ try {
63
+ await page.waitForLoadState("networkidle");
64
+ } catch (err) {
65
+ console.error(`Failed to wait for networkidle. Error: ${err}`);
66
+ }
67
+ }
54
68
  const timeoutPromise = new Promise(resolve => {
55
69
  setTimeout(() => {
56
70
  isTimeout = true;
71
+ console.error("Captcha solve timeout reached");
57
72
  settledResolve?.();
58
73
  resolve();
59
74
  }, timeoutInMs);
@@ -61,33 +76,32 @@ async function withWaitForCaptchaSolve(callback, options) {
61
76
  await extensionServer.subscribe(page, onCaptchaUpdate);
62
77
  try {
63
78
  const initialPending = await getPendingCaptchas();
79
+ console.error(`Found ${initialPending.length} ongoing captchas`);
64
80
  if (initialPending.length > 0) {
65
81
  captchasAppeared = true;
66
82
  }
67
- const result = await callback(page);
68
- actionDone = true;
69
- if (waitForNetworkSettled) {
70
- try {
71
- await page.waitForLoadState("networkidle");
72
- } catch (err) {
73
- console.error(`Failed to wait for networkidle. Error: ${err}`);
74
- }
75
- }
76
83
  await maybeSettle();
77
84
  let shouldContinue = true;
78
85
  while (shouldContinue) {
79
86
  await Promise.race([settledPromise, timeoutPromise]);
87
+ console.error(`Settled event received, waiting ${settleDurationMs}ms before checking`);
80
88
  await new Promise(r => setTimeout(r, settleDurationMs));
81
89
  if (error) {
90
+ console.error(`Raising captcha error: ${error.code}`);
82
91
  throw new _types.CaptchaSolveError(`CAPTCHA Solve Error: ${error.code}`, error);
83
92
  }
84
93
  const noPendingCaptchas = await hasNoPendingCaptchas();
94
+ const pending = await getPendingCaptchas();
95
+ console.error(`Check point: actionDone=${actionDone}, noPendingCaptchas=${noPendingCaptchas}, isTimeout=${isTimeout}, pendingCount=${pending.length}`);
85
96
  if (actionDone && noPendingCaptchas || isTimeout) {
86
97
  if (isTimeout && !noPendingCaptchas) {
98
+ console.error(`Timeout with ${pending.length} pending captchas`);
87
99
  throw new _types.TimeoutError("CAPTCHA Solve timed out with pending captchas.");
88
100
  }
101
+ console.error("Captcha solve completed successfully");
89
102
  shouldContinue = false;
90
103
  } else {
104
+ console.error(`Still have ${pending.length} pending captchas, waiting for more updates`);
91
105
  settledPromise = new Promise(resolve => {
92
106
  settledResolve = resolve;
93
107
  });
@@ -164,13 +178,13 @@ async function setAutoSolve(context, enabled) {
164
178
  `, enabled);
165
179
  }
166
180
  async function pauseCaptchaSolver(context) {
167
- if (!(0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
181
+ if (!(await (0, _extensionsHelpers.isIntunedExtensionEnabled)())) {
168
182
  throw new Error("Intuned extension is not enabled. Cannot pause captcha solver.");
169
183
  }
170
184
  await setAutoSolve(context, false);
171
185
  }
172
186
  async function resumeCaptchaSolver(context) {
173
- if (!(0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
187
+ if (!(await (0, _extensionsHelpers.isIntunedExtensionEnabled)())) {
174
188
  throw new Error("Intuned extension is not enabled. Cannot resume captcha solver.");
175
189
  }
176
190
  await setAutoSolve(context, true);
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@intuned/runtime",
3
- "version": "1.3.15",
3
+ "version": "1.3.17",
4
4
  "description": "Intuned runtime",
5
+ "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
5
6
  "exports": {
6
7
  ".": "./dist/index.js",
7
8
  "./dist/runtime": "./dist/runtime/index.js",
@@ -70,18 +71,19 @@
70
71
  "commander": "14.0.0",
71
72
  "cross-fetch": "^4.0.0",
72
73
  "dotenv": "^16.3.1",
73
- "fastify": "4.29.0",
74
+ "fastify": "4.29.1",
74
75
  "fs-extra": "^11.3.0",
76
+ "ignore": "^7.0.5",
75
77
  "image-size": "^1.1.1",
76
78
  "jsonc-parser": "^3.3.1",
77
79
  "jsonwebtoken": "9.0.2",
78
80
  "lodash": "4.17.21",
79
81
  "milliparsec": "2.3.0",
80
- "minimatch": "10.0.1",
81
82
  "nanoid": "3",
82
83
  "neverthrow": "6.1.0",
83
84
  "playwright-extra": "4.3.6",
84
85
  "portfinder": "^1.0.37",
86
+ "press-any-key": "^1.1.0",
85
87
  "prettier": "2.8.0",
86
88
  "promptly": "3.2.0",
87
89
  "prompts": "^2.4.2",
@@ -1 +0,0 @@
1
- export declare const initCommand: import("commander").Command;
@@ -1,13 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.initCommand = void 0;
7
- var _command = require("./command");
8
- var _helpers = require("../helpers");
9
- const initCommand = exports.initCommand = _command.program.command("init").description("Deprecated: Initialize a new Intuned project").allowExcessArguments(true).allowUnknownOption(true).action((0, _helpers.cliCommandWrapper)(undefined, undefined, async () => {
10
- throw new _helpers.CLIError("^r^+The init command has been deprecated. Please use^ ^c^/npx create-intuned-project^ ^r^+instead.^:", {
11
- autoColor: false
12
- });
13
- }));
@@ -1,42 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.saveOrDeployOptionsSchema = exports.saveOrDeployArgsSchema = exports.saveCommand = void 0;
7
- var _command = require("./command");
8
- var _dotenv = _interopRequireDefault(require("dotenv"));
9
- var _save = require("../controller/save");
10
- var _helpers = require("../helpers");
11
- var _zod = require("zod");
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
- _dotenv.default.config({
14
- path: `.env`
15
- });
16
- const saveOrDeployArgsSchema = exports.saveOrDeployArgsSchema = _zod.z.tuple([_zod.z.union([_zod.z.string(), _zod.z.undefined()])]);
17
- const saveOrDeployOptionsSchema = exports.saveOrDeployOptionsSchema = _zod.z.object({
18
- workspaceId: _zod.z.string().optional(),
19
- apiKey: _zod.z.string().optional()
20
- });
21
- const saveCommand = exports.saveCommand = _command.program.command("save").description("Save an Intuned project to the platform without deploying it").argument("[project-name]", "Name of the project to save").option("-w, --workspace-id <id>", "Your Intuned workspace ID").option("-k, --api-key <key>", "Your Intuned API key").action((0, _helpers.cliCommandWrapper)(saveOrDeployArgsSchema, saveOrDeployOptionsSchema, async ([projectName], options) => {
22
- const {
23
- isValid,
24
- errorMessage
25
- } = await (0, _save.validateIntunedProject)();
26
- if (!isValid) {
27
- const message = `^r^+Project to be saved is not a valid Intuned project:^:^R ${errorMessage}:\n`;
28
- throw new _helpers.CLIError(message, {
29
- autoColor: false
30
- });
31
- }
32
- const _projectName = projectName || (await (0, _helpers.loadIntunedJson)()).projectName;
33
- if (!_projectName) {
34
- throw new _helpers.CLIError("Project name is required");
35
- }
36
- const projectNameValidation = (0, _save.validateProjectName)(_projectName);
37
- if (!projectNameValidation.isValid) {
38
- throw new _helpers.CLIError(projectNameValidation.errorMessage);
39
- }
40
- const auth = await (0, _helpers.getAuthCredentials)(options);
41
- await (0, _save.runSaveProject)(_projectName, auth);
42
- }));
@@ -1,351 +0,0 @@
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
- enableFirstRunExperience: _zod.z.boolean().optional()
38
- }));
39
- async function runSaveProject(projectName, auth) {
40
- const {
41
- workspaceId,
42
- apiKey
43
- } = auth;
44
- const baseUrl = (0, _helpers.getBaseUrl)();
45
- const url = `${baseUrl}/api/v1/workspace/${workspaceId}/projects/${projectName}`;
46
- const headers = {
47
- [_constants2.API_KEY_HEADER_NAME]: apiKey,
48
- "Content-Type": "application/json"
49
- };
50
- const projectPath = process.cwd();
51
- const codeTree = await convertProjectToCodeTree(projectPath);
52
- const intunedSettingsFile = await (0, _helpers.getIntunedSettingsFile)();
53
- codeTree["Intuned.json"] = {
54
- file: {
55
- contents: JSON.stringify(intunedSettingsFile.parse(await fs.readFile(intunedSettingsFile.path, "utf-8")))
56
- }
57
- };
58
- codeTree["tsconfig.json"] = {
59
- file: {
60
- contents: JSON.stringify(_constants.tsConfigCli, null, 2)
61
- }
62
- };
63
- const saveProjectPayload = {
64
- codeTree,
65
- platformType: "CLI",
66
- language: "typescript"
67
- };
68
- const response = await fetch(url, {
69
- headers,
70
- method: "PUT",
71
- body: JSON.stringify(saveProjectPayload)
72
- });
73
- if (!response.ok) {
74
- if (response.status === 401) {
75
- throw new _helpers.CLIError(`Invalid API key. Please check your API key and try again.`);
76
- }
77
- throw new _helpers.CLIError(`^r^+Invalid response from server\n^:^R${response.status} ${await response.text()}^:\n^r^+Project save failed^:\n`, {
78
- autoColor: false
79
- });
80
- }
81
- (0, _terminal.terminal)("^g^+Project saved successfully!^:\n");
82
- const body = await response.text();
83
- const parseResult = saveProjectApiResponseSchema.safeParse(body);
84
- if (!parseResult.success) {
85
- (0, _terminal.terminal)(`^yWarning: Could not parse save project response:^:\n`);
86
- (0, _terminal.terminal)(body + "\n");
87
- return;
88
- }
89
- const {
90
- id: projectId,
91
- enableFirstRunExperience
92
- } = parseResult.data;
93
- const dotEnvPath = path.join(projectPath, ".env");
94
- if (!(await fs.exists(dotEnvPath))) {
95
- await fs.writeFile(dotEnvPath, `${_constants2.PROJECT_ID_ENV_VAR_KEY}=${projectId}
96
- ${_constants2.WORKSPACE_ID_ENV_VAR_KEY}=${workspaceId}
97
- ${_constants2.API_KEY_ENV_VAR_KEY}=${apiKey}`);
98
- (0, _terminal.terminal)(`^g^+Created .env file with project credentials.^:\n`);
99
- }
100
- const envContent = await fs.readFile(dotEnvPath, "utf-8");
101
- const dotenvContent = dotenv.parse(envContent);
102
- let contentToAppend = "";
103
- if (!dotenvContent[_constants2.PROJECT_ID_ENV_VAR_KEY] || dotenvContent[_constants2.PROJECT_ID_ENV_VAR_KEY] !== projectId) {
104
- contentToAppend += `\n${_constants2.PROJECT_ID_ENV_VAR_KEY}=${projectId}`;
105
- }
106
- if (!dotenvContent[_constants2.WORKSPACE_ID_ENV_VAR_KEY]) {
107
- contentToAppend += `\n${_constants2.WORKSPACE_ID_ENV_VAR_KEY}=${workspaceId}`;
108
- }
109
- if (!dotenvContent[_constants2.API_KEY_ENV_VAR_KEY]) {
110
- contentToAppend += `\n${_constants2.API_KEY_ENV_VAR_KEY}=${apiKey}`;
111
- }
112
- if (contentToAppend) {
113
- await fs.appendFile(dotEnvPath, contentToAppend + "\n");
114
- (0, _terminal.terminal)(`^g^+Updated .env file with project credentials.^:\n`);
115
- }
116
- return {
117
- projectId,
118
- enableFirstRunExperience
119
- };
120
- }
121
- const projectNameSchema = exports.projectNameSchema = _zod.z.string().min(1, "Project Name is required").max(200, "Name must be 200 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, {
122
- message: "Name cannot be a UUID"
123
- });
124
- const validateProjectName = projectName => {
125
- const validation = projectNameSchema.safeParse(projectName);
126
- if (!validation.success) {
127
- return {
128
- isValid: false,
129
- errorMessage: validation.error.errors[0].message
130
- };
131
- }
132
- return {
133
- isValid: true
134
- };
135
- };
136
- exports.validateProjectName = validateProjectName;
137
- const validateIntunedProject = async () => {
138
- const currentDirectoryToSave = process.cwd();
139
- const intunedSettingsFile = await (0, _helpers.getIntunedSettingsFile)();
140
- const validationSteps = [{
141
- name: "build",
142
- check: async () => {
143
- try {
144
- const buildResult = await (0, _build.runBuild)();
145
- if (!buildResult) {
146
- return {
147
- isValid: false,
148
- errorMessage: "Build failed"
149
- };
150
- }
151
- return {
152
- isValid: true
153
- };
154
- } catch (error) {
155
- return {
156
- isValid: false,
157
- errorMessage: "Build failed"
158
- };
159
- }
160
- }
161
- }, {
162
- name: intunedSettingsFile.name,
163
- check: async () => {
164
- try {
165
- const intunedJsonPath = path.join(currentDirectoryToSave, intunedSettingsFile.name);
166
- await fs.exists(intunedJsonPath);
167
- return {
168
- isValid: true
169
- };
170
- } catch (error) {
171
- return {
172
- isValid: false,
173
- errorMessage: `${intunedSettingsFile.name} file not found`
174
- };
175
- }
176
- }
177
- }, {
178
- name: "api folder",
179
- check: async () => {
180
- try {
181
- const apiFolderPath = path.join(currentDirectoryToSave, "api");
182
- await fs.access(apiFolderPath);
183
- return {
184
- isValid: true
185
- };
186
- } catch (error) {
187
- return {
188
- isValid: false,
189
- errorMessage: "API folder not found"
190
- };
191
- }
192
- }
193
- }];
194
- for (const step of validationSteps) {
195
- const result = await step.check();
196
- if (!result.isValid) {
197
- return result;
198
- }
199
- }
200
- return {
201
- isValid: true
202
- };
203
- };
204
- exports.validateIntunedProject = validateIntunedProject;
205
- function ignoreFilesByPattern(filePath, patterns, projectPath) {
206
- const relativePath = path.relative(projectPath, filePath);
207
- if (relativePath.startsWith("node_modules")) {
208
- return true;
209
- }
210
- for (const pattern of patterns) {
211
- if (!pattern || pattern.startsWith("#")) continue;
212
- if (pattern.startsWith("!")) {
213
- if ((0, _minimatch.minimatch)(relativePath, pattern.substring(1))) {
214
- return false;
215
- }
216
- } else if ((0, _minimatch.minimatch)(relativePath, pattern)) {
217
- return true;
218
- }
219
- }
220
- return false;
221
- }
222
- function listFilesNotIgnored(projectPath, ignorePatterns) {
223
- const results = [];
224
- function traverseDirectory(dirPath) {
225
- try {
226
- const entries = fs.readdirSync(dirPath);
227
- for (const entry of entries) {
228
- const fullPath = path.join(dirPath, entry);
229
- if (ignoreFilesByPattern(fullPath, ignorePatterns, projectPath)) {
230
- continue;
231
- }
232
- try {
233
- const stats = fs.statSync(fullPath);
234
- if (stats.isDirectory()) {
235
- traverseDirectory(fullPath);
236
- } else if (stats.isFile()) {
237
- results.push(path.relative(projectPath, fullPath));
238
- }
239
- } catch (error) {
240
- (0, _terminal.terminal)(`^yWarning: Could not access ${fullPath}^:\n`);
241
- }
242
- }
243
- } catch (error) {
244
- (0, _terminal.terminal)(`^YWarning: Could not read directory ${dirPath}^:\n`);
245
- }
246
- }
247
- traverseDirectory(projectPath);
248
- return results;
249
- }
250
- async function convertProjectToCodeTree(projectPath) {
251
- const filesToSave = listFilesNotIgnored(projectPath, _projectExclusions.default);
252
- const filesToSaveText = " " + filesToSave.join("\n ");
253
- (0, _terminal.terminal)("^CFiles to be saved:^:\n");
254
- (0, _terminal.terminal)(filesToSaveText + "\n");
255
- function readDirectory(dirPath) {
256
- const tree = {};
257
- try {
258
- const entries = fs.readdirSync(dirPath);
259
- for (const entry of entries) {
260
- const entryPath = path.join(dirPath, entry);
261
- if (ignoreFilesByPattern(entryPath, _projectExclusions.default, projectPath)) {
262
- continue;
263
- }
264
- try {
265
- const stats = fs.statSync(entryPath);
266
- if (stats.isFile()) {
267
- try {
268
- const content = fs.readFileSync(entryPath, "utf-8");
269
- tree[entry] = {
270
- file: {
271
- contents: content
272
- }
273
- };
274
- } catch (error) {
275
- (0, _terminal.terminal)(`^yWarning: Could not read file ${entryPath}^:\n`);
276
- }
277
- } else if (stats.isDirectory()) {
278
- const subTree = readDirectory(entryPath);
279
- if (Object.keys(subTree).length > 0) {
280
- tree[entry] = {
281
- directory: subTree
282
- };
283
- }
284
- }
285
- } catch (error) {
286
- (0, _terminal.terminal)(`^yWarning: Could not access ${entryPath}^:\n`);
287
- }
288
- }
289
- } catch (error) {
290
- (0, _terminal.terminal)(`^YWarning: Could not read directory ${dirPath}^:\n`);
291
- }
292
- return tree;
293
- }
294
- const tree = readDirectory(projectPath);
295
- mapToIDEParams(tree);
296
- return tree;
297
- }
298
- function mapToIDEParams(tree) {
299
- if (!tree) {
300
- return;
301
- }
302
- if (!tree["parameters"] || "file" in tree["parameters"]) {
303
- return;
304
- }
305
- const apiParametersMap = {};
306
- const cliParameters = Object.keys(tree["parameters"].directory);
307
- const ____testParameters = {
308
- directory: {}
309
- };
310
- for (const parameterKey of cliParameters) {
311
- const parameter = tree["parameters"].directory[parameterKey];
312
- if ("directory" in parameter) {
313
- continue;
314
- }
315
- if ((0, _lodash.isEmpty)(parameter.file.contents)) {
316
- continue;
317
- }
318
- const parameterPayload = JSON.parse(parameter.file.contents);
319
- if (!parameterPayload["__api-name"]) {
320
- continue;
321
- }
322
- const api = parameterPayload["__api-name"];
323
- const {
324
- "__api-name": _,
325
- ...parameterValue
326
- } = parameterPayload;
327
- const testParameter = {
328
- name: parameterKey.replace(".json", ""),
329
- lastUsed: false,
330
- id: (0, _uuid.v4)(),
331
- value: JSON.stringify(parameterValue)
332
- };
333
- if (!apiParametersMap[api]) {
334
- apiParametersMap[api] = [];
335
- }
336
- apiParametersMap[api].push(testParameter);
337
- }
338
- for (const api in apiParametersMap) {
339
- if (apiParametersMap[api].length > 0) {
340
- apiParametersMap[api][apiParametersMap[api].length - 1].lastUsed = true;
341
- }
342
- ____testParameters.directory[`${api}.json`] = {
343
- file: {
344
- contents: JSON.stringify(apiParametersMap[api], null, 2)
345
- }
346
- };
347
- }
348
- delete tree["parameters"];
349
- tree["____testParameters"] = ____testParameters;
350
- return;
351
- }
File without changes