farseer-cli 1.3.0 → 1.4.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 +102 -30
- package/dist/commands/checkout.js +3 -8
- package/dist/commands/checkout.js.map +2 -2
- package/dist/commands/pull.js +159 -46
- package/dist/commands/pull.js.map +2 -2
- package/dist/commands/push.js +185 -75
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/run.js +31 -30
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/status.js +26 -33
- package/dist/commands/status.js.map +2 -2
- package/dist/index.js +5 -3
- package/dist/index.js.map +2 -2
- package/dist/mcp/tools/appTools.js +6 -20
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +2 -1
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +2 -10
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +12 -23
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +5 -16
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/folderTools.js +3 -11
- package/dist/mcp/tools/folderTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +14 -40
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +3 -8
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +11 -22
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +132 -47
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +2 -2
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/services/appSyncService.js +3 -2
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/farseerApi.js +13 -36
- package/dist/services/farseerApi.js.map +2 -2
- package/dist/services/farseerFactory.js +1 -1
- package/dist/services/farseerFactory.js.map +2 -2
- package/dist/services/farseerService.js +22 -14
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/syncService.js +322 -182
- package/dist/services/syncService.js.map +3 -3
- package/dist/utils/cliOptions.js +36 -0
- package/dist/utils/cliOptions.js.map +7 -0
- package/dist/utils/errorFormatter.js +152 -0
- package/dist/utils/errorFormatter.js.map +7 -0
- package/dist/utils/fileLogger.js +13 -0
- package/dist/utils/fileLogger.js.map +2 -2
- package/dist/utils/fileValidation.js +180 -0
- package/dist/utils/fileValidation.js.map +7 -0
- package/dist/utils/helpers.js +85 -14
- package/dist/utils/helpers.js.map +2 -2
- package/docs/cli-guide.md +49 -4
- package/package.json +1 -1
|
@@ -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 { fileLogger } from '../utils/fileLogger';\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 .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\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 const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const syncFilterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n };\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(syncFilterOptions);\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(syncFilterOptions);\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 fileLogger.error('push', error, { tenant, organisation });\n logger.error('Push failed.');\n if (error instanceof Error) {\n logger.error(error.message);\n if (error.cause) {\n logger.dim(String(error.cause));\n }\n } else {\n logger.dim(String(error));\n }\n const logPath = fileLogger.getLogPath();\n if (logPath) {\n logger.dim(`Debug log: ${logPath}`);\n }\n process.exit(1);\n }\n });\n}\n\nfunction collectValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\nfunction normalizeExtensions(exts: string[]): string[] {\n return exts.map((ext) => (ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`));\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,wBAA2B;AAC3B,4BAAgF;AAChF,yBAA4B;AAC5B,4BAA+B;AAC/B,
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { fileLogger } from '../utils/fileLogger';\nimport { getFarseerClientWithFallback, showLoginPrompt, ensureFreshToken } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantFilesDir, resolveTenantWithOrgMapping, safeResolveWithinBase } from '../utils/helpers';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { ValidationFailure, partitionForUpload } from '../utils/fileValidation';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport type { SyncStatus } from '../services/syncService';\nimport * as fs from 'fs';\n\n/**\n * Push semantics (in plain English, since this is the easiest part of the\n * CLI to misunderstand):\n *\n * farseer push\n * 1. Pre-flight: refuse local files that the backend will reject\n * (extension whitelist, name length, empty body). Print them and\n * exit non-zero so the user fixes them before we touch the network.\n * 2. Compare local vs remote (no remote download \u2014 we trust the\n * recorded sync baseline). If remote diverged from baseline,\n * refuse and ask the user to pull first.\n * 3. Show a diff (added / modified / deleted).\n * 4. Confirm.\n * 5. Upload modified files. Re-check each one against current remote\n * right before overwrite to avoid clobbering a concurrent edit.\n *\n * farseer push --force\n * Same as above, but:\n * \u2022 Skip step 2 (allow pushing over remote drift).\n * \u2022 Make remote mirror local: also delete any remote files that\n * have no local counterpart (not just ones you previously pulled).\n * Because --force is destructive, we always show the full plan\n * (including deletions of remote-only files) and require an explicit\n * \"yes\". `-y` won't bypass --force confirmation; you must answer the\n * prompt.\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(\n '--force',\n 'Force-mirror remote to local: overwrite remote drift AND delete remote files with no local counterpart (always asks for confirmation)',\n )\n .option('-y, --yes', 'Skip confirmation prompt for non-destructive pushes (ignored under --force)')\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\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 const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const syncFilterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n };\n\n // Step 1: Drift check. Skipped under --force; the user has\n // explicitly opted into overwriting whatever's on remote.\n if (!options.force) {\n logger.info('Checking for remote changes...');\n const driftResult = await syncService.checkRemoteChanges(syncFilterOptions);\n if (driftResult.drift) {\n logger.error(\n `Remote has ${driftResult.addedRemotely.length + driftResult.deletedRemotely.length} change(s) within your sync scope that aren't recorded locally.`,\n );\n if (driftResult.addedRemotely.length > 0) {\n console.log(chalk.cyan(' New on remote (need to pull):'));\n for (const f of driftResult.addedRemotely) console.log(chalk.cyan(` + ${f}`));\n }\n if (driftResult.deletedRemotely.length > 0) {\n console.log(chalk.red(' Removed on remote (need to pull to clean local):'));\n for (const f of driftResult.deletedRemotely) console.log(chalk.red(` - ${f}`));\n }\n // Echo back the same scope flags the user passed so the\n // suggested pull command actually fetches the files\n // causing the drift. Without this, `farseer pull` runs\n // in default scope and says \"Already up to date\",\n // leaving the user stuck in a loop.\n const scopeFlags: string[] = [];\n for (const ext of options.includeExt as string[]) scopeFlags.push(`--include-ext ${ext}`);\n for (const folder of options.includeFolder as string[])\n scopeFlags.push(`--include-folder \"${folder}\"`);\n const pullCmd = ['farseer pull', tenant, ...scopeFlags].filter(Boolean).join(' ');\n logger.dim(`Run \\`${pullCmd}\\` first, then try pushing again.`);\n logger.dim('Or use --force to overwrite remote (this will also mirror deletions).');\n process.exit(1);\n }\n logger.dim('Remote is in sync with local baseline.');\n }\n\n // Step 2: Build a single status snapshot \u2014 same buckets the\n // `farseer status` command uses, so the user sees the same\n // categorisation in both places.\n //\n // Under --force, run a DEEP status. Reason: fast status can't\n // see remote-side content drift (it trusts our recorded\n // baseline), so a mirror push where someone else has edited\n // a file we still match locally would short-circuit at the\n // hasFileChanges check and never invoke service.push() \u2014\n // even though service.push({ mirror: true }) was specifically\n // built to overwrite that drift. Deep is slow on big tenants\n // but the user has already opted into a destructive, slow\n // operation by passing --force.\n const status = await syncService.getStatus({\n ...syncFilterOptions,\n deep: !!options.force,\n });\n\n const plan = buildPushPlan(status, { force: !!options.force });\n const { filesToUpload, filesToDelete, remoteOnlyFiles, filesToRecreate, filesToOverwrite } = plan;\n\n // Apps are independent of the file pre-flight gate.\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n const appStatus = await appSyncService.getStatus();\n\n const hasConflicts = status.conflicts.length > 0;\n const hasFileChanges =\n filesToUpload.length > 0 || filesToDelete.length > 0 || remoteOnlyFiles.length > 0 || hasConflicts;\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(options.force ? 'Mirror plan (--force):' : 'Changes to push:');\n\n if (status.addedLocally.length > 0) {\n for (const file of status.addedLocally) console.log(chalk.green(` + ${file}`));\n }\n if (status.modifiedLocally.length > 0) {\n for (const file of status.modifiedLocally) console.log(chalk.yellow(` M ${file}`));\n }\n if (filesToDelete.length > 0) {\n for (const file of filesToDelete) console.log(chalk.red(` - ${file}`));\n }\n if (remoteOnlyFiles.length > 0) {\n console.log(chalk.red.bold('Remote-only files that will be DELETED on remote:'));\n for (const file of remoteOnlyFiles) console.log(chalk.red(` - ${file} (remote only)`));\n }\n if (filesToRecreate.length > 0) {\n console.log(chalk.green.bold('Files deleted on remote that will be RECREATED:'));\n for (const file of filesToRecreate) console.log(chalk.green(` + ${file} (re-uploading local copy)`));\n }\n if (filesToOverwrite.length > 0) {\n console.log(chalk.yellow.bold('Files where remote drifted \u2014 local will OVERWRITE:'));\n for (const file of filesToOverwrite)\n console.log(chalk.yellow(` M ${file} (remote content drift; local wins)`));\n }\n\n // Conflicts surface BEFORE the confirmation prompt so the user\n // never confirms a plan that secretly contains skipped files.\n // Without --force these will be skipped (and the user can re-run\n // with `farseer pull` to resolve); under --force the upload step\n // will overwrite local\u2192remote anyway, but the user still deserves\n // to see what's affected.\n if (hasConflicts) {\n const headerText = options.force\n ? 'Conflicts (will be force-overwritten on remote):'\n : 'Conflicts (will be SKIPPED \u2014 pull first to resolve):';\n console.log(chalk.red.bold(headerText));\n for (const conflict of status.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n }\n\n if (appStatus.newLocal.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appStatus.newLocal) console.log(chalk.green(` + ${app}`));\n }\n if (appStatus.modified.length > 0) {\n console.log(chalk.yellow('Modified apps:'));\n for (const app of appStatus.modified) console.log(chalk.yellow(` ~ ${app}`));\n }\n\n // Pre-flight in the preview, BEFORE the confirm prompt. README\n // promises rejections show up in the plan; running pre-flight\n // only inside syncService.push() pushed them to AFTER the user\n // had already said \"yes\". Cost: every upload candidate is read\n // twice (preview + push). For big tenants this is measurable\n // but predictability is the user-visible contract \u2014 they'd\n // rather know about a 256-char-name reject before pressing\n // ENTER on a 200-file mirror push.\n const previewCandidates = [...filesToUpload, ...filesToRecreate, ...filesToOverwrite];\n const previewRejections = previewPushPlan(filesDir, previewCandidates);\n if (previewRejections.length > 0) {\n console.log();\n console.log(chalk.red.bold('Files that pre-flight will reject (skipped from upload):'));\n for (const r of previewRejections) {\n console.log(chalk.red(` \u2717 ${r.filePath}`));\n console.log(chalk.dim(` ${r.detail}`));\n if (r.hint) console.log(chalk.dim(` ${r.hint}`));\n }\n }\n\n console.log();\n\n // filesToUpload already includes filesToRecreate under --force,\n // so don't double-count.\n const totalChanges =\n filesToUpload.length +\n filesToDelete.length +\n remoteOnlyFiles.length +\n appStatus.newLocal.length +\n appStatus.modified.length;\n\n // Step 3: Confirm. --force always confirms (cannot be skipped\n // with -y) because mirror mode includes destructive deletes.\n //\n // Spell out every bucket in the prompt itself, not just the\n // total. A 200-overwrite + 2-delete mirror with the old\n // \"Mirror N change(s) (including K remote deletion(s))\"\n // headline read like \"small change\" \u2014 the eye-catching K\n // hid the bigger blast radius. The plan above the prompt is\n // already explicit; the prompt-line should match it.\n const confirmMessage = options.force\n ? `Mirror to ${tenant}: ${remoteOnlyFiles.length} remote deletion(s), ` +\n `${filesToOverwrite.length} drift overwrite(s), ${filesToRecreate.length} recreation(s), ` +\n `${status.addedLocally.length} new upload(s), ${status.modifiedLocally.length} local edit(s), ` +\n `${filesToDelete.length} local-rm deletion(s). This is destructive.`\n : `Push ${totalChanges} change(s) to ${tenant}?`;\n\n if (options.force || !options.yes) {\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: confirmMessage,\n default: !options.force,\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 // Mirror the service's actual return type so every field is\n // present and non-optional. The earlier hand-rolled inline\n // type marked conflicts/rejected/failed as optional, which\n // forced `?.length ?? 0` defensiveness at every read site\n // even though the service always returns those arrays.\n let result: Awaited<ReturnType<SyncService['push']>> = {\n uploaded: [],\n updated: [],\n deleted: [],\n unchanged: [],\n conflicts: [],\n rejected: [],\n failed: [],\n };\n\n if (hasFileChanges) {\n logger.info(`Pushing files to ${tenant}...`);\n // Pass syncFilterOptions so mirror-mode deletes honour\n // --include-folder / --include-ext scope. Without this\n // the preview's \"remote-only DELETE\" line and the actual\n // mirror step diverged for non-default extensions.\n //\n // Hand `status.remoteHashes` (populated when deep status\n // ran above, i.e. under --force) into service.push so\n // the candidate-content fetch skips files we already\n // have hashes for. Without it, --force re-downloaded\n // every remote file a second time inside push().\n result = await syncService.push({\n force: options.force,\n mirror: options.force,\n ...syncFilterOptions,\n precomputedRemoteHashes: status.remoteHashes,\n });\n\n console.log();\n\n if (result.rejected.length > 0) {\n console.log(chalk.red.bold('Files skipped (backend would reject):'));\n renderRejections(result.rejected);\n }\n\n if (result.conflicts.length > 0) {\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\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 (overwrites remote and mirrors deletions).');\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) console.log(chalk.green(` + ${file}`));\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) console.log(chalk.yellow(` M ${file}`));\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) console.log(chalk.red(` - ${file}`));\n console.log();\n }\n\n if (result.failed.length > 0) {\n // Per-file errors that the backend rejected mid-flight\n // (5xx, validation we couldn't pre-flight, etc.).\n // Distinct from `rejected` (pre-flight) \u2014 these\n // already attempted the call. State for files that\n // succeeded before the failure has been saved.\n console.log(chalk.red.bold(`${result.failed.length} file(s) failed during push:`));\n for (const failure of result.failed) {\n console.log(chalk.red(` ! ${failure.filePath} (${failure.operation})`));\n console.log(chalk.dim(` ${failure.reason}`));\n }\n console.log();\n }\n }\n\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) console.log(chalk.green(` + ${app}`));\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) console.log(chalk.yellow(` ~ ${app}`));\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) console.log(chalk.red(` - ${app}`));\n console.log();\n }\n }\n\n console.log();\n const fileSideEffects = result.uploaded.length + result.updated.length + result.deleted.length;\n const appSideEffects = appResult.created.length + appResult.updated.length + appResult.deleted.length;\n const conflictCount = result.conflicts.length;\n const rejectedCount = result.rejected.length;\n const failedCount = result.failed.length;\n if (fileSideEffects + appSideEffects === 0 && (conflictCount > 0 || rejectedCount > 0)) {\n // Nothing was actually pushed (every candidate hit a\n // conflict or pre-flight rejection). Surface as a\n // warning + EXIT 1 so CI and shell scripts can branch\n // \u2014 the bare \"Push complete!\" line was misleading.\n if (rejectedCount > 0 && conflictCount === 0) {\n logger.warning(`Push did nothing \u2014 ${rejectedCount} file(s) rejected by pre-flight.`);\n logger.dim('Fix the issues listed above and re-run `farseer push`.');\n } else if (conflictCount > 0 && rejectedCount === 0) {\n logger.warning(`Push did nothing \u2014 ${conflictCount} conflict(s) blocked the upload.`);\n logger.dim(`Resolve via 'farseer pull ${tenant}' or rerun with --force.`);\n } else {\n logger.warning(\n `Push did nothing \u2014 ${rejectedCount} file(s) rejected and ${conflictCount} conflict(s) blocked the upload.`,\n );\n }\n process.exit(1);\n }\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 if (rejectedCount > 0 || failedCount > 0) {\n // Partial success: at least some side effects landed\n // but some candidates were skipped (rejected pre-flight)\n // or failed mid-push (network/backend error). EXIT 1\n // (not 2 \u2014 the previous split was undocumented and most\n // CI scripts treat any non-zero as failure anyway).\n if (rejectedCount > 0 && failedCount > 0) {\n logger.warning(\n `${rejectedCount} file(s) skipped pre-flight, ${failedCount} failed mid-push \u2014 see above and rerun.`,\n );\n } else if (rejectedCount > 0) {\n logger.warning(`${rejectedCount} file(s) skipped (see above) \u2014 fix and rerun.`);\n } else {\n logger.warning(`${failedCount} file(s) failed during push (see above) \u2014 rerun to retry.`);\n }\n process.exit(1);\n }\n } catch (error) {\n fileLogger.error('push', error, { tenant, organisation });\n logger.error('Push failed.');\n logger.error(await formatClientError(error));\n const logPath = fileLogger.getLogPath();\n if (logPath) {\n logger.dim(`Debug log: ${logPath}`);\n }\n process.exit(1);\n }\n });\n}\n\n/**\n * Translate a SyncStatus + force flag into the buckets the push command\n * actually acts on. Pure: takes a status, returns lists. Lives at the\n * top level (not inside the action closure) so it can be exported and\n * unit-tested directly \u2014 the status engine has its own coverage, and\n * before this extraction the bucket logic was inline in the action and\n * only reachable via mocking commander + inquirer + fs.\n *\n * Default push: upload the added/modified locally, delete the locally-\n * removed. Remote-side activity is not in scope (drift check refuses\n * before we reach this).\n *\n * Force push (mirror): also re-upload files the remote has lost\n * (deletedRemotely \u2192 recreate) and files the remote has drifted away\n * from (modifiedRemotely \u2192 local wins, overwrite). Plus mirror-deletes\n * remote files that have no local counterpart (addedRemotely).\n */\nexport function buildPushPlan(\n status: SyncStatus,\n options: { force: boolean },\n): {\n filesToUpload: string[];\n filesToDelete: string[];\n remoteOnlyFiles: string[];\n filesToRecreate: string[];\n filesToOverwrite: string[];\n} {\n return {\n filesToUpload: [\n ...status.addedLocally,\n ...status.modifiedLocally,\n ...(options.force ? status.deletedRemotely : []),\n ...(options.force ? status.modifiedRemotely : []),\n ],\n filesToDelete: [...status.deletedLocally],\n remoteOnlyFiles: options.force ? [...status.addedRemotely] : [],\n filesToRecreate: options.force ? [...status.deletedRemotely] : [],\n filesToOverwrite: options.force ? [...status.modifiedRemotely] : [],\n };\n}\n\nfunction renderRejections(rejections: ValidationFailure[]): void {\n for (const r of rejections) {\n console.log(chalk.red(` x ${r.filePath}`));\n console.log(chalk.dim(` ${r.detail}`));\n if (r.hint) console.log(chalk.dim(` ${r.hint}`));\n }\n console.log();\n}\n\n/**\n * Run pre-flight against a list of upload candidates and return only the\n * rejections so the preview can show them BEFORE the confirm prompt. We\n * read each file once here; syncService.push() reads them again at upload\n * time. The duplicate read is the price of putting rejections into the\n * confirmation plan \u2014 without this, the user only learned about rejected\n * files after pressing ENTER, which contradicted the README.\n *\n * Files that fail to read (permission errors, race with deletion) get\n * skipped \u2014 push() will surface that as a real failure if the file\n * actually still mattered.\n */\nfunction previewPushPlan(filesDir: string, candidates: string[]): ValidationFailure[] {\n const validationInputs: { filePath: string; size: number; content: Buffer }[] = [];\n for (const filePath of candidates) {\n try {\n const fullPath = safeResolveWithinBase(filesDir, filePath);\n const content = fs.readFileSync(fullPath);\n validationInputs.push({ filePath, size: content.length, content });\n } catch {\n // Race: file disappeared between getStatus and the preview\n // read, or unreadable. Push() will see the same condition\n // and surface a real error. Don't pretend to know more here.\n continue;\n }\n }\n const { rejected } = partitionForUpload(validationInputs);\n return rejected;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,wBAA2B;AAC3B,4BAAgF;AAChF,yBAA4B;AAC5B,4BAA+B;A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6
|
"names": ["chalk", "inquirer"]
|
|
7
7
|
}
|
package/dist/commands/run.js
CHANGED
|
@@ -59,49 +59,50 @@ function findScriptRecursively(baseDir, scriptName) {
|
|
|
59
59
|
};
|
|
60
60
|
return search(baseDir);
|
|
61
61
|
}
|
|
62
|
-
async function getRunCredentials(tenant,
|
|
62
|
+
async function getRunCredentials(organisation, tenant, tenantIdOverride) {
|
|
63
63
|
const credential = (0, import_configService.getCredential)(tenant);
|
|
64
64
|
if (credential) {
|
|
65
65
|
return {
|
|
66
|
-
tenantId: credential.tenantId,
|
|
66
|
+
tenantId: tenantIdOverride || credential.tenantId,
|
|
67
67
|
apiKey: credential.apiKey,
|
|
68
68
|
basePath: credential.basePath
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
71
|
const auth = (0, import_configService.getUserAuth)();
|
|
72
|
-
if (
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
72
|
+
if (auth) {
|
|
73
|
+
if (!(0, import_configService.isUserAuthValid)()) {
|
|
74
|
+
import_logger.logger.dim("Token expired, refreshing...");
|
|
75
|
+
const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
|
|
76
|
+
if (refreshed) {
|
|
77
|
+
(0, import_configService.setUserAuth)({
|
|
78
|
+
accessToken: refreshed.accessToken,
|
|
79
|
+
refreshToken: refreshed.refreshToken,
|
|
80
|
+
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
81
|
+
realm: auth.realm
|
|
82
|
+
});
|
|
83
|
+
import_logger.logger.success("Token refreshed");
|
|
84
|
+
} else {
|
|
85
|
+
import_logger.logger.warning("Could not refresh token. Please login again with: farseer login");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const updatedAuth = (0, import_configService.getUserAuth)();
|
|
89
|
+
if (updatedAuth && (0, import_configService.isUserAuthValid)()) {
|
|
90
|
+
return {
|
|
91
|
+
tenantId: tenantIdOverride || tenant,
|
|
92
|
+
accessToken: updatedAuth.accessToken,
|
|
93
|
+
basePath: (0, import_configService.generateBasePath)(organisation)
|
|
94
|
+
};
|
|
81
95
|
}
|
|
82
|
-
(0, import_configService.setUserAuth)({
|
|
83
|
-
accessToken: refreshed.accessToken,
|
|
84
|
-
refreshToken: refreshed.refreshToken,
|
|
85
|
-
expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
|
|
86
|
-
realm: auth.realm
|
|
87
|
-
});
|
|
88
|
-
import_logger.logger.success("Token refreshed");
|
|
89
96
|
}
|
|
90
|
-
|
|
91
|
-
if (!updatedAuth) return null;
|
|
92
|
-
return {
|
|
93
|
-
tenantId: tenantId || tenant,
|
|
94
|
-
accessToken: updatedAuth.accessToken,
|
|
95
|
-
basePath: (0, import_configService.generateBasePath)(tenant)
|
|
96
|
-
};
|
|
97
|
+
return null;
|
|
97
98
|
}
|
|
98
99
|
function collectArgs(value, previous) {
|
|
99
100
|
return previous.concat([value]);
|
|
100
101
|
}
|
|
101
102
|
function registerRunCommand(program) {
|
|
102
103
|
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) => {
|
|
103
|
-
const { tenant, appName } = (0, import_helpers.parseAppArgs)(args);
|
|
104
|
-
const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(
|
|
104
|
+
const { organisation, tenant, appName } = (0, import_helpers.parseAppArgs)(args);
|
|
105
|
+
const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(organisation, tenant);
|
|
105
106
|
if (!clientResult) {
|
|
106
107
|
(0, import_farseerFactory.showLoginPrompt)(tenant);
|
|
107
108
|
process.exit(1);
|
|
@@ -129,7 +130,7 @@ function registerRunCommand(program) {
|
|
|
129
130
|
if (scriptName.toLowerCase().startsWith("scripts/")) {
|
|
130
131
|
scriptName = scriptName.substring("scripts/".length);
|
|
131
132
|
}
|
|
132
|
-
const credentials = await getRunCredentials(tenant, options.tenantId);
|
|
133
|
+
const credentials = await getRunCredentials(organisation, tenant, options.tenantId);
|
|
133
134
|
if (!credentials) {
|
|
134
135
|
(0, import_farseerFactory.showLoginPrompt)(tenant);
|
|
135
136
|
process.exit(1);
|
|
@@ -265,9 +266,9 @@ function registerRunCommand(program) {
|
|
|
265
266
|
});
|
|
266
267
|
});
|
|
267
268
|
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) => {
|
|
268
|
-
const { tenant, appName } = (0, import_helpers.parseAppArgs)(args);
|
|
269
|
+
const { organisation, tenant, appName } = (0, import_helpers.parseAppArgs)(args);
|
|
269
270
|
let script = appName;
|
|
270
|
-
const credentials = await getRunCredentials(tenant, options.tenantId);
|
|
271
|
+
const credentials = await getRunCredentials(organisation, tenant, options.tenantId);
|
|
271
272
|
if (!credentials) {
|
|
272
273
|
(0, import_farseerFactory.showLoginPrompt)(tenant);
|
|
273
274
|
process.exit(1);
|
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 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 // When using access token (JWT login) instead of API key, FarseerClient's\n // constructor only reads FARSEER_API_KEY from env vars.\n // We temporarily patch farseerClient.js in node_modules to also support\n // FARSEER_ACCESS_TOKEN, then restore it after the script runs.\n const clientJsPath = path.join(tenantDir, 'node_modules/farseer-client/dist/client/farseerClient.js');\n let originalClientJs: string | null = null;\n\n if (credentials.accessToken && !credentials.apiKey && fs.existsSync(clientJsPath)) {\n originalClientJs = fs.readFileSync(clientJsPath, 'utf-8');\n const patched = originalClientJs.replace(\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerApiKey === '' || farseerUrl === '') {\n throw new Error('Tenant id, api key and url not set up');\n }\n // configure client with parameters\n super({\n headers: {\n 'X-TENANT-ID': tenantId,\n 'X-API-KEY': farseerApiKey,\n },\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerAccessToken = process.env.FARSEER_ACCESS_TOKEN ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerUrl === '' || (farseerApiKey === '' && farseerAccessToken === '')) {\n throw new Error('Tenant id, api key and url not set up');\n }\n const headers = { 'X-TENANT-ID': tenantId };\n if (farseerApiKey) { headers['X-API-KEY'] = farseerApiKey; }\n else { headers['Authorization'] = 'Bearer ' + farseerAccessToken; }\n super({\n headers,\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n );\n fs.writeFileSync(clientJsPath, patched, 'utf-8');\n }\n\n // Run with credentials injected via environment variables, arguments via command line\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 (originalClientJs !== null) {\n try {\n fs.writeFileSync(clientJsPath, originalClientJs, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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 if (originalClientJs !== null) {\n try {\n fs.writeFileSync(clientJsPath, originalClientJs, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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 // Patch farseerClient.js for access token support (same as run command)\n const clientJsPath2 = path.join(tenantDir, 'node_modules/farseer-client/dist/client/farseerClient.js');\n let originalClientJs2: string | null = null;\n\n if (credentials.accessToken && !credentials.apiKey && fs.existsSync(clientJsPath2)) {\n originalClientJs2 = fs.readFileSync(clientJsPath2, 'utf-8');\n const patched = originalClientJs2.replace(\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerApiKey === '' || farseerUrl === '') {\n throw new Error('Tenant id, api key and url not set up');\n }\n // configure client with parameters\n super({\n headers: {\n 'X-TENANT-ID': tenantId,\n 'X-API-KEY': farseerApiKey,\n },\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerAccessToken = process.env.FARSEER_ACCESS_TOKEN ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerUrl === '' || (farseerApiKey === '' && farseerAccessToken === '')) {\n throw new Error('Tenant id, api key and url not set up');\n }\n const headers = { 'X-TENANT-ID': tenantId };\n if (farseerApiKey) { headers['X-API-KEY'] = farseerApiKey; }\n else { headers['Authorization'] = 'Bearer ' + farseerAccessToken; }\n super({\n headers,\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n );\n fs.writeFileSync(clientJsPath2, patched, 'utf-8');\n }\n\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 (originalClientJs2 !== null) {\n try {\n fs.writeFileSync(clientJsPath2, originalClientJs2, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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 if (originalClientJs2 !== null) {\n try {\n fs.writeFileSync(clientJsPath2, originalClientJs2, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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,QAAQ,OAAO;AACtB,YAAM,cAAc,eAAe,GAAG,YAAY,IAAI,KAAK,IAAI,KAAK,KAAK;AAEzE,UAAI,KAAK,OAAO,KAAK,KAAK,SAAS,YAAY;AAC3C,eAAO;AAAA,MACX;AAEA,UAAI,KAAK,YAAY,GAAG;AACpB,cAAM,QAAQ,OAAO,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG,WAAW;AAC3D,YAAI,MAAO,QAAO;AAAA,MACtB;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AAEA,SAAO,OAAO,OAAO;AACzB;AASA,eAAe,
|
|
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(\n organisation: string,\n tenant: string,\n tenantIdOverride?: string,\n): Promise<RunCredentials | null> {\n // 1. Prefer API key when one is saved for this tenant \u2014 it's already the\n // canonical credential, has the correct basePath, and doesn't expire\n // during a long-running script.\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: tenantIdOverride || credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // 2. Fall back to browser-login JWT. Refresh proactively if expired.\n const auth = getUserAuth();\n if (auth) {\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\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 } else {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n }\n }\n\n const updatedAuth = getUserAuth();\n if (updatedAuth && isUserAuthValid()) {\n return {\n tenantId: tenantIdOverride || tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(organisation),\n };\n }\n }\n\n return null;\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 { organisation, tenant, appName } = parseAppArgs(args);\n // First, get the app details to find the entrypoint script.\n // getFarseerClientWithFallback takes (organisation, tenant) \u2014 the\n // organisation is the subdomain and the tenant is the X-TENANT-ID\n // header. Previously we passed (tenant, options.tenantId), which\n // left tenant=undefined in the factory and broke the API-key\n // fallback when the JWT connection test failed.\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\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(organisation, 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 // When using access token (JWT login) instead of API key, FarseerClient's\n // constructor only reads FARSEER_API_KEY from env vars.\n // We temporarily patch farseerClient.js in node_modules to also support\n // FARSEER_ACCESS_TOKEN, then restore it after the script runs.\n const clientJsPath = path.join(tenantDir, 'node_modules/farseer-client/dist/client/farseerClient.js');\n let originalClientJs: string | null = null;\n\n if (credentials.accessToken && !credentials.apiKey && fs.existsSync(clientJsPath)) {\n originalClientJs = fs.readFileSync(clientJsPath, 'utf-8');\n const patched = originalClientJs.replace(\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerApiKey === '' || farseerUrl === '') {\n throw new Error('Tenant id, api key and url not set up');\n }\n // configure client with parameters\n super({\n headers: {\n 'X-TENANT-ID': tenantId,\n 'X-API-KEY': farseerApiKey,\n },\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerAccessToken = process.env.FARSEER_ACCESS_TOKEN ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerUrl === '' || (farseerApiKey === '' && farseerAccessToken === '')) {\n throw new Error('Tenant id, api key and url not set up');\n }\n const headers = { 'X-TENANT-ID': tenantId };\n if (farseerApiKey) { headers['X-API-KEY'] = farseerApiKey; }\n else { headers['Authorization'] = 'Bearer ' + farseerAccessToken; }\n super({\n headers,\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n );\n fs.writeFileSync(clientJsPath, patched, 'utf-8');\n }\n\n // Run with credentials injected via environment variables, arguments via command line\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 (originalClientJs !== null) {\n try {\n fs.writeFileSync(clientJsPath, originalClientJs, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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 if (originalClientJs !== null) {\n try {\n fs.writeFileSync(clientJsPath, originalClientJs, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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 { organisation, tenant, appName } = parseAppArgs(args);\n let script = appName;\n const credentials = await getRunCredentials(organisation, 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 // Patch farseerClient.js for access token support (same as run command)\n const clientJsPath2 = path.join(tenantDir, 'node_modules/farseer-client/dist/client/farseerClient.js');\n let originalClientJs2: string | null = null;\n\n if (credentials.accessToken && !credentials.apiKey && fs.existsSync(clientJsPath2)) {\n originalClientJs2 = fs.readFileSync(clientJsPath2, 'utf-8');\n const patched = originalClientJs2.replace(\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerApiKey === '' || farseerUrl === '') {\n throw new Error('Tenant id, api key and url not set up');\n }\n // configure client with parameters\n super({\n headers: {\n 'X-TENANT-ID': tenantId,\n 'X-API-KEY': farseerApiKey,\n },\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n `const farseerApiKey = arg2 ?? process.env.FARSEER_API_KEY ?? '';\n const farseerAccessToken = process.env.FARSEER_ACCESS_TOKEN ?? '';\n const farseerUrl = arg3 ?? process.env.FARSEER_URL ?? '';\n if (tenantId === '' || farseerUrl === '' || (farseerApiKey === '' && farseerAccessToken === '')) {\n throw new Error('Tenant id, api key and url not set up');\n }\n const headers = { 'X-TENANT-ID': tenantId };\n if (farseerApiKey) { headers['X-API-KEY'] = farseerApiKey; }\n else { headers['Authorization'] = 'Bearer ' + farseerAccessToken; }\n super({\n headers,\n basePath: farseerUrl,\n fetchApi: util_1.patchedFetchApi,\n });`,\n );\n fs.writeFileSync(clientJsPath2, patched, 'utf-8');\n }\n\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 (originalClientJs2 !== null) {\n try {\n fs.writeFileSync(clientJsPath2, originalClientJs2, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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 if (originalClientJs2 !== null) {\n try {\n fs.writeFileSync(clientJsPath2, originalClientJs2, 'utf-8');\n } catch {\n /* restore best-effort */\n }\n }\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,2BAAs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,CAAC;AAAA,IAClB,CAAC;AAAA,EACL,CAAC;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/commands/status.js
CHANGED
|
@@ -37,11 +37,15 @@ var import_farseerFactory = require("../services/farseerFactory");
|
|
|
37
37
|
var import_syncService = require("../services/syncService");
|
|
38
38
|
var import_appSyncService = require("../services/appSyncService");
|
|
39
39
|
var import_helpers = require("../utils/helpers");
|
|
40
|
+
var import_cliOptions = require("../utils/cliOptions");
|
|
40
41
|
var fs = __toESM(require("fs"));
|
|
41
42
|
function registerStatusCommand(program) {
|
|
42
43
|
program.command("status [org] [tenant]").description(
|
|
43
44
|
"Show sync status between local and remote\n\nUsage: status <org> <tenant> OR status <tenant> (if org is known)"
|
|
44
|
-
).option("--all", "Show status for all files (default: only scripts .ts, .js)").option(
|
|
45
|
+
).option("--all", "Show status for all files (default: only scripts .ts, .js)").option(
|
|
46
|
+
"--deep",
|
|
47
|
+
"Hash remote file contents to detect remote-side edits (slower; default skips this and trusts the last sync)"
|
|
48
|
+
).option("--include-ext <ext>", "Include extra file extension (repeatable)", import_cliOptions.collectValues, []).option("--include-folder <folder>", "Include all files in folder (repeatable)", import_cliOptions.collectValues, []).action(async (arg1, arg2, options) => {
|
|
45
49
|
const { organisation, tenant } = (0, import_helpers.resolveTenantWithOrgMapping)(arg1, arg2);
|
|
46
50
|
const clientResult = await (0, import_farseerFactory.getFarseerClientWithFallback)(organisation, tenant);
|
|
47
51
|
if (!clientResult) {
|
|
@@ -58,52 +62,44 @@ function registerStatusCommand(program) {
|
|
|
58
62
|
console.log();
|
|
59
63
|
const syncService = new import_syncService.SyncService(tenant, clientResult.client);
|
|
60
64
|
try {
|
|
61
|
-
const includeExtensions = normalizeExtensions(options.includeExt);
|
|
65
|
+
const includeExtensions = (0, import_cliOptions.normalizeExtensions)(options.includeExt);
|
|
62
66
|
const includeFolders = options.includeFolder;
|
|
63
67
|
const status = await syncService.getStatus({
|
|
64
68
|
all: options.all,
|
|
69
|
+
deep: Boolean(options.deep),
|
|
65
70
|
includeExtensions: includeExtensions.length > 0 ? includeExtensions : void 0,
|
|
66
71
|
includeFolders: includeFolders.length > 0 ? includeFolders : void 0
|
|
67
72
|
});
|
|
68
|
-
const hasChanges = status.modifiedLocally.length > 0 || status.modifiedRemotely.length > 0 || status.
|
|
73
|
+
const hasChanges = status.modifiedLocally.length > 0 || status.modifiedRemotely.length > 0 || status.addedLocally.length > 0 || status.addedRemotely.length > 0 || status.deletedLocally.length > 0 || status.deletedRemotely.length > 0 || status.conflicts.length > 0;
|
|
69
74
|
if (!hasChanges) {
|
|
70
75
|
import_logger.logger.success("Everything is in sync!");
|
|
71
76
|
import_logger.logger.dim(`${status.inSync.length} file(s) synchronized.`);
|
|
77
|
+
if (!status.deepCompare) {
|
|
78
|
+
import_logger.logger.dim("Tip: pass --deep to also detect remote-side edits made since last pull.");
|
|
79
|
+
}
|
|
72
80
|
return;
|
|
73
81
|
}
|
|
74
|
-
if (status.modifiedLocally.length > 0) {
|
|
75
|
-
console.log(import_chalk.default.
|
|
76
|
-
for (const file of status.
|
|
77
|
-
|
|
78
|
-
}
|
|
82
|
+
if (status.addedLocally.length > 0 || status.modifiedLocally.length > 0 || status.deletedLocally.length > 0) {
|
|
83
|
+
console.log(import_chalk.default.bold("Local changes:"));
|
|
84
|
+
for (const file of status.addedLocally) console.log(import_chalk.default.green(` + ${file}`));
|
|
85
|
+
for (const file of status.modifiedLocally) console.log(import_chalk.default.yellow(` M ${file}`));
|
|
86
|
+
for (const file of status.deletedLocally) console.log(import_chalk.default.red(` - ${file}`));
|
|
79
87
|
console.log();
|
|
80
88
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
89
|
+
const syncState = syncService.loadSyncState();
|
|
90
|
+
if (status.addedRemotely.length > 0 || status.modifiedRemotely.length > 0 || status.deletedRemotely.length > 0) {
|
|
91
|
+
console.log(import_chalk.default.bold("Remote changes:"));
|
|
92
|
+
for (const file of status.addedRemotely) console.log(import_chalk.default.cyan(` + ${file}`));
|
|
84
93
|
for (const file of status.modifiedRemotely) {
|
|
85
94
|
const metadata = syncState.files[file]?.metadata;
|
|
86
95
|
const uploaderInfo = metadata?.uploaderName ? ` (by ${metadata.uploaderName})` : metadata?.uploaderEmail ? ` (by ${metadata.uploaderEmail})` : "";
|
|
87
96
|
console.log(import_chalk.default.cyan(` M ${file}`) + import_chalk.default.dim(uploaderInfo));
|
|
88
97
|
}
|
|
98
|
+
for (const file of status.deletedRemotely) console.log(import_chalk.default.red(` - ${file}`));
|
|
89
99
|
console.log();
|
|
90
100
|
}
|
|
91
|
-
if (status.
|
|
92
|
-
console.log(import_chalk.default.
|
|
93
|
-
for (const file of status.onlyLocal) {
|
|
94
|
-
console.log(import_chalk.default.green(` + ${file}`));
|
|
95
|
-
}
|
|
96
|
-
console.log();
|
|
97
|
-
}
|
|
98
|
-
if (status.onlyRemote.length > 0) {
|
|
99
|
-
console.log(import_chalk.default.red("Only on remote:"));
|
|
100
|
-
for (const file of status.onlyRemote) {
|
|
101
|
-
console.log(import_chalk.default.red(` - ${file}`));
|
|
102
|
-
}
|
|
103
|
-
console.log();
|
|
104
|
-
}
|
|
105
|
-
if (status.conflicts && status.conflicts.length > 0) {
|
|
106
|
-
console.log(import_chalk.default.red.bold("CONFLICTS:"));
|
|
101
|
+
if (status.conflicts.length > 0) {
|
|
102
|
+
console.log(import_chalk.default.red.bold("Conflicts:"));
|
|
107
103
|
for (const conflict of status.conflicts) {
|
|
108
104
|
console.log(import_chalk.default.red(` ! ${conflict.filePath}`));
|
|
109
105
|
console.log(import_chalk.default.dim(` ${conflict.description}`));
|
|
@@ -146,6 +142,9 @@ function registerStatusCommand(program) {
|
|
|
146
142
|
import_logger.logger.dim(`${appStatus.synced.length} app(s) in sync.`);
|
|
147
143
|
}
|
|
148
144
|
console.log();
|
|
145
|
+
if (!status.deepCompare) {
|
|
146
|
+
import_logger.logger.dim("Run with --deep to also check for remote-side content edits.");
|
|
147
|
+
}
|
|
149
148
|
import_logger.logger.dim('Use "farseer push <tenant>" to upload local changes.');
|
|
150
149
|
import_logger.logger.dim('Use "farseer pull <tenant>" to download remote changes.');
|
|
151
150
|
} catch (error) {
|
|
@@ -157,12 +156,6 @@ function registerStatusCommand(program) {
|
|
|
157
156
|
}
|
|
158
157
|
});
|
|
159
158
|
}
|
|
160
|
-
function collectValues(value, previous) {
|
|
161
|
-
return previous.concat([value]);
|
|
162
|
-
}
|
|
163
|
-
function normalizeExtensions(exts) {
|
|
164
|
-
return exts.map((ext) => ext.startsWith(".") ? ext.toLowerCase() : `.${ext.toLowerCase()}`);
|
|
165
|
-
}
|
|
166
159
|
// Annotate the CommonJS export names for ESM import in node:
|
|
167
160
|
0 && (module.exports = {
|
|
168
161
|
registerStatusCommand
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/status.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { getFarseerClientWithFallback, showLoginPrompt } 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 registerStatusCommand(program: Command): void {\n program\n .command('status [org] [tenant]')\n .description(\n 'Show sync status between local and remote\\n\\nUsage: status <org> <tenant> OR status <tenant> (if org is known)',\n )\n .option('--all', 'Show status for all files (default: only scripts .ts, .js)')\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\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.warning(`Local folder not found: apps/${tenant}/files/`);\n logger.dim('Run \"farseer pull <tenant>\" to download files from the instance.');\n return;\n }\n\n logger.info(`Comparing local (apps/${tenant}/files/) with remote (Files/)...`);\n console.log();\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n try {\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const status = await syncService.getStatus({\n all: options.all,\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n });\n\n const hasChanges =\n status.modifiedLocally.length > 0 ||\n status.modifiedRemotely.length > 0 ||\n status.
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,oBAAuB;AACvB,4BAA8D;AAC9D,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAA+D;AAC/D,SAAoB;AAEb,SAAS,sBAAsB,SAAwB;AAC1D,UACK,QAAQ,uBAAuB,EAC/B;AAAA,IACG;AAAA,EACJ,EACC,OAAO,SAAS,4DAA4D,EAC5E,OAAO,uBAAuB,6CAA6C,
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantFilesDir, resolveTenantWithOrgMapping } from '../utils/helpers';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport * as fs from 'fs';\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command('status [org] [tenant]')\n .description(\n 'Show sync status between local and remote\\n\\nUsage: status <org> <tenant> OR status <tenant> (if org is known)',\n )\n .option('--all', 'Show status for all files (default: only scripts .ts, .js)')\n .option(\n '--deep',\n 'Hash remote file contents to detect remote-side edits (slower; default skips this and trusts the last sync)',\n )\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\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.warning(`Local folder not found: apps/${tenant}/files/`);\n logger.dim('Run \"farseer pull <tenant>\" to download files from the instance.');\n return;\n }\n\n logger.info(`Comparing local (apps/${tenant}/files/) with remote (Files/)...`);\n console.log();\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n try {\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const status = await syncService.getStatus({\n all: options.all,\n deep: Boolean(options.deep),\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n });\n\n const hasChanges =\n status.modifiedLocally.length > 0 ||\n status.modifiedRemotely.length > 0 ||\n status.addedLocally.length > 0 ||\n status.addedRemotely.length > 0 ||\n status.deletedLocally.length > 0 ||\n status.deletedRemotely.length > 0 ||\n status.conflicts.length > 0;\n\n if (!hasChanges) {\n logger.success('Everything is in sync!');\n logger.dim(`${status.inSync.length} file(s) synchronized.`);\n if (!status.deepCompare) {\n logger.dim('Tip: pass --deep to also detect remote-side edits made since last pull.');\n }\n return;\n }\n\n if (\n status.addedLocally.length > 0 ||\n status.modifiedLocally.length > 0 ||\n status.deletedLocally.length > 0\n ) {\n console.log(chalk.bold('Local changes:'));\n for (const file of status.addedLocally) console.log(chalk.green(` + ${file}`));\n for (const file of status.modifiedLocally) console.log(chalk.yellow(` M ${file}`));\n for (const file of status.deletedLocally) console.log(chalk.red(` - ${file}`));\n console.log();\n }\n\n const syncState = syncService.loadSyncState();\n if (\n status.addedRemotely.length > 0 ||\n status.modifiedRemotely.length > 0 ||\n status.deletedRemotely.length > 0\n ) {\n console.log(chalk.bold('Remote changes:'));\n for (const file of status.addedRemotely) console.log(chalk.cyan(` + ${file}`));\n for (const file of status.modifiedRemotely) {\n // Modified-on-remote rows pick up `(by <name>)` when\n // the recorded sync metadata knows who last uploaded\n // the file. Falls back to email when only that's set.\n const metadata = syncState.files[file]?.metadata;\n const uploaderInfo = metadata?.uploaderName\n ? ` (by ${metadata.uploaderName})`\n : metadata?.uploaderEmail\n ? ` (by ${metadata.uploaderEmail})`\n : '';\n console.log(chalk.cyan(` M ${file}`) + chalk.dim(uploaderInfo));\n }\n for (const file of status.deletedRemotely) console.log(chalk.red(` - ${file}`));\n console.log();\n }\n\n if (status.conflicts.length > 0) {\n console.log(chalk.red.bold('Conflicts:'));\n for (const conflict of status.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n logger.dim(`Resolve conflicts during pull: farseer pull ${tenant}`);\n console.log();\n }\n\n // Apps status (works with both JWT and API key)\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n const appStatus = await appSyncService.getStatus();\n\n const hasAppChanges =\n appStatus.newLocal.length > 0 || appStatus.newRemote.length > 0 || appStatus.modified.length > 0;\n\n if (hasAppChanges) {\n console.log(chalk.bold('Apps:'));\n console.log();\n\n if (appStatus.newLocal.length > 0) {\n console.log(chalk.green('New local apps (to be created on remote):'));\n for (const app of appStatus.newLocal) {\n console.log(chalk.green(` + ${app}`));\n }\n console.log();\n }\n\n if (appStatus.newRemote.length > 0) {\n console.log(chalk.cyan('New remote apps (to be downloaded):'));\n for (const app of appStatus.newRemote) {\n console.log(chalk.cyan(` + ${app}`));\n }\n console.log();\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 console.log();\n }\n\n if (appStatus.synced.length > 0) {\n logger.dim(`${appStatus.synced.length} app(s) in sync.`);\n }\n } else if (appStatus.synced.length > 0) {\n logger.dim(`${appStatus.synced.length} app(s) in sync.`);\n }\n\n console.log();\n // Show the --deep hint whenever we're in fast mode AND there\n // are any changes to look at \u2014 fast mode might be hiding a\n // remote content edit precisely because it shows up only\n // under deep compare. Earlier we gated on add/delete buckets,\n // which is exactly the wrong condition: those are the cases\n // where --deep can NOT help.\n if (!status.deepCompare) {\n logger.dim('Run with --deep to also check for remote-side content edits.');\n }\n logger.dim('Use \"farseer push <tenant>\" to upload local changes.');\n logger.dim('Use \"farseer pull <tenant>\" to download remote changes.');\n } catch (error) {\n logger.error('Failed to check status.');\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,oBAAuB;AACvB,4BAA8D;AAC9D,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAA+D;AAC/D,wBAAmD;AACnD,SAAoB;AAEb,SAAS,sBAAsB,SAAwB;AAC1D,UACK,QAAQ,uBAAuB,EAC/B;AAAA,IACG;AAAA,EACJ,EACC,OAAO,SAAS,4DAA4D,EAC5E;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,uBAAuB,6CAA6C,iCAAe,CAAC,CAAC,EAC5F,OAAO,6BAA6B,4CAA4C,iCAAe,CAAC,CAAC,EACjG,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,G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,yDAAyD;AAAA,IACxE,SAAS,OAAO;AACZ,2BAAO,MAAM,yBAAyB;AACtC,UAAI,iBAAiB,OAAO;AACxB,6BAAO,IAAI,MAAM,OAAO;AAAA,MAC5B;AACA,cAAQ,KAAK,CAAC;AAAA,IAClB;AAAA,EACJ,CAAC;AACT;",
|
|
6
6
|
"names": ["chalk"]
|
|
7
7
|
}
|
package/dist/index.js
CHANGED
|
@@ -98,16 +98,18 @@ ${import_chalk.default.bold.underline("Configuration")} ${import_chalk.default.
|
|
|
98
98
|
${import_chalk.default.bold.underline("Sync Operations")} ${import_chalk.default.dim("(tenant optional if checked out)")}
|
|
99
99
|
pull [org] [tenant] Pull files and apps from remote
|
|
100
100
|
${import_chalk.default.dim("--all")} Download all files (not just .ts/.js)
|
|
101
|
-
${import_chalk.default.dim("--force")}
|
|
101
|
+
${import_chalk.default.dim("--force")} Mirror remote \u2192 local: overwrite local edits AND delete local-only (asks confirmation)
|
|
102
|
+
${import_chalk.default.dim("-y, --yes")} Skip confirm when local has uncommitted changes
|
|
102
103
|
${import_chalk.default.dim("--include-ext <ext>")} Include extra extension (repeatable)
|
|
103
104
|
${import_chalk.default.dim("--include-folder <folder>")} Include all files in folder (repeatable)
|
|
104
105
|
push [org] [tenant] Push local changes to remote
|
|
105
|
-
${import_chalk.default.dim("-y, --yes")} Skip confirmation
|
|
106
|
-
${import_chalk.default.dim("--force")}
|
|
106
|
+
${import_chalk.default.dim("-y, --yes")} Skip confirmation for non-destructive pushes
|
|
107
|
+
${import_chalk.default.dim("--force")} Mirror local \u2192 remote: overwrite drift AND delete remote-only (asks confirmation)
|
|
107
108
|
${import_chalk.default.dim("--include-ext <ext>")} Include extra extension (repeatable)
|
|
108
109
|
${import_chalk.default.dim("--include-folder <folder>")} Include all files in folder (repeatable)
|
|
109
110
|
status [tenant] Show sync status (local vs remote)
|
|
110
111
|
${import_chalk.default.dim("--all")} Show all files (not just .ts/.js)
|
|
112
|
+
${import_chalk.default.dim("--deep")} Hash remote contents to also detect remote-side edits (slower)
|
|
111
113
|
${import_chalk.default.dim("--include-ext <ext>")} Include extra extension (repeatable)
|
|
112
114
|
${import_chalk.default.dim("--include-folder <folder>")} Include all files in folder (repeatable)
|
|
113
115
|
diff [tenant] [file] Show file differences
|