farseer-cli 1.10.2 → 1.11.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 +7 -0
- package/dist/commands/app.js +15 -12
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/apps.js +3 -3
- package/dist/commands/apps.js.map +2 -2
- package/dist/commands/cells.js +3 -3
- package/dist/commands/cells.js.map +2 -2
- package/dist/commands/config.js +23 -15
- package/dist/commands/config.js.map +2 -2
- package/dist/commands/dashboards.js +3 -3
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/dimensions.js +3 -3
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/files.js +5 -4
- package/dist/commands/files.js.map +2 -2
- package/dist/commands/formula.js +3 -3
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/list.js +5 -4
- package/dist/commands/list.js.map +2 -2
- package/dist/commands/login.js +6 -5
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/model.js +5 -4
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/push.js +5 -7
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/run.js +3 -3
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/sheets.js +3 -3
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/variables.js +5 -4
- package/dist/commands/variables.js.map +2 -2
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/index.js.map +2 -2
- package/dist/mcp/tools/appTools.js +30 -60
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +4 -6
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +34 -56
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +17 -38
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/folderTools.js +7 -11
- package/dist/mcp/tools/folderTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +104 -159
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +5 -11
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +31 -51
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +27 -57
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/session.js +2 -2
- package/dist/mcp/utils/session.js.map +2 -2
- package/dist/services/appSyncService.js.map +1 -1
- package/dist/services/apps.js +149 -0
- package/dist/services/apps.js.map +7 -0
- package/dist/services/authErrors.js +77 -0
- package/dist/services/authErrors.js.map +7 -0
- package/dist/services/configService.js +7 -4
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +87 -0
- package/dist/services/credentials.js.map +7 -0
- package/dist/services/farseerService.js +247 -112
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/httpError.js +35 -0
- package/dist/services/httpError.js.map +7 -0
- package/dist/services/modelExport.js +63 -0
- package/dist/services/modelExport.js.map +7 -0
- package/dist/services/organisation.js +88 -0
- package/dist/services/organisation.js.map +7 -0
- package/dist/services/preflight.js +10 -13
- package/dist/services/preflight.js.map +2 -2
- package/dist/services/syncService.js +2 -2
- package/dist/services/syncService.js.map +2 -2
- package/dist/utils/constants.js +2 -5
- package/dist/utils/constants.js.map +2 -2
- package/dist/utils/fileLogger.js +24 -1
- package/dist/utils/fileLogger.js.map +2 -2
- package/dist/utils/folderMatch.js +49 -0
- package/dist/utils/folderMatch.js.map +7 -0
- package/dist/utils/helpers.js +26 -0
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/syncScope.js +44 -0
- package/dist/utils/syncScope.js.map +7 -0
- package/docs/api-reference.md +13 -1
- package/package.json +1 -1
- package/dist/services/farseerApi.js +0 -716
- package/dist/services/farseerApi.js.map +0 -7
- package/dist/services/farseerFactory.js +0 -288
- package/dist/services/farseerFactory.js.map +0 -7
|
@@ -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 { ensureFreshToken } from '../services/farseerFactory';\nimport { preflight } from '../services/preflight';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantFilesDir, safeResolveWithinBase, validateOnlyFilePaths, displayLocalPath } from '../utils/helpers';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { ValidationFailure, partitionForUpload } from '../utils/fileValidation';\nimport { collectValues, normalizeExtensions, normalizeRelativePath } from '../utils/cliOptions';\nimport { reportIgnoredLocal } from '../utils/syncReporting';\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(\n '--shallow',\n 'Skip the remote-content hash check in the pre-flight (faster on big tenants; trusts the last-pull baseline). Ignored under --force, where deep is required for correct mirror semantics.',\n )\n // Accept `--deep` as a no-op alias so 1.6.1-era scripts keep\n // working \u2014 deep is now the default; see status.ts for context.\n .option('--deep', '(Deprecated; now the default) Force the deep remote-content hash pre-flight')\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\n .option(\n '--only <path>',\n 'Only push the listed file(s) (repeatable, paths relative to tenant files dir, e.g. Scripts/foo.ts). Other local edits are not touched; the drift check still fires on these paths if remote has changed them.',\n collectValues,\n [],\n )\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant, client } = await preflight(arg1, arg2);\n\n const filesDir = getTenantFilesDir(tenant);\n\n if (!fs.existsSync(filesDir)) {\n logger.error(`Local folder not found: ${displayLocalPath(filesDir)}`);\n logger.dim('Run \"farseer pull <tenant>\" first to initialize the folder.');\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, client);\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n // POSIX-normalise: the sync engine canonicalises every candidate\n // to forward slashes before include/onlyFiles matching, so a\n // Windows user typing `--only Scripts\\foo.ts` would otherwise\n // miss the comparison and the file would silently fall out of\n // scope.\n const onlyFiles = (options.only as string[]).map(normalizeRelativePath);\n const syncFilterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n onlyFiles: onlyFiles.length > 0 ? onlyFiles : undefined,\n };\n\n // --only is a surgical-push escape hatch. Skip the apps path\n // entirely (which has its own drift logic that doesn't know\n // about file whitelists) and skip the remote-drift check \u2014\n // the user has narrowed the blast radius to a known set of\n // files, that's the whole point. Without this short-circuit\n // both the drift gate and apps push could touch things\n // outside the requested scope, defeating --only.\n const onlyMode = onlyFiles.length > 0;\n\n // Pre-flight: every --only path must resolve to a real file\n // under filesDir. Without this check, a typo (wrong case,\n // double slash, deleted file) silently produces \"Nothing to\n // push. Everything is in sync.\" \u2014 same exit code as a real\n // no-op, and the user assumes the push went through.\n // Traversal paths (`--only ../x`) join the same missing list\n // so the user gets one consolidated error.\n if (onlyMode) {\n const { missing } = validateOnlyFilePaths(filesDir, onlyFiles);\n if (missing.length > 0) {\n logger.error(`--only path(s) not found under ${filesDir}:`);\n for (const m of missing) console.log(chalk.red(` ${m}`));\n logger.dim('Paths are relative to the tenant files dir and case-sensitive.');\n process.exit(1);\n }\n }\n\n // 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 // Run a DEEP pre-flight by default. Shallow status can't see\n // remote-side content drift (it trusts our recorded baseline),\n // so without it we'd silently overwrite remote edits that\n // landed since the last pull. `--shallow` opts out for users\n // who explicitly want the faster path on large tenants.\n //\n // --force ALWAYS implies deep, overriding --shallow. Mirror\n // mode means \"make remote = local\" \u2014 we need to know the\n // current remote content to decide what to overwrite. A\n // shallow status would miss remote-side content drift and\n // silently no-op when local matches the baseline. Force +\n // shallow is a contradiction, so deep wins.\n const deep = !!options.force || !options.shallow;\n const status = await syncService.getStatus({\n ...syncFilterOptions,\n deep,\n });\n\n // Drift gate: non-force push must not silently overwrite\n // remote-side drift. Block here, after deep status has run,\n // so the user sees the actual remote drift paths and can\n // choose between pull (merge remote) or --force (mirror,\n // overwrite remote). All three remote-side buckets count as\n // drift \u2014 adds, deletes, and content edits.\n //\n // Suppressed under --only: that's an explicit narrow-scope\n // push and only fires the block if a remote-drift path\n // overlaps the requested set.\n if (!options.force) {\n const conflictingAdded = onlyMode\n ? status.addedRemotely.filter((p) => onlyFiles.includes(p))\n : status.addedRemotely;\n const conflictingDeleted = onlyMode\n ? status.deletedRemotely.filter((p) => onlyFiles.includes(p))\n : status.deletedRemotely;\n const conflictingModified = onlyMode\n ? status.modifiedRemotely.filter((p) => onlyFiles.includes(p))\n : status.modifiedRemotely;\n const totalConflicts = conflictingAdded.length + conflictingDeleted.length + conflictingModified.length;\n if (totalConflicts > 0) {\n logger.error(`Remote has changes for ${totalConflicts} file(s) since last pull:`);\n if (conflictingAdded.length > 0) {\n console.log(chalk.cyan(' New on remote (need to pull):'));\n for (const f of conflictingAdded) console.log(chalk.cyan(` + ${f}`));\n }\n if (conflictingDeleted.length > 0) {\n console.log(chalk.red(' Removed on remote (need to pull to clean local):'));\n for (const f of conflictingDeleted) console.log(chalk.red(` - ${f}`));\n }\n if (conflictingModified.length > 0) {\n console.log(chalk.yellow(' Modified on remote (need to pull to merge):'));\n for (const f of conflictingModified) console.log(chalk.yellow(` M ${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 the drift remains blocking.\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}\\` to merge remote changes, then push.`);\n logger.dim('Or use --force to mirror (overwrite remote with local).');\n process.exit(1);\n }\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 // In --only mode we deliberately don't touch apps at all\n // (the user asked for a file-scoped push). Stub the app\n // status to \"nothing to do\" so downstream code can treat\n // the two modes uniformly.\n const appSyncService = new AppSyncService(tenant, client);\n const appStatus = onlyMode\n ? { newLocal: [], newRemote: [], modified: [], synced: [] }\n : 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 // Print the out-of-scope warning BEFORE the success line\n // so the \"within current scope\" qualifier reads as a\n // follow-up to the count the user just saw, not a\n // contradiction of a bare \"Nothing to push\" message.\n reportIgnoredLocal(status.ignoredLocal, status.ignoredLocalTotal);\n if (status.ignoredLocalTotal > 0) {\n logger.success('Everything is in sync within current scope.');\n logger.dim(\n `(${status.ignoredLocalTotal} file(s) outside scope were not compared \u2014 see warning above for details.)`,\n );\n } else {\n logger.success('Nothing to push. Everything is in sync.');\n }\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 // Surface scope-skipped files BEFORE the confirmation prompt so\n // the user never confirms a push thinking it covers everything in\n // the workspace when in fact .md / .json / .py etc. were silently\n // excluded by the default whitelist.\n reportIgnoredLocal(status.ignoredLocal, status.ignoredLocalTotal);\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(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 ignoredLocal: [],\n ignoredLocalTotal: 0,\n ignoredLocalTotalByReason: { unsupportedExtension: 0, blocklistedFolder: 0 },\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,4BAAiC;AACjC,uBAA0B;AAC1B,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAAkG;AAClG,4BAAkC;AAClC,4BAAsD;AACtD,wBAA0E;AAC1E,2BAAmC;AAEnC,SAAoB;AA4Bb,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,aAAa,6EAA6E,EACjG;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EAGC,OAAO,UAAU,6EAA6E,EAC9F,OAAO,uBAAuB,6CAA6C,iCAAe,CAAC,CAAC,EAC5F,OAAO,6BAA6B,4CAA4C,iCAAe,CAAC,CAAC,EACjG;AAAA,IACG;A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AAa,IAAI,CAAC;AAAA,IAC9D,iBAAiB,QAAQ,QAAQ,CAAC,GAAG,OAAO,eAAe,IAAI,CAAC;AAAA,IAChE,kBAAkB,QAAQ,QAAQ,CAAC,GAAG,OAAO,gBAAgB,IAAI,CAAC;AAAA,EACtE;AACJ;AAEA,SAAS,iBAAiB,YAAuC;AAC7D,aAAW,KAAK,YAAY;AACxB,YAAQ,IAAI,aAAAA,QAAM,IAAI,OAAO,EAAE,QAAQ,EAAE,CAAC;AAC1C,YAAQ,IAAI,aAAAA,QAAM,IAAI,OAAO,EAAE,MAAM,EAAE,CAAC;AACxC,QAAI,EAAE,KAAM,SAAQ,IAAI,aAAAA,QAAM,IAAI,OAAO,EAAE,IAAI,EAAE,CAAC;AAAA,EACtD;AACA,UAAQ,IAAI;AAChB;AAcA,SAAS,gBAAgB,UAAkB,YAA2C;AAClF,QAAM,mBAA0E,CAAC;AACjF,aAAW,YAAY,YAAY;AAC/B,QAAI;AACA,YAAM,eAAW,sCAAsB,UAAU,QAAQ;AACzD,YAAM,UAAU,GAAG,aAAa,QAAQ;AACxC,uBAAiB,KAAK,EAAE,UAAU,MAAM,QAAQ,QAAQ,QAAQ,CAAC;AAAA,IACrE,QAAQ;AAIJ;AAAA,IACJ;AAAA,EACJ;AACA,QAAM,EAAE,SAAS,QAAI,0CAAmB,gBAAgB;AACxD,SAAO;AACX;",
|
|
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 { preflight } from '../services/preflight';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport {\n getTenantFilesDir,\n orExit,\n safeResolveWithinBase,\n validateOnlyFilePaths,\n displayLocalPath,\n} from '../utils/helpers';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { ValidationFailure, partitionForUpload } from '../utils/fileValidation';\nimport { collectValues, normalizeExtensions, normalizeRelativePath } from '../utils/cliOptions';\nimport { reportIgnoredLocal } from '../utils/syncReporting';\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(\n '--shallow',\n 'Skip the remote-content hash check in the pre-flight (faster on big tenants; trusts the last-pull baseline). Ignored under --force, where deep is required for correct mirror semantics.',\n )\n // Accept `--deep` as a no-op alias so 1.6.1-era scripts keep\n // working \u2014 deep is now the default; see status.ts for context.\n .option('--deep', '(Deprecated; now the default) Force the deep remote-content hash pre-flight')\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\n .option(\n '--only <path>',\n 'Only push the listed file(s) (repeatable, paths relative to tenant files dir, e.g. Scripts/foo.ts). Other local edits are not touched; the drift check still fires on these paths if remote has changed them.',\n collectValues,\n [],\n )\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant, client } = await preflight(arg1, arg2);\n\n const filesDir = getTenantFilesDir(tenant);\n\n if (!fs.existsSync(filesDir)) {\n logger.error(`Local folder not found: ${displayLocalPath(filesDir)}`);\n logger.dim('Run \"farseer pull <tenant>\" first to initialize the folder.');\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, client);\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n // POSIX-normalise: the sync engine canonicalises every candidate\n // to forward slashes before include/onlyFiles matching, so a\n // Windows user typing `--only Scripts\\foo.ts` would otherwise\n // miss the comparison and the file would silently fall out of\n // scope.\n const onlyFiles = (options.only as string[]).map(normalizeRelativePath);\n const syncFilterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n onlyFiles: onlyFiles.length > 0 ? onlyFiles : undefined,\n };\n\n // --only is a surgical-push escape hatch. Skip the apps path\n // entirely (which has its own drift logic that doesn't know\n // about file whitelists) and skip the remote-drift check \u2014\n // the user has narrowed the blast radius to a known set of\n // files, that's the whole point. Without this short-circuit\n // both the drift gate and apps push could touch things\n // outside the requested scope, defeating --only.\n const onlyMode = onlyFiles.length > 0;\n\n // Pre-flight: every --only path must resolve to a real file\n // under filesDir. Without this check, a typo (wrong case,\n // double slash, deleted file) silently produces \"Nothing to\n // push. Everything is in sync.\" \u2014 same exit code as a real\n // no-op, and the user assumes the push went through.\n // Traversal paths (`--only ../x`) join the same missing list\n // so the user gets one consolidated error.\n if (onlyMode) {\n const { missing } = validateOnlyFilePaths(filesDir, onlyFiles);\n if (missing.length > 0) {\n logger.error(`--only path(s) not found under ${filesDir}:`);\n for (const m of missing) console.log(chalk.red(` ${m}`));\n logger.dim('Paths are relative to the tenant files dir and case-sensitive.');\n process.exit(1);\n }\n }\n\n // 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 // Run a DEEP pre-flight by default. Shallow status can't see\n // remote-side content drift (it trusts our recorded baseline),\n // so without it we'd silently overwrite remote edits that\n // landed since the last pull. `--shallow` opts out for users\n // who explicitly want the faster path on large tenants.\n //\n // --force ALWAYS implies deep, overriding --shallow. Mirror\n // mode means \"make remote = local\" \u2014 we need to know the\n // current remote content to decide what to overwrite. A\n // shallow status would miss remote-side content drift and\n // silently no-op when local matches the baseline. Force +\n // shallow is a contradiction, so deep wins.\n const deep = !!options.force || !options.shallow;\n // Both status reads sit ahead of the push's own try block, and both\n // reach the network. Nothing is uploaded yet, so a failure here means\n // the push did not start \u2014 which has to be said, and said with a\n // non-zero exit, rather than falling through to an empty plan that\n // reads as \"everything is in sync\".\n const status = await orExit(\n syncService.getStatus({ ...syncFilterOptions, deep }),\n 'Failed to compare local files with the tenant.',\n );\n\n // Drift gate: non-force push must not silently overwrite\n // remote-side drift. Block here, after deep status has run,\n // so the user sees the actual remote drift paths and can\n // choose between pull (merge remote) or --force (mirror,\n // overwrite remote). All three remote-side buckets count as\n // drift \u2014 adds, deletes, and content edits.\n //\n // Suppressed under --only: that's an explicit narrow-scope\n // push and only fires the block if a remote-drift path\n // overlaps the requested set.\n if (!options.force) {\n const conflictingAdded = onlyMode\n ? status.addedRemotely.filter((p) => onlyFiles.includes(p))\n : status.addedRemotely;\n const conflictingDeleted = onlyMode\n ? status.deletedRemotely.filter((p) => onlyFiles.includes(p))\n : status.deletedRemotely;\n const conflictingModified = onlyMode\n ? status.modifiedRemotely.filter((p) => onlyFiles.includes(p))\n : status.modifiedRemotely;\n const totalConflicts = conflictingAdded.length + conflictingDeleted.length + conflictingModified.length;\n if (totalConflicts > 0) {\n logger.error(`Remote has changes for ${totalConflicts} file(s) since last pull:`);\n if (conflictingAdded.length > 0) {\n console.log(chalk.cyan(' New on remote (need to pull):'));\n for (const f of conflictingAdded) console.log(chalk.cyan(` + ${f}`));\n }\n if (conflictingDeleted.length > 0) {\n console.log(chalk.red(' Removed on remote (need to pull to clean local):'));\n for (const f of conflictingDeleted) console.log(chalk.red(` - ${f}`));\n }\n if (conflictingModified.length > 0) {\n console.log(chalk.yellow(' Modified on remote (need to pull to merge):'));\n for (const f of conflictingModified) console.log(chalk.yellow(` M ${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 the drift remains blocking.\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}\\` to merge remote changes, then push.`);\n logger.dim('Or use --force to mirror (overwrite remote with local).');\n process.exit(1);\n }\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 // In --only mode we deliberately don't touch apps at all\n // (the user asked for a file-scoped push). Stub the app\n // status to \"nothing to do\" so downstream code can treat\n // the two modes uniformly.\n const appSyncService = new AppSyncService(tenant, client);\n const appStatus = onlyMode\n ? { newLocal: [], newRemote: [], modified: [], synced: [] }\n : await orExit(appSyncService.getStatus(), \"Failed to read the tenant's apps.\");\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 // Print the out-of-scope warning BEFORE the success line\n // so the \"within current scope\" qualifier reads as a\n // follow-up to the count the user just saw, not a\n // contradiction of a bare \"Nothing to push\" message.\n reportIgnoredLocal(status.ignoredLocal, status.ignoredLocalTotal);\n if (status.ignoredLocalTotal > 0) {\n logger.success('Everything is in sync within current scope.');\n logger.dim(\n `(${status.ignoredLocalTotal} file(s) outside scope were not compared \u2014 see warning above for details.)`,\n );\n } else {\n logger.success('Nothing to push. Everything is in sync.');\n }\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 // Surface scope-skipped files BEFORE the confirmation prompt so\n // the user never confirms a push thinking it covers everything in\n // the workspace when in fact .md / .json / .py etc. were silently\n // excluded by the default whitelist.\n reportIgnoredLocal(status.ignoredLocal, status.ignoredLocalTotal);\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 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 ignoredLocal: [],\n ignoredLocalTotal: 0,\n ignoredLocalTotalByReason: { unsupportedExtension: 0, blocklistedFolder: 0 },\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,uBAA0B;AAC1B,yBAA4B;AAC5B,4BAA+B;AAC/B,qBAMO;AACP,4BAAkC;AAClC,4BAAsD;AACtD,wBAA0E;AAC1E,2BAAmC;AAEnC,SAAoB;AA4Bb,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,aAAa,6EAA6E,EACjG;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EAGC,OAAO,UAAU,6EAA6E,EAC9F,OAAO,uBAAuB,6CAA6C,iCAAe,CAAC,CAAC,EAC5F,OAAO,6BAA6B,4CAA4C,iCAAe,CAAC,CAAC,EACjG;AAAA,IACG;AAAA,IACA;AAAA,IACA;AAAA,IACA,CAAC;AAAA,EACL,EACC,OAAO,OAAO,MAAM,MAAM,YAAY;AACnC,UAAM,EAAE,cAAc,QAAQ,OAAO,IAAI,UAAM,4BAAU,MAAM,IAAI;AAEnE,UAAM,eAAW,kCAAkB,MAAM;AAEzC,QAAI,CAAC,GAAG,WAAW,QAAQ,GAAG;AAC1B,2BAAO,MAAM,+BAA2B,iCAAiB,QAAQ,CAAC,EAAE;AACpE,2BAAO,IAAI,6DAA6D;AACxE,cAAQ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C,YAAQ,IAAI,aAAAA,QAAM,IAAI,OAAO,EAAE,MAAM,EAAE,CAAC;AACxC,QAAI,EAAE,KAAM,SAAQ,IAAI,aAAAA,QAAM,IAAI,OAAO,EAAE,IAAI,EAAE,CAAC;AAAA,EACtD;AACA,UAAQ,IAAI;AAChB;AAcA,SAAS,gBAAgB,UAAkB,YAA2C;AAClF,QAAM,mBAA0E,CAAC;AACjF,aAAW,YAAY,YAAY;AAC/B,QAAI;AACA,YAAM,eAAW,sCAAsB,UAAU,QAAQ;AACzD,YAAM,UAAU,GAAG,aAAa,QAAQ;AACxC,uBAAiB,KAAK,EAAE,UAAU,MAAM,QAAQ,QAAQ,QAAQ,CAAC;AAAA,IACrE,QAAQ;AAIJ;AAAA,IACJ;AAAA,EACJ;AACA,QAAM,EAAE,SAAS,QAAI,0CAAmB,gBAAgB;AACxD,SAAO;AACX;",
|
|
6
6
|
"names": ["chalk", "inquirer"]
|
|
7
7
|
}
|
package/dist/commands/run.js
CHANGED
|
@@ -34,7 +34,7 @@ module.exports = __toCommonJS(run_exports);
|
|
|
34
34
|
var import_logger = require("../utils/logger");
|
|
35
35
|
var import_configService = require("../services/configService");
|
|
36
36
|
var import_farseerService = require("../services/farseerService");
|
|
37
|
-
var
|
|
37
|
+
var import_authErrors = require("../services/authErrors");
|
|
38
38
|
var import_preflight = require("../services/preflight");
|
|
39
39
|
var import_helpers = require("../utils/helpers");
|
|
40
40
|
var fs = __toESM(require("fs"));
|
|
@@ -128,7 +128,7 @@ function registerRunCommand(program) {
|
|
|
128
128
|
}
|
|
129
129
|
const credentials = await getRunCredentials(organisation, tenant, options.tenantId);
|
|
130
130
|
if (!credentials) {
|
|
131
|
-
(0,
|
|
131
|
+
(0, import_authErrors.showLoginPrompt)(tenant);
|
|
132
132
|
process.exit(1);
|
|
133
133
|
}
|
|
134
134
|
const tenantDir = (0, import_helpers.getTenantDir)(tenant);
|
|
@@ -219,7 +219,7 @@ function registerRunCommand(program) {
|
|
|
219
219
|
let script = appName;
|
|
220
220
|
const credentials = await getRunCredentials(organisation, tenant, options.tenantId);
|
|
221
221
|
if (!credentials) {
|
|
222
|
-
(0,
|
|
222
|
+
(0, import_authErrors.showLoginPrompt)(tenant);
|
|
223
223
|
process.exit(1);
|
|
224
224
|
}
|
|
225
225
|
if (script.toLowerCase().startsWith("scripts/")) {
|
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 { showLoginPrompt } from '../services/farseerFactory';\nimport { preflightForPair } from '../services/preflight';\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 // Guard (auth + org\u220Btenant) first, then fetch the app details.\n const { client: api } = await preflightForPair(organisation, tenant);\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 // defaultValue is optional on the API type; treat missing as ''\n // so we always hand a string to the runner.\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_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 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 { organisation, tenant, appName } = parseAppArgs(args);\n // Same guard as `run`, but the result is discarded: run-script needs\n // no client of its own. It's here for the gate alone \u2014 the script is\n // handed live credentials for this tenant a few lines down, so the\n // pair has to be proven before that happens. That makes it the one\n // command that trades zero network calls for one.\n await preflightForPair(organisation, tenant);\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_TOKEN = credentials.accessToken;\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 (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,
|
|
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 { showLoginPrompt } from '../services/authErrors';\nimport { preflightForPair } from '../services/preflight';\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 // Guard (auth + org\u220Btenant) first, then fetch the app details.\n const { client: api } = await preflightForPair(organisation, tenant);\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 // defaultValue is optional on the API type; treat missing as ''\n // so we always hand a string to the runner.\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_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 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 { organisation, tenant, appName } = parseAppArgs(args);\n // Same guard as `run`, but the result is discarded: run-script needs\n // no client of its own. It's here for the gate alone \u2014 the script is\n // handed live credentials for this tenant a few lines down, so the\n // pair has to be proven before that happens. That makes it the one\n // command that trades zero network calls for one.\n await preflightForPair(organisation, tenant);\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_TOKEN = credentials.accessToken;\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 (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,wBAAgC;AAChC,uBAAiC;AACjC,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,kBACX,cACA,QACA,kBAC8B;AAI9B,QAAM,iBAAa,oCAAc,MAAM;AACvC,MAAI,YAAY;AACZ,WAAO;AAA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B,GAAG;AAAA,MAClD,OAAO;AAAA,MACP,KAAK;AAAA,MACL,OAAO;AAAA,MACP,KAAK;AAAA,IACT,CAAC;AAED,UAAM,GAAG,SAAS,CAAC,SAAS;AACxB,UAAI,SAAS,GAAG;AACZ,6BAAO,MAAM,2BAA2B,IAAI,EAAE;AAC9C,gBAAQ,KAAK,QAAQ,CAAC;AAAA,MAC1B;AAAA,IACJ,CAAC;AAED,UAAM,GAAG,SAAS,CAAC,QAAQ;AACvB,2BAAO,MAAM,yBAAyB,IAAI,OAAO,EAAE;AACnD,2BAAO,IAAI,gDAAgD;AAC3D,cAAQ,KAAK,CAAC;AAAA,IAClB,CAAC;AAAA,EACL,CAAC;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/commands/sheets.js
CHANGED
|
@@ -35,7 +35,7 @@ var fs = __toESM(require("fs"));
|
|
|
35
35
|
var farseer = __toESM(require("farseer-client"));
|
|
36
36
|
var import_chalk = __toESM(require("chalk"));
|
|
37
37
|
var import_logger = require("../utils/logger");
|
|
38
|
-
var
|
|
38
|
+
var import_authErrors = require("../services/authErrors");
|
|
39
39
|
var import_preflight = require("../services/preflight");
|
|
40
40
|
var import_entityResolver = require("../utils/entityResolver");
|
|
41
41
|
var import_farseer_client = require("farseer-client");
|
|
@@ -185,8 +185,8 @@ async function collectFolderItems(client, folderId, path, itemType) {
|
|
|
185
185
|
}
|
|
186
186
|
function handleSheetError(error, tenant) {
|
|
187
187
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
188
|
-
if ((0,
|
|
189
|
-
(0,
|
|
188
|
+
if ((0, import_authErrors.isAuthError)(error)) {
|
|
189
|
+
(0, import_authErrors.showLoginPrompt)(tenant);
|
|
190
190
|
} else if (errorMessage.includes("404")) {
|
|
191
191
|
import_logger.logger.error("Sheet not found or tenant not accessible.");
|
|
192
192
|
} else if (errorMessage.includes("ENOTFOUND") || errorMessage.includes("ECONNREFUSED")) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/sheets.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport * as fs from 'fs';\nimport * as farseer from 'farseer-client';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,SAAoB;AACpB,cAAyB;AACzB,mBAAkB;AAClB,oBAAuB;AACvB,
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport * as fs from 'fs';\nimport * as farseer from 'farseer-client';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/authErrors';\nimport { preflight } from '../services/preflight';\nimport { resolveSheetId } from '../utils/entityResolver';\nimport { EntityType } from 'farseer-client';\n\nexport function registerSheetsCommand(program: Command): void {\n const sheetsCmd = program.command('sheets').description('List and inspect sheets');\n\n // farseer sheets list [org] [tenant]\n sheetsCmd\n .command('list [org] [tenant]')\n .description('List all sheets')\n .option('--json', 'Output raw JSON')\n .action(async (first, second, options) => {\n const { native: nativeClient, tenant } = await preflight(first, second);\n\n try {\n // Try entities API first, fall back to folder traversal\n let sheets: { id: number; name: string; folderPath?: string[] }[];\n try {\n const entities = await nativeClient.entities.getAll([EntityType.Sheet]);\n sheets = entities.map((e: any) => ({\n id: e.id,\n name: e.meta?.name || `Sheet ${e.id}`,\n }));\n } catch {\n sheets = [];\n }\n\n // If entities returned nothing, fall back to folder traversal\n if (sheets.length === 0) {\n sheets = await collectFolderItems(nativeClient, null, [], farseer.FolderItemType.Sheet);\n }\n\n if (options.json) {\n console.log(JSON.stringify(sheets, null, 2));\n return;\n }\n\n logger.header(`Sheets (${sheets.length})`);\n if (sheets.length === 0) {\n logger.dim(' No sheets found.');\n return;\n }\n for (const sheet of sheets) {\n const folder = sheet.folderPath?.length ? chalk.dim(` (${sheet.folderPath.join(' / ')})`) : '';\n console.log(` ${chalk.dim(String(sheet.id).padEnd(8))} ${chalk.bold(sheet.name)}${folder}`);\n }\n } catch (error) {\n handleSheetError(error, tenant);\n }\n });\n\n // farseer sheets show <nameOrId> [org] [tenant]\n sheetsCmd\n .command('show <nameOrId> [org] [tenant]')\n .description('Show sheet configuration')\n .option('--json', 'Output raw JSON')\n .action(async (nameOrId, first, second, options) => {\n const { native: nativeClient, tenant } = await preflight(first, second);\n\n try {\n const resolved = await resolveSheetId(nativeClient, nameOrId);\n if (!resolved) {\n logger.error(`Sheet \"${nameOrId}\" not found.`);\n process.exit(1);\n }\n\n const sheet = await nativeClient.sheets.get(resolved.id);\n\n if (options.json) {\n console.log(JSON.stringify(sheet, null, 2));\n return;\n }\n\n logger.header(`Sheet: ${sheet.name}`);\n console.log(` ID: ${sheet.id}`);\n console.log(` Stacked: ${sheet.stacked}`);\n if (sheet.rows) {\n console.log(` Rows: ${JSON.stringify(sheet.rows)}`);\n }\n if (sheet.columns) {\n console.log(` Columns: ${JSON.stringify(sheet.columns)}`);\n }\n } catch (error) {\n handleSheetError(error, tenant);\n }\n });\n\n // farseer sheets data <nameOrId> [org] [tenant]\n sheetsCmd\n .command('data <nameOrId> [org] [tenant]')\n .description('Get sheet data')\n .option('--json', 'Output raw JSON')\n .option('--limit <n>', 'Limit number of rows', parseInt)\n .action(async (nameOrId, first, second, options) => {\n const { native: nativeClient, tenant } = await preflight(first, second);\n\n try {\n const resolved = await resolveSheetId(nativeClient, nameOrId);\n if (!resolved) {\n logger.error(`Sheet \"${nameOrId}\" not found.`);\n process.exit(1);\n }\n\n const sheet = await nativeClient.sheets.get(resolved.id);\n const dataRequest: any = {\n path: `/${resolved.id}`,\n includeData: true,\n stacked: sheet.stacked,\n rows: sheet.rows,\n columns: sheet.columns,\n sharing: sheet.sharing,\n };\n\n const data = await nativeClient.sheets.getData(dataRequest);\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2));\n return;\n }\n\n logger.header(`Sheet Data: ${resolved.name}`);\n const dataObj = data as any;\n if (dataObj.cells && Array.isArray(dataObj.cells)) {\n const limit = options.limit || dataObj.cells.length;\n const cells = dataObj.cells.slice(0, limit);\n console.log(\n ` Cells: ${cells.length}${dataObj.cells.length > limit ? ` (of ${dataObj.cells.length})` : ''}`,\n );\n for (const cell of cells) {\n console.log(` ${JSON.stringify(cell)}`);\n }\n } else {\n console.log(JSON.stringify(data, null, 2));\n }\n } catch (error) {\n handleSheetError(error, tenant);\n }\n });\n\n // farseer sheets set-data [org] [tenant]\n sheetsCmd\n .command('set-data [org] [tenant]')\n .description('Set sheet data from JSON file')\n .requiredOption('--sheet <nameOrId>', 'Sheet name or ID')\n .requiredOption('--input <file>', 'JSON file with sheet data')\n .option('-y, --yes', 'Skip confirmation')\n .action(async (first, second, options) => {\n const { native: nativeClient, tenant } = await preflight(first, second);\n\n try {\n const resolved = await resolveSheetId(nativeClient, options.sheet);\n if (!resolved) {\n logger.error(`Sheet \"${options.sheet}\" not found.`);\n process.exit(1);\n }\n\n if (!fs.existsSync(options.input)) {\n logger.error(`File not found: ${options.input}`);\n process.exit(1);\n }\n\n const inputData = JSON.parse(fs.readFileSync(options.input, 'utf-8'));\n\n if (!options.yes) {\n logger.warning(`This will update data in sheet \"${resolved.name}\" (ID: ${resolved.id}).`);\n logger.dim('Use -y to skip confirmation.');\n process.exit(0);\n }\n\n const setDataRequest: any = {\n sheetId: resolved.id,\n ...inputData,\n };\n\n await nativeClient.sheets.setData(setDataRequest);\n logger.success(`Sheet data updated for \"${resolved.name}\".`);\n } catch (error) {\n handleSheetError(error, tenant);\n }\n });\n}\n\nasync function collectFolderItems(\n client: farseer.FarseerClient,\n folderId: number | null,\n path: string[],\n itemType: farseer.FolderItemType,\n): Promise<{ id: number; name: string; folderPath: string[] }[]> {\n const items: { id: number; name: string; folderPath: string[] }[] = [];\n const results = await client.folders.listItemsBatch([{ id: folderId }]);\n const children = results[0]?.items ?? [];\n\n for (const child of children) {\n if (child.type === itemType) {\n items.push({ id: child.id, name: child.name, folderPath: path });\n } else if (child.type === farseer.FolderItemType.Folder) {\n const sub = await collectFolderItems(client, child.id, [...path, child.name], itemType);\n items.push(...sub);\n }\n }\n return items;\n}\n\nfunction handleSheetError(error: unknown, tenant: string): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (isAuthError(error)) {\n showLoginPrompt(tenant);\n } else if (errorMessage.includes('404')) {\n logger.error('Sheet not found or tenant not accessible.');\n } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('ECONNREFUSED')) {\n logger.error('Failed to connect to Farseer.');\n } else {\n logger.error('Sheet operation failed.');\n logger.dim(errorMessage);\n }\n process.exit(1);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,SAAoB;AACpB,cAAyB;AACzB,mBAAkB;AAClB,oBAAuB;AACvB,wBAA6C;AAC7C,uBAA0B;AAC1B,4BAA+B;AAC/B,4BAA2B;AAEpB,SAAS,sBAAsB,SAAwB;AAC1D,QAAM,YAAY,QAAQ,QAAQ,QAAQ,EAAE,YAAY,yBAAyB;AAGjF,YACK,QAAQ,qBAAqB,EAC7B,YAAY,iBAAiB,EAC7B,OAAO,UAAU,iBAAiB,EAClC,OAAO,OAAO,OAAO,QAAQ,YAAY;AACtC,UAAM,EAAE,QAAQ,cAAc,OAAO,IAAI,UAAM,4BAAU,OAAO,MAAM;AAEtE,QAAI;AAEA,UAAI;AACJ,UAAI;AACA,cAAM,WAAW,MAAM,aAAa,SAAS,OAAO,CAAC,iCAAW,KAAK,CAAC;AACtE,iBAAS,SAAS,IAAI,CAAC,OAAY;AAAA,UAC/B,IAAI,EAAE;AAAA,UACN,MAAM,EAAE,MAAM,QAAQ,SAAS,EAAE,EAAE;AAAA,QACvC,EAAE;AAAA,MACN,QAAQ;AACJ,iBAAS,CAAC;AAAA,MACd;AAGA,UAAI,O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;AAAA,EAC3B;AACA,UAAQ,KAAK,CAAC;AAClB;",
|
|
6
6
|
"names": ["chalk"]
|
|
7
7
|
}
|
|
@@ -34,8 +34,9 @@ module.exports = __toCommonJS(variables_exports);
|
|
|
34
34
|
var fs = __toESM(require("fs"));
|
|
35
35
|
var import_chalk = __toESM(require("chalk"));
|
|
36
36
|
var import_logger = require("../utils/logger");
|
|
37
|
-
var
|
|
37
|
+
var import_authErrors = require("../services/authErrors");
|
|
38
38
|
var import_preflight = require("../services/preflight");
|
|
39
|
+
var import_modelExport = require("../services/modelExport");
|
|
39
40
|
function registerVariablesCommand(program) {
|
|
40
41
|
const variablesCmd = program.command("variables").description("List and manage variables");
|
|
41
42
|
variablesCmd.command("list [org] [tenant]").description("List all variables").option("--json", "Output raw JSON").action(async (first, second, options) => {
|
|
@@ -96,7 +97,7 @@ function registerVariablesCommand(program) {
|
|
|
96
97
|
}
|
|
97
98
|
console.log(` Dimensions: ${variable.tables.join(", ")}`);
|
|
98
99
|
if (variable.members.length > 0) {
|
|
99
|
-
console.log(` Specific members: ${
|
|
100
|
+
console.log(` Specific members: ${(0, import_modelExport.formatVariableMembers)(variable.members)}`);
|
|
100
101
|
}
|
|
101
102
|
console.log(` Roll-up type: ${variable.rollupType}`);
|
|
102
103
|
console.log(` Data type: ${variable.dataType}`);
|
|
@@ -221,8 +222,8 @@ function registerVariablesCommand(program) {
|
|
|
221
222
|
}
|
|
222
223
|
function handleModelError(error, tenant) {
|
|
223
224
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
224
|
-
if ((0,
|
|
225
|
-
(0,
|
|
225
|
+
if ((0, import_authErrors.isAuthError)(error)) {
|
|
226
|
+
(0, import_authErrors.showLoginPrompt)(tenant);
|
|
226
227
|
} else if (errorMessage.includes("404")) {
|
|
227
228
|
import_logger.logger.error(`Tenant "${tenant}" not found or not accessible.`);
|
|
228
229
|
} else if (errorMessage.includes("ENOTFOUND") || errorMessage.includes("ECONNREFUSED")) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/variables.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/farseerFactory';\nimport { preflight } from '../services/preflight';\n\nexport function registerVariablesCommand(program: Command): void {\n // farseer variables list\n const variablesCmd = program.command('variables').description('List and manage variables');\n\n variablesCmd\n .command('list [org] [tenant]')\n .description('List all variables')\n .option('--json', 'Output raw JSON')\n .action(async (first, second, options) => {\n const { tenant, client } = await preflight(first, second);\n\n try {\n // VAR-only \u2014 pulling the full dimension member matrix\n // breaks the response limit on large tenants.\n const model = await client.exportModel({ types: ['VAR'] });\n\n if (options.json) {\n console.log(JSON.stringify(model.variables, null, 2));\n return;\n }\n\n logger.header(`Variables (${model.variables.length})`);\n console.log();\n for (const variable of model.variables) {\n const flags = [];\n if (variable.readonly) flags.push('readonly');\n if (variable.calculateOnDemand) flags.push('on-demand');\n const flagStr = flags.length > 0 ? chalk.dim(` [${flags.join(', ')}]`) : '';\n\n console.log(` ${chalk.bold(variable.name)}${flagStr}`);\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n console.log(` Rollup: ${variable.rollupType} | Type: ${variable.dataType}`);\n if (variable.formula) {\n console.log(\n ` Formula: ${chalk.dim(variable.formula.substring(0, 80))}${variable.formula.length > 80 ? '...' : ''}`,\n );\n }\n console.log();\n }\n } catch (error) {\n handleModelError(error, tenant);\n }\n });\n\n // farseer variable details / export (singular)\n const variableCmd = program.command('variable').description('Variable details and export');\n\n variableCmd\n .command('details <name>')\n .description('Show variable details (dimensions, formula, rollup, etc.)')\n .option('--json', 'Output raw JSON')\n .action(async (name, options) => {\n const { tenant, client } = await preflight();\n\n try {\n const model = await client.exportModel({ types: ['VAR'] });\n const variable = model.variables.find((v) => v.name.toLowerCase() === name.toLowerCase());\n\n if (!variable) {\n logger.error(`Variable \"${name}\" not found.`);\n logger.dim('Available variables:');\n model.variables.slice(0, 10).forEach((v) => logger.dim(` - ${v.name}`));\n if (model.variables.length > 10) {\n logger.dim(` ... and ${model.variables.length - 10} more`);\n }\n process.exit(1);\n }\n\n if (options.json) {\n console.log(JSON.stringify(variable, null, 2));\n return;\n }\n\n logger.header(`Variable: ${variable.name}`);\n console.log();\n if (variable.description) {\n console.log(` Description: ${variable.description}`);\n }\n if (variable.formula) {\n console.log(` Formula: ${variable.formula}`);\n }\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n if (variable.members.length > 0) {\n console.log(` Specific members: ${variable.members.join(', ')}`);\n }\n console.log(` Roll-up type: ${variable.rollupType}`);\n console.log(` Data type: ${variable.dataType}`);\n if (variable.numberFormat) {\n console.log(\n ` Format: ${variable.numberFormat.type}${variable.numberFormat.formatString ? ` (${variable.numberFormat.formatString})` : ''}`,\n );\n }\n console.log(` Readonly: ${variable.readonly}`);\n console.log(` Calculate on demand: ${variable.calculateOnDemand}`);\n if (variable.folderPath) {\n console.log(` Folder: ${variable.folderPath.join(' / ')}`);\n }\n } catch (error) {\n handleModelError(error, tenant);\n }\n });\n\n // farseer variables create [org] [tenant]\n variablesCmd\n .command('create [org] [tenant]')\n .description('Create a new variable')\n .requiredOption('--name <name>', 'Variable name')\n .option('--dimensions <csv>', 'Comma-separated dimension table names')\n .option('--formula <expr>', 'Formula expression')\n .option('--rollup <type>', 'Rollup type (Sum, Average, Min, Max, Last, First, Count)')\n .option('--data-type <type>', 'Data type (Decimal, Integer, Text)', 'Decimal')\n .option('--description <text>', 'Variable description')\n .option('--readonly', 'Set variable as read-only')\n .action(async (first, second, options) => {\n const { native: nativeClient } = await preflight(first, second);\n\n try {\n await nativeClient.initTagMap();\n\n // Resolve dimension table names to IDs\n const tableGids: number[] = [];\n if (options.dimensions) {\n const tableNames = options.dimensions.split(',').map((s: string) => s.trim());\n for (const tableName of tableNames) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n }\n\n const createEntity: any = {\n type: 'VAR',\n meta: {\n name: options.name,\n description: options.description || null,\n },\n variable: {\n tableGids,\n rollupType: options.rollup || 'Sum',\n dataType: options.dataType || 'Decimal',\n readonly: options.readonly || false,\n },\n };\n\n if (options.formula) {\n createEntity.calculation = { formula: options.formula };\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n logger.success(`Created variable \"${options.name}\".`);\n if ((result as any).created?.length > 0) {\n logger.dim(` ID: ${(result as any).created[0].id}`);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to create variable \"${options.name}\".`);\n logger.dim(errorMessage);\n process.exit(1);\n }\n });\n\n // farseer variables update [org] [tenant]\n variablesCmd\n .command('update [org] [tenant]')\n .description('Update an existing variable')\n .requiredOption('--name <name>', 'Variable name')\n .option('--dimensions <csv>', 'New comma-separated dimension table names (replaces all)')\n .option('--formula <expr>', 'New formula expression')\n .option('--rollup <type>', 'New rollup type')\n .option('--description <text>', 'New description')\n .option('--readonly', 'Set as read-only')\n .option('--no-readonly', 'Set as editable')\n .action(async (first, second, options) => {\n const { native: nativeClient } = await preflight(first, second);\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(options.name);\n\n const updateEntity: any = {\n id: variable.id,\n type: 'VAR',\n };\n\n if (options.description !== undefined) {\n updateEntity.meta = { name: variable.name, description: options.description };\n }\n\n const variableUpdate: any = {};\n if (options.dimensions) {\n const tableNames = options.dimensions.split(',').map((s: string) => s.trim());\n const tableGids: number[] = [];\n for (const tableName of tableNames) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n variableUpdate.tableGids = tableGids;\n }\n if (options.rollup) variableUpdate.rollupType = options.rollup;\n if (options.readonly !== undefined) variableUpdate.readonly = options.readonly;\n if (Object.keys(variableUpdate).length > 0) {\n updateEntity.variable = variableUpdate;\n }\n\n if (options.formula !== undefined) {\n updateEntity.calculation = { formula: options.formula };\n }\n\n await nativeClient.entities.mutate({ updated: [updateEntity] });\n logger.success(`Updated variable \"${options.name}\".`);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to update variable \"${options.name}\".`);\n logger.dim(errorMessage);\n process.exit(1);\n }\n });\n\n variableCmd\n .command('export <name>')\n .description('Export variable data to CSV file')\n .option('--output <file>', 'Output file path')\n .option('--format <format>', 'Output format: csv, json, xlsx', 'csv')\n .option('--limit <n>', 'Limit number of rows', parseInt)\n .action(async (name, options) => {\n const { native: nativeClient, tenant } = await preflight();\n\n try {\n logger.info(`Exporting variable \"${name}\" from ${tenant}...`);\n\n const exportRequest: any = {\n formula: `\"${name}\"`,\n format: options.format || 'csv',\n };\n if (options.limit) {\n exportRequest.limit = options.limit;\n }\n\n const blob = await nativeClient.export.exportFormula(exportRequest);\n const content = await blob.text();\n\n const outputFile =\n options.output || `${name.replace(/[^a-zA-Z0-9_-]/g, '_')}.${options.format || 'csv'}`;\n fs.writeFileSync(outputFile, content, 'utf-8');\n\n logger.success(`Exported to ${outputFile}`);\n const lines = content.split('\\n').filter((l) => l.trim()).length;\n logger.dim(`${lines - 1} data rows`);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to export variable \"${name}\".`);\n logger.dim(errorMessage);\n process.exit(1);\n }\n });\n}\n\nfunction handleModelError(error: unknown, tenant: string): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (isAuthError(error)) {\n showLoginPrompt(tenant);\n } else if (errorMessage.includes('404')) {\n logger.error(`Tenant \"${tenant}\" not found or not accessible.`);\n } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('ECONNREFUSED')) {\n logger.error('Failed to connect to Farseer.');\n } else {\n logger.error('Failed to fetch model.');\n logger.dim(errorMessage);\n }\n process.exit(1);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,SAAoB;AAEpB,mBAAkB;AAClB,oBAAuB;AACvB,
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/authErrors';\nimport { preflight } from '../services/preflight';\nimport { formatVariableMembers } from '../services/modelExport';\n\nexport function registerVariablesCommand(program: Command): void {\n // farseer variables list\n const variablesCmd = program.command('variables').description('List and manage variables');\n\n variablesCmd\n .command('list [org] [tenant]')\n .description('List all variables')\n .option('--json', 'Output raw JSON')\n .action(async (first, second, options) => {\n const { tenant, client } = await preflight(first, second);\n\n try {\n // VAR-only \u2014 pulling the full dimension member matrix\n // breaks the response limit on large tenants.\n const model = await client.exportModel({ types: ['VAR'] });\n\n if (options.json) {\n console.log(JSON.stringify(model.variables, null, 2));\n return;\n }\n\n logger.header(`Variables (${model.variables.length})`);\n console.log();\n for (const variable of model.variables) {\n const flags = [];\n if (variable.readonly) flags.push('readonly');\n if (variable.calculateOnDemand) flags.push('on-demand');\n const flagStr = flags.length > 0 ? chalk.dim(` [${flags.join(', ')}]`) : '';\n\n console.log(` ${chalk.bold(variable.name)}${flagStr}`);\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n console.log(` Rollup: ${variable.rollupType} | Type: ${variable.dataType}`);\n if (variable.formula) {\n console.log(\n ` Formula: ${chalk.dim(variable.formula.substring(0, 80))}${variable.formula.length > 80 ? '...' : ''}`,\n );\n }\n console.log();\n }\n } catch (error) {\n handleModelError(error, tenant);\n }\n });\n\n // farseer variable details / export (singular)\n const variableCmd = program.command('variable').description('Variable details and export');\n\n variableCmd\n .command('details <name>')\n .description('Show variable details (dimensions, formula, rollup, etc.)')\n .option('--json', 'Output raw JSON')\n .action(async (name, options) => {\n const { tenant, client } = await preflight();\n\n try {\n const model = await client.exportModel({ types: ['VAR'] });\n const variable = model.variables.find((v) => v.name.toLowerCase() === name.toLowerCase());\n\n if (!variable) {\n logger.error(`Variable \"${name}\" not found.`);\n logger.dim('Available variables:');\n model.variables.slice(0, 10).forEach((v) => logger.dim(` - ${v.name}`));\n if (model.variables.length > 10) {\n logger.dim(` ... and ${model.variables.length - 10} more`);\n }\n process.exit(1);\n }\n\n if (options.json) {\n console.log(JSON.stringify(variable, null, 2));\n return;\n }\n\n logger.header(`Variable: ${variable.name}`);\n console.log();\n if (variable.description) {\n console.log(` Description: ${variable.description}`);\n }\n if (variable.formula) {\n console.log(` Formula: ${variable.formula}`);\n }\n console.log(` Dimensions: ${variable.tables.join(', ')}`);\n if (variable.members.length > 0) {\n console.log(` Specific members: ${formatVariableMembers(variable.members)}`);\n }\n console.log(` Roll-up type: ${variable.rollupType}`);\n console.log(` Data type: ${variable.dataType}`);\n if (variable.numberFormat) {\n console.log(\n ` Format: ${variable.numberFormat.type}${variable.numberFormat.formatString ? ` (${variable.numberFormat.formatString})` : ''}`,\n );\n }\n console.log(` Readonly: ${variable.readonly}`);\n console.log(` Calculate on demand: ${variable.calculateOnDemand}`);\n if (variable.folderPath) {\n console.log(` Folder: ${variable.folderPath.join(' / ')}`);\n }\n } catch (error) {\n handleModelError(error, tenant);\n }\n });\n\n // farseer variables create [org] [tenant]\n variablesCmd\n .command('create [org] [tenant]')\n .description('Create a new variable')\n .requiredOption('--name <name>', 'Variable name')\n .option('--dimensions <csv>', 'Comma-separated dimension table names')\n .option('--formula <expr>', 'Formula expression')\n .option('--rollup <type>', 'Rollup type (Sum, Average, Min, Max, Last, First, Count)')\n .option('--data-type <type>', 'Data type (Decimal, Integer, Text)', 'Decimal')\n .option('--description <text>', 'Variable description')\n .option('--readonly', 'Set variable as read-only')\n .action(async (first, second, options) => {\n const { native: nativeClient } = await preflight(first, second);\n\n try {\n await nativeClient.initTagMap();\n\n // Resolve dimension table names to IDs\n const tableGids: number[] = [];\n if (options.dimensions) {\n const tableNames = options.dimensions.split(',').map((s: string) => s.trim());\n for (const tableName of tableNames) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n }\n\n const createEntity: any = {\n type: 'VAR',\n meta: {\n name: options.name,\n description: options.description || null,\n },\n variable: {\n tableGids,\n rollupType: options.rollup || 'Sum',\n dataType: options.dataType || 'Decimal',\n readonly: options.readonly || false,\n },\n };\n\n if (options.formula) {\n createEntity.calculation = { formula: options.formula };\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n logger.success(`Created variable \"${options.name}\".`);\n if ((result as any).created?.length > 0) {\n logger.dim(` ID: ${(result as any).created[0].id}`);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to create variable \"${options.name}\".`);\n logger.dim(errorMessage);\n process.exit(1);\n }\n });\n\n // farseer variables update [org] [tenant]\n variablesCmd\n .command('update [org] [tenant]')\n .description('Update an existing variable')\n .requiredOption('--name <name>', 'Variable name')\n .option('--dimensions <csv>', 'New comma-separated dimension table names (replaces all)')\n .option('--formula <expr>', 'New formula expression')\n .option('--rollup <type>', 'New rollup type')\n .option('--description <text>', 'New description')\n .option('--readonly', 'Set as read-only')\n .option('--no-readonly', 'Set as editable')\n .action(async (first, second, options) => {\n const { native: nativeClient } = await preflight(first, second);\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(options.name);\n\n const updateEntity: any = {\n id: variable.id,\n type: 'VAR',\n };\n\n if (options.description !== undefined) {\n updateEntity.meta = { name: variable.name, description: options.description };\n }\n\n const variableUpdate: any = {};\n if (options.dimensions) {\n const tableNames = options.dimensions.split(',').map((s: string) => s.trim());\n const tableGids: number[] = [];\n for (const tableName of tableNames) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n variableUpdate.tableGids = tableGids;\n }\n if (options.rollup) variableUpdate.rollupType = options.rollup;\n if (options.readonly !== undefined) variableUpdate.readonly = options.readonly;\n if (Object.keys(variableUpdate).length > 0) {\n updateEntity.variable = variableUpdate;\n }\n\n if (options.formula !== undefined) {\n updateEntity.calculation = { formula: options.formula };\n }\n\n await nativeClient.entities.mutate({ updated: [updateEntity] });\n logger.success(`Updated variable \"${options.name}\".`);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to update variable \"${options.name}\".`);\n logger.dim(errorMessage);\n process.exit(1);\n }\n });\n\n variableCmd\n .command('export <name>')\n .description('Export variable data to CSV file')\n .option('--output <file>', 'Output file path')\n .option('--format <format>', 'Output format: csv, json, xlsx', 'csv')\n .option('--limit <n>', 'Limit number of rows', parseInt)\n .action(async (name, options) => {\n const { native: nativeClient, tenant } = await preflight();\n\n try {\n logger.info(`Exporting variable \"${name}\" from ${tenant}...`);\n\n const exportRequest: any = {\n formula: `\"${name}\"`,\n format: options.format || 'csv',\n };\n if (options.limit) {\n exportRequest.limit = options.limit;\n }\n\n const blob = await nativeClient.export.exportFormula(exportRequest);\n const content = await blob.text();\n\n const outputFile =\n options.output || `${name.replace(/[^a-zA-Z0-9_-]/g, '_')}.${options.format || 'csv'}`;\n fs.writeFileSync(outputFile, content, 'utf-8');\n\n logger.success(`Exported to ${outputFile}`);\n const lines = content.split('\\n').filter((l) => l.trim()).length;\n logger.dim(`${lines - 1} data rows`);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to export variable \"${name}\".`);\n logger.dim(errorMessage);\n process.exit(1);\n }\n });\n}\n\nfunction handleModelError(error: unknown, tenant: string): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (isAuthError(error)) {\n showLoginPrompt(tenant);\n } else if (errorMessage.includes('404')) {\n logger.error(`Tenant \"${tenant}\" not found or not accessible.`);\n } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('ECONNREFUSED')) {\n logger.error('Failed to connect to Farseer.');\n } else {\n logger.error('Failed to fetch model.');\n logger.dim(errorMessage);\n }\n process.exit(1);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;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