farseer-cli 1.0.9 → 1.1.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.
- package/README.md +19 -0
- package/dist/commands/app.js +50 -18
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/apps.js +14 -6
- package/dist/commands/apps.js.map +2 -2
- package/dist/commands/cells.js +161 -0
- package/dist/commands/cells.js.map +7 -0
- package/dist/commands/checkout.js +10 -3
- package/dist/commands/checkout.js.map +2 -2
- package/dist/commands/config.js +6 -2
- package/dist/commands/config.js.map +2 -2
- package/dist/commands/dashboards.js +130 -0
- package/dist/commands/dashboards.js.map +7 -0
- package/dist/commands/diff.js +4 -1
- package/dist/commands/diff.js.map +2 -2
- package/dist/commands/dimensions.js +91 -3
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/files.js +12 -4
- package/dist/commands/files.js.map +2 -2
- package/dist/commands/formula.js +116 -0
- package/dist/commands/formula.js.map +7 -0
- package/dist/commands/install.js +1 -0
- package/dist/commands/install.js.map +1 -1
- package/dist/commands/list.js +4 -1
- package/dist/commands/list.js.map +2 -2
- package/dist/commands/login.js +16 -2
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/logout.js +4 -1
- package/dist/commands/logout.js.map +2 -2
- package/dist/commands/mcp-server.js +2 -4
- package/dist/commands/mcp-server.js.map +2 -2
- package/dist/commands/model.js +8 -5
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/pull.js +50 -32
- package/dist/commands/pull.js.map +2 -2
- package/dist/commands/push.js +21 -11
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/run.js +6 -3
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/sheets.js +200 -0
- package/dist/commands/sheets.js.map +7 -0
- package/dist/commands/status.js +4 -1
- package/dist/commands/status.js.map +2 -2
- package/dist/commands/variables.js +88 -5
- package/dist/commands/variables.js.map +2 -2
- package/dist/commands/whoami.js +5 -0
- package/dist/commands/whoami.js.map +2 -2
- package/dist/index.js +64 -2
- package/dist/index.js.map +2 -2
- package/dist/mcp/index.js +1 -0
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/prompts/workflows.js +1 -0
- package/dist/mcp/prompts/workflows.js.map +1 -1
- package/dist/mcp/resources/documentation.js +1 -0
- package/dist/mcp/resources/documentation.js.map +2 -2
- package/dist/mcp/server.js +7 -0
- package/dist/mcp/server.js.map +2 -2
- package/dist/mcp/tools/appTools.js +7 -4
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +2 -0
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +148 -0
- package/dist/mcp/tools/cellTools.js.map +7 -0
- package/dist/mcp/tools/dashboardTools.js +133 -0
- package/dist/mcp/tools/dashboardTools.js.map +7 -0
- package/dist/mcp/tools/dataTools.js +22 -23
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +317 -3
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +12 -8
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +240 -0
- package/dist/mcp/tools/sheetTools.js.map +7 -0
- package/dist/mcp/tools/syncTools.js +6 -11
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +2 -1
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/services/appSyncService.js +60 -57
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/configService.js +1 -0
- package/dist/services/configService.js.map +2 -2
- package/dist/services/farseerApi.js +11 -6
- package/dist/services/farseerApi.js.map +2 -2
- package/dist/services/farseerFactory.js +2 -1
- package/dist/services/farseerFactory.js.map +2 -2
- package/dist/services/farseerService.js +34 -35
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/syncService.js +20 -15
- package/dist/services/syncService.js.map +2 -2
- package/dist/utils/constants.js +15 -7
- package/dist/utils/constants.js.map +3 -3
- package/dist/utils/entityResolver.js +78 -0
- package/dist/utils/entityResolver.js.map +7 -0
- package/dist/utils/helpers.js +2 -3
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/logger.js +1 -0
- package/dist/utils/logger.js.map +2 -2
- package/package.json +10 -2
package/dist/commands/pull.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
"use strict";
|
|
1
2
|
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -38,7 +39,9 @@ var import_syncService = require("../services/syncService");
|
|
|
38
39
|
var import_appSyncService = require("../services/appSyncService");
|
|
39
40
|
var import_helpers = require("../utils/helpers");
|
|
40
41
|
function registerPullCommand(program) {
|
|
41
|
-
program.command("pull [org] [tenant]").description(
|
|
42
|
+
program.command("pull [org] [tenant]").description(
|
|
43
|
+
"Pull files from Farseer instance to local\n\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)"
|
|
44
|
+
).option("--all", "Pull all files (default: only scripts .ts, .js)").option("--force", "Force pull, overwriting local changes on conflicts").action(async (arg1, arg2, options) => {
|
|
42
45
|
const { organisation, tenant } = (0, import_helpers.resolveTenantWithOrgMapping)(arg1, arg2);
|
|
43
46
|
const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(organisation, tenant);
|
|
44
47
|
if (!clientResult) {
|
|
@@ -83,12 +86,14 @@ function registerPullCommand(program) {
|
|
|
83
86
|
{ name: "Keep both (save remote as .remote file)", value: "keep_both" }
|
|
84
87
|
];
|
|
85
88
|
}
|
|
86
|
-
const answer = await import_inquirer.default.prompt([
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
89
|
+
const answer = await import_inquirer.default.prompt([
|
|
90
|
+
{
|
|
91
|
+
type: "list",
|
|
92
|
+
name: "resolution",
|
|
93
|
+
message: `${conflict.filePath} - ${conflict.description}`,
|
|
94
|
+
choices
|
|
95
|
+
}
|
|
96
|
+
]);
|
|
92
97
|
resolutions[conflict.filePath] = answer.resolution;
|
|
93
98
|
}
|
|
94
99
|
result = await syncService.pull({ all: options.all, conflictResolutions: resolutions });
|
|
@@ -111,7 +116,9 @@ function registerPullCommand(program) {
|
|
|
111
116
|
console.log(import_chalk.default.yellow(` ~ ${file}`));
|
|
112
117
|
}
|
|
113
118
|
}
|
|
114
|
-
import_logger.logger.dim(
|
|
119
|
+
import_logger.logger.dim(
|
|
120
|
+
`Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`
|
|
121
|
+
);
|
|
115
122
|
if (result.downloaded.length > 0) {
|
|
116
123
|
const syncState = syncService.loadSyncState();
|
|
117
124
|
const auditEntries = result.downloaded.map((filePath) => ({
|
|
@@ -124,7 +131,12 @@ function registerPullCommand(program) {
|
|
|
124
131
|
(0, import_helpers.appendToAuditLog)(tenant, auditEntries);
|
|
125
132
|
}
|
|
126
133
|
let hasChanges = result.downloaded.length > 0 || result.deleted.length > 0;
|
|
127
|
-
let appResult = {
|
|
134
|
+
let appResult = {
|
|
135
|
+
created: [],
|
|
136
|
+
updated: [],
|
|
137
|
+
deleted: [],
|
|
138
|
+
unchanged: []
|
|
139
|
+
};
|
|
128
140
|
console.log();
|
|
129
141
|
console.log(import_chalk.default.bold("\u2550\u2550\u2550 Apps \u2550\u2550\u2550"));
|
|
130
142
|
import_logger.logger.info(`Pulling apps from ${tenant}...`);
|
|
@@ -148,7 +160,9 @@ function registerPullCommand(program) {
|
|
|
148
160
|
console.log(import_chalk.default.red(` - ${app}`));
|
|
149
161
|
}
|
|
150
162
|
}
|
|
151
|
-
import_logger.logger.dim(
|
|
163
|
+
import_logger.logger.dim(
|
|
164
|
+
`Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`
|
|
165
|
+
);
|
|
152
166
|
hasChanges = hasChanges || appResult.created.length > 0 || appResult.updated.length > 0 || appResult.deleted.length > 0;
|
|
153
167
|
if (!hasChanges) {
|
|
154
168
|
import_logger.logger.success("Already up to date.");
|
|
@@ -157,8 +171,12 @@ function registerPullCommand(program) {
|
|
|
157
171
|
console.log();
|
|
158
172
|
console.log(import_chalk.default.bold("\u2550\u2550\u2550 Summary \u2550\u2550\u2550"));
|
|
159
173
|
import_logger.logger.success("Pull complete!");
|
|
160
|
-
import_logger.logger.dim(
|
|
161
|
-
|
|
174
|
+
import_logger.logger.dim(
|
|
175
|
+
`Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`
|
|
176
|
+
);
|
|
177
|
+
import_logger.logger.dim(
|
|
178
|
+
`Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`
|
|
179
|
+
);
|
|
162
180
|
} catch (error) {
|
|
163
181
|
import_logger.logger.error("Pull failed.");
|
|
164
182
|
if (error instanceof Error) {
|
|
@@ -191,42 +209,42 @@ async function createDefaultPackageJson(tenantDir, tenant) {
|
|
|
191
209
|
"@sendgrid/mail": "^7.7.0",
|
|
192
210
|
"@types/node-forge": "^1.3.11",
|
|
193
211
|
"@xmldom/xmldom": "^0.9.8",
|
|
194
|
-
|
|
195
|
-
|
|
212
|
+
arquero: "^5.4.1",
|
|
213
|
+
axios: "^1.10.0",
|
|
196
214
|
"axios-retry": "^3.9.1",
|
|
197
215
|
"basic-ftp": "^5.0.5",
|
|
198
216
|
"client-oauth2": "^4.3.3",
|
|
199
217
|
"csv-parser": "^3.0.0",
|
|
200
|
-
|
|
218
|
+
dotenv: "^16.4.5",
|
|
201
219
|
"draft-js": "^0.11.7",
|
|
202
|
-
|
|
220
|
+
exceljs: "^4.4.0",
|
|
203
221
|
"farseer-client": "https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar",
|
|
204
222
|
"farseer-client-axios": "https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar",
|
|
205
223
|
"fast-xml-parser": "^4.5.0",
|
|
206
224
|
"form-data": "^4.0.0",
|
|
207
|
-
|
|
208
|
-
|
|
225
|
+
googleapis: "^144.0.0",
|
|
226
|
+
heapdump: "^0.3.15",
|
|
209
227
|
"image-size": "^1.1.1",
|
|
210
|
-
|
|
228
|
+
jszip: "^3.10.1",
|
|
211
229
|
"lossless-json": "^4.0.1",
|
|
212
|
-
|
|
230
|
+
mssql: "^10.0.4",
|
|
213
231
|
"node-fetch": "^2.7.0",
|
|
214
232
|
"node-forge": "^1.3.1",
|
|
215
233
|
"node-sp-auth": "^3.0.8",
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
234
|
+
numeral: "^2.0.6",
|
|
235
|
+
oracledb: "^6.6.0",
|
|
236
|
+
papaparse: "^5.5.1",
|
|
237
|
+
pdfkit: "^0.14.0",
|
|
238
|
+
pdfmake: "^0.2.20",
|
|
239
|
+
soap: "^1.1.11",
|
|
222
240
|
"ssh2-sftp-client": "^11.0.0",
|
|
223
241
|
"strong-soap": "^4.1.13",
|
|
224
242
|
"ts-node": "^10.9.2",
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
243
|
+
typescript: "^5.5.4",
|
|
244
|
+
undici: "^6.19.8",
|
|
245
|
+
uuid: "^11.1.0",
|
|
246
|
+
winston: "^3.17.0",
|
|
247
|
+
xlsx: "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
|
|
230
248
|
"xml-crypto": "^6.1.2"
|
|
231
249
|
},
|
|
232
250
|
devDependencies: {
|
|
@@ -245,7 +263,7 @@ async function createDefaultPackageJson(tenantDir, tenant) {
|
|
|
245
263
|
"@types/uuid": "^10.0.0",
|
|
246
264
|
"@types/xmldom": "^0.1.34",
|
|
247
265
|
"ts-node": "^10.9.2",
|
|
248
|
-
|
|
266
|
+
typescript: "^5.5.4"
|
|
249
267
|
}
|
|
250
268
|
};
|
|
251
269
|
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), "utf-8");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/pull.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService, ConflictResolutions } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantDir, ensureDirectoryExists, resolveTenantWithOrgMapping, appendToAuditLog, AuditLogEntry } from '../utils/helpers';\n\nexport function registerPullCommand(program: Command): void {\n program\n .command('pull [org] [tenant]')\n .description('Pull files from Farseer instance to local\\n\\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)')\n .option('--all', 'Pull all files (default: only scripts .ts, .js)')\n .option('--force', 'Force pull, overwriting local changes on conflicts')\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n // Step 1: Ensure tenant folder exists\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n // Create default package.json if it doesn't exist\n await createDefaultPackageJson(tenantDir, tenant);\n\n // Step 2: Pull files from Farseer\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Files \u2550\u2550\u2550'));\n logger.info(`Pulling files from ${tenant}...`);\n\n try {\n let result = await syncService.pull({ all: options.all, force: options.force });\n\n // Handle conflicts interactively\n if (result.conflicts.length > 0 && !options.force) {\n console.log();\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n\n const resolutions: ConflictResolutions = {};\n\n for (const conflict of result.conflicts) {\n let choices: { name: string; value: string }[];\n\n if (conflict.type === 'local_modified_remote_deleted') {\n choices = [\n { name: 'Keep local (keep your modified file)', value: 'keep_local' },\n { name: 'Accept deletion (delete local file)', value: 'keep_remote' },\n ];\n } else if (conflict.type === 'local_deleted_remote_modified') {\n choices = [\n { name: 'Keep deleted (don\\'t restore file)', value: 'keep_local' },\n { name: 'Restore remote version', value: 'keep_remote' },\n ];\n } else {\n choices = [\n { name: 'Keep local version', value: 'keep_local' },\n { name: 'Use remote version (overwrite local)', value: 'keep_remote' },\n { name: 'Keep both (save remote as .remote file)', value: 'keep_both' },\n ];\n }\n\n const answer = await inquirer.prompt([{\n type: 'list',\n name: 'resolution',\n message: `${conflict.filePath} - ${conflict.description}`,\n choices,\n }]);\n\n resolutions[conflict.filePath] = answer.resolution;\n }\n\n // Re-pull with resolutions\n result = await syncService.pull({ all: options.all, conflictResolutions: resolutions });\n }\n\n if (result.downloaded.length > 0) {\n console.log(chalk.green('Downloaded:'));\n for (const file of result.downloaded) {\n console.log(chalk.green(` + ${file}`));\n }\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted (removed from remote):'));\n for (const file of result.deleted) {\n console.log(chalk.red(` - ${file}`));\n }\n }\n\n if (result.conflictFilesWritten.length > 0) {\n console.log(chalk.yellow('Conflict files created:'));\n for (const file of result.conflictFilesWritten) {\n console.log(chalk.yellow(` ~ ${file}`));\n }\n }\n\n logger.dim(`Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`);\n\n // Create audit log entries for downloaded files\n if (result.downloaded.length > 0) {\n const syncState = syncService.loadSyncState();\n const auditEntries: AuditLogEntry[] = result.downloaded.map(filePath => ({\n operation: 'pulled' as const,\n filePath,\n uploadTime: syncState.files[filePath]?.metadata?.uploadTime,\n uploaderEmail: syncState.files[filePath]?.metadata?.uploaderEmail,\n uploaderName: syncState.files[filePath]?.metadata?.uploaderName,\n }));\n\n appendToAuditLog(tenant, auditEntries);\n }\n\n let hasChanges = result.downloaded.length > 0 || result.deleted.length > 0;\n\n // Step 3: Pull apps\n let appResult = { created: [] as string[], updated: [] as string[], deleted: [] as string[], unchanged: [] as string[] };\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Apps \u2550\u2550\u2550'));\n logger.info(`Pulling apps from ${tenant}...`);\n\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n appResult = await appSyncService.pull();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appResult.created) {\n console.log(chalk.green(` + ${app}`));\n }\n }\n\n if (appResult.updated.length > 0) {\n console.log(chalk.yellow('Updated apps:'));\n for (const app of appResult.updated) {\n console.log(chalk.yellow(` ~ ${app}`));\n }\n }\n\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps (removed from remote):'));\n for (const app of appResult.deleted) {\n console.log(chalk.red(` - ${app}`));\n }\n }\n\n logger.dim(`Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`);\n\n hasChanges = hasChanges || appResult.created.length > 0 || appResult.updated.length > 0 || appResult.deleted.length > 0;\n\n if (!hasChanges) {\n logger.success('Already up to date.');\n return;\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Summary \u2550\u2550\u2550'));\n logger.success('Pull complete!');\n logger.dim(`Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`);\n logger.dim(`Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`);\n } catch (error) {\n logger.error('Pull failed.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n process.exit(1);\n }\n });\n}\n\nasync function createDefaultPackageJson(tenantDir: string, tenant: string): Promise<void> {\n const fs = await import('fs');\n const path = await import('path');\n\n const packageJsonPath = path.join(tenantDir, 'package.json');\n\n if (fs.existsSync(packageJsonPath)) {\n return;\n }\n\n const packageJson = {\n name: `farseer-scripts-${tenant}`,\n version: '1.0.0',\n description: `Farseer App scripts for ${tenant}`,\n main: 'src/index.ts',\n scripts: {},\n keywords: ['farseer', 'scripts', tenant],\n author: 'Farseer',\n license: 'ISC',\n dependencies: {\n '@google-cloud/bigquery': '^7.9.0',\n '@google-cloud/storage': '^7.12.1',\n '@googleapis/sheets': '^5.0.5',\n '@sendgrid/mail': '^7.7.0',\n '@types/node-forge': '^1.3.11',\n '@xmldom/xmldom': '^0.9.8',\n 'arquero': '^5.4.1',\n 'axios': '^1.10.0',\n 'axios-retry': '^3.9.1',\n 'basic-ftp': '^5.0.5',\n 'client-oauth2': '^4.3.3',\n 'csv-parser': '^3.0.0',\n 'dotenv': '^16.4.5',\n 'draft-js': '^0.11.7',\n 'exceljs': '^4.4.0',\n 'farseer-client': 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar',\n 'farseer-client-axios': 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar',\n 'fast-xml-parser': '^4.5.0',\n 'form-data': '^4.0.0',\n 'googleapis': '^144.0.0',\n 'heapdump': '^0.3.15',\n 'image-size': '^1.1.1',\n 'jszip': '^3.10.1',\n 'lossless-json': '^4.0.1',\n 'mssql': '^10.0.4',\n 'node-fetch': '^2.7.0',\n 'node-forge': '^1.3.1',\n 'node-sp-auth': '^3.0.8',\n 'numeral': '^2.0.6',\n 'oracledb': '^6.6.0',\n 'papaparse': '^5.5.1',\n 'pdfkit': '^0.14.0',\n 'pdfmake': '^0.2.20',\n 'soap': '^1.1.11',\n 'ssh2-sftp-client': '^11.0.0',\n 'strong-soap': '^4.1.13',\n 'ts-node': '^10.9.2',\n 'typescript': '^5.5.4',\n 'undici': '^6.19.8',\n 'uuid': '^11.1.0',\n 'winston': '^3.17.0',\n 'xlsx': 'https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz',\n 'xml-crypto': '^6.1.2',\n },\n devDependencies: {\n '@types/draft-js': '^0.11.18',\n '@types/heapdump': '^0.3.4',\n '@types/mssql': '^9.1.5',\n '@types/node': '^18.19.50',\n '@types/node-fetch': '^2.6.11',\n '@types/numeral': '^2.0.5',\n '@types/oracledb': '^6.5.3',\n '@types/papaparse': '^5.3.15',\n '@types/pdfmake': '^0.2.11',\n '@types/soap': '^0.18.0',\n '@types/ssh2-sftp-client': '^9.0.4',\n '@types/tough-cookie': '^4.0.5',\n '@types/uuid': '^10.0.0',\n '@types/xmldom': '^0.1.34',\n 'ts-node': '^10.9.2',\n 'typescript': '^5.5.4',\n },\n };\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');\n logger.dim(`Created package.json for ${tenant}`);\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService, ConflictResolutions } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport {\n getTenantDir,\n ensureDirectoryExists,\n resolveTenantWithOrgMapping,\n appendToAuditLog,\n AuditLogEntry,\n} from '../utils/helpers';\n\nexport function registerPullCommand(program: Command): void {\n program\n .command('pull [org] [tenant]')\n .description(\n 'Pull files from Farseer instance to local\\n\\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)',\n )\n .option('--all', 'Pull all files (default: only scripts .ts, .js)')\n .option('--force', 'Force pull, overwriting local changes on conflicts')\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n // Step 1: Ensure tenant folder exists\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n // Create default package.json if it doesn't exist\n await createDefaultPackageJson(tenantDir, tenant);\n\n // Step 2: Pull files from Farseer\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Files \u2550\u2550\u2550'));\n logger.info(`Pulling files from ${tenant}...`);\n\n try {\n let result = await syncService.pull({ all: options.all, force: options.force });\n\n // Handle conflicts interactively\n if (result.conflicts.length > 0 && !options.force) {\n console.log();\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n\n const resolutions: ConflictResolutions = {};\n\n for (const conflict of result.conflicts) {\n let choices: { name: string; value: string }[];\n\n if (conflict.type === 'local_modified_remote_deleted') {\n choices = [\n { name: 'Keep local (keep your modified file)', value: 'keep_local' },\n { name: 'Accept deletion (delete local file)', value: 'keep_remote' },\n ];\n } else if (conflict.type === 'local_deleted_remote_modified') {\n choices = [\n { name: \"Keep deleted (don't restore file)\", value: 'keep_local' },\n { name: 'Restore remote version', value: 'keep_remote' },\n ];\n } else {\n choices = [\n { name: 'Keep local version', value: 'keep_local' },\n { name: 'Use remote version (overwrite local)', value: 'keep_remote' },\n { name: 'Keep both (save remote as .remote file)', value: 'keep_both' },\n ];\n }\n\n const answer = await inquirer.prompt([\n {\n type: 'list',\n name: 'resolution',\n message: `${conflict.filePath} - ${conflict.description}`,\n choices,\n },\n ]);\n\n resolutions[conflict.filePath] = answer.resolution;\n }\n\n // Re-pull with resolutions\n result = await syncService.pull({ all: options.all, conflictResolutions: resolutions });\n }\n\n if (result.downloaded.length > 0) {\n console.log(chalk.green('Downloaded:'));\n for (const file of result.downloaded) {\n console.log(chalk.green(` + ${file}`));\n }\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted (removed from remote):'));\n for (const file of result.deleted) {\n console.log(chalk.red(` - ${file}`));\n }\n }\n\n if (result.conflictFilesWritten.length > 0) {\n console.log(chalk.yellow('Conflict files created:'));\n for (const file of result.conflictFilesWritten) {\n console.log(chalk.yellow(` ~ ${file}`));\n }\n }\n\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // Create audit log entries for downloaded files\n if (result.downloaded.length > 0) {\n const syncState = syncService.loadSyncState();\n const auditEntries: AuditLogEntry[] = result.downloaded.map((filePath) => ({\n operation: 'pulled' as const,\n filePath,\n uploadTime: syncState.files[filePath]?.metadata?.uploadTime,\n uploaderEmail: syncState.files[filePath]?.metadata?.uploaderEmail,\n uploaderName: syncState.files[filePath]?.metadata?.uploaderName,\n }));\n\n appendToAuditLog(tenant, auditEntries);\n }\n\n let hasChanges = result.downloaded.length > 0 || result.deleted.length > 0;\n\n // Step 3: Pull apps\n let appResult = {\n created: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n };\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Apps \u2550\u2550\u2550'));\n logger.info(`Pulling apps from ${tenant}...`);\n\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n appResult = await appSyncService.pull();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appResult.created) {\n console.log(chalk.green(` + ${app}`));\n }\n }\n\n if (appResult.updated.length > 0) {\n console.log(chalk.yellow('Updated apps:'));\n for (const app of appResult.updated) {\n console.log(chalk.yellow(` ~ ${app}`));\n }\n }\n\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps (removed from remote):'));\n for (const app of appResult.deleted) {\n console.log(chalk.red(` - ${app}`));\n }\n }\n\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n hasChanges =\n hasChanges ||\n appResult.created.length > 0 ||\n appResult.updated.length > 0 ||\n appResult.deleted.length > 0;\n\n if (!hasChanges) {\n logger.success('Already up to date.');\n return;\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Summary \u2550\u2550\u2550'));\n logger.success('Pull complete!');\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n } catch (error) {\n logger.error('Pull failed.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n process.exit(1);\n }\n });\n}\n\nasync function createDefaultPackageJson(tenantDir: string, tenant: string): Promise<void> {\n const fs = await import('fs');\n const path = await import('path');\n\n const packageJsonPath = path.join(tenantDir, 'package.json');\n\n if (fs.existsSync(packageJsonPath)) {\n return;\n }\n\n const packageJson = {\n name: `farseer-scripts-${tenant}`,\n version: '1.0.0',\n description: `Farseer App scripts for ${tenant}`,\n main: 'src/index.ts',\n scripts: {},\n keywords: ['farseer', 'scripts', tenant],\n author: 'Farseer',\n license: 'ISC',\n dependencies: {\n '@google-cloud/bigquery': '^7.9.0',\n '@google-cloud/storage': '^7.12.1',\n '@googleapis/sheets': '^5.0.5',\n '@sendgrid/mail': '^7.7.0',\n '@types/node-forge': '^1.3.11',\n '@xmldom/xmldom': '^0.9.8',\n arquero: '^5.4.1',\n axios: '^1.10.0',\n 'axios-retry': '^3.9.1',\n 'basic-ftp': '^5.0.5',\n 'client-oauth2': '^4.3.3',\n 'csv-parser': '^3.0.0',\n dotenv: '^16.4.5',\n 'draft-js': '^0.11.7',\n exceljs: '^4.4.0',\n 'farseer-client':\n 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar',\n 'farseer-client-axios':\n 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar',\n 'fast-xml-parser': '^4.5.0',\n 'form-data': '^4.0.0',\n googleapis: '^144.0.0',\n heapdump: '^0.3.15',\n 'image-size': '^1.1.1',\n jszip: '^3.10.1',\n 'lossless-json': '^4.0.1',\n mssql: '^10.0.4',\n 'node-fetch': '^2.7.0',\n 'node-forge': '^1.3.1',\n 'node-sp-auth': '^3.0.8',\n numeral: '^2.0.6',\n oracledb: '^6.6.0',\n papaparse: '^5.5.1',\n pdfkit: '^0.14.0',\n pdfmake: '^0.2.20',\n soap: '^1.1.11',\n 'ssh2-sftp-client': '^11.0.0',\n 'strong-soap': '^4.1.13',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n undici: '^6.19.8',\n uuid: '^11.1.0',\n winston: '^3.17.0',\n xlsx: 'https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz',\n 'xml-crypto': '^6.1.2',\n },\n devDependencies: {\n '@types/draft-js': '^0.11.18',\n '@types/heapdump': '^0.3.4',\n '@types/mssql': '^9.1.5',\n '@types/node': '^18.19.50',\n '@types/node-fetch': '^2.6.11',\n '@types/numeral': '^2.0.5',\n '@types/oracledb': '^6.5.3',\n '@types/papaparse': '^5.3.15',\n '@types/pdfmake': '^0.2.11',\n '@types/soap': '^0.18.0',\n '@types/ssh2-sftp-client': '^9.0.4',\n '@types/tough-cookie': '^4.0.5',\n '@types/uuid': '^10.0.0',\n '@types/xmldom': '^0.1.34',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n },\n };\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');\n logger.dim(`Created package.json for ${tenant}`);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,4BAA8D;AAC9D,yBAAiD;AACjD,4BAA+B;AAC/B,qBAMO;AAEA,SAAS,oBAAoB,SA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A,MACb,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,qBAAqB;AAAA,MACrB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,oBAAoB;AAAA,MACpB,kBAAkB;AAAA,MAClB,eAAe;AAAA,MACf,2BAA2B;AAAA,MAC3B,uBAAuB;AAAA,MACvB,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,WAAW;AAAA,MACX,YAAY;AAAA,IAChB;AAAA,EACJ;AAEA,KAAG,cAAc,iBAAiB,KAAK,UAAU,aAAa,MAAM,CAAC,GAAG,OAAO;AAC/E,uBAAO,IAAI,4BAA4B,MAAM,EAAE;AACnD;",
|
|
6
6
|
"names": ["chalk", "inquirer"]
|
|
7
7
|
}
|
package/dist/commands/push.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
"use strict";
|
|
1
2
|
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -39,7 +40,9 @@ var import_appSyncService = require("../services/appSyncService");
|
|
|
39
40
|
var import_helpers = require("../utils/helpers");
|
|
40
41
|
var fs = __toESM(require("fs"));
|
|
41
42
|
function registerPushCommand(program) {
|
|
42
|
-
program.command("push [org] [tenant]").description(
|
|
43
|
+
program.command("push [org] [tenant]").description(
|
|
44
|
+
"Push local files to Farseer instance\n\nUsage: push <org> <tenant> OR push <tenant> (if org is known)"
|
|
45
|
+
).option("--force", "Force push even if remote has changes").option("-y, --yes", "Skip confirmation prompt (auto-confirm)").action(async (arg1, arg2, options) => {
|
|
43
46
|
const { organisation, tenant } = (0, import_helpers.resolveTenantWithOrgMapping)(arg1, arg2);
|
|
44
47
|
const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(organisation, tenant);
|
|
45
48
|
if (!clientResult) {
|
|
@@ -65,14 +68,14 @@ function registerPushCommand(program) {
|
|
|
65
68
|
import_logger.logger.dim("Remote is in sync.");
|
|
66
69
|
}
|
|
67
70
|
const status = await syncService.getStatusFast();
|
|
68
|
-
const filesToPush = [
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
71
|
+
const filesToPush = [...status.modifiedLocally, ...status.onlyLocal];
|
|
72
|
+
const filesToDelete = status.modifiedRemotely.filter((f) => !fs.existsSync(`${filesDir}/${f}`));
|
|
73
|
+
let appStatus = {
|
|
74
|
+
newLocal: [],
|
|
75
|
+
modified: [],
|
|
76
|
+
newRemote: [],
|
|
77
|
+
synced: []
|
|
78
|
+
};
|
|
76
79
|
const appSyncService = new import_appSyncService.AppSyncService(tenant, clientResult.client);
|
|
77
80
|
appStatus = await appSyncService.getStatus();
|
|
78
81
|
const hasFileChanges = filesToPush.length > 0 || filesToDelete.length > 0;
|
|
@@ -167,7 +170,12 @@ function registerPushCommand(program) {
|
|
|
167
170
|
console.log();
|
|
168
171
|
}
|
|
169
172
|
}
|
|
170
|
-
let appResult = {
|
|
173
|
+
let appResult = {
|
|
174
|
+
created: [],
|
|
175
|
+
updated: [],
|
|
176
|
+
deleted: [],
|
|
177
|
+
unchanged: []
|
|
178
|
+
};
|
|
171
179
|
if (hasAppChanges) {
|
|
172
180
|
import_logger.logger.info(`Pushing apps to ${tenant}...`);
|
|
173
181
|
appResult = await appSyncService.push();
|
|
@@ -196,7 +204,9 @@ function registerPushCommand(program) {
|
|
|
196
204
|
console.log();
|
|
197
205
|
import_logger.logger.success("Push complete!");
|
|
198
206
|
import_logger.logger.dim(`Files: +${result.uploaded.length} ~${result.updated.length} -${result.deleted.length}`);
|
|
199
|
-
import_logger.logger.dim(
|
|
207
|
+
import_logger.logger.dim(
|
|
208
|
+
`Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length}`
|
|
209
|
+
);
|
|
200
210
|
} catch (error) {
|
|
201
211
|
import_logger.logger.error("Push failed.");
|
|
202
212
|
if (error instanceof Error) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/push.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { getFarseerClientWithFallback, showLoginPrompt, ensureFreshToken } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantFilesDir, resolveTenantWithOrgMapping } from '../utils/helpers';\nimport * as fs from 'fs';\n\nexport function registerPushCommand(program: Command): void {\n program\n .command('push [org] [tenant]')\n .description('Push local files to Farseer instance\\n\\nUsage: push <org> <tenant> OR push <tenant> (if org is known)')\n .option('--force', 'Force push even if remote has changes')\n .option('-y, --yes', 'Skip confirmation prompt (auto-confirm)')\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const filesDir = getTenantFilesDir(tenant);\n\n if (!fs.existsSync(filesDir)) {\n logger.error(`Local folder not found: farseer-apps/${tenant}/files/`);\n logger.dim('Run \"farseer pull <tenant>\" first to initialize the folder.');\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n // Step 1: Check if remote has unpulled changes\n if (!options.force) {\n logger.info('Checking for remote changes...');\n\n const hasRemoteChanges = await syncService.checkRemoteChanges();\n\n if (hasRemoteChanges) {\n logger.error('Remote has changes that are not synced locally.');\n logger.dim(`Run 'farseer pull ${tenant}' first, then try pushing again.`);\n logger.dim('Or use --force to push anyway (will overwrite remote changes).');\n process.exit(1);\n }\n\n logger.dim('Remote is in sync.');\n }\n\n // Step 2: Show what will be pushed (using fast status check that doesn't download remote content)\n const status = await syncService.getStatusFast();\n\n const filesToPush = [\n ...status.modifiedLocally,\n ...status.onlyLocal,\n ];\n\n const filesToDelete = status.modifiedRemotely.filter((f) =>\n !fs.existsSync(`${filesDir}/${f}`)\n );\n\n // Check app changes too\n let appStatus = { newLocal: [] as string[], modified: [] as string[], newRemote: [] as string[], synced: [] as string[] };\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n appStatus = await appSyncService.getStatus();\n\n const hasFileChanges = filesToPush.length > 0 || filesToDelete.length > 0;\n const hasAppChanges = appStatus.newLocal.length > 0 || appStatus.modified.length > 0;\n\n if (!hasFileChanges && !hasAppChanges) {\n logger.success('Nothing to push. Everything is in sync.');\n return;\n }\n\n console.log();\n logger.header('Changes to push:');\n\n if (filesToPush.length > 0) {\n for (const file of filesToPush) {\n const isNew = status.onlyLocal.includes(file);\n if (isNew) {\n console.log(chalk.green(` + ${file}`));\n } else {\n console.log(chalk.yellow(` M ${file}`));\n }\n }\n }\n\n if (filesToDelete.length > 0) {\n for (const file of filesToDelete) {\n console.log(chalk.red(` - ${file}`));\n }\n }\n\n // Show app changes\n if (appStatus.newLocal.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appStatus.newLocal) {\n console.log(chalk.green(` + ${app}`));\n }\n }\n\n if (appStatus.modified.length > 0) {\n console.log(chalk.yellow('Modified apps:'));\n for (const app of appStatus.modified) {\n console.log(chalk.yellow(` ~ ${app}`));\n }\n }\n\n console.log();\n\n const totalChanges = filesToPush.length + filesToDelete.length + appStatus.newLocal.length + appStatus.modified.length;\n\n // Step 3: Confirm push (skip if --yes flag is set)\n if (!options.yes) {\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Push ${totalChanges} change(s) to ${tenant}?`,\n default: true,\n },\n ]);\n\n if (!confirm.proceed) {\n logger.info('Push cancelled.');\n return;\n }\n }\n\n // Ensure token is fresh before push operations (may have expired during user input)\n await ensureFreshToken(clientResult.client);\n\n try {\n // Step 4: Push files only if there are file changes\n let result: { uploaded: string[]; updated: string[]; deleted: string[]; unchanged: string[]; conflicts?: import('../services/syncService').SyncConflict[] } = { uploaded: [], updated: [], deleted: [], unchanged: [] };\n\n if (hasFileChanges) {\n logger.info(`Pushing files to ${tenant}...`);\n result = await syncService.push({ force: options.force });\n\n console.log();\n\n if (result.conflicts && result.conflicts.length > 0) {\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n logger.dim(`Resolve conflicts by pulling first: farseer pull ${tenant}`);\n logger.dim('Or use --force to push anyway (may overwrite remote changes).');\n console.log();\n }\n\n if (result.uploaded.length > 0) {\n console.log(chalk.green('Uploaded files (new):'));\n for (const file of result.uploaded) {\n console.log(chalk.green(` + ${file}`));\n }\n console.log();\n }\n\n if (result.updated.length > 0) {\n console.log(chalk.yellow('Updated files:'));\n for (const file of result.updated) {\n console.log(chalk.yellow(` M ${file}`));\n }\n console.log();\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted files:'));\n for (const file of result.deleted) {\n console.log(chalk.red(` - ${file}`));\n }\n console.log();\n }\n }\n\n // Step 5: Push apps only if there are app changes\n let appResult = { created: [] as string[], updated: [] as string[], deleted: [] as string[], unchanged: [] as string[] };\n\n if (hasAppChanges) {\n logger.info(`Pushing apps to ${tenant}...`);\n appResult = await appSyncService.push();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('Created apps:'));\n for (const app of appResult.created) {\n console.log(chalk.green(` + ${app}`));\n }\n console.log();\n }\n\n if (appResult.updated.length > 0) {\n console.log(chalk.yellow('Updated apps:'));\n for (const app of appResult.updated) {\n console.log(chalk.yellow(` ~ ${app}`));\n }\n console.log();\n }\n\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps:'));\n for (const app of appResult.deleted) {\n console.log(chalk.red(` - ${app}`));\n }\n console.log();\n }\n }\n\n console.log();\n logger.success('Push complete!');\n logger.dim(`Files: +${result.uploaded.length} ~${result.updated.length} -${result.deleted.length}`);\n logger.dim(`Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length}`);\n } catch (error) {\n logger.error('Push failed.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n process.exit(1);\n }\n });\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { getFarseerClientWithFallback, showLoginPrompt, ensureFreshToken } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantFilesDir, resolveTenantWithOrgMapping } from '../utils/helpers';\nimport * as fs from 'fs';\n\nexport function registerPushCommand(program: Command): void {\n program\n .command('push [org] [tenant]')\n .description(\n 'Push local files to Farseer instance\\n\\nUsage: push <org> <tenant> OR push <tenant> (if org is known)',\n )\n .option('--force', 'Force push even if remote has changes')\n .option('-y, --yes', 'Skip confirmation prompt (auto-confirm)')\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const filesDir = getTenantFilesDir(tenant);\n\n if (!fs.existsSync(filesDir)) {\n logger.error(`Local folder not found: farseer-apps/${tenant}/files/`);\n logger.dim('Run \"farseer pull <tenant>\" first to initialize the folder.');\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n // Step 1: Check if remote has unpulled changes\n if (!options.force) {\n logger.info('Checking for remote changes...');\n\n const hasRemoteChanges = await syncService.checkRemoteChanges();\n\n if (hasRemoteChanges) {\n logger.error('Remote has changes that are not synced locally.');\n logger.dim(`Run 'farseer pull ${tenant}' first, then try pushing again.`);\n logger.dim('Or use --force to push anyway (will overwrite remote changes).');\n process.exit(1);\n }\n\n logger.dim('Remote is in sync.');\n }\n\n // Step 2: Show what will be pushed (using fast status check that doesn't download remote content)\n const status = await syncService.getStatusFast();\n\n const filesToPush = [...status.modifiedLocally, ...status.onlyLocal];\n\n const filesToDelete = status.modifiedRemotely.filter((f) => !fs.existsSync(`${filesDir}/${f}`));\n\n // Check app changes too\n let appStatus = {\n newLocal: [] as string[],\n modified: [] as string[],\n newRemote: [] as string[],\n synced: [] as string[],\n };\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n appStatus = await appSyncService.getStatus();\n\n const hasFileChanges = filesToPush.length > 0 || filesToDelete.length > 0;\n const hasAppChanges = appStatus.newLocal.length > 0 || appStatus.modified.length > 0;\n\n if (!hasFileChanges && !hasAppChanges) {\n logger.success('Nothing to push. Everything is in sync.');\n return;\n }\n\n console.log();\n logger.header('Changes to push:');\n\n if (filesToPush.length > 0) {\n for (const file of filesToPush) {\n const isNew = status.onlyLocal.includes(file);\n if (isNew) {\n console.log(chalk.green(` + ${file}`));\n } else {\n console.log(chalk.yellow(` M ${file}`));\n }\n }\n }\n\n if (filesToDelete.length > 0) {\n for (const file of filesToDelete) {\n console.log(chalk.red(` - ${file}`));\n }\n }\n\n // Show app changes\n if (appStatus.newLocal.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appStatus.newLocal) {\n console.log(chalk.green(` + ${app}`));\n }\n }\n\n if (appStatus.modified.length > 0) {\n console.log(chalk.yellow('Modified apps:'));\n for (const app of appStatus.modified) {\n console.log(chalk.yellow(` ~ ${app}`));\n }\n }\n\n console.log();\n\n const totalChanges =\n filesToPush.length + filesToDelete.length + appStatus.newLocal.length + appStatus.modified.length;\n\n // Step 3: Confirm push (skip if --yes flag is set)\n if (!options.yes) {\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Push ${totalChanges} change(s) to ${tenant}?`,\n default: true,\n },\n ]);\n\n if (!confirm.proceed) {\n logger.info('Push cancelled.');\n return;\n }\n }\n\n // Ensure token is fresh before push operations (may have expired during user input)\n await ensureFreshToken(clientResult.client);\n\n try {\n // Step 4: Push files only if there are file changes\n let result: {\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n conflicts?: import('../services/syncService').SyncConflict[];\n } = { uploaded: [], updated: [], deleted: [], unchanged: [] };\n\n if (hasFileChanges) {\n logger.info(`Pushing files to ${tenant}...`);\n result = await syncService.push({ force: options.force });\n\n console.log();\n\n if (result.conflicts && result.conflicts.length > 0) {\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n logger.dim(`Resolve conflicts by pulling first: farseer pull ${tenant}`);\n logger.dim('Or use --force to push anyway (may overwrite remote changes).');\n console.log();\n }\n\n if (result.uploaded.length > 0) {\n console.log(chalk.green('Uploaded files (new):'));\n for (const file of result.uploaded) {\n console.log(chalk.green(` + ${file}`));\n }\n console.log();\n }\n\n if (result.updated.length > 0) {\n console.log(chalk.yellow('Updated files:'));\n for (const file of result.updated) {\n console.log(chalk.yellow(` M ${file}`));\n }\n console.log();\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted files:'));\n for (const file of result.deleted) {\n console.log(chalk.red(` - ${file}`));\n }\n console.log();\n }\n }\n\n // Step 5: Push apps only if there are app changes\n let appResult = {\n created: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n };\n\n if (hasAppChanges) {\n logger.info(`Pushing apps to ${tenant}...`);\n appResult = await appSyncService.push();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('Created apps:'));\n for (const app of appResult.created) {\n console.log(chalk.green(` + ${app}`));\n }\n console.log();\n }\n\n if (appResult.updated.length > 0) {\n console.log(chalk.yellow('Updated apps:'));\n for (const app of appResult.updated) {\n console.log(chalk.yellow(` ~ ${app}`));\n }\n console.log();\n }\n\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps:'));\n for (const app of appResult.deleted) {\n console.log(chalk.red(` - ${app}`));\n }\n console.log();\n }\n }\n\n console.log();\n logger.success('Push complete!');\n logger.dim(`Files: +${result.uploaded.length} ~${result.updated.length} -${result.deleted.length}`);\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length}`,\n );\n } catch (error) {\n logger.error('Push failed.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n process.exit(1);\n }\n });\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,4BAAgF;AAChF,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAA+D;AAC/D,SAAoB;AAEb,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC,OAAO,WAAW,uCAAuC,EACzD,OAAO,aAAa,yCAAyC,EAC7D,OAAO,OAAO,MAAM,MAAM,YAAY;AACnC,UAAM,EAAE,cAAc,OAAO,QAAI,4CAA4B,MAAM,IAAI;AACvE,UAAM,eAAe,UAAM,oDAA6B,cAAc,MAAM;AAE5E,QAAI,CAAC,cAAc;AACf,iDAAgB,MAAM;AACtB,cAAQ,KAAK,CAAC;AAAA,IAClB;AAEA,UAAM,eAAW,kCAAkB,MAAM;AAEzC,QAAI,CAAC,GAAG,WAAW,QAAQ,GAAG;AAC1B,2BAAO,MAAM,wCAAwC,MAAM,SAAS;AACpE,2BAAO,IAAI,6DAA6D;AACxE,cAAQ,KAAK,CAAC;AAAA,IAClB;AAEA,UAAM,cAAc,IAAI,+BAAY,QAAQ,aAAa,MAAM;AAG/D,QAAI,CAAC,QAAQ,OAAO;AAChB,2BAAO,KAAK,gCAAgC;AAE5C,YAAM,mBAAmB,MAAM,YAAY,mBAAmB;AAE9D,UAAI,kB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|
|
6
6
|
"names": ["chalk", "inquirer"]
|
|
7
7
|
}
|
package/dist/commands/run.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
"use strict";
|
|
1
2
|
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -113,12 +114,13 @@ function registerRunCommand(program) {
|
|
|
113
114
|
import_logger.logger.dim("List available apps with: farseer apps " + tenant);
|
|
114
115
|
process.exit(1);
|
|
115
116
|
}
|
|
116
|
-
|
|
117
|
+
const runScripts = app.scriptFiles ?? [];
|
|
118
|
+
if (!app.mainScriptFileId || runScripts.length === 0) {
|
|
117
119
|
import_logger.logger.error(`App "${appName}" has no scripts configured.`);
|
|
118
120
|
import_logger.logger.dim('Configure the app with: farseer app configure "' + appName + '" --entrypoint <script>');
|
|
119
121
|
process.exit(1);
|
|
120
122
|
}
|
|
121
|
-
const mainScript =
|
|
123
|
+
const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);
|
|
122
124
|
if (!mainScript) {
|
|
123
125
|
import_logger.logger.error(`Entrypoint script not found for app "${appName}".`);
|
|
124
126
|
process.exit(1);
|
|
@@ -215,7 +217,8 @@ function registerRunCommand(program) {
|
|
|
215
217
|
});
|
|
216
218
|
});
|
|
217
219
|
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
|
-
|
|
220
|
+
const { tenant, appName } = (0, import_helpers.parseAppArgs)(args);
|
|
221
|
+
let script = appName;
|
|
219
222
|
const credentials = await getRunCredentials(tenant, options.tenantId);
|
|
220
223
|
if (!credentials) {
|
|
221
224
|
(0, import_farseerFactory.showLoginPrompt)(tenant);
|
package/dist/commands/run.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/run.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from '../services/configService';\nimport { refreshAccessToken } from '../services/farseerService';\nimport { getFarseerClientWithFallback, showLoginPrompt, IFarseerClient } from '../services/farseerFactory';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir, parseAppArgs } from '../utils/helpers';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { spawn } from 'child_process';\n\n/**\n * Find a script file recursively in a directory.\n * Returns the relative path from baseDir if found, null otherwise.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) {\n return null;\n }\n\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n\n if (item.isFile() && item.name === scriptName) {\n return itemRelPath;\n }\n\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n\n return null;\n };\n\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(tenant: string, tenantId?: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login)\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n\n // Check if token needs refresh\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n return null;\n }\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n logger.success('Token refreshed');\n }\n\n const updatedAuth = getUserAuth();\n if (!updatedAuth) return null;\n\n // Use tenant name as organisation for basePath, tenantId for TENANT_ID env var\n return {\n tenantId: tenantId || tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(tenant),\n };\n}\n\n// Helper to collect multiple --arg options\nfunction collectArgs(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\nexport function registerRunCommand(program: Command): void {\n program\n .command('run <args...>')\n .description('Run an app locally with injected credentials')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .option('--arg <value>', 'Pass argument in format \"Name=Value\" (can be used multiple times)', collectArgs, [])\n .action(async (args: string[], options) => {\n const { tenant, appName } = parseAppArgs(args);\n // First, get the app details to find the entrypoint script\n const clientResult = await getFarseerClientWithFallback(tenant, options.tenantId);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const api: IFarseerClient = clientResult.client;\n\n // Find the app\n logger.info(`Loading app: ${appName}...`);\n const app = await api.getAppByName(appName);\n\n if (!app) {\n logger.error(`App not found: ${appName}`);\n logger.dim('List available apps with: farseer apps ' + tenant);\n process.exit(1);\n }\n\n if (!app.mainScriptFileId || app.scriptFiles.length === 0) {\n logger.error(`App \"${appName}\" has no scripts configured.`);\n logger.dim('Configure the app with: farseer app configure \"' + appName + '\" --entrypoint <script>');\n process.exit(1);\n }\n\n // Find the entrypoint script name\n const mainScript = app.scriptFiles.find(s => s.id === app.mainScriptFileId);\n if (!mainScript) {\n logger.error(`Entrypoint script not found for app \"${appName}\".`);\n process.exit(1);\n }\n\n // Normalize script name - handle both \"test.ts\" and \"Scripts/test.ts\" formats\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Get credentials for running\n const credentials = await getRunCredentials(tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found locally: ${scriptPath}`);\n logger.dim('Run \"farseer pull ' + tenant + '\" to download scripts first.');\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n // Parse arguments\n const appArgs: Record<string, string> = {};\n\n // Start with default values from app config\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue;\n }\n\n // Override with provided arguments\n for (const argStr of options.arg) {\n const eqIndex = argStr.indexOf('=');\n if (eqIndex === -1) {\n logger.error(`Invalid argument format: ${argStr}`);\n logger.dim('Use format: --arg \"Name=Value\"');\n process.exit(1);\n }\n const name = argStr.substring(0, eqIndex);\n const value = argStr.substring(eqIndex + 1);\n appArgs[name] = value;\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running app \"${app.name}\" (${scriptName}) for tenant ${tenant} (using ${authType})...`);\n\n // Show arguments being used\n if (Object.keys(appArgs).length > 0) {\n logger.dim('Arguments:');\n for (const [key, value] of Object.entries(appArgs)) {\n logger.dim(` ${key}: ${value}`);\n }\n }\n console.log();\n\n // Build environment variables based on auth type\n const envVars: Record<string, string> = {\n ...process.env as Record<string, string>,\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments from app arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue);\n }\n\n // Run with credentials injected via environment variables, arguments via command line\n // Quote the script path to handle spaces in folder names\n const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath, ...cmdArgs], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n\n // Keep the old script-based run as a separate command\n program\n .command('run-script <args...>')\n .description('Run a script directly (without app wrapper)')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .action(async (args: string[], options) => {\n let { tenant, appName: script } = parseAppArgs(args);\n const credentials = await getRunCredentials(tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n // Normalize script path - strip Scripts/ prefix if present\n if (script.toLowerCase().startsWith('scripts/')) {\n script = script.substring('scripts/'.length);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, script);\n let relativeScriptPath = `files/Scripts/${script}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(script));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found: ${scriptPath}`);\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);\n console.log();\n\n // Build environment variables based on auth type\n const envVars: Record<string, string> = {\n ...process.env as Record<string, string>,\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;\n }\n\n // Run with credentials injected via environment variables\n // Quote the script path to handle spaces in folder names\n const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from '../services/configService';\nimport { refreshAccessToken } from '../services/farseerService';\nimport { getFarseerClientWithFallback, showLoginPrompt, IFarseerClient } from '../services/farseerFactory';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir, parseAppArgs } from '../utils/helpers';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { spawn } from 'child_process';\n\n/**\n * Find a script file recursively in a directory.\n * Returns the relative path from baseDir if found, null otherwise.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) {\n return null;\n }\n\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n\n if (item.isFile() && item.name === scriptName) {\n return itemRelPath;\n }\n\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n\n return null;\n };\n\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(tenant: string, tenantId?: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login)\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n\n // Check if token needs refresh\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n return null;\n }\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n logger.success('Token refreshed');\n }\n\n const updatedAuth = getUserAuth();\n if (!updatedAuth) return null;\n\n // Use tenant name as organisation for basePath, tenantId for TENANT_ID env var\n return {\n tenantId: tenantId || tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(tenant),\n };\n}\n\n// Helper to collect multiple --arg options\nfunction collectArgs(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\nexport function registerRunCommand(program: Command): void {\n program\n .command('run <args...>')\n .description('Run an app locally with injected credentials')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .option('--arg <value>', 'Pass argument in format \"Name=Value\" (can be used multiple times)', collectArgs, [])\n .action(async (args: string[], options) => {\n const { tenant, appName } = parseAppArgs(args);\n // First, get the app details to find the entrypoint script\n const clientResult = await getFarseerClientWithFallback(tenant, options.tenantId);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const api: IFarseerClient = clientResult.client;\n\n // Find the app\n logger.info(`Loading app: ${appName}...`);\n const app = await api.getAppByName(appName);\n\n if (!app) {\n logger.error(`App not found: ${appName}`);\n logger.dim('List available apps with: farseer apps ' + tenant);\n process.exit(1);\n }\n\n const runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n logger.error(`App \"${appName}\" has no scripts configured.`);\n logger.dim('Configure the app with: farseer app configure \"' + appName + '\" --entrypoint <script>');\n process.exit(1);\n }\n\n // Find the entrypoint script name\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n logger.error(`Entrypoint script not found for app \"${appName}\".`);\n process.exit(1);\n }\n\n // Normalize script name - handle both \"test.ts\" and \"Scripts/test.ts\" formats\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Get credentials for running\n const credentials = await getRunCredentials(tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found locally: ${scriptPath}`);\n logger.dim('Run \"farseer pull ' + tenant + '\" to download scripts first.');\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n // Parse arguments\n const appArgs: Record<string, string> = {};\n\n // Start with default values from app config\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue;\n }\n\n // Override with provided arguments\n for (const argStr of options.arg) {\n const eqIndex = argStr.indexOf('=');\n if (eqIndex === -1) {\n logger.error(`Invalid argument format: ${argStr}`);\n logger.dim('Use format: --arg \"Name=Value\"');\n process.exit(1);\n }\n const name = argStr.substring(0, eqIndex);\n const value = argStr.substring(eqIndex + 1);\n appArgs[name] = value;\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running app \"${app.name}\" (${scriptName}) for tenant ${tenant} (using ${authType})...`);\n\n // Show arguments being used\n if (Object.keys(appArgs).length > 0) {\n logger.dim('Arguments:');\n for (const [key, value] of Object.entries(appArgs)) {\n logger.dim(` ${key}: ${value}`);\n }\n }\n console.log();\n\n // Build environment variables based on auth type\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments from app arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue);\n }\n\n // Run with credentials injected via environment variables, arguments via command line\n // Quote the script path to handle spaces in folder names\n const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath, ...cmdArgs], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n\n // Keep the old script-based run as a separate command\n program\n .command('run-script <args...>')\n .description('Run a script directly (without app wrapper)')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .action(async (args: string[], options) => {\n const { tenant, appName } = parseAppArgs(args);\n let script = appName;\n const credentials = await getRunCredentials(tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n // Normalize script path - strip Scripts/ prefix if present\n if (script.toLowerCase().startsWith('scripts/')) {\n script = script.substring('scripts/'.length);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, script);\n let relativeScriptPath = `files/Scripts/${script}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(script));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found: ${scriptPath}`);\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);\n console.log();\n\n // Build environment variables based on auth type\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_ACCESS_TOKEN = credentials.accessToken;\n }\n\n // Run with credentials injected via environment variables\n // Quote the script path to handle spaces in folder names\n const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,2BAA2F;AAC3F,4BAAmC;AACnC,4BAA8E;AAC9E,qBAA+E;AAC/E,SAAoB;AACpB,WAAsB;AACtB,2BAAsB;AAMtB,SAAS,sBAAsB,SAAiB,YAAmC;AAC/E,MAAI,CAAC,GAAG,WAAW,OAAO,GAAG;AACzB,WAAO;AAAA,EACX;AAEA,QAAM,SAAS,CAAC,KAAa,eAAuB,OAAsB;AACtE,UAAM,QAAQ,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC;AAEzD,eAAW,Q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