farseer-cli 1.0.9 → 1.0.10

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 (81) hide show
  1. package/dist/commands/app.js +344 -316
  2. package/dist/commands/apps.js +83 -103
  3. package/dist/commands/checkout.js +156 -134
  4. package/dist/commands/config.js +126 -124
  5. package/dist/commands/diff.js +194 -169
  6. package/dist/commands/dimensions.js +122 -137
  7. package/dist/commands/files.js +77 -88
  8. package/dist/commands/install.js +77 -74
  9. package/dist/commands/list.js +74 -89
  10. package/dist/commands/login.js +101 -126
  11. package/dist/commands/logout.js +42 -57
  12. package/dist/commands/mcp-server.js +24 -39
  13. package/dist/commands/model.js +176 -184
  14. package/dist/commands/pull.js +276 -248
  15. package/dist/commands/push.js +222 -200
  16. package/dist/commands/run.js +322 -274
  17. package/dist/commands/status.js +170 -147
  18. package/dist/commands/variables.js +192 -168
  19. package/dist/commands/whoami.js +45 -61
  20. package/dist/index.js +115 -117
  21. package/dist/mcp/index.js +17 -33
  22. package/dist/mcp/prompts/workflows.js +146 -191
  23. package/dist/mcp/resources/documentation.js +149 -158
  24. package/dist/mcp/server.js +34 -50
  25. package/dist/mcp/tools/appTools.js +278 -307
  26. package/dist/mcp/tools/authTools.js +123 -130
  27. package/dist/mcp/tools/dataTools.js +271 -275
  28. package/dist/mcp/tools/modelTools.js +233 -265
  29. package/dist/mcp/tools/runTools.js +205 -199
  30. package/dist/mcp/tools/syncTools.js +315 -341
  31. package/dist/mcp/utils/helpers.js +124 -117
  32. package/dist/services/appSyncService.js +438 -379
  33. package/dist/services/configService.js +144 -154
  34. package/dist/services/farseerApi.js +401 -401
  35. package/dist/services/farseerFactory.js +274 -208
  36. package/dist/services/farseerService.js +488 -455
  37. package/dist/services/syncService.js +732 -657
  38. package/dist/utils/constants.js +20 -45
  39. package/dist/utils/helpers.js +366 -333
  40. package/dist/utils/logger.js +43 -74
  41. package/package.json +8 -1
  42. package/dist/commands/app.js.map +0 -7
  43. package/dist/commands/apps.js.map +0 -7
  44. package/dist/commands/checkout.js.map +0 -7
  45. package/dist/commands/config.js.map +0 -7
  46. package/dist/commands/diff.js.map +0 -7
  47. package/dist/commands/dimensions.js.map +0 -7
  48. package/dist/commands/files.js.map +0 -7
  49. package/dist/commands/install.js.map +0 -7
  50. package/dist/commands/list.js.map +0 -7
  51. package/dist/commands/login.js.map +0 -7
  52. package/dist/commands/logout.js.map +0 -7
  53. package/dist/commands/mcp-server.js.map +0 -7
  54. package/dist/commands/model.js.map +0 -7
  55. package/dist/commands/pull.js.map +0 -7
  56. package/dist/commands/push.js.map +0 -7
  57. package/dist/commands/run.js.map +0 -7
  58. package/dist/commands/status.js.map +0 -7
  59. package/dist/commands/variables.js.map +0 -7
  60. package/dist/commands/whoami.js.map +0 -7
  61. package/dist/index.js.map +0 -7
  62. package/dist/mcp/index.js.map +0 -7
  63. package/dist/mcp/prompts/workflows.js.map +0 -7
  64. package/dist/mcp/resources/documentation.js.map +0 -7
  65. package/dist/mcp/server.js.map +0 -7
  66. package/dist/mcp/tools/appTools.js.map +0 -7
  67. package/dist/mcp/tools/authTools.js.map +0 -7
  68. package/dist/mcp/tools/dataTools.js.map +0 -7
  69. package/dist/mcp/tools/modelTools.js.map +0 -7
  70. package/dist/mcp/tools/runTools.js.map +0 -7
  71. package/dist/mcp/tools/syncTools.js.map +0 -7
  72. package/dist/mcp/utils/helpers.js.map +0 -7
  73. package/dist/services/appSyncService.js.map +0 -7
  74. package/dist/services/configService.js.map +0 -7
  75. package/dist/services/farseerApi.js.map +0 -7
  76. package/dist/services/farseerFactory.js.map +0 -7
  77. package/dist/services/farseerService.js.map +0 -7
  78. package/dist/services/syncService.js.map +0 -7
  79. package/dist/utils/constants.js.map +0 -7
  80. package/dist/utils/helpers.js.map +0 -7
  81. package/dist/utils/logger.js.map +0 -7
@@ -1,288 +1,336 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
- var run_exports = {};
29
- __export(run_exports, {
30
- registerRunCommand: () => registerRunCommand
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
31
17
  });
32
- module.exports = __toCommonJS(run_exports);
33
- var import_logger = require("../utils/logger");
34
- var import_configService = require("../services/configService");
35
- var import_farseerService = require("../services/farseerService");
36
- var import_farseerFactory = require("../services/farseerFactory");
37
- var import_helpers = require("../utils/helpers");
38
- var fs = __toESM(require("fs"));
39
- var path = __toESM(require("path"));
40
- var import_child_process = require("child_process");
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.registerRunCommand = registerRunCommand;
37
+ const logger_1 = require("../utils/logger");
38
+ const configService_1 = require("../services/configService");
39
+ const farseerService_1 = require("../services/farseerService");
40
+ const farseerFactory_1 = require("../services/farseerFactory");
41
+ const helpers_1 = require("../utils/helpers");
42
+ const fs = __importStar(require("fs"));
43
+ const path = __importStar(require("path"));
44
+ const child_process_1 = require("child_process");
45
+ /**
46
+ * Find a script file recursively in a directory.
47
+ * Returns the relative path from baseDir if found, null otherwise.
48
+ */
41
49
  function findScriptRecursively(baseDir, scriptName) {
42
- if (!fs.existsSync(baseDir)) {
43
- return null;
44
- }
45
- const search = (dir, relativePath = "") => {
46
- const items = fs.readdirSync(dir, { withFileTypes: true });
47
- for (const item of items) {
48
- const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;
49
- if (item.isFile() && item.name === scriptName) {
50
- return itemRelPath;
51
- }
52
- if (item.isDirectory()) {
53
- const found = search(path.join(dir, item.name), itemRelPath);
54
- if (found) return found;
55
- }
50
+ if (!fs.existsSync(baseDir)) {
51
+ return null;
56
52
  }
57
- return null;
58
- };
59
- return search(baseDir);
53
+ const search = (dir, relativePath = '') => {
54
+ const items = fs.readdirSync(dir, { withFileTypes: true });
55
+ for (const item of items) {
56
+ const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;
57
+ if (item.isFile() && item.name === scriptName) {
58
+ return itemRelPath;
59
+ }
60
+ if (item.isDirectory()) {
61
+ const found = search(path.join(dir, item.name), itemRelPath);
62
+ if (found)
63
+ return found;
64
+ }
65
+ }
66
+ return null;
67
+ };
68
+ return search(baseDir);
60
69
  }
61
70
  async function getRunCredentials(tenant, tenantId) {
62
- const credential = (0, import_configService.getCredential)(tenant);
63
- if (credential) {
71
+ // First try API key config
72
+ const credential = (0, configService_1.getCredential)(tenant);
73
+ if (credential) {
74
+ return {
75
+ tenantId: credential.tenantId,
76
+ apiKey: credential.apiKey,
77
+ basePath: credential.basePath,
78
+ };
79
+ }
80
+ // Try user auth (browser login)
81
+ const auth = (0, configService_1.getUserAuth)();
82
+ if (!auth) {
83
+ return null;
84
+ }
85
+ // Check if token needs refresh
86
+ if (!(0, configService_1.isUserAuthValid)()) {
87
+ logger_1.logger.dim('Token expired, refreshing...');
88
+ const refreshed = await (0, farseerService_1.refreshAccessToken)(auth.refreshToken, auth.realm || 'master');
89
+ if (!refreshed) {
90
+ logger_1.logger.warning('Could not refresh token. Please login again with: farseer login');
91
+ return null;
92
+ }
93
+ // Save refreshed token
94
+ (0, configService_1.setUserAuth)({
95
+ accessToken: refreshed.accessToken,
96
+ refreshToken: refreshed.refreshToken,
97
+ expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),
98
+ realm: auth.realm,
99
+ });
100
+ logger_1.logger.success('Token refreshed');
101
+ }
102
+ const updatedAuth = (0, configService_1.getUserAuth)();
103
+ if (!updatedAuth)
104
+ return null;
105
+ // Use tenant name as organisation for basePath, tenantId for TENANT_ID env var
64
106
  return {
65
- tenantId: credential.tenantId,
66
- apiKey: credential.apiKey,
67
- basePath: credential.basePath
107
+ tenantId: tenantId || tenant,
108
+ accessToken: updatedAuth.accessToken,
109
+ basePath: (0, configService_1.generateBasePath)(tenant),
68
110
  };
69
- }
70
- const auth = (0, import_configService.getUserAuth)();
71
- if (!auth) {
72
- return null;
73
- }
74
- if (!(0, import_configService.isUserAuthValid)()) {
75
- import_logger.logger.dim("Token expired, refreshing...");
76
- const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
77
- if (!refreshed) {
78
- import_logger.logger.warning("Could not refresh token. Please login again with: farseer login");
79
- return null;
80
- }
81
- (0, import_configService.setUserAuth)({
82
- accessToken: refreshed.accessToken,
83
- refreshToken: refreshed.refreshToken,
84
- expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
85
- realm: auth.realm
86
- });
87
- import_logger.logger.success("Token refreshed");
88
- }
89
- const updatedAuth = (0, import_configService.getUserAuth)();
90
- if (!updatedAuth) return null;
91
- return {
92
- tenantId: tenantId || tenant,
93
- accessToken: updatedAuth.accessToken,
94
- basePath: (0, import_configService.generateBasePath)(tenant)
95
- };
96
111
  }
112
+ // Helper to collect multiple --arg options
97
113
  function collectArgs(value, previous) {
98
- return previous.concat([value]);
114
+ return previous.concat([value]);
99
115
  }
100
116
  function registerRunCommand(program) {
101
- program.command("run <args...>").description("Run an app locally with injected credentials").option("--tenant-id <id>", "Tenant ID for env variables (defaults to tenant name)").option("--arg <value>", 'Pass argument in format "Name=Value" (can be used multiple times)', collectArgs, []).action(async (args, options) => {
102
- const { tenant, appName } = (0, import_helpers.parseAppArgs)(args);
103
- const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(tenant, options.tenantId);
104
- if (!clientResult) {
105
- (0, import_farseerFactory.showLoginPrompt)(tenant);
106
- process.exit(1);
107
- }
108
- const api = clientResult.client;
109
- import_logger.logger.info(`Loading app: ${appName}...`);
110
- const app = await api.getAppByName(appName);
111
- if (!app) {
112
- import_logger.logger.error(`App not found: ${appName}`);
113
- import_logger.logger.dim("List available apps with: farseer apps " + tenant);
114
- process.exit(1);
115
- }
116
- if (!app.mainScriptFileId || app.scriptFiles.length === 0) {
117
- import_logger.logger.error(`App "${appName}" has no scripts configured.`);
118
- import_logger.logger.dim('Configure the app with: farseer app configure "' + appName + '" --entrypoint <script>');
119
- process.exit(1);
120
- }
121
- const mainScript = app.scriptFiles.find((s) => s.id === app.mainScriptFileId);
122
- if (!mainScript) {
123
- import_logger.logger.error(`Entrypoint script not found for app "${appName}".`);
124
- process.exit(1);
125
- }
126
- let scriptName = mainScript.name;
127
- if (scriptName.toLowerCase().startsWith("scripts/")) {
128
- scriptName = scriptName.substring("scripts/".length);
129
- }
130
- const credentials = await getRunCredentials(tenant, options.tenantId);
131
- if (!credentials) {
132
- (0, import_farseerFactory.showLoginPrompt)(tenant);
133
- process.exit(1);
134
- }
135
- const tenantDir = (0, import_helpers.getTenantDir)(tenant);
136
- const srcDir = (0, import_helpers.getTenantSrcDir)(tenant);
137
- const filesDir = (0, import_helpers.getTenantFilesDir)(tenant);
138
- let scriptPath = path.resolve(srcDir, scriptName);
139
- let relativeScriptPath = `files/Scripts/${scriptName}`;
140
- if (!fs.existsSync(scriptPath)) {
141
- const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));
142
- if (foundPath) {
143
- scriptPath = path.resolve(filesDir, foundPath);
144
- relativeScriptPath = `files/${foundPath}`;
145
- import_logger.logger.dim(`Found script at: ${foundPath}`);
146
- }
147
- }
148
- if (!fs.existsSync(scriptPath)) {
149
- import_logger.logger.error(`Script not found locally: ${scriptPath}`);
150
- import_logger.logger.dim('Run "farseer pull ' + tenant + '" to download scripts first.');
151
- process.exit(1);
152
- }
153
- const nodeModulesPath = path.join(tenantDir, "node_modules");
154
- if (!fs.existsSync(nodeModulesPath)) {
155
- import_logger.logger.error(`Dependencies not installed for ${tenant}`);
156
- import_logger.logger.dim(`Run: farseer install ${tenant}`);
157
- process.exit(1);
158
- }
159
- const appArgs = {};
160
- for (const arg of app.expectedArguments) {
161
- appArgs[arg.name] = arg.defaultValue;
162
- }
163
- for (const argStr of options.arg) {
164
- const eqIndex = argStr.indexOf("=");
165
- if (eqIndex === -1) {
166
- import_logger.logger.error(`Invalid argument format: ${argStr}`);
167
- import_logger.logger.dim('Use format: --arg "Name=Value"');
168
- process.exit(1);
169
- }
170
- const name = argStr.substring(0, eqIndex);
171
- const value = argStr.substring(eqIndex + 1);
172
- appArgs[name] = value;
173
- }
174
- const authType = credentials.apiKey ? "API key" : "access token";
175
- import_logger.logger.info(`Running app "${app.name}" (${scriptName}) for tenant ${tenant} (using ${authType})...`);
176
- if (Object.keys(appArgs).length > 0) {
177
- import_logger.logger.dim("Arguments:");
178
- for (const [key, value] of Object.entries(appArgs)) {
179
- import_logger.logger.dim(` ${key}: ${value}`);
180
- }
181
- }
182
- console.log();
183
- const envVars = {
184
- ...process.env,
185
- TENANT_ID: credentials.tenantId,
186
- FARSEER_URL: credentials.basePath
187
- };
188
- if (credentials.apiKey) {
189
- envVars.FARSEER_API_KEY = credentials.apiKey;
190
- }
191
- if (credentials.accessToken) {
192
- envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
193
- }
194
- const cmdArgs = [];
195
- for (const arg of app.expectedArguments) {
196
- cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue);
197
- }
198
- const quotedScriptPath = `"${relativeScriptPath}"`;
199
- const child = (0, import_child_process.spawn)("npx", ["tsx", quotedScriptPath, ...cmdArgs], {
200
- stdio: "inherit",
201
- cwd: tenantDir,
202
- shell: true,
203
- env: envVars
204
- });
205
- child.on("close", (code) => {
206
- if (code !== 0) {
207
- import_logger.logger.error(`Script exited with code ${code}`);
208
- process.exit(code || 1);
209
- }
117
+ program
118
+ .command('run <args...>')
119
+ .description('Run an app locally with injected credentials')
120
+ .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')
121
+ .option('--arg <value>', 'Pass argument in format "Name=Value" (can be used multiple times)', collectArgs, [])
122
+ .action(async (args, options) => {
123
+ const { tenant, appName } = (0, helpers_1.parseAppArgs)(args);
124
+ // First, get the app details to find the entrypoint script
125
+ const clientResult = await (0, farseerFactory_1.getFarseerClientWithFallback)(tenant, options.tenantId);
126
+ if (!clientResult) {
127
+ (0, farseerFactory_1.showLoginPrompt)(tenant);
128
+ process.exit(1);
129
+ }
130
+ const api = clientResult.client;
131
+ // Find the app
132
+ logger_1.logger.info(`Loading app: ${appName}...`);
133
+ const app = await api.getAppByName(appName);
134
+ if (!app) {
135
+ logger_1.logger.error(`App not found: ${appName}`);
136
+ logger_1.logger.dim('List available apps with: farseer apps ' + tenant);
137
+ process.exit(1);
138
+ }
139
+ const runScripts = app.scriptFiles ?? [];
140
+ if (!app.mainScriptFileId || runScripts.length === 0) {
141
+ logger_1.logger.error(`App "${appName}" has no scripts configured.`);
142
+ logger_1.logger.dim('Configure the app with: farseer app configure "' + appName + '" --entrypoint <script>');
143
+ process.exit(1);
144
+ }
145
+ // Find the entrypoint script name
146
+ const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);
147
+ if (!mainScript) {
148
+ logger_1.logger.error(`Entrypoint script not found for app "${appName}".`);
149
+ process.exit(1);
150
+ }
151
+ // Normalize script name - handle both "test.ts" and "Scripts/test.ts" formats
152
+ let scriptName = mainScript.name;
153
+ if (scriptName.toLowerCase().startsWith('scripts/')) {
154
+ scriptName = scriptName.substring('scripts/'.length);
155
+ }
156
+ // Get credentials for running
157
+ const credentials = await getRunCredentials(tenant, options.tenantId);
158
+ if (!credentials) {
159
+ (0, farseerFactory_1.showLoginPrompt)(tenant);
160
+ process.exit(1);
161
+ }
162
+ const tenantDir = (0, helpers_1.getTenantDir)(tenant);
163
+ const srcDir = (0, helpers_1.getTenantSrcDir)(tenant);
164
+ const filesDir = (0, helpers_1.getTenantFilesDir)(tenant);
165
+ // Script path is relative to files/Scripts/ folder
166
+ // First try direct path, then search recursively if not found
167
+ let scriptPath = path.resolve(srcDir, scriptName);
168
+ let relativeScriptPath = `files/Scripts/${scriptName}`;
169
+ if (!fs.existsSync(scriptPath)) {
170
+ // Try to find the script recursively in the files directory
171
+ const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));
172
+ if (foundPath) {
173
+ scriptPath = path.resolve(filesDir, foundPath);
174
+ relativeScriptPath = `files/${foundPath}`;
175
+ logger_1.logger.dim(`Found script at: ${foundPath}`);
176
+ }
177
+ }
178
+ if (!fs.existsSync(scriptPath)) {
179
+ logger_1.logger.error(`Script not found locally: ${scriptPath}`);
180
+ logger_1.logger.dim('Run "farseer pull ' + tenant + '" to download scripts first.');
181
+ process.exit(1);
182
+ }
183
+ // Check if node_modules exists
184
+ const nodeModulesPath = path.join(tenantDir, 'node_modules');
185
+ if (!fs.existsSync(nodeModulesPath)) {
186
+ logger_1.logger.error(`Dependencies not installed for ${tenant}`);
187
+ logger_1.logger.dim(`Run: farseer install ${tenant}`);
188
+ process.exit(1);
189
+ }
190
+ // Parse arguments
191
+ const appArgs = {};
192
+ // Start with default values from app config
193
+ for (const arg of app.expectedArguments) {
194
+ appArgs[arg.name] = arg.defaultValue;
195
+ }
196
+ // Override with provided arguments
197
+ for (const argStr of options.arg) {
198
+ const eqIndex = argStr.indexOf('=');
199
+ if (eqIndex === -1) {
200
+ logger_1.logger.error(`Invalid argument format: ${argStr}`);
201
+ logger_1.logger.dim('Use format: --arg "Name=Value"');
202
+ process.exit(1);
203
+ }
204
+ const name = argStr.substring(0, eqIndex);
205
+ const value = argStr.substring(eqIndex + 1);
206
+ appArgs[name] = value;
207
+ }
208
+ const authType = credentials.apiKey ? 'API key' : 'access token';
209
+ logger_1.logger.info(`Running app "${app.name}" (${scriptName}) for tenant ${tenant} (using ${authType})...`);
210
+ // Show arguments being used
211
+ if (Object.keys(appArgs).length > 0) {
212
+ logger_1.logger.dim('Arguments:');
213
+ for (const [key, value] of Object.entries(appArgs)) {
214
+ logger_1.logger.dim(` ${key}: ${value}`);
215
+ }
216
+ }
217
+ console.log();
218
+ // Build environment variables based on auth type
219
+ const envVars = {
220
+ ...process.env,
221
+ TENANT_ID: credentials.tenantId,
222
+ FARSEER_URL: credentials.basePath,
223
+ };
224
+ if (credentials.apiKey) {
225
+ envVars.FARSEER_API_KEY = credentials.apiKey;
226
+ }
227
+ if (credentials.accessToken) {
228
+ envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
229
+ }
230
+ // Build command line arguments from app arguments (in order)
231
+ const cmdArgs = [];
232
+ for (const arg of app.expectedArguments) {
233
+ cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue);
234
+ }
235
+ // Run with credentials injected via environment variables, arguments via command line
236
+ // Quote the script path to handle spaces in folder names
237
+ const quotedScriptPath = `"${relativeScriptPath}"`;
238
+ const child = (0, child_process_1.spawn)('npx', ['tsx', quotedScriptPath, ...cmdArgs], {
239
+ stdio: 'inherit',
240
+ cwd: tenantDir,
241
+ shell: true,
242
+ env: envVars,
243
+ });
244
+ child.on('close', (code) => {
245
+ if (code !== 0) {
246
+ logger_1.logger.error(`Script exited with code ${code}`);
247
+ process.exit(code || 1);
248
+ }
249
+ });
250
+ child.on('error', (err) => {
251
+ logger_1.logger.error(`Failed to run script: ${err.message}`);
252
+ logger_1.logger.dim('Make sure tsx is installed: npm install -g tsx');
253
+ process.exit(1);
254
+ });
210
255
  });
211
- child.on("error", (err) => {
212
- import_logger.logger.error(`Failed to run script: ${err.message}`);
213
- import_logger.logger.dim("Make sure tsx is installed: npm install -g tsx");
214
- process.exit(1);
256
+ // Keep the old script-based run as a separate command
257
+ program
258
+ .command('run-script <args...>')
259
+ .description('Run a script directly (without app wrapper)')
260
+ .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')
261
+ .action(async (args, options) => {
262
+ const { tenant, appName } = (0, helpers_1.parseAppArgs)(args);
263
+ let script = appName;
264
+ const credentials = await getRunCredentials(tenant, options.tenantId);
265
+ if (!credentials) {
266
+ (0, farseerFactory_1.showLoginPrompt)(tenant);
267
+ process.exit(1);
268
+ }
269
+ // Normalize script path - strip Scripts/ prefix if present
270
+ if (script.toLowerCase().startsWith('scripts/')) {
271
+ script = script.substring('scripts/'.length);
272
+ }
273
+ const tenantDir = (0, helpers_1.getTenantDir)(tenant);
274
+ const srcDir = (0, helpers_1.getTenantSrcDir)(tenant);
275
+ const filesDir = (0, helpers_1.getTenantFilesDir)(tenant);
276
+ // Script path is relative to files/Scripts/ folder
277
+ // First try direct path, then search recursively if not found
278
+ let scriptPath = path.resolve(srcDir, script);
279
+ let relativeScriptPath = `files/Scripts/${script}`;
280
+ if (!fs.existsSync(scriptPath)) {
281
+ // Try to find the script recursively in the files directory
282
+ const foundPath = findScriptRecursively(filesDir, path.basename(script));
283
+ if (foundPath) {
284
+ scriptPath = path.resolve(filesDir, foundPath);
285
+ relativeScriptPath = `files/${foundPath}`;
286
+ logger_1.logger.dim(`Found script at: ${foundPath}`);
287
+ }
288
+ }
289
+ if (!fs.existsSync(scriptPath)) {
290
+ logger_1.logger.error(`Script not found: ${scriptPath}`);
291
+ process.exit(1);
292
+ }
293
+ // Check if node_modules exists
294
+ const nodeModulesPath = path.join(tenantDir, 'node_modules');
295
+ if (!fs.existsSync(nodeModulesPath)) {
296
+ logger_1.logger.error(`Dependencies not installed for ${tenant}`);
297
+ logger_1.logger.dim(`Run: farseer install ${tenant}`);
298
+ process.exit(1);
299
+ }
300
+ const authType = credentials.apiKey ? 'API key' : 'access token';
301
+ logger_1.logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);
302
+ console.log();
303
+ // Build environment variables based on auth type
304
+ const envVars = {
305
+ ...process.env,
306
+ TENANT_ID: credentials.tenantId,
307
+ FARSEER_URL: credentials.basePath,
308
+ };
309
+ if (credentials.apiKey) {
310
+ envVars.FARSEER_API_KEY = credentials.apiKey;
311
+ }
312
+ if (credentials.accessToken) {
313
+ envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
314
+ }
315
+ // Run with credentials injected via environment variables
316
+ // Quote the script path to handle spaces in folder names
317
+ const quotedScriptPath = `"${relativeScriptPath}"`;
318
+ const child = (0, child_process_1.spawn)('npx', ['tsx', quotedScriptPath], {
319
+ stdio: 'inherit',
320
+ cwd: tenantDir,
321
+ shell: true,
322
+ env: envVars,
323
+ });
324
+ child.on('close', (code) => {
325
+ if (code !== 0) {
326
+ logger_1.logger.error(`Script exited with code ${code}`);
327
+ process.exit(code || 1);
328
+ }
329
+ });
330
+ child.on('error', (err) => {
331
+ logger_1.logger.error(`Failed to run script: ${err.message}`);
332
+ logger_1.logger.dim('Make sure tsx is installed: npm install -g tsx');
333
+ process.exit(1);
334
+ });
215
335
  });
216
- });
217
- program.command("run-script <args...>").description("Run a script directly (without app wrapper)").option("--tenant-id <id>", "Tenant ID for env variables (defaults to tenant name)").action(async (args, options) => {
218
- let { tenant, appName: script } = (0, import_helpers.parseAppArgs)(args);
219
- const credentials = await getRunCredentials(tenant, options.tenantId);
220
- if (!credentials) {
221
- (0, import_farseerFactory.showLoginPrompt)(tenant);
222
- process.exit(1);
223
- }
224
- if (script.toLowerCase().startsWith("scripts/")) {
225
- script = script.substring("scripts/".length);
226
- }
227
- const tenantDir = (0, import_helpers.getTenantDir)(tenant);
228
- const srcDir = (0, import_helpers.getTenantSrcDir)(tenant);
229
- const filesDir = (0, import_helpers.getTenantFilesDir)(tenant);
230
- let scriptPath = path.resolve(srcDir, script);
231
- let relativeScriptPath = `files/Scripts/${script}`;
232
- if (!fs.existsSync(scriptPath)) {
233
- const foundPath = findScriptRecursively(filesDir, path.basename(script));
234
- if (foundPath) {
235
- scriptPath = path.resolve(filesDir, foundPath);
236
- relativeScriptPath = `files/${foundPath}`;
237
- import_logger.logger.dim(`Found script at: ${foundPath}`);
238
- }
239
- }
240
- if (!fs.existsSync(scriptPath)) {
241
- import_logger.logger.error(`Script not found: ${scriptPath}`);
242
- process.exit(1);
243
- }
244
- const nodeModulesPath = path.join(tenantDir, "node_modules");
245
- if (!fs.existsSync(nodeModulesPath)) {
246
- import_logger.logger.error(`Dependencies not installed for ${tenant}`);
247
- import_logger.logger.dim(`Run: farseer install ${tenant}`);
248
- process.exit(1);
249
- }
250
- const authType = credentials.apiKey ? "API key" : "access token";
251
- import_logger.logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);
252
- console.log();
253
- const envVars = {
254
- ...process.env,
255
- TENANT_ID: credentials.tenantId,
256
- FARSEER_URL: credentials.basePath
257
- };
258
- if (credentials.apiKey) {
259
- envVars.FARSEER_API_KEY = credentials.apiKey;
260
- }
261
- if (credentials.accessToken) {
262
- envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;
263
- }
264
- const quotedScriptPath = `"${relativeScriptPath}"`;
265
- const child = (0, import_child_process.spawn)("npx", ["tsx", quotedScriptPath], {
266
- stdio: "inherit",
267
- cwd: tenantDir,
268
- shell: true,
269
- env: envVars
270
- });
271
- child.on("close", (code) => {
272
- if (code !== 0) {
273
- import_logger.logger.error(`Script exited with code ${code}`);
274
- process.exit(code || 1);
275
- }
276
- });
277
- child.on("error", (err) => {
278
- import_logger.logger.error(`Failed to run script: ${err.message}`);
279
- import_logger.logger.dim("Make sure tsx is installed: npm install -g tsx");
280
- process.exit(1);
281
- });
282
- });
283
336
  }
284
- // Annotate the CommonJS export names for ESM import in node:
285
- 0 && (module.exports = {
286
- registerRunCommand
287
- });
288
- //# sourceMappingURL=run.js.map