farseer-cli 1.8.2 → 1.8.4

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/commands/pull.ts"],
4
- "sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { fileLogger } from '../utils/fileLogger';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService, ConflictResolutions, SyncStatus } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport {\n getTenantDir,\n getTenantFilesDir,\n ensureDirectoryExists,\n resolveTenantWithOrgMapping,\n appendToAuditLog,\n AuditLogEntry,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { isLikelyTextFile } from '../utils/fileValidation';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport { FARSEER_CLIENT_URL, FARSEER_CLIENT_AXIOS_URL } from '../utils/constants';\nimport { ensureGitignoreEntries } from '../utils/workspace';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * Pull semantics:\n *\n * farseer pull\n * 1. Show local-vs-remote diff. If you have unsynced local edits the\n * command stops here and asks for confirmation before doing\n * anything (we don't merge silently).\n * 2. Apply remote-side changes (downloads, deletions, modifications).\n * Per-file conflicts are resolved interactively.\n *\n * farseer pull --force\n * Hard reset to remote. After it runs, the working tree mirrors what's\n * on remote: any file that exists locally but not on remote is deleted,\n * remote versions overwrite local edits, deletions are accepted. Always\n * asks for confirmation because the operation is destructive.\n */\nexport function registerPullCommand(program: Command): void {\n program\n .command('pull [org] [tenant]')\n .description(\n 'Pull files from Farseer instance to local\\n\\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)',\n )\n .option(\n '--all',\n 'Pull every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in via --include-ext .csv or `farseer config include --ext .csv`.',\n )\n .option(\n '--force',\n 'Hard reset local to remote within the current sync scope: overwrite local edits, delete local-only files. Files outside scope (data files like .csv on a default run without --include-ext .csv) are NOT touched. Always asks for confirmation.',\n )\n .option('-y, --yes', 'Skip confirmation when local has uncommitted changes (ignored under --force)')\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n // Ensure .gitignore covers `.farseer-sync.json` on every direct\n // pull, not only checkout-driven pulls. A workspace that\n // initializes with `farseer pull` (no prior checkout, or\n // `checkout --no-pull` then `pull`) would otherwise commit the\n // per-machine baseline and reproduce the cross-machine drift\n // bug the gitignore exists to prevent.\n ensureGitignoreEntries(path.join(tenantDir, '.gitignore'));\n\n await createDefaultPackageJson(tenantDir, tenant);\n\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const filterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n };\n const syncOptions = {\n all: options.all,\n force: options.force,\n ...filterOptions,\n };\n\n // Step 1: Inspect current state. We do this BEFORE mutating\n // anything so the user can decide whether to bail.\n const filesDir = getTenantFilesDir(tenant);\n const folderInitialised = fs.existsSync(filesDir);\n let preStatus: SyncStatus | null = null;\n let preStatusError: Error | null = null;\n if (folderInitialised) {\n try {\n preStatus = await syncService.getStatus({ ...filterOptions, all: options.all, deep: false });\n } catch (error) {\n preStatusError = error as Error;\n logger.dim(`Could not compute pre-pull status: ${preStatusError.message}`);\n }\n }\n\n const localChanges = preStatus\n ? preStatus.addedLocally.length +\n preStatus.modifiedLocally.length +\n preStatus.deletedLocally.length +\n preStatus.conflicts.length\n : 0;\n\n // Step 2: Decide whether to confirm. The matrix:\n // --force \u2192 always confirm (destructive reset).\n // uncommitted changes + not -y \u2192 confirm (avoid silent merge).\n // clean tree \u2192 just go.\n if (options.force) {\n console.log();\n console.log(chalk.red.bold('--force will hard-reset local to match remote.'));\n if (preStatus) {\n summarisePreStatus(preStatus);\n } else if (preStatusError) {\n // Without a local diff we'd be confirming a destructive\n // mirror operation blind. Refuse rather than press on \u2014\n // the cost of failing here is one re-run; the cost of\n // pressing on is silent loss of in-progress files.\n console.log(\n chalk.red(\n 'Cannot show what will be lost \u2014 pre-pull status failed (see line above). Refusing to --force without visibility.',\n ),\n );\n logger.dim('Re-run after the underlying issue clears, or use a non-force pull to merge.');\n process.exit(1);\n } else {\n // Folder isn't initialised yet \u2014 first --force pull on a\n // brand-new tenant. Nothing local to lose; proceed.\n logger.dim('No local files yet \u2014 nothing to discard.');\n }\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Discard local changes and reset ${tenant} to remote?`,\n default: false,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n } else if (localChanges > 0 && !options.yes) {\n console.log();\n logger.warning(`Local has ${localChanges} unsynced change(s).`);\n summarisePreStatus(preStatus!);\n logger.dim('Pull will keep your edits and merge remote-side changes around them.');\n logger.dim('To wipe local and reset to remote: re-run with --force.');\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Continue pulling into a dirty working tree?`,\n default: true,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Files \u2550\u2550\u2550'));\n logger.info(`Pulling files from ${tenant}...`);\n\n try {\n let result = await syncService.pull(syncOptions);\n\n // Conflicts: prompt per file (only when not --force).\n if (result.conflicts.length > 0 && !options.force) {\n console.log();\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n\n const resolutions: ConflictResolutions = {};\n for (const conflict of result.conflicts) {\n let choices: { name: string; value: string }[];\n if (conflict.type === 'local_modified_remote_deleted') {\n choices = [\n { name: 'Keep local (keep your modified file)', value: 'keep_local' },\n { name: 'Accept deletion (delete local file)', value: 'keep_remote' },\n ];\n } else if (conflict.type === 'local_deleted_remote_modified') {\n choices = [\n { name: \"Keep deleted (don't restore file)\", value: 'keep_local' },\n { name: 'Restore remote version', value: 'keep_remote' },\n ];\n } else {\n choices = [\n { name: 'Keep local version', value: 'keep_local' },\n { name: 'Use remote version (overwrite local)', value: 'keep_remote' },\n { name: 'Keep both (save remote as .remote file)', value: 'keep_both' },\n ];\n // Only offer git-style merge for files we know\n // are text. Binary blobs would just get\n // corrupted by UTF-8 splicing. The service has\n // a defensive fallback for binary anyway, but\n // not showing the option avoids the confusing\n // \"I picked merge_markers but got keep_both\"\n // experience.\n if (isLikelyTextFile(conflict.filePath)) {\n choices.push({\n name: 'Merge with markers (git-style \u2014 edit file, then push to finish)',\n value: 'merge_markers',\n });\n }\n }\n const answer = await inquirer.prompt([\n {\n type: 'list',\n name: 'resolution',\n message: `${conflict.filePath} - ${conflict.description}`,\n choices,\n },\n ]);\n resolutions[conflict.filePath] = answer.resolution;\n }\n result = await syncService.pull({ ...syncOptions, conflictResolutions: resolutions });\n }\n\n if (result.downloaded.length > 0) {\n console.log(chalk.green('Downloaded:'));\n for (const file of result.downloaded) console.log(chalk.green(` + ${file}`));\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted (removed from remote):'));\n for (const file of result.deleted) console.log(chalk.red(` - ${file}`));\n }\n\n if (result.conflictFilesWritten.length > 0) {\n console.log(chalk.yellow('Conflict files created:'));\n for (const file of result.conflictFilesWritten) console.log(chalk.yellow(` ~ ${file}`));\n if (result.conflictFilesWritten.some((f) => f.includes('(merge markers)'))) {\n console.log();\n logger.dim('Files marked with \"(merge markers)\" contain git-style <<<<<<</=======/>>>>>>>');\n logger.dim('blocks. Open them, pick which version to keep, remove the marker lines,');\n logger.dim(`then run \\`farseer push ${tenant}\\` to upload the resolved version.`);\n }\n }\n\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // --force extra: also delete any local-only files. The\n // service-level pull keeps `local_new` files unchanged\n // (it's the right default for a non-destructive pull),\n // but --force at the command layer means \"mirror remote\",\n // so remove those locally.\n let extraLocalDeletes: string[] = [];\n if (options.force) {\n // Forward `--all` so `pull --force --all` wipes every\n // local-only file in scope, not just those that match\n // the default sync scope.\n extraLocalDeletes = await wipeLocalOnly(syncService, filesDir, {\n ...filterOptions,\n all: options.all,\n });\n if (extraLocalDeletes.length > 0) {\n console.log(chalk.red('Local-only files removed (mirror remote):'));\n for (const file of extraLocalDeletes) console.log(chalk.red(` - ${file}`));\n }\n }\n\n // Audit log\n if (result.downloaded.length > 0) {\n const syncState = syncService.loadSyncState();\n const auditEntries: AuditLogEntry[] = result.downloaded.map((filePath) => ({\n operation: 'pulled' as const,\n filePath,\n uploadTime: syncState.files[filePath]?.metadata?.uploadTime,\n uploaderEmail: syncState.files[filePath]?.metadata?.uploaderEmail,\n uploaderName: syncState.files[filePath]?.metadata?.uploaderName,\n }));\n appendToAuditLog(tenant, auditEntries);\n }\n\n let hasChanges =\n result.downloaded.length > 0 || result.deleted.length > 0 || extraLocalDeletes.length > 0;\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Apps \u2550\u2550\u2550'));\n logger.info(`Pulling apps from ${tenant}...`);\n\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n const appResult = await appSyncService.pull();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appResult.created) console.log(chalk.green(` + ${app}`));\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 }\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps (removed from remote):'));\n for (const app of appResult.deleted) console.log(chalk.red(` - ${app}`));\n }\n\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n hasChanges =\n hasChanges ||\n appResult.created.length > 0 ||\n appResult.updated.length > 0 ||\n appResult.deleted.length > 0;\n\n if (!hasChanges) {\n logger.success('Already up to date.');\n return;\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Summary \u2550\u2550\u2550'));\n logger.success('Pull complete!');\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} ${\n extraLocalDeletes.length > 0 ? `(${extraLocalDeletes.length} local-only removed) ` : ''\n }(${result.unchanged.length} unchanged)`,\n );\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n } catch (error) {\n fileLogger.error('pull', error);\n logger.error('Pull 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 * Print actual paths (not just counts) so the user can see what local\n * changes a `pull --force` is about to overwrite. Counts alone hid the\n * destructive blast radius: under `--force --all` someone could lose\n * dozens of in-progress files without knowing which ones. Cap at\n * MAX_PATHS_PER_SECTION per section to avoid scrollback floods on huge\n * trees \u2014 anything beyond that collapses into \"+ N more\".\n */\nfunction summarisePreStatus(status: SyncStatus): void {\n const MAX_PATHS_PER_SECTION = 20;\n const renderSection = (label: string, paths: string[], color: (s: string) => string) => {\n if (paths.length === 0) return;\n console.log(color(` ${label} (${paths.length}):`));\n const visible = paths.slice(0, MAX_PATHS_PER_SECTION);\n for (const p of visible) console.log(color(` ${p}`));\n if (paths.length > MAX_PATHS_PER_SECTION) {\n console.log(chalk.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));\n }\n };\n renderSection('+ new local file(s)', status.addedLocally, chalk.green);\n renderSection('M locally modified file(s)', status.modifiedLocally, chalk.yellow);\n renderSection('- locally deleted file(s)', status.deletedLocally, chalk.red);\n if (status.conflicts.length > 0) {\n const conflictPaths = status.conflicts.map((c) => c.filePath);\n renderSection('! conflict(s)', conflictPaths, chalk.red.bold);\n }\n console.log();\n}\n\n/**\n * Hard-reset helper for `pull --force`. Removes local files that have no\n * remote counterpart (the regular pull keeps them \u2014 see service comment).\n * Cleans up the syncState entry too so the next status doesn't show ghosts.\n */\nasync function wipeLocalOnly(\n syncService: SyncService,\n filesDir: string,\n filterOptions: { all?: boolean; includeExtensions?: string[]; includeFolders?: string[] },\n): Promise<string[]> {\n // `all` matters: under `pull --force --all` the user expects every\n // local-only file to be wiped, not just files in the default sync\n // scope. Without it, getStatus filters down to the curated developer\n // files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden\n // directories and the folder blocklist, so the wipe loop never sees\n // anything those rules exclude.\n const status = await syncService.getStatus({ ...filterOptions, deep: false });\n const removed: string[] = [];\n const failed: { file: string; reason: string }[] = [];\n const syncState = syncService.loadSyncState();\n for (const file of status.addedLocally) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n if (fs.existsSync(fullPath)) {\n // Wrap each unlink so a single permission error / file lock\n // doesn't strand the rest of the wipe. syncState is saved\n // incrementally as each unlink succeeds so a mid-run failure\n // leaves a consistent record for the next run, and the failed\n // list is surfaced at the end for manual cleanup.\n try {\n fs.unlinkSync(fullPath);\n removed.push(file);\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n } catch (err) {\n failed.push({ file, reason: err instanceof Error ? err.message : String(err) });\n }\n } else {\n // File was already gone \u2014 just drop the syncState entry.\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n }\n }\n if (failed.length > 0) {\n logger.warning(`${failed.length} local-only file(s) could not be removed:`);\n for (const f of failed) logger.dim(` ${f.file} \u2014 ${f.reason}`);\n }\n return removed;\n}\n\nasync function createDefaultPackageJson(tenantDir: string, tenant: string): Promise<void> {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n\n if (fs.existsSync(packageJsonPath)) {\n return;\n }\n\n const packageJson = {\n name: `farseer-scripts-${tenant}`,\n version: '1.0.0',\n description: `Farseer App scripts for ${tenant}`,\n main: 'src/index.ts',\n scripts: {},\n keywords: ['farseer', 'scripts', tenant],\n author: 'Farseer',\n license: 'ISC',\n dependencies: {\n '@google-cloud/bigquery': '^7.9.0',\n '@google-cloud/storage': '^7.12.1',\n '@googleapis/sheets': '^5.0.5',\n '@sendgrid/mail': '^7.7.0',\n '@types/node-forge': '^1.3.11',\n '@xmldom/xmldom': '^0.9.8',\n arquero: '^5.4.1',\n axios: '^1.10.0',\n 'axios-retry': '^3.9.1',\n 'basic-ftp': '^5.0.5',\n 'client-oauth2': '^4.3.3',\n 'csv-parser': '^3.0.0',\n dotenv: '^16.4.5',\n 'draft-js': '^0.11.7',\n exceljs: '^4.4.0',\n 'farseer-client': FARSEER_CLIENT_URL,\n 'farseer-client-axios': FARSEER_CLIENT_AXIOS_URL,\n 'fast-xml-parser': '^4.5.0',\n 'form-data': '^4.0.0',\n googleapis: '^144.0.0',\n heapdump: '^0.3.15',\n 'image-size': '^1.1.1',\n jszip: '^3.10.1',\n 'lossless-json': '^4.0.1',\n mssql: '^10.0.4',\n 'node-fetch': '^2.7.0',\n 'node-forge': '^1.3.1',\n 'node-sp-auth': '^3.0.8',\n numeral: '^2.0.6',\n oracledb: '^6.6.0',\n papaparse: '^5.5.1',\n pdfkit: '^0.14.0',\n pdfmake: '^0.2.20',\n soap: '^1.1.11',\n 'ssh2-sftp-client': '^11.0.0',\n 'strong-soap': '^4.1.13',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n undici: '^6.19.8',\n uuid: '^11.1.0',\n winston: '^3.17.0',\n xlsx: 'https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz',\n 'xml-crypto': '^6.1.2',\n },\n devDependencies: {\n '@types/draft-js': '^0.11.18',\n '@types/heapdump': '^0.3.4',\n '@types/mssql': '^9.1.5',\n '@types/node': '^18.19.50',\n '@types/node-fetch': '^2.6.11',\n '@types/numeral': '^2.0.5',\n '@types/oracledb': '^6.5.3',\n '@types/papaparse': '^5.3.15',\n '@types/pdfmake': '^0.2.11',\n '@types/soap': '^0.18.0',\n '@types/ssh2-sftp-client': '^9.0.4',\n '@types/tough-cookie': '^4.0.5',\n '@types/uuid': '^10.0.0',\n '@types/xmldom': '^0.1.34',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n },\n };\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');\n logger.dim(`Created package.json for ${tenant}`);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,wBAA2B;AAC3B,4BAA8D;AAC9D,yBAA6D;AAC7D,4BAA+B;AAC/B,qBAQO;AACP,4BAAkC;AAClC,4BAAiC;AACjC,wBAAmD;AACnD,uBAA6D;AAC7D,uBAAuC;AACvC,SAAoB;AACpB,WAAsB;AAkBf,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,aAAa,8EAA8E,EAClG,OAAO,uBAAuB,6CAA6C,iCAAe,CAAC,CAAC,E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MACpB,eAAe;AAAA,MACf,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,SAAS;AAAA,MACT,MAAM;AAAA,MACN,cAAc;AAAA,IAClB;AAAA,IACA,iBAAiB;AAAA,MACb,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,qBAAqB;AAAA,MACrB,kBAAkB;AAAA,MAClB,mBAAmB;AAAA,MACnB,oBAAoB;AAAA,MACpB,kBAAkB;AAAA,MAClB,eAAe;AAAA,MACf,2BAA2B;AAAA,MAC3B,uBAAuB;AAAA,MACvB,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,WAAW;AAAA,MACX,YAAY;AAAA,IAChB;AAAA,EACJ;AAEA,KAAG,cAAc,iBAAiB,KAAK,UAAU,aAAa,MAAM,CAAC,GAAG,OAAO;AAC/E,uBAAO,IAAI,4BAA4B,MAAM,EAAE;AACnD;",
4
+ "sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { logger } from '../utils/logger';\nimport { fileLogger } from '../utils/fileLogger';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService, ConflictResolutions, SyncStatus } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport {\n getTenantDir,\n getTenantFilesDir,\n ensureDirectoryExists,\n resolveTenantWithOrgMapping,\n appendToAuditLog,\n AuditLogEntry,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { isLikelyTextFile } from '../utils/fileValidation';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport { FARSEER_CLIENT_URL, FARSEER_CLIENT_AXIOS_URL } from '../utils/constants';\nimport { ensureGitignoreEntries } from '../utils/workspace';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n/**\n * Pull semantics:\n *\n * farseer pull\n * 1. Show local-vs-remote diff. If you have unsynced local edits OR\n * remote has deletions that would remove local files/apps, the\n * command stops here and asks for confirmation before doing\n * anything (we don't merge or delete silently).\n * 2. Apply remote-side changes (downloads, deletions, modifications).\n * Per-file conflicts are resolved interactively.\n *\n * farseer pull --force\n * Hard reset to remote. After it runs, the working tree mirrors what's\n * on remote: any file that exists locally but not on remote is deleted,\n * remote versions overwrite local edits, deletions are accepted. Always\n * asks for confirmation because the operation is destructive.\n */\nexport function registerPullCommand(program: Command): void {\n program\n .command('pull [org] [tenant]')\n .description(\n 'Pull files from Farseer instance to local\\n\\nUsage: pull <org> <tenant> OR pull <tenant> (if org is known)',\n )\n .option(\n '--all',\n 'Pull every non-hidden, non-blocklisted file (default: developer files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden directories and the folder blocklist). Data files (.csv, .xlsx, .parquet, \u2026) are backend-accepted but excluded from default \u2014 opt in via --include-ext .csv or `farseer config include --ext .csv`.',\n )\n .option(\n '--force',\n 'Hard reset local to remote within the current sync scope: overwrite local edits, delete local-only files. Files outside scope (data files like .csv on a default run without --include-ext .csv) are NOT touched. Always asks for confirmation.',\n )\n .option(\n '-y, --yes',\n 'Skip confirmation when local has uncommitted changes OR remote has deletions that would remove local files/apps (ignored under --force)',\n )\n .option('--include-ext <ext>', 'Include extra file extension (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder (repeatable)', collectValues, [])\n .action(async (arg1, arg2, options) => {\n const { organisation, tenant } = resolveTenantWithOrgMapping(arg1, arg2);\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const syncService = new SyncService(tenant, clientResult.client);\n\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n // Ensure .gitignore covers `.farseer-sync.json` on every direct\n // pull, not only checkout-driven pulls. A workspace that\n // initializes with `farseer pull` (no prior checkout, or\n // `checkout --no-pull` then `pull`) would otherwise commit the\n // per-machine baseline and reproduce the cross-machine drift\n // bug the gitignore exists to prevent.\n ensureGitignoreEntries(path.join(tenantDir, '.gitignore'));\n\n await createDefaultPackageJson(tenantDir, tenant);\n\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const filterOptions = {\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n };\n const syncOptions = {\n all: options.all,\n force: options.force,\n ...filterOptions,\n };\n\n // Step 1: Inspect current state. We do this BEFORE mutating\n // anything so the user can decide whether to bail.\n const filesDir = getTenantFilesDir(tenant);\n const folderInitialised = fs.existsSync(filesDir);\n let preStatus: SyncStatus | null = null;\n let preStatusError: Error | null = null;\n if (folderInitialised) {\n try {\n preStatus = await syncService.getStatus({ ...filterOptions, all: options.all, deep: false });\n } catch (error) {\n preStatusError = error as Error;\n logger.dim(`Could not compute pre-pull status: ${preStatusError.message}`);\n }\n }\n\n // Preview app deletions too. Without this the destructive\n // prompt only covers files and the user discovers (post-pull)\n // that an app JSON was wiped because someone deleted the app\n // on remote. Uses listApps only \u2014 no per-app fetch \u2014 so this\n // doesn't double the network cost of the apps pull below.\n //\n // Best-effort: a failure here shouldn't block the pull. Worst\n // case the user gets the legacy behaviour (silent app\n // deletion) on this run.\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n let appDeletions: string[] = [];\n try {\n appDeletions = await appSyncService.getRemoteDeletions();\n } catch (error) {\n logger.dim(`Could not compute pre-pull app deletions: ${(error as Error).message}`);\n }\n\n const localChanges = preStatus\n ? preStatus.addedLocally.length +\n preStatus.modifiedLocally.length +\n preStatus.deletedLocally.length +\n preStatus.conflicts.length\n : 0;\n const remoteDeletions = (preStatus?.deletedRemotely.length ?? 0) + appDeletions.length;\n\n // Step 2: Decide whether to confirm. The matrix:\n // --force \u2192 always confirm (destructive reset).\n // local edits OR remote deletions \u2192 confirm unless -y.\n // clean tree, no deletes \u2192 just go.\n //\n // Remote deletions are gated because pull would silently\n // remove a previously-synced local file/app if someone deleted\n // it on remote \u2014 a real script could vanish without warning.\n // Local edits stay gated for the existing reason: we don't\n // want to merge into a dirty tree without an opt-in.\n if (options.force) {\n console.log();\n console.log(chalk.red.bold('--force will hard-reset local to match remote.'));\n if (preStatus) {\n summarisePreStatus(preStatus);\n } else if (preStatusError) {\n // Without a local diff we'd be confirming a destructive\n // mirror operation blind. Refuse rather than press on \u2014\n // the cost of failing here is one re-run; the cost of\n // pressing on is silent loss of in-progress files.\n console.log(\n chalk.red(\n 'Cannot show what will be lost \u2014 pre-pull status failed (see line above). Refusing to --force without visibility.',\n ),\n );\n logger.dim('Re-run after the underlying issue clears, or use a non-force pull to merge.');\n process.exit(1);\n } else {\n // Folder isn't initialised yet \u2014 first --force pull on a\n // brand-new tenant. Nothing local to lose; proceed.\n logger.dim('No local files yet \u2014 nothing to discard.');\n }\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Discard local changes and reset ${tenant} to remote?`,\n default: false,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n } else if ((localChanges > 0 || remoteDeletions > 0) && !options.yes) {\n console.log();\n if (localChanges > 0) {\n logger.warning(`Local has ${localChanges} unsynced change(s).`);\n summarisePreStatus(preStatus!);\n logger.dim('Pull will keep your edits and merge remote-side changes around them.');\n }\n if (remoteDeletions > 0) {\n logger.warning(`Pull will remove ${remoteDeletions} local item(s) that were deleted on remote:`);\n summariseRemoteDeletions(preStatus?.deletedRemotely ?? [], appDeletions);\n logger.dim('Decline to abort and keep your local copies (you can push them back to restore).');\n }\n if (localChanges > 0 && remoteDeletions === 0) {\n logger.dim('To wipe local and reset to remote: re-run with --force.');\n }\n const promptMessage =\n remoteDeletions > 0 && localChanges > 0\n ? `Continue pull (merge into dirty tree AND delete ${remoteDeletions} local item(s))?`\n : remoteDeletions > 0\n ? `Continue pull and delete ${remoteDeletions} local item(s)?`\n : `Continue pulling into a dirty working tree?`;\n // Dirty-tree-only keeps the soft default (Enter = continue\n // merge). The moment remote deletions are on the table we\n // flip to default-false: a wrong \"yes\" wipes local items\n // for good, same calculus as `pull --force` below.\n const confirm = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: promptMessage,\n default: remoteDeletions === 0,\n },\n ]);\n if (!confirm.proceed) {\n logger.info('Pull cancelled.');\n return;\n }\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Files \u2550\u2550\u2550'));\n logger.info(`Pulling files from ${tenant}...`);\n\n try {\n let result = await syncService.pull(syncOptions);\n\n // Conflicts: prompt per file (only when not --force).\n if (result.conflicts.length > 0 && !options.force) {\n console.log();\n console.log(chalk.red.bold(`${result.conflicts.length} conflict(s) detected:`));\n console.log();\n for (const conflict of result.conflicts) {\n console.log(chalk.red(` ! ${conflict.filePath}`));\n console.log(chalk.dim(` ${conflict.description}`));\n }\n console.log();\n\n const resolutions: ConflictResolutions = {};\n for (const conflict of result.conflicts) {\n let choices: { name: string; value: string }[];\n if (conflict.type === 'local_modified_remote_deleted') {\n choices = [\n { name: 'Keep local (keep your modified file)', value: 'keep_local' },\n { name: 'Accept deletion (delete local file)', value: 'keep_remote' },\n ];\n } else if (conflict.type === 'local_deleted_remote_modified') {\n choices = [\n { name: \"Keep deleted (don't restore file)\", value: 'keep_local' },\n { name: 'Restore remote version', value: 'keep_remote' },\n ];\n } else {\n choices = [\n { name: 'Keep local version', value: 'keep_local' },\n { name: 'Use remote version (overwrite local)', value: 'keep_remote' },\n { name: 'Keep both (save remote as .remote file)', value: 'keep_both' },\n ];\n // Only offer git-style merge for files we know\n // are text. Binary blobs would just get\n // corrupted by UTF-8 splicing. The service has\n // a defensive fallback for binary anyway, but\n // not showing the option avoids the confusing\n // \"I picked merge_markers but got keep_both\"\n // experience.\n if (isLikelyTextFile(conflict.filePath)) {\n choices.push({\n name: 'Merge with markers (git-style \u2014 edit file, then push to finish)',\n value: 'merge_markers',\n });\n }\n }\n const answer = await inquirer.prompt([\n {\n type: 'list',\n name: 'resolution',\n message: `${conflict.filePath} - ${conflict.description}`,\n choices,\n },\n ]);\n resolutions[conflict.filePath] = answer.resolution;\n }\n result = await syncService.pull({ ...syncOptions, conflictResolutions: resolutions });\n }\n\n if (result.downloaded.length > 0) {\n console.log(chalk.green('Downloaded:'));\n for (const file of result.downloaded) console.log(chalk.green(` + ${file}`));\n }\n\n if (result.deleted.length > 0) {\n console.log(chalk.red('Deleted (removed from remote):'));\n for (const file of result.deleted) console.log(chalk.red(` - ${file}`));\n }\n\n if (result.conflictFilesWritten.length > 0) {\n console.log(chalk.yellow('Conflict files created:'));\n for (const file of result.conflictFilesWritten) console.log(chalk.yellow(` ~ ${file}`));\n if (result.conflictFilesWritten.some((f) => f.includes('(merge markers)'))) {\n console.log();\n logger.dim('Files marked with \"(merge markers)\" contain git-style <<<<<<</=======/>>>>>>>');\n logger.dim('blocks. Open them, pick which version to keep, remove the marker lines,');\n logger.dim(`then run \\`farseer push ${tenant}\\` to upload the resolved version.`);\n }\n }\n\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // --force extra: also delete any local-only files. The\n // service-level pull keeps `local_new` files unchanged\n // (it's the right default for a non-destructive pull),\n // but --force at the command layer means \"mirror remote\",\n // so remove those locally.\n let extraLocalDeletes: string[] = [];\n if (options.force) {\n // Forward `--all` so `pull --force --all` wipes every\n // local-only file in scope, not just those that match\n // the default sync scope.\n extraLocalDeletes = await wipeLocalOnly(syncService, filesDir, {\n ...filterOptions,\n all: options.all,\n });\n if (extraLocalDeletes.length > 0) {\n console.log(chalk.red('Local-only files removed (mirror remote):'));\n for (const file of extraLocalDeletes) console.log(chalk.red(` - ${file}`));\n }\n }\n\n // Audit log\n if (result.downloaded.length > 0) {\n const syncState = syncService.loadSyncState();\n const auditEntries: AuditLogEntry[] = result.downloaded.map((filePath) => ({\n operation: 'pulled' as const,\n filePath,\n uploadTime: syncState.files[filePath]?.metadata?.uploadTime,\n uploaderEmail: syncState.files[filePath]?.metadata?.uploaderEmail,\n uploaderName: syncState.files[filePath]?.metadata?.uploaderName,\n }));\n appendToAuditLog(tenant, auditEntries);\n }\n\n let hasChanges =\n result.downloaded.length > 0 || result.deleted.length > 0 || extraLocalDeletes.length > 0;\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Apps \u2550\u2550\u2550'));\n logger.info(`Pulling apps from ${tenant}...`);\n\n const appResult = await appSyncService.pull();\n\n if (appResult.created.length > 0) {\n console.log(chalk.green('New apps:'));\n for (const app of appResult.created) console.log(chalk.green(` + ${app}`));\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 }\n if (appResult.deleted.length > 0) {\n console.log(chalk.red('Deleted apps (removed from remote):'));\n for (const app of appResult.deleted) console.log(chalk.red(` - ${app}`));\n }\n\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n hasChanges =\n hasChanges ||\n appResult.created.length > 0 ||\n appResult.updated.length > 0 ||\n appResult.deleted.length > 0;\n\n if (!hasChanges) {\n logger.success('Already up to date.');\n return;\n }\n\n console.log();\n console.log(chalk.bold('\u2550\u2550\u2550 Summary \u2550\u2550\u2550'));\n logger.success('Pull complete!');\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} ${\n extraLocalDeletes.length > 0 ? `(${extraLocalDeletes.length} local-only removed) ` : ''\n }(${result.unchanged.length} unchanged)`,\n );\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n } catch (error) {\n fileLogger.error('pull', error);\n logger.error('Pull 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 * Print actual paths (not just counts) so the user can see what local\n * changes a `pull --force` is about to overwrite. Counts alone hid the\n * destructive blast radius: under `--force --all` someone could lose\n * dozens of in-progress files without knowing which ones. Cap at\n * MAX_PATHS_PER_SECTION per section to avoid scrollback floods on huge\n * trees \u2014 anything beyond that collapses into \"+ N more\".\n */\nfunction summarisePreStatus(status: SyncStatus): void {\n const MAX_PATHS_PER_SECTION = 20;\n const renderSection = (label: string, paths: string[], color: (s: string) => string) => {\n if (paths.length === 0) return;\n console.log(color(` ${label} (${paths.length}):`));\n const visible = paths.slice(0, MAX_PATHS_PER_SECTION);\n for (const p of visible) console.log(color(` ${p}`));\n if (paths.length > MAX_PATHS_PER_SECTION) {\n console.log(chalk.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));\n }\n };\n renderSection('+ new local file(s)', status.addedLocally, chalk.green);\n renderSection('M locally modified file(s)', status.modifiedLocally, chalk.yellow);\n renderSection('- locally deleted file(s)', status.deletedLocally, chalk.red);\n if (status.conflicts.length > 0) {\n const conflictPaths = status.conflicts.map((c) => c.filePath);\n renderSection('! conflict(s)', conflictPaths, chalk.red.bold);\n }\n console.log();\n}\n\n/**\n * Print the file + app paths that pull is about to delete because remote\n * removed them. Same cap as `summarisePreStatus` so a huge purge doesn't\n * flood the scrollback \u2014 the user still gets the count above.\n */\nfunction summariseRemoteDeletions(deletedFiles: string[], deletedApps: string[]): void {\n const MAX_PATHS_PER_SECTION = 20;\n const renderSection = (label: string, paths: string[]) => {\n if (paths.length === 0) return;\n console.log(chalk.red(` ${label} (${paths.length}):`));\n const visible = paths.slice(0, MAX_PATHS_PER_SECTION);\n for (const p of visible) console.log(chalk.red(` - ${p}`));\n if (paths.length > MAX_PATHS_PER_SECTION) {\n console.log(chalk.dim(` ... and ${paths.length - MAX_PATHS_PER_SECTION} more`));\n }\n };\n renderSection('file(s) deleted on remote', deletedFiles);\n renderSection('app(s) deleted on remote', deletedApps);\n console.log();\n}\n\n/**\n * Hard-reset helper for `pull --force`. Removes local files that have no\n * remote counterpart (the regular pull keeps them \u2014 see service comment).\n * Cleans up the syncState entry too so the next status doesn't show ghosts.\n */\nasync function wipeLocalOnly(\n syncService: SyncService,\n filesDir: string,\n filterOptions: { all?: boolean; includeExtensions?: string[]; includeFolders?: string[] },\n): Promise<string[]> {\n // `all` matters: under `pull --force --all` the user expects every\n // local-only file to be wiped, not just files in the default sync\n // scope. Without it, getStatus filters down to the curated developer\n // files (.ts, .js, .py, .yml, .yaml, .md, .json) outside hidden\n // directories and the folder blocklist, so the wipe loop never sees\n // anything those rules exclude.\n const status = await syncService.getStatus({ ...filterOptions, deep: false });\n const removed: string[] = [];\n const failed: { file: string; reason: string }[] = [];\n const syncState = syncService.loadSyncState();\n for (const file of status.addedLocally) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n if (fs.existsSync(fullPath)) {\n // Wrap each unlink so a single permission error / file lock\n // doesn't strand the rest of the wipe. syncState is saved\n // incrementally as each unlink succeeds so a mid-run failure\n // leaves a consistent record for the next run, and the failed\n // list is surfaced at the end for manual cleanup.\n try {\n fs.unlinkSync(fullPath);\n removed.push(file);\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n } catch (err) {\n failed.push({ file, reason: err instanceof Error ? err.message : String(err) });\n }\n } else {\n // File was already gone \u2014 just drop the syncState entry.\n delete syncState.files[file];\n syncService.saveSyncState(syncState);\n }\n }\n if (failed.length > 0) {\n logger.warning(`${failed.length} local-only file(s) could not be removed:`);\n for (const f of failed) logger.dim(` ${f.file} \u2014 ${f.reason}`);\n }\n return removed;\n}\n\nasync function createDefaultPackageJson(tenantDir: string, tenant: string): Promise<void> {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n\n if (fs.existsSync(packageJsonPath)) {\n return;\n }\n\n const packageJson = {\n name: `farseer-scripts-${tenant}`,\n version: '1.0.0',\n description: `Farseer App scripts for ${tenant}`,\n main: 'src/index.ts',\n scripts: {},\n keywords: ['farseer', 'scripts', tenant],\n author: 'Farseer',\n license: 'ISC',\n dependencies: {\n '@google-cloud/bigquery': '^7.9.0',\n '@google-cloud/storage': '^7.12.1',\n '@googleapis/sheets': '^5.0.5',\n '@sendgrid/mail': '^7.7.0',\n '@types/node-forge': '^1.3.11',\n '@xmldom/xmldom': '^0.9.8',\n arquero: '^5.4.1',\n axios: '^1.10.0',\n 'axios-retry': '^3.9.1',\n 'basic-ftp': '^5.0.5',\n 'client-oauth2': '^4.3.3',\n 'csv-parser': '^3.0.0',\n dotenv: '^16.4.5',\n 'draft-js': '^0.11.7',\n exceljs: '^4.4.0',\n 'farseer-client': FARSEER_CLIENT_URL,\n 'farseer-client-axios': FARSEER_CLIENT_AXIOS_URL,\n 'fast-xml-parser': '^4.5.0',\n 'form-data': '^4.0.0',\n googleapis: '^144.0.0',\n heapdump: '^0.3.15',\n 'image-size': '^1.1.1',\n jszip: '^3.10.1',\n 'lossless-json': '^4.0.1',\n mssql: '^10.0.4',\n 'node-fetch': '^2.7.0',\n 'node-forge': '^1.3.1',\n 'node-sp-auth': '^3.0.8',\n numeral: '^2.0.6',\n oracledb: '^6.6.0',\n papaparse: '^5.5.1',\n pdfkit: '^0.14.0',\n pdfmake: '^0.2.20',\n soap: '^1.1.11',\n 'ssh2-sftp-client': '^11.0.0',\n 'strong-soap': '^4.1.13',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n undici: '^6.19.8',\n uuid: '^11.1.0',\n winston: '^3.17.0',\n xlsx: 'https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz',\n 'xml-crypto': '^6.1.2',\n },\n devDependencies: {\n '@types/draft-js': '^0.11.18',\n '@types/heapdump': '^0.3.4',\n '@types/mssql': '^9.1.5',\n '@types/node': '^18.19.50',\n '@types/node-fetch': '^2.6.11',\n '@types/numeral': '^2.0.5',\n '@types/oracledb': '^6.5.3',\n '@types/papaparse': '^5.3.15',\n '@types/pdfmake': '^0.2.11',\n '@types/soap': '^0.18.0',\n '@types/ssh2-sftp-client': '^9.0.4',\n '@types/tough-cookie': '^4.0.5',\n '@types/uuid': '^10.0.0',\n '@types/xmldom': '^0.1.34',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n },\n };\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');\n logger.dim(`Created package.json for ${tenant}`);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,wBAA2B;AAC3B,4BAA8D;AAC9D,yBAA6D;AAC7D,4BAA+B;AAC/B,qBAQO;AACP,4BAAkC;AAClC,4BAAiC;AACjC,wBAAmD;AACnD,uBAA6D;AAC7D,uBAAuC;AACvC,SAAoB;AACpB,WAAsB;AAmBf,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,uBAAuB,6CAA6C,iCAAe,CAAC,CAAC,EAC5F,OAAO,6BAA6B,4CAA4C,iCAAe,CAAC,CAAC,EACjG,OAAO,OAAO,MAAM,MAAM,YAAY;AACnC,UAAM,EAAE,cAAc,OAAO,QAAI,4CAA4B,MAAM,IAAI;AACvE,UAAM,eAAe,UAAM,oDAA6B,cAAc,MAAM;AAE5E,QAAI,CAAC,cAAc;AACf,iDAAgB,MAAM;AACtB,cAAQ,KAAK,CAAC;AAAA,IAClB;AAEA,UAAM,cAAc,IAAI,+BAAY,QAAQ,aAAa,MAAM;AAE/D,UAAM,gBAAY,6BAAa,MAAM;AACrC,8CAAsB,SAAS;AAQ/B,iDAAuB,KAAK,KAAK,WAAW,YAAY,CAAC;AAEzD,UAAM,yBAAyB,WAAW,MAAM;AAEhD,UAAM,wBAAoB,u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AAI,4BAA4B,MAAM,EAAE;AACnD;",
6
6
  "names": ["chalk", "inquirer"]
7
7
  }
@@ -116,8 +116,8 @@ Steps to follow:
116
116
  3. Create the app with farseer_create_app (name: "${appName}")
117
117
 
118
118
  4. Configure the app with farseer_configure_app:
119
+ - sourceFolder: "Scripts"
119
120
  - entrypoint: "${script}"
120
- - scripts: ["${script}"]
121
121
  - arguments: Add any arguments the script expects (they arrive via process.argv)
122
122
 
123
123
  5. Test with farseer_run_app
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/prompts/workflows.ts"],
4
- "sourcesContent": ["/**\n * Workflow Prompts\n *\n * Reusable prompt templates for common Farseer workflows.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\n// Define schemas outside of prompt registration to avoid deep type instantiation\nconst setupTenantSchema = {\n tenant: z.string().describe('Tenant name to setup'),\n};\n\nconst createAppSchema = {\n tenant: z.string().describe('Tenant name'),\n appName: z.string().describe('Name for the new app'),\n scriptName: z.string().optional().describe('Main script filename (default: index.ts)'),\n};\n\nconst understandModelSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nconst writeImportScriptSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Target variable to import into'),\n};\n\nconst copyAppSchema = {\n tenant: z.string().describe('Tenant name'),\n sourceApp: z.string().describe('Name of app to copy'),\n newAppName: z.string().describe('Name for the new app'),\n};\n\nconst exportDataSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Variable to export'),\n};\n\nconst debugSyncSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nexport function registerWorkflowPrompts(server: McpServer): void {\n // Cast to any to avoid very deep generic type instantiation from the MCP SDK\n const anyServer = server as any;\n // Setup new tenant\n anyServer.prompt(\n 'setup_new_tenant',\n 'Guide for setting up a new Farseer tenant: login, checkout, pull, install dependencies.',\n setupTenantSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `You are setting up a new Farseer tenant \"${tenant}\".\n\nSteps to follow:\n\n1. First, check authentication status with farseer_whoami\n2. If not logged in, inform the user to run \"farseer login\" in terminal (MCP cannot do browser login)\n3. Use farseer_checkout to set \"${tenant}\" as the default tenant (this also pulls files and apps)\n4. Tell user to run \"farseer install ${tenant}\" in terminal to install npm dependencies\n5. Use farseer_list_apps to show available apps\n6. Use farseer_export_model to understand the data structure\n\nAfter setup, the user can:\n- Run apps with farseer_run_app\n- Edit scripts in apps/${tenant}/files/Scripts/\n- Push changes with farseer_push\n- Check model with farseer_get_variable or farseer_get_table`,\n },\n },\n ],\n };\n },\n );\n\n // Create new app\n anyServer.prompt(\n 'create_new_app',\n 'Guide for creating a new Farseer app from scratch.',\n createAppSchema,\n async (params: { tenant: string; appName: string; scriptName?: string }) => {\n const { tenant, appName, scriptName } = params;\n const script = scriptName || 'index.ts';\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Creating a new Farseer app \"${appName}\" for tenant \"${tenant}\".\n\nIMPORTANT: A Farseer App = a TypeScript script + an app config that tells Farseer which script to run and with what arguments.\nThe script uses \\`farseer-client\\` to interact with the Farseer API.\nAuthentication is automatic - \\`new FarseerClient()\\` reads credentials from environment variables injected by the CLI.\nYou NEVER hardcode credentials in scripts.\n\nSteps to follow:\n\n1. Write the script file at farseer-apps/${tenant}/files/Scripts/${script}\n Use the template below as a starting point.\n\n2. Push the script to remote with farseer_push\n (Scripts must exist on remote before they can be assigned to an app)\n\n3. Create the app with farseer_create_app (name: \"${appName}\")\n\n4. Configure the app with farseer_configure_app:\n - entrypoint: \"${script}\"\n - scripts: [\"${script}\"]\n - arguments: Add any arguments the script expects (they arrive via process.argv)\n\n5. Test with farseer_run_app\n The CLI injects auth credentials as env vars and runs the script with npx tsx.\n\nScript template:\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\n// FarseerClient auto-configures from env vars injected by \"farseer run\"\n// NEVER hardcode credentials - just use the empty constructor\nconst client = new farseer.FarseerClient();\n\n// Arguments come via process.argv in the order defined by app config\nconst args = process.argv.slice(2);\n\nasync function main() {\n // Load dimension/variable metadata\n await client.initTagMap();\n\n // Your code here\n console.log('App running successfully');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\``,\n },\n },\n ],\n };\n },\n );\n\n // Understand model\n anyServer.prompt(\n 'understand_model',\n 'Explore and understand the data model of a Farseer tenant.',\n understandModelSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Analyzing the data model for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_export_model to get the full model structure\n\n2. Review dimension tables:\n - Use farseer_list_tables for overview\n - Key dimensions usually include: Products, Regions, Time (Months, Years), Versions\n - Check foreign key relationships between tables\n\n3. Review variables:\n - Use farseer_list_variables for overview\n - Use farseer_get_variable for specific variable details\n - Note which dimensions each variable has\n\n4. For import scripts, you need to know:\n - Target variable name\n - All dimensions the variable has\n - Valid members for each dimension\n\nKey concepts:\n- Dimensions structure the data (Product, Region, Month, Year, Version)\n- Variables store values at dimension intersections\n- Formulas calculate values automatically\n- Roll-up types determine aggregation (SUM, AVERAGE, etc.)\n\nCommon dimension tables:\n- Months, Years (time)\n- Versions (Plan, Actual, Forecast)\n- Products, Categories, Brands\n- Regions, Entities, Cost Centers`,\n },\n },\n ],\n };\n },\n );\n\n // Write import script\n anyServer.prompt(\n 'write_import_script',\n 'Guide for writing a data import script.',\n writeImportScriptSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Writing an import script for variable \"${variableName}\" in tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the target variable:\n - What dimensions does it have?\n - What is the roll-up type?\n\n2. Use farseer_get_table for each dimension to see valid members\n\n3. Create the import script with this pattern:\n\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\nconst client = new farseer.FarseerClient();\n\nasync function main() {\n await client.initTagMap();\n\n // Create import job with column definitions\n const importJob = await client.createImportJob({\n title: 'Import ${variableName}',\n columns: [\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Product' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Years' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Months' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Versions' },\n { type: 'VARIABLE', variableName: '${variableName}' },\n ],\n labels: ['auto', 'import-${variableName.toLowerCase().replace(/\\s+/g, '-')}']\n });\n\n // Add rows - each row matches column order\n const rows = [\n ['ProductA', 'Y2025', 'M1', 'Plan', 1000],\n ['ProductB', 'Y2025', 'M1', 'Plan', 2000],\n ];\n\n await importJob.addRows(rows);\n await importJob.flushRows();\n await importJob.undoPrevious(); // Remove previous import\n await importJob.commit();\n\n console.log('Import completed!');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\`\n\n4. Save script to apps/${tenant}/files/Scripts/\n5. Push with farseer_push\n6. Create app with farseer_create_app\n7. Configure with farseer_configure_app\n8. Test with farseer_run_app\n\nALTERNATIVE: For simple imports without a script, use the farseer_create_import_job tool directly.\nIt handles the full workflow (create metadata, add rows, undo previous, commit) in a single call.\nUse farseer_create_import_job when:\n- Data is already available (no need to fetch from external source)\n- The import is a one-time or simple operation\n- You want to quickly import without creating a full script\n\nUse a script when:\n- Data comes from external sources (APIs, databases, files)\n- Complex data transformation is needed\n- The import runs on a schedule as an App`,\n },\n },\n ],\n };\n },\n );\n\n // Copy existing app\n anyServer.prompt(\n 'copy_app',\n 'Guide for copying an existing app to create a new one.',\n copyAppSchema,\n async (params: { tenant: string; sourceApp: string; newAppName: string }) => {\n const { tenant, sourceApp, newAppName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Copying app \"${sourceApp}\" to create \"${newAppName}\" for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Pull latest with farseer_pull to get current app JSON\n\n2. Use farseer_get_app to see the source app configuration\n\n3. The app JSON files are in apps/${tenant}/apps/\n\n Copy the source JSON file and modify:\n - Change \"name\" to \"${newAppName}\"\n - **IMPORTANT: Remove \"_remote\" field** (this makes it a new app)\n - Modify arguments, description as needed\n\n4. JSON format for new app:\n\\`\\`\\`json\n{\n \"name\": \"${newAppName}\",\n \"description\": \"Copied from ${sourceApp}\",\n \"entrypoint\": \"script.ts\",\n \"scripts\": [\"script.ts\"],\n \"arguments\": [\n { \"name\": \"Year\", \"defaultValue\": \"2025\" }\n ]\n}\n\\`\\`\\`\n\nNote: Do NOT include \"_remote\" for new apps - CLI adds it after first push.\n\n5. Push with farseer_push to create the new app\n\n6. Test with farseer_run_app`,\n },\n },\n ],\n };\n },\n );\n\n // Export data\n anyServer.prompt(\n 'export_data',\n 'Guide for exporting variable data from Farseer.',\n exportDataSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Exporting data for variable \"${variableName}\" from tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the variable:\n - What dimensions does it span?\n - What is its data type?\n\n2. Choose export method:\n\n **Option A: Quick export (farseer_export_variable_data)**\n - Uses ExportApi.exportFormula() internally\n - Returns CSV/JSON data inline\n - Good for quick inspection or small datasets\n - Use 'limit' parameter for large datasets\n\n **Option B: Structured export (farseer_load_variable_data)**\n - Uses data.loadFarseerVariable() internally\n - Can specify which dimensions to include as columns\n - Returns structured CSV data\n - Good when you need specific dimension breakdowns\n\n **Option C: CLI export (farseer variable export)**\n - Saves CSV/JSON/XLSX to a local file\n - Best for saving data locally for analysis\n\n3. For analysis:\n - Parse the CSV data returned by the tools\n - Summarize, filter, or transform as needed`,\n },\n },\n ],\n };\n },\n );\n\n // Debug sync issues\n anyServer.prompt(\n 'debug_sync_issues',\n 'Troubleshoot synchronization problems between local and remote.',\n debugSyncSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Debugging sync issues for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Check authentication: farseer_whoami\n - Is JWT valid?\n - Is tenant checked out?\n\n2. Check sync status: farseer_status\n - Are there modified files?\n - Are there only-local or only-remote files?\n\n3. If files show as modified:\n - Use farseer_diff to see differences\n - Decide: pull (accept remote) or push (upload local)\n\n4. Common issues and solutions:\n\n **\"No credentials found\"**\n \u2192 User needs to run \"farseer login\" in terminal\n \u2192 Or configure API key: \"farseer config set ${tenant} --api-key KEY\"\n\n **\"Remote has changes\"**\n \u2192 Pull first with farseer_pull\n \u2192 Then push with farseer_push\n\n **\"Token expired\"**\n \u2192 User needs to run \"farseer login\" again\n\n **Apps not syncing**\n \u2192 Need JWT login (browser), not API key\n \u2192 API key only syncs files, not apps\n\n5. Force resolution:\n - To accept all remote changes: farseer_pull with force=true (overwrites local)\n - To accept all local changes: farseer_push with force=true (overwrites remote)\n - For selective resolution: farseer_pull without force will skip conflicts (resolve via CLI)\n\n6. Check specific file diff:\n - Use farseer_diff with file parameter to see exact changes`,\n },\n },\n ],\n };\n },\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAGlB,MAAM,oBAAoB;AAAA,EACtB,QAAQ,aAAE,OAAO,EAAE,SAAS,sBAAsB;AACtD;AAEA,MAAM,kBAAkB;AAAA,EACpB,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACzC,SAAS,aAAE,OAAO,EAAE,SAAS,sBAAsB;AAAA,EACnD,YAAY,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,0CAA0C;AACzF;AAEA,MAAM,wBAAwB;AAAA,EAC1B,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAC7C;AAEA,MAA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AA,YACN,SAAS;AAAA,cACL,MAAM;AAAA,cACN,MAAM,gCAAgC,YAAY,kBAAkB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YA6B9E;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AAGA,YAAU;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO,WAA+B;AAClC,YAAM,EAAE,OAAO,IAAI;AACnB,aAAO;AAAA,QACH,UAAU;AAAA,UACN;AAAA,YACI,MAAM;AAAA,YACN,SAAS;AAAA,cACL,MAAM;AAAA,cACN,MAAM,qCAAqC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sDAoB5B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAoB/B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;",
4
+ "sourcesContent": ["/**\n * Workflow Prompts\n *\n * Reusable prompt templates for common Farseer workflows.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\n// Define schemas outside of prompt registration to avoid deep type instantiation\nconst setupTenantSchema = {\n tenant: z.string().describe('Tenant name to setup'),\n};\n\nconst createAppSchema = {\n tenant: z.string().describe('Tenant name'),\n appName: z.string().describe('Name for the new app'),\n scriptName: z.string().optional().describe('Main script filename (default: index.ts)'),\n};\n\nconst understandModelSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nconst writeImportScriptSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Target variable to import into'),\n};\n\nconst copyAppSchema = {\n tenant: z.string().describe('Tenant name'),\n sourceApp: z.string().describe('Name of app to copy'),\n newAppName: z.string().describe('Name for the new app'),\n};\n\nconst exportDataSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Variable to export'),\n};\n\nconst debugSyncSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nexport function registerWorkflowPrompts(server: McpServer): void {\n // Cast to any to avoid very deep generic type instantiation from the MCP SDK\n const anyServer = server as any;\n // Setup new tenant\n anyServer.prompt(\n 'setup_new_tenant',\n 'Guide for setting up a new Farseer tenant: login, checkout, pull, install dependencies.',\n setupTenantSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `You are setting up a new Farseer tenant \"${tenant}\".\n\nSteps to follow:\n\n1. First, check authentication status with farseer_whoami\n2. If not logged in, inform the user to run \"farseer login\" in terminal (MCP cannot do browser login)\n3. Use farseer_checkout to set \"${tenant}\" as the default tenant (this also pulls files and apps)\n4. Tell user to run \"farseer install ${tenant}\" in terminal to install npm dependencies\n5. Use farseer_list_apps to show available apps\n6. Use farseer_export_model to understand the data structure\n\nAfter setup, the user can:\n- Run apps with farseer_run_app\n- Edit scripts in apps/${tenant}/files/Scripts/\n- Push changes with farseer_push\n- Check model with farseer_get_variable or farseer_get_table`,\n },\n },\n ],\n };\n },\n );\n\n // Create new app\n anyServer.prompt(\n 'create_new_app',\n 'Guide for creating a new Farseer app from scratch.',\n createAppSchema,\n async (params: { tenant: string; appName: string; scriptName?: string }) => {\n const { tenant, appName, scriptName } = params;\n const script = scriptName || 'index.ts';\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Creating a new Farseer app \"${appName}\" for tenant \"${tenant}\".\n\nIMPORTANT: A Farseer App = a TypeScript script + an app config that tells Farseer which script to run and with what arguments.\nThe script uses \\`farseer-client\\` to interact with the Farseer API.\nAuthentication is automatic - \\`new FarseerClient()\\` reads credentials from environment variables injected by the CLI.\nYou NEVER hardcode credentials in scripts.\n\nSteps to follow:\n\n1. Write the script file at farseer-apps/${tenant}/files/Scripts/${script}\n Use the template below as a starting point.\n\n2. Push the script to remote with farseer_push\n (Scripts must exist on remote before they can be assigned to an app)\n\n3. Create the app with farseer_create_app (name: \"${appName}\")\n\n4. Configure the app with farseer_configure_app:\n - sourceFolder: \"Scripts\"\n - entrypoint: \"${script}\"\n - arguments: Add any arguments the script expects (they arrive via process.argv)\n\n5. Test with farseer_run_app\n The CLI injects auth credentials as env vars and runs the script with npx tsx.\n\nScript template:\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\n// FarseerClient auto-configures from env vars injected by \"farseer run\"\n// NEVER hardcode credentials - just use the empty constructor\nconst client = new farseer.FarseerClient();\n\n// Arguments come via process.argv in the order defined by app config\nconst args = process.argv.slice(2);\n\nasync function main() {\n // Load dimension/variable metadata\n await client.initTagMap();\n\n // Your code here\n console.log('App running successfully');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\``,\n },\n },\n ],\n };\n },\n );\n\n // Understand model\n anyServer.prompt(\n 'understand_model',\n 'Explore and understand the data model of a Farseer tenant.',\n understandModelSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Analyzing the data model for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_export_model to get the full model structure\n\n2. Review dimension tables:\n - Use farseer_list_tables for overview\n - Key dimensions usually include: Products, Regions, Time (Months, Years), Versions\n - Check foreign key relationships between tables\n\n3. Review variables:\n - Use farseer_list_variables for overview\n - Use farseer_get_variable for specific variable details\n - Note which dimensions each variable has\n\n4. For import scripts, you need to know:\n - Target variable name\n - All dimensions the variable has\n - Valid members for each dimension\n\nKey concepts:\n- Dimensions structure the data (Product, Region, Month, Year, Version)\n- Variables store values at dimension intersections\n- Formulas calculate values automatically\n- Roll-up types determine aggregation (SUM, AVERAGE, etc.)\n\nCommon dimension tables:\n- Months, Years (time)\n- Versions (Plan, Actual, Forecast)\n- Products, Categories, Brands\n- Regions, Entities, Cost Centers`,\n },\n },\n ],\n };\n },\n );\n\n // Write import script\n anyServer.prompt(\n 'write_import_script',\n 'Guide for writing a data import script.',\n writeImportScriptSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Writing an import script for variable \"${variableName}\" in tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the target variable:\n - What dimensions does it have?\n - What is the roll-up type?\n\n2. Use farseer_get_table for each dimension to see valid members\n\n3. Create the import script with this pattern:\n\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\nconst client = new farseer.FarseerClient();\n\nasync function main() {\n await client.initTagMap();\n\n // Create import job with column definitions\n const importJob = await client.createImportJob({\n title: 'Import ${variableName}',\n columns: [\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Product' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Years' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Months' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Versions' },\n { type: 'VARIABLE', variableName: '${variableName}' },\n ],\n labels: ['auto', 'import-${variableName.toLowerCase().replace(/\\s+/g, '-')}']\n });\n\n // Add rows - each row matches column order\n const rows = [\n ['ProductA', 'Y2025', 'M1', 'Plan', 1000],\n ['ProductB', 'Y2025', 'M1', 'Plan', 2000],\n ];\n\n await importJob.addRows(rows);\n await importJob.flushRows();\n await importJob.undoPrevious(); // Remove previous import\n await importJob.commit();\n\n console.log('Import completed!');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\`\n\n4. Save script to apps/${tenant}/files/Scripts/\n5. Push with farseer_push\n6. Create app with farseer_create_app\n7. Configure with farseer_configure_app\n8. Test with farseer_run_app\n\nALTERNATIVE: For simple imports without a script, use the farseer_create_import_job tool directly.\nIt handles the full workflow (create metadata, add rows, undo previous, commit) in a single call.\nUse farseer_create_import_job when:\n- Data is already available (no need to fetch from external source)\n- The import is a one-time or simple operation\n- You want to quickly import without creating a full script\n\nUse a script when:\n- Data comes from external sources (APIs, databases, files)\n- Complex data transformation is needed\n- The import runs on a schedule as an App`,\n },\n },\n ],\n };\n },\n );\n\n // Copy existing app\n anyServer.prompt(\n 'copy_app',\n 'Guide for copying an existing app to create a new one.',\n copyAppSchema,\n async (params: { tenant: string; sourceApp: string; newAppName: string }) => {\n const { tenant, sourceApp, newAppName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Copying app \"${sourceApp}\" to create \"${newAppName}\" for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Pull latest with farseer_pull to get current app JSON\n\n2. Use farseer_get_app to see the source app configuration\n\n3. The app JSON files are in apps/${tenant}/apps/\n\n Copy the source JSON file and modify:\n - Change \"name\" to \"${newAppName}\"\n - **IMPORTANT: Remove \"_remote\" field** (this makes it a new app)\n - Modify arguments, description as needed\n\n4. JSON format for new app:\n\\`\\`\\`json\n{\n \"name\": \"${newAppName}\",\n \"description\": \"Copied from ${sourceApp}\",\n \"entrypoint\": \"script.ts\",\n \"scripts\": [\"script.ts\"],\n \"arguments\": [\n { \"name\": \"Year\", \"defaultValue\": \"2025\" }\n ]\n}\n\\`\\`\\`\n\nNote: Do NOT include \"_remote\" for new apps - CLI adds it after first push.\n\n5. Push with farseer_push to create the new app\n\n6. Test with farseer_run_app`,\n },\n },\n ],\n };\n },\n );\n\n // Export data\n anyServer.prompt(\n 'export_data',\n 'Guide for exporting variable data from Farseer.',\n exportDataSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Exporting data for variable \"${variableName}\" from tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the variable:\n - What dimensions does it span?\n - What is its data type?\n\n2. Choose export method:\n\n **Option A: Quick export (farseer_export_variable_data)**\n - Uses ExportApi.exportFormula() internally\n - Returns CSV/JSON data inline\n - Good for quick inspection or small datasets\n - Use 'limit' parameter for large datasets\n\n **Option B: Structured export (farseer_load_variable_data)**\n - Uses data.loadFarseerVariable() internally\n - Can specify which dimensions to include as columns\n - Returns structured CSV data\n - Good when you need specific dimension breakdowns\n\n **Option C: CLI export (farseer variable export)**\n - Saves CSV/JSON/XLSX to a local file\n - Best for saving data locally for analysis\n\n3. For analysis:\n - Parse the CSV data returned by the tools\n - Summarize, filter, or transform as needed`,\n },\n },\n ],\n };\n },\n );\n\n // Debug sync issues\n anyServer.prompt(\n 'debug_sync_issues',\n 'Troubleshoot synchronization problems between local and remote.',\n debugSyncSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Debugging sync issues for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Check authentication: farseer_whoami\n - Is JWT valid?\n - Is tenant checked out?\n\n2. Check sync status: farseer_status\n - Are there modified files?\n - Are there only-local or only-remote files?\n\n3. If files show as modified:\n - Use farseer_diff to see differences\n - Decide: pull (accept remote) or push (upload local)\n\n4. Common issues and solutions:\n\n **\"No credentials found\"**\n \u2192 User needs to run \"farseer login\" in terminal\n \u2192 Or configure API key: \"farseer config set ${tenant} --api-key KEY\"\n\n **\"Remote has changes\"**\n \u2192 Pull first with farseer_pull\n \u2192 Then push with farseer_push\n\n **\"Token expired\"**\n \u2192 User needs to run \"farseer login\" again\n\n **Apps not syncing**\n \u2192 Need JWT login (browser), not API key\n \u2192 API key only syncs files, not apps\n\n5. Force resolution:\n - To accept all remote changes: farseer_pull with force=true (overwrites local)\n - To accept all local changes: farseer_push with force=true (overwrites remote)\n - For selective resolution: farseer_pull without force will skip conflicts (resolve via CLI)\n\n6. Check specific file di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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAoB/B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;",
6
6
  "names": []
7
7
  }
@@ -24,6 +24,7 @@ __export(appTools_exports, {
24
24
  module.exports = __toCommonJS(appTools_exports);
25
25
  var import_zod = require("zod");
26
26
  var import_farseerFactory = require("../../services/farseerFactory");
27
+ var import_farseerApi = require("../../services/farseerApi");
27
28
  var import_helpers = require("../utils/helpers");
28
29
  var import_errorFormatter = require("../../utils/errorFormatter");
29
30
  const listAppsSchema = {
@@ -62,8 +63,8 @@ const configureAppSchema = {
62
63
  organisation: import_zod.z.string().optional().describe("Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping."),
63
64
  tenant: import_zod.z.string().optional().describe("Tenant ID. Uses checked-out tenant if omitted."),
64
65
  appName: import_zod.z.string().describe("Name of the app to configure"),
65
- entrypoint: import_zod.z.string().optional().describe('Main script filename (e.g., "index.ts")'),
66
- scripts: import_zod.z.array(import_zod.z.string()).optional().describe("List of script filenames to include"),
66
+ entrypoint: import_zod.z.string().optional().describe(`Main script filename \u2014 must be a file in the app's source folder (e.g., "index.ts")`),
67
+ sourceFolder: import_zod.z.string().optional().describe(`Source folder the app's scripts come from (path under Files/, e.g. "Scripts/MyApp")`),
67
68
  description: import_zod.z.string().optional().describe("App description"),
68
69
  arguments: import_zod.z.array(argumentSchema).optional().describe("App arguments with default values"),
69
70
  newName: import_zod.z.string().optional().describe("Rename the app")
@@ -254,8 +255,8 @@ If no tenant is specified, uses the currently checked-out tenant.`,
254
255
  `Configure an existing Farseer app.
255
256
 
256
257
  You can set:
257
- - entrypoint: Main script to execute (e.g., "index.ts")
258
- - scripts: List of scripts to include in the app
258
+ - sourceFolder: Folder under Files/ the app's scripts come from (e.g. "Scripts/MyApp")
259
+ - entrypoint: Main script to execute \u2014 must be a file in the source folder (e.g., "index.ts")
259
260
  - description: App description
260
261
  - arguments: List of expected arguments. Each has a name, optional dataType
261
262
  ('string' | 'boolean' \u2014 defaults to 'string'), optional fixed (locks the
@@ -264,8 +265,11 @@ You can set:
264
265
  - newName: Rename the app
265
266
 
266
267
  Important:
267
- - Scripts must exist on the remote (push them first)
268
- - If you set scripts but not entrypoint, the first script becomes entrypoint
268
+ - The app's scripts are derived from its source folder; the entrypoint must be
269
+ one of those files. To use a script from another folder, set sourceFolder first.
270
+ - Changing sourceFolder to a folder that doesn't contain the current entrypoint
271
+ requires passing entrypoint in the same call.
272
+ - Settings you don't pass are preserved (this only changes what you specify).
269
273
  - Arguments are passed to the script as a JSON-encoded FARSEER_ARGS env var
270
274
  - Boolean dataType requires defaultValue \u2208 { "true", "false" }; defaultValue
271
275
  must be one of options when options is set
@@ -287,30 +291,16 @@ If no tenant is specified, uses the currently checked-out tenant.`,
287
291
  if (!app) {
288
292
  return (0, import_helpers.errorResponse)(`App "${params.appName}" not found`, "NOT_FOUND");
289
293
  }
290
- const availableScripts = await clientResult.client.getScriptFiles();
291
- const scriptIdByPath = /* @__PURE__ */ new Map();
292
- const scriptIdByName = /* @__PURE__ */ new Map();
293
- for (const s2 of availableScripts) {
294
- scriptIdByPath.set(s2.name.toLowerCase(), s2.id);
295
- const filename = s2.name.split("/").pop()?.toLowerCase() || s2.name.toLowerCase();
296
- if (!scriptIdByName.has(filename)) {
297
- scriptIdByName.set(filename, s2.id);
298
- }
299
- }
300
- const resolveScriptId = (name) => {
301
- const lower = name.toLowerCase();
302
- return scriptIdByPath.get(lower) || scriptIdByName.get(lower);
303
- };
304
- const update = {};
294
+ const changes = {};
305
295
  if (params.newName) {
306
- update.name = params.newName;
296
+ changes.name = params.newName;
307
297
  }
308
298
  if (params.description !== void 0) {
309
- update.description = params.description;
299
+ changes.description = params.description;
310
300
  }
311
301
  if (params.arguments) {
312
302
  const existingByName = new Map(app.expectedArguments.map((e) => [e.name.toLowerCase(), e]));
313
- update.expectedArguments = params.arguments.map((a) => {
303
+ changes.expectedArguments = params.arguments.map((a) => {
314
304
  const existing = existingByName.get(a.name.toLowerCase());
315
305
  const arg = {
316
306
  name: existing?.name ?? a.name,
@@ -327,47 +317,22 @@ If no tenant is specified, uses the currently checked-out tenant.`,
327
317
  return arg;
328
318
  });
329
319
  }
330
- if (params.scripts && params.scripts.length > 0) {
331
- const scriptIds = [];
332
- const notFound = [];
333
- for (const scriptName of params.scripts) {
334
- const id = resolveScriptId(scriptName);
335
- if (id) {
336
- scriptIds.push(id);
337
- } else {
338
- notFound.push(scriptName);
339
- }
340
- }
341
- if (notFound.length > 0) {
342
- return (0, import_helpers.errorResponse)(
343
- `Scripts not found on remote: ${notFound.join(", ")}. Push them first.`,
344
- "VALIDATION_ERROR"
345
- );
346
- }
347
- update.scriptFileIds = scriptIds;
348
- if (!params.entrypoint && scriptIds.length > 0) {
349
- update.mainScriptFileId = scriptIds[0];
350
- }
351
- }
352
- if (params.entrypoint) {
353
- const entrypointId = resolveScriptId(params.entrypoint);
354
- if (!entrypointId) {
355
- return (0, import_helpers.errorResponse)(
356
- `Entrypoint script "${params.entrypoint}" not found on remote. Push it first.`,
357
- "VALIDATION_ERROR"
358
- );
359
- }
360
- update.mainScriptFileId = entrypointId;
361
- }
362
- if (!update.name) {
363
- update.name = app.name;
320
+ const sourceFolderError = await (0, import_farseerApi.applySourceFolderChange)(
321
+ clientResult.client,
322
+ app,
323
+ changes,
324
+ { sourceFolder: params.sourceFolder, entrypoint: params.entrypoint },
325
+ "mcp"
326
+ );
327
+ if (sourceFolderError) {
328
+ return (0, import_helpers.errorResponse)(sourceFolderError, "VALIDATION_ERROR");
364
329
  }
365
330
  const reference = app.id.toString();
366
- await clientResult.client.updateApp(reference, update);
331
+ await clientResult.client.updateApp(reference, changes, app);
367
332
  return (0, import_helpers.successResponse)({
368
333
  tenant,
369
334
  appName: params.newName || params.appName,
370
- updated: Object.keys(update),
335
+ updated: Object.keys(changes),
371
336
  message: `App "${params.appName}" configured successfully`
372
337
  });
373
338
  } catch (error) {
@@ -401,7 +366,14 @@ If no tenant is specified, uses the currently checked-out tenant.`,
401
366
  if (!appItem) {
402
367
  return (0, import_helpers.errorResponse)(`App "${params.appName}" not found`, "NOT_FOUND");
403
368
  }
404
- await clientResult.client.deleteApp(appItem.id.toString());
369
+ await clientResult.client.deleteApp(appItem.id);
370
+ const remaining = await clientResult.client.listApps();
371
+ if (remaining.some((a) => a.id === appItem.id)) {
372
+ return (0, import_helpers.errorResponse)(
373
+ `Delete reported success but "${params.appName}" is still present`,
374
+ "NETWORK_ERROR"
375
+ );
376
+ }
405
377
  return (0, import_helpers.successResponse)({
406
378
  tenant,
407
379
  deletedApp: params.appName,