farseer-cli 1.6.0 → 1.6.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.
- package/dist/commands/checkout.js +2 -1
- package/dist/commands/checkout.js.map +2 -2
- package/dist/commands/pull.js +3 -2
- package/dist/commands/pull.js.map +2 -2
- package/dist/utils/constants.js +4 -1
- package/dist/utils/constants.js.map +2 -2
- package/dist/utils/fileValidation.js +1 -1
- package/dist/utils/fileValidation.js.map +2 -2
- package/dist/utils/packageManager.js +3 -3
- package/dist/utils/packageManager.js.map +2 -2
- package/package.json +1 -1
|
@@ -39,6 +39,7 @@ var import_syncService = require("../services/syncService");
|
|
|
39
39
|
var import_appSyncService = require("../services/appSyncService");
|
|
40
40
|
var import_helpers = require("../utils/helpers");
|
|
41
41
|
var import_cliOptions = require("../utils/cliOptions");
|
|
42
|
+
var import_constants = require("../utils/constants");
|
|
42
43
|
var fs = __toESM(require("fs"));
|
|
43
44
|
var path = __toESM(require("path"));
|
|
44
45
|
function registerCheckoutCommand(program) {
|
|
@@ -134,7 +135,7 @@ function createDefaultPackageJson(tenant, packageJsonPath) {
|
|
|
134
135
|
build: "tsc"
|
|
135
136
|
},
|
|
136
137
|
dependencies: {
|
|
137
|
-
"farseer-client":
|
|
138
|
+
"farseer-client": import_constants.FARSEER_CLIENT_URL,
|
|
138
139
|
arquero: "^7.0.1",
|
|
139
140
|
xlsx: "^0.18.5",
|
|
140
141
|
xmldom: "^0.6.0"
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/commands/checkout.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport {\n getCurrentCheckout,\n setCurrentCheckout,\n clearCurrentTenant,\n saveTenantOrgMapping,\n} from '../services/configService';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantDir, ensureDirectoryExists } from '../utils/helpers';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport function registerCheckoutCommand(program: Command): void {\n program\n .command('checkout [org] [tenant]')\n .description('Set default tenant for commands (runs auth check and pull)')\n .option('--no-pull', 'Skip automatic pull')\n .option('--clear', 'Clear current checkout')\n .option('--include-ext <ext>', 'Include extra file extension for pull (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder for pull (repeatable)', collectValues, [])\n .action(async (first, second, options) => {\n // Handle --clear flag\n if (options.clear) {\n clearCurrentTenant();\n logger.success('Checkout cleared. You now need to specify tenant for each command.');\n return;\n }\n\n // If no arguments specified, show current checkout status\n if (!first) {\n const current = getCurrentCheckout();\n if (current) {\n if (current.organisation === current.tenant) {\n logger.info(`Currently checked out: ${chalk.bold(current.tenant)}`);\n } else {\n logger.info(\n `Currently checked out: ${chalk.bold(current.tenant)} (org: ${chalk.bold(current.organisation)})`,\n );\n }\n logger.dim('Run \"farseer checkout <tenant>\" to switch tenants.');\n logger.dim('Run \"farseer checkout --clear\" to clear checkout.');\n } else {\n logger.info('No tenant currently checked out.');\n logger.dim('Run \"farseer checkout <tenant>\" to set a default tenant.');\n logger.dim('Run \"farseer checkout <org> <tenant>\" if organisation and tenant differ.');\n }\n return;\n }\n\n // Determine organisation and tenant\n // If two arguments: first=organisation, second=tenant\n // If one argument: organisation=tenant=first\n const organisation = second ? first : first;\n const tenant = second || first;\n\n logger.info(`Checking out tenant: ${chalk.bold(tenant)} (org: ${chalk.bold(organisation)})...`);\n console.log();\n\n // Step 1: Verify authentication\n logger.info('Verifying authentication...');\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const authLabel = clientResult.authType === 'apiKey' ? 'API key' : 'browser login';\n logger.success(`Authenticated (using ${authLabel})`);\n\n // Step 2: Set as current checkout and save org-tenant mapping\n setCurrentCheckout(organisation, tenant);\n saveTenantOrgMapping(tenant, organisation);\n\n // Step 3: Auto-pull (unless --no-pull)\n if (options.pull) {\n console.log();\n logger.info('Pulling latest files and apps...');\n\n const syncService = new SyncService(tenant, clientResult.client);\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n try {\n // Ensure package.json exists\n const packageJsonPath = path.join(tenantDir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n createDefaultPackageJson(tenant, packageJsonPath);\n }\n\n // Pull files (scripts + includes by default)\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const result = await syncService.pull({\n all: false,\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n });\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // Pull apps\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n const appResult = await appSyncService.pull();\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n logger.success('Pull complete!');\n } catch (error) {\n logger.warning('Pull failed, but checkout is complete.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n }\n }\n\n // Final message\n console.log();\n logger.success(`Tenant ${chalk.bold(tenant)} is now checked out.`);\n logger.dim('You can now run commands without specifying the tenant:');\n logger.dim(' farseer status');\n logger.dim(' farseer model --variables');\n logger.dim(' farseer apps');\n logger.dim(' farseer push');\n });\n}\n\nfunction createDefaultPackageJson(tenant: string, packageJsonPath: string): void {\n const packageJson = {\n name: `farseer-${tenant}`,\n version: '1.0.0',\n description: `Farseer scripts for ${tenant}`,\n type: 'module',\n scripts: {\n build: 'tsc',\n },\n dependencies: {\n 'farseer-client'
|
|
5
|
-
"mappings": ";;;;;;;;;;;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AA,MACnC,SAAS,OAAO;AACZ,6BAAO,QAAQ,wCAAwC;AACvD,YAAI,iBAAiB,OAAO;AACxB,+BAAO,IAAI,MAAM,OAAO;AAAA,QAC5B;AAAA,MACJ;AAAA,IACJ;AAGA,YAAQ,IAAI;AACZ,yBAAO,QAAQ,UAAU,aAAAA,QAAM,KAAK,MAAM,CAAC,sBAAsB;AACjE,yBAAO,IAAI,yDAAyD;AACpE,yBAAO,IAAI,kBAAkB;AAC7B,yBAAO,IAAI,6BAA6B;AACxC,yBAAO,IAAI,gBAAgB;AAC3B,yBAAO,IAAI,gBAAgB;AAAA,EAC/B,CAAC;AACT;AAEA,SAAS,yBAAyB,QAAgB,iBAA+B;AAC7E,QAAM,cAAc;AAAA,IAChB,MAAM,WAAW,MAAM;AAAA,IACvB,SAAS;AAAA,IACT,aAAa,uBAAuB,MAAM;AAAA,IAC1C,MAAM;AAAA,IACN,SAAS;AAAA,MACL,OAAO;AAAA,IACX;AAAA,IACA,cAAc;AAAA,MACV,
|
|
4
|
+
"sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport {\n getCurrentCheckout,\n setCurrentCheckout,\n clearCurrentTenant,\n saveTenantOrgMapping,\n} from '../services/configService';\nimport { getFarseerClientWithFallback, showLoginPrompt } from '../services/farseerFactory';\nimport { SyncService } from '../services/syncService';\nimport { AppSyncService } from '../services/appSyncService';\nimport { getTenantDir, ensureDirectoryExists } from '../utils/helpers';\nimport { collectValues, normalizeExtensions } from '../utils/cliOptions';\nimport { FARSEER_CLIENT_URL } from '../utils/constants';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nexport function registerCheckoutCommand(program: Command): void {\n program\n .command('checkout [org] [tenant]')\n .description('Set default tenant for commands (runs auth check and pull)')\n .option('--no-pull', 'Skip automatic pull')\n .option('--clear', 'Clear current checkout')\n .option('--include-ext <ext>', 'Include extra file extension for pull (repeatable)', collectValues, [])\n .option('--include-folder <folder>', 'Include all files in folder for pull (repeatable)', collectValues, [])\n .action(async (first, second, options) => {\n // Handle --clear flag\n if (options.clear) {\n clearCurrentTenant();\n logger.success('Checkout cleared. You now need to specify tenant for each command.');\n return;\n }\n\n // If no arguments specified, show current checkout status\n if (!first) {\n const current = getCurrentCheckout();\n if (current) {\n if (current.organisation === current.tenant) {\n logger.info(`Currently checked out: ${chalk.bold(current.tenant)}`);\n } else {\n logger.info(\n `Currently checked out: ${chalk.bold(current.tenant)} (org: ${chalk.bold(current.organisation)})`,\n );\n }\n logger.dim('Run \"farseer checkout <tenant>\" to switch tenants.');\n logger.dim('Run \"farseer checkout --clear\" to clear checkout.');\n } else {\n logger.info('No tenant currently checked out.');\n logger.dim('Run \"farseer checkout <tenant>\" to set a default tenant.');\n logger.dim('Run \"farseer checkout <org> <tenant>\" if organisation and tenant differ.');\n }\n return;\n }\n\n // Determine organisation and tenant\n // If two arguments: first=organisation, second=tenant\n // If one argument: organisation=tenant=first\n const organisation = second ? first : first;\n const tenant = second || first;\n\n logger.info(`Checking out tenant: ${chalk.bold(tenant)} (org: ${chalk.bold(organisation)})...`);\n console.log();\n\n // Step 1: Verify authentication\n logger.info('Verifying authentication...');\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n\n if (!clientResult) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const authLabel = clientResult.authType === 'apiKey' ? 'API key' : 'browser login';\n logger.success(`Authenticated (using ${authLabel})`);\n\n // Step 2: Set as current checkout and save org-tenant mapping\n setCurrentCheckout(organisation, tenant);\n saveTenantOrgMapping(tenant, organisation);\n\n // Step 3: Auto-pull (unless --no-pull)\n if (options.pull) {\n console.log();\n logger.info('Pulling latest files and apps...');\n\n const syncService = new SyncService(tenant, clientResult.client);\n const tenantDir = getTenantDir(tenant);\n ensureDirectoryExists(tenantDir);\n\n try {\n // Ensure package.json exists\n const packageJsonPath = path.join(tenantDir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n createDefaultPackageJson(tenant, packageJsonPath);\n }\n\n // Pull files (scripts + includes by default)\n const includeExtensions = normalizeExtensions(options.includeExt);\n const includeFolders = options.includeFolder as string[];\n const result = await syncService.pull({\n all: false,\n includeExtensions: includeExtensions.length > 0 ? includeExtensions : undefined,\n includeFolders: includeFolders.length > 0 ? includeFolders : undefined,\n });\n logger.dim(\n `Files: +${result.downloaded.length} -${result.deleted.length} (${result.unchanged.length} unchanged)`,\n );\n\n // Pull apps\n const appSyncService = new AppSyncService(tenant, clientResult.client);\n const appResult = await appSyncService.pull();\n logger.dim(\n `Apps: +${appResult.created.length} ~${appResult.updated.length} -${appResult.deleted.length} (${appResult.unchanged.length} unchanged)`,\n );\n\n logger.success('Pull complete!');\n } catch (error) {\n logger.warning('Pull failed, but checkout is complete.');\n if (error instanceof Error) {\n logger.dim(error.message);\n }\n }\n }\n\n // Final message\n console.log();\n logger.success(`Tenant ${chalk.bold(tenant)} is now checked out.`);\n logger.dim('You can now run commands without specifying the tenant:');\n logger.dim(' farseer status');\n logger.dim(' farseer model --variables');\n logger.dim(' farseer apps');\n logger.dim(' farseer push');\n });\n}\n\nfunction createDefaultPackageJson(tenant: string, packageJsonPath: string): void {\n const packageJson = {\n name: `farseer-${tenant}`,\n version: '1.0.0',\n description: `Farseer scripts for ${tenant}`,\n type: 'module',\n scripts: {\n build: 'tsc',\n },\n dependencies: {\n 'farseer-client': FARSEER_CLIENT_URL,\n arquero: '^7.0.1',\n xlsx: '^0.18.5',\n xmldom: '^0.6.0',\n },\n devDependencies: {\n '@types/node': '^22.5.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,oBAAuB;AACvB,2BAKO;AACP,4B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BAAO,IAAI,MAAM,OAAO;AAAA,QAC5B;AAAA,MACJ;AAAA,IACJ;AAGA,YAAQ,IAAI;AACZ,yBAAO,QAAQ,UAAU,aAAAA,QAAM,KAAK,MAAM,CAAC,sBAAsB;AACjE,yBAAO,IAAI,yDAAyD;AACpE,yBAAO,IAAI,kBAAkB;AAC7B,yBAAO,IAAI,6BAA6B;AACxC,yBAAO,IAAI,gBAAgB;AAC3B,yBAAO,IAAI,gBAAgB;AAAA,EAC/B,CAAC;AACT;AAEA,SAAS,yBAAyB,QAAgB,iBAA+B;AAC7E,QAAM,cAAc;AAAA,IAChB,MAAM,WAAW,MAAM;AAAA,IACvB,SAAS;AAAA,IACT,aAAa,uBAAuB,MAAM;AAAA,IAC1C,MAAM;AAAA,IACN,SAAS;AAAA,MACL,OAAO;AAAA,IACX;AAAA,IACA,cAAc;AAAA,MACV,kBAAkB;AAAA,MAClB,SAAS;AAAA,MACT,MAAM;AAAA,MACN,QAAQ;AAAA,IACZ;AAAA,IACA,iBAAiB;AAAA,MACb,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,WAAW;AAAA,MACX,YAAY;AAAA,IAChB;AAAA,EACJ;AAEA,KAAG,cAAc,iBAAiB,KAAK,UAAU,aAAa,MAAM,CAAC,GAAG,OAAO;AAC/E,uBAAO,IAAI,4BAA4B,MAAM,EAAE;AACnD;",
|
|
6
6
|
"names": ["chalk"]
|
|
7
7
|
}
|
package/dist/commands/pull.js
CHANGED
|
@@ -42,6 +42,7 @@ var import_helpers = require("../utils/helpers");
|
|
|
42
42
|
var import_errorFormatter = require("../utils/errorFormatter");
|
|
43
43
|
var import_fileValidation = require("../utils/fileValidation");
|
|
44
44
|
var import_cliOptions = require("../utils/cliOptions");
|
|
45
|
+
var import_constants = require("../utils/constants");
|
|
45
46
|
var fs = __toESM(require("fs"));
|
|
46
47
|
var path = __toESM(require("path"));
|
|
47
48
|
function registerPullCommand(program) {
|
|
@@ -351,8 +352,8 @@ async function createDefaultPackageJson(tenantDir, tenant) {
|
|
|
351
352
|
dotenv: "^16.4.5",
|
|
352
353
|
"draft-js": "^0.11.7",
|
|
353
354
|
exceljs: "^4.4.0",
|
|
354
|
-
"farseer-client":
|
|
355
|
-
"farseer-client-axios":
|
|
355
|
+
"farseer-client": import_constants.FARSEER_CLIENT_URL,
|
|
356
|
+
"farseer-client-axios": import_constants.FARSEER_CLIENT_AXIOS_URL,
|
|
356
357
|
"fast-xml-parser": "^4.5.0",
|
|
357
358
|
"form-data": "^4.0.0",
|
|
358
359
|
googleapis: "^144.0.0",
|
|
@@ -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 * 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('--all', 'Pull all files (default: only scripts .ts, .js)')\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 (e.g. previously-pulled .csv on a default --force 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 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, not just the default-scope scripts.\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 (not just default scripts) to be wiped. Without it\n // getStatus filters down to .ts/.js and the wipe loop never sees\n // .csv/.xlsx/etc.\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':\n 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-1.4.5.tar',\n 'farseer-client-axios':\n 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar',\n 'fast-xml-parser': '^4.5.0',\n 'form-data': '^4.0.0',\n googleapis: '^144.0.0',\n heapdump: '^0.3.15',\n 'image-size': '^1.1.1',\n jszip: '^3.10.1',\n 'lossless-json': '^4.0.1',\n mssql: '^10.0.4',\n 'node-fetch': '^2.7.0',\n 'node-forge': '^1.3.1',\n 'node-sp-auth': '^3.0.8',\n numeral: '^2.0.6',\n oracledb: '^6.6.0',\n papaparse: '^5.5.1',\n pdfkit: '^0.14.0',\n pdfmake: '^0.2.20',\n soap: '^1.1.11',\n 'ssh2-sftp-client': '^11.0.0',\n 'strong-soap': '^4.1.13',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n undici: '^6.19.8',\n uuid: '^11.1.0',\n winston: '^3.17.0',\n xlsx: 'https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz',\n 'xml-crypto': '^6.1.2',\n },\n devDependencies: {\n '@types/draft-js': '^0.11.18',\n '@types/heapdump': '^0.3.4',\n '@types/mssql': '^9.1.5',\n '@types/node': '^18.19.50',\n '@types/node-fetch': '^2.6.11',\n '@types/numeral': '^2.0.5',\n '@types/oracledb': '^6.5.3',\n '@types/papaparse': '^5.3.15',\n '@types/pdfmake': '^0.2.11',\n '@types/soap': '^0.18.0',\n '@types/ssh2-sftp-client': '^9.0.4',\n '@types/tough-cookie': '^4.0.5',\n '@types/uuid': '^10.0.0',\n '@types/xmldom': '^0.1.34',\n 'ts-node': '^10.9.2',\n typescript: '^5.5.4',\n },\n };\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf-8');\n logger.dim(`Created package.json for ${tenant}`);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,sBAAqB;AACrB,oBAAuB;AACvB,wBAA2B;AAC3B,4BAA8D;AAC9D,yBAA6D;AAC7D,4BAA+B;AAC/B,qBAQO;AACP,4BAAkC;AAClC,4BAAiC;AACjC,wBAAmD;AACnD,SAAoB;AACpB,WAAsB;AAkBf,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC,OAAO,SAAS,iDAAiD,EACjE;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,aAAa,8EAA8E,EAClG,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,oDAA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A,eAAe,yBAAyB,WAAmB,QAA+B;AACtF,QAAM,kBAAkB,KAAK,KAAK,WAAW,cAAc;AAE3D,MAAI,GAAG,WAAW,eAAe,GAAG;AAChC;AAAA,EACJ;AAEA,QAAM,cAAc;AAAA,IAChB,MAAM,mBAAmB,MAAM;AAAA,IAC/B,SAAS;AAAA,IACT,aAAa,2BAA2B,MAAM;AAAA,IAC9C,MAAM;AAAA,IACN,SAAS,CAAC;AAAA,IACV,UAAU,CAAC,WAAW,WAAW,MAAM;AAAA,IACvC,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,cAAc;AAAA,MACV,0BAA0B;AAAA,MAC1B,yBAAyB;AAAA,MACzB,sBAAsB;AAAA,MACtB,kBAAkB;AAAA,MAClB,qBAAqB;AAAA,MACrB,kBAAkB;AAAA,MAClB,SAAS;AAAA,MACT,OAAO;AAAA,MACP,eAAe;AAAA,MACf,aAAa;AAAA,MACb,iBAAiB;AAAA,MACjB,cAAc;AAAA,MACd,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,SAAS;AAAA,MACT,
|
|
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 * 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('--all', 'Pull all files (default: only scripts .ts, .js)')\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 (e.g. previously-pulled .csv on a default --force 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 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, not just the default-scope scripts.\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 (not just default scripts) to be wiped. Without it\n // getStatus filters down to .ts/.js and the wipe loop never sees\n // .csv/.xlsx/etc.\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,SAAoB;AACpB,WAAsB;AAkBf,SAAS,oBAAoB,SAAwB;AACxD,UACK,QAAQ,qBAAqB,EAC7B;AAAA,IACG;AAAA,EACJ,EACC,OAAO,SAAS,iDAAiD,EACjE;AAAA,IACG;AAAA,IACA;AAAA,EACJ,EACC,OAAO,aAAa,8EAA8E,EAClG,OAAO,uBAAuB,6CAA6C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AW;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;",
|
|
6
6
|
"names": ["chalk", "inquirer"]
|
|
7
7
|
}
|
package/dist/utils/constants.js
CHANGED
|
@@ -31,6 +31,7 @@ __export(constants_exports, {
|
|
|
31
31
|
CLI_VERSION: () => CLI_VERSION,
|
|
32
32
|
FARSEER_CLIENT_AXIOS_URL: () => FARSEER_CLIENT_AXIOS_URL,
|
|
33
33
|
FARSEER_CLIENT_URL: () => FARSEER_CLIENT_URL,
|
|
34
|
+
FARSEER_CLIENT_VERSION: () => FARSEER_CLIENT_VERSION,
|
|
34
35
|
SCRIPTS_FOLDER_PATH: () => SCRIPTS_FOLDER_PATH,
|
|
35
36
|
SCRIPT_EXTENSIONS: () => SCRIPT_EXTENSIONS
|
|
36
37
|
});
|
|
@@ -39,7 +40,8 @@ var import_fs = __toESM(require("fs"));
|
|
|
39
40
|
var import_path = __toESM(require("path"));
|
|
40
41
|
const packageJson = JSON.parse(import_fs.default.readFileSync(import_path.default.join(__dirname, "../../package.json"), "utf-8"));
|
|
41
42
|
const CLI_VERSION = packageJson.version;
|
|
42
|
-
const
|
|
43
|
+
const FARSEER_CLIENT_VERSION = "1.8.11";
|
|
44
|
+
const FARSEER_CLIENT_URL = `https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-${FARSEER_CLIENT_VERSION}.tar`;
|
|
43
45
|
const FARSEER_CLIENT_AXIOS_URL = "https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar";
|
|
44
46
|
const SCRIPTS_FOLDER_PATH = ["Files", "Scripts"];
|
|
45
47
|
const SCRIPT_EXTENSIONS = [".ts", ".js", ".mjs", ".cjs"];
|
|
@@ -48,6 +50,7 @@ const SCRIPT_EXTENSIONS = [".ts", ".js", ".mjs", ".cjs"];
|
|
|
48
50
|
CLI_VERSION,
|
|
49
51
|
FARSEER_CLIENT_AXIOS_URL,
|
|
50
52
|
FARSEER_CLIENT_URL,
|
|
53
|
+
FARSEER_CLIENT_VERSION,
|
|
51
54
|
SCRIPTS_FOLDER_PATH,
|
|
52
55
|
SCRIPT_EXTENSIONS
|
|
53
56
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/constants.ts"],
|
|
4
|
-
"sourcesContent": ["// CLI version - read dynamically from package.json\nimport fs from 'fs';\nimport path from 'path';\n\nconst packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf-8'));\nexport const CLI_VERSION: string = packageJson.version;\n\n// Farseer client package
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,gBAAe;AACf,kBAAiB;AAEjB,MAAM,cAAc,KAAK,MAAM,UAAAA,QAAG,aAAa,YAAAC,QAAK,KAAK,WAAW,oBAAoB,GAAG,OAAO,CAAC;AAC5F,MAAM,cAAsB,YAAY;
|
|
4
|
+
"sourcesContent": ["// CLI version - read dynamically from package.json\nimport fs from 'fs';\nimport path from 'path';\n\nconst packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf-8'));\nexport const CLI_VERSION: string = packageJson.version;\n\n// Farseer client version consumed by tenant package.json files the CLI\n// generates. The matching tarball is mirrored to public GCS by\n// clients/cloudbuild.yaml on every clients-v* release tag.\nexport const FARSEER_CLIENT_VERSION = '1.8.11';\nexport const FARSEER_CLIENT_URL = `https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client/release-${FARSEER_CLIENT_VERSION}.tar`;\nexport const FARSEER_CLIENT_AXIOS_URL =\n 'https://storage.googleapis.com/farseer-remote-jobs-results/farseer-client-axios/6898c0cb-5dca-4b2f-b325-119efc7f099e/v1.0.1.tar';\n\n// Default paths\nexport const SCRIPTS_FOLDER_PATH = ['Files', 'Scripts'];\n\n// Supported script file extensions\nexport const SCRIPT_EXTENSIONS = ['.ts', '.js', '.mjs', '.cjs'];\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,gBAAe;AACf,kBAAiB;AAEjB,MAAM,cAAc,KAAK,MAAM,UAAAA,QAAG,aAAa,YAAAC,QAAK,KAAK,WAAW,oBAAoB,GAAG,OAAO,CAAC;AAC5F,MAAM,cAAsB,YAAY;AAKxC,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB,qFAAqF,sBAAsB;AACtI,MAAM,2BACT;AAGG,MAAM,sBAAsB,CAAC,SAAS,SAAS;AAG/C,MAAM,oBAAoB,CAAC,OAAO,OAAO,QAAQ,MAAM;",
|
|
6
6
|
"names": ["fs", "path"]
|
|
7
7
|
}
|
|
@@ -105,7 +105,7 @@ function hasUnresolvedConflictMarkers(content) {
|
|
|
105
105
|
function getBackendExtension(fileName) {
|
|
106
106
|
const base = path.basename(fileName);
|
|
107
107
|
const parts = base.split(".");
|
|
108
|
-
return parts[parts.length - 1];
|
|
108
|
+
return parts[parts.length - 1].toLowerCase();
|
|
109
109
|
}
|
|
110
110
|
function isExtensionAllowed(fileName) {
|
|
111
111
|
return BACKEND_EXTENSION_WHITELIST.has(getBackendExtension(fileName));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/fileValidation.ts"],
|
|
4
|
-
"sourcesContent": ["import * as path from 'path';\n\n/**\n * Pre-flight validation that mirrors the backend's Farseer Files rules so the\n * CLI can refuse a doomed upload locally \u2014 with an actionable message \u2014\n * instead of letting the user see a cryptic `HTTP 400 {\"code\":\"BadRequest\"}`\n * coming back from the API after the request is already in flight.\n *\n * Source of truth on the backend:\n * - Extension whitelist:\n * `backend/app/openapi/v3/services/farseerFileService.ts`\n * (FILE_EXTENSION_WHITELIST static + validateFileExtension())\n * - Name length: `backend/app/openapi/util/itemNodeNameUtil.ts`\n * (MAX_NAME_SIZE = 256, trim, non-empty)\n *\n * Keep this list in lockstep with the backend. If the backend adds an\n * extension, add it here so users stop seeing \"File type not allowed\" for\n * something that is actually allowed.\n */\n\nexport const BACKEND_EXTENSION_WHITELIST: ReadonlySet<string> = new Set([\n // Office / spreadsheets\n 'xls',\n 'xlsx',\n 'csv',\n 'pdf',\n // Code (frontend / scripts)\n 'js',\n 'jsx',\n 'ts',\n 'tsx',\n // Code (Python)\n 'py',\n // Markup / config / data\n 'xml',\n 'json',\n 'yaml',\n 'yml',\n 'html',\n 'css',\n 'scss',\n 'md',\n 'txt',\n // Images\n 'jpg',\n 'jpeg',\n 'png',\n 'gif',\n 'webp',\n // Archives\n 'zip',\n]);\n\nexport const MAX_FILE_NAME_LENGTH = 256;\n\nexport interface ValidationFailure {\n filePath: string;\n reason: 'extension_not_allowed' | 'name_empty' | 'name_too_long' | 'empty_content' | 'unresolved_conflict_markers';\n detail: string;\n hint?: string;\n}\n\n/**\n * Detect git-style conflict markers left over from an unresolved\n * `merge_markers` pull. Pushing a file with these markers would upload\n * broken syntax to the backend (the file wouldn't compile / parse). The\n * patterns intentionally match the exact strings the CLI writes\n * (syncService.ts: MERGE_MARKER_*) so we don't false-positive on user\n * code that happens to contain `<<<<<<<` in some other context.\n *\n * We refuse on EITHER unique sentinel \u2014 the earlier \"require both\n * LOCAL and REMOTE\" gate let a partially-resolved file slip through\n * (user deleted only one half of the block). The `=======` separator\n * is intentionally NOT included: bare `=======` lines are common in\n * RST headings and ASCII tables, so flagging them would false-positive\n * on legitimate text content.\n */\nconst CONFLICT_MARKER_LOCAL = /^<<<<<<< LOCAL \\(your version\\)$/m;\nconst CONFLICT_MARKER_REMOTE = /^>>>>>>> REMOTE$/m;\n\n/**\n * Best-effort check for \"is this file content text we can safely splice\n * git-style merge markers into?\". Used to gate the `merge_markers`\n * conflict resolution: writing markers into a .png / .xlsx / .zip\n * corrupts the binary, and the .toString('utf-8') round-trip used by\n * the merge logic flips bytes silently.\n *\n * Two-step check:\n * 1. File extension allowlist \u2014 fast path, deterministic.\n * 2. Null-byte heuristic on the content \u2014 covers misnamed files\n * and unknown extensions.\n *\n * False negatives (binary that passes both checks) just write garbage\n * markers; push pre-flight then refuses to upload because the marker\n * pattern is mangled. False positives (text that trips null-byte) just\n * mean the user gets the keep_both fallback \u2014 annoying but safe.\n */\n// Symmetrical with BACKEND_EXTENSION_WHITELIST: only formats the user\n// can actually push end up here. .mjs / .cjs are technically text but\n// they're not on the backend whitelist (and not in DEFAULT_SCRIPT_EXTENSIONS),\n// so offering merge_markers for them would lead the user through a manual\n// resolve only to hit pre-flight rejection on push. Drop them to match\n// the pre-flight's reality.\nconst KNOWN_TEXT_EXTENSIONS: ReadonlySet<string> = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.html',\n '.css',\n '.scss',\n '.yaml',\n '.yml',\n '.xml',\n '.py',\n '.csv',\n]);\n\nexport function isLikelyTextFile(filePath: string, content?: Buffer): boolean {\n const ext = path.extname(filePath).toLowerCase();\n if (KNOWN_TEXT_EXTENSIONS.has(ext)) return true;\n if (!content) return false;\n // Sample first 8KB for a NUL byte. Binary formats (PDF, PNG, ZIP,\n // XLSX, \u2026) have one almost immediately; text files practically never.\n const slice = content.subarray(0, 8 * 1024);\n return !slice.includes(0);\n}\n\nexport function hasUnresolvedConflictMarkers(content: string | Buffer): boolean {\n const text = Buffer.isBuffer(content) ? content.toString('utf-8') : content;\n // OR (not AND) across the unique sentinels: a half-resolved file where\n // the user kept only the LOCAL or REMOTE marker still uploads broken\n // text. The `=======` separator is omitted on purpose \u2014 RST headings\n // and ASCII tables use bare `=======` lines and would false-positive.\n return CONFLICT_MARKER_LOCAL.test(text) || CONFLICT_MARKER_REMOTE.test(text);\n}\n\n/**\n * Same algorithm the backend uses (`tail(name.split('.'))`): split on `.`\n * and take the last segment. This means:\n * - `foo.ts` \u2192 `ts`\n * -
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAsB;AAoBf,MAAM,8BAAmD,oBAAI,IAAI;AAAA;AAAA,EAEpE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACJ,CAAC;AAEM,MAAM,uBAAuB;AAwBpC,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAyB/B,MAAM,wBAA6C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAEM,SAAS,iBAAiB,UAAkB,SAA2B;AAC1E,QAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAC/C,MAAI,sBAAsB,IAAI,GAAG,EAAG,QAAO;AAC3C,MAAI,CAAC,QAAS,QAAO;AAGrB,QAAM,QAAQ,QAAQ,SAAS,GAAG,IAAI,IAAI;AAC1C,SAAO,CAAC,MAAM,SAAS,CAAC;AAC5B;AAEO,SAAS,6BAA6B,SAAmC;AAC5E,QAAM,OAAO,OAAO,SAAS,OAAO,IAAI,QAAQ,SAAS,OAAO,IAAI;AAKpE,SAAO,sBAAsB,KAAK,IAAI,KAAK,uBAAuB,KAAK,IAAI;AAC/E;
|
|
4
|
+
"sourcesContent": ["import * as path from 'path';\n\n/**\n * Pre-flight validation that mirrors the backend's Farseer Files rules so the\n * CLI can refuse a doomed upload locally \u2014 with an actionable message \u2014\n * instead of letting the user see a cryptic `HTTP 400 {\"code\":\"BadRequest\"}`\n * coming back from the API after the request is already in flight.\n *\n * Source of truth on the backend:\n * - Extension whitelist:\n * `backend/app/openapi/v3/services/farseerFileService.ts`\n * (FILE_EXTENSION_WHITELIST static + validateFileExtension())\n * - Name length: `backend/app/openapi/util/itemNodeNameUtil.ts`\n * (MAX_NAME_SIZE = 256, trim, non-empty)\n *\n * Keep this list in lockstep with the backend. If the backend adds an\n * extension, add it here so users stop seeing \"File type not allowed\" for\n * something that is actually allowed.\n */\n\nexport const BACKEND_EXTENSION_WHITELIST: ReadonlySet<string> = new Set([\n // Office / spreadsheets\n 'xls',\n 'xlsx',\n 'csv',\n 'pdf',\n // Code (frontend / scripts)\n 'js',\n 'jsx',\n 'ts',\n 'tsx',\n // Code (Python)\n 'py',\n // Markup / config / data\n 'xml',\n 'json',\n 'yaml',\n 'yml',\n 'html',\n 'css',\n 'scss',\n 'md',\n 'txt',\n // Images\n 'jpg',\n 'jpeg',\n 'png',\n 'gif',\n 'webp',\n // Archives\n 'zip',\n]);\n\nexport const MAX_FILE_NAME_LENGTH = 256;\n\nexport interface ValidationFailure {\n filePath: string;\n reason: 'extension_not_allowed' | 'name_empty' | 'name_too_long' | 'empty_content' | 'unresolved_conflict_markers';\n detail: string;\n hint?: string;\n}\n\n/**\n * Detect git-style conflict markers left over from an unresolved\n * `merge_markers` pull. Pushing a file with these markers would upload\n * broken syntax to the backend (the file wouldn't compile / parse). The\n * patterns intentionally match the exact strings the CLI writes\n * (syncService.ts: MERGE_MARKER_*) so we don't false-positive on user\n * code that happens to contain `<<<<<<<` in some other context.\n *\n * We refuse on EITHER unique sentinel \u2014 the earlier \"require both\n * LOCAL and REMOTE\" gate let a partially-resolved file slip through\n * (user deleted only one half of the block). The `=======` separator\n * is intentionally NOT included: bare `=======` lines are common in\n * RST headings and ASCII tables, so flagging them would false-positive\n * on legitimate text content.\n */\nconst CONFLICT_MARKER_LOCAL = /^<<<<<<< LOCAL \\(your version\\)$/m;\nconst CONFLICT_MARKER_REMOTE = /^>>>>>>> REMOTE$/m;\n\n/**\n * Best-effort check for \"is this file content text we can safely splice\n * git-style merge markers into?\". Used to gate the `merge_markers`\n * conflict resolution: writing markers into a .png / .xlsx / .zip\n * corrupts the binary, and the .toString('utf-8') round-trip used by\n * the merge logic flips bytes silently.\n *\n * Two-step check:\n * 1. File extension allowlist \u2014 fast path, deterministic.\n * 2. Null-byte heuristic on the content \u2014 covers misnamed files\n * and unknown extensions.\n *\n * False negatives (binary that passes both checks) just write garbage\n * markers; push pre-flight then refuses to upload because the marker\n * pattern is mangled. False positives (text that trips null-byte) just\n * mean the user gets the keep_both fallback \u2014 annoying but safe.\n */\n// Symmetrical with BACKEND_EXTENSION_WHITELIST: only formats the user\n// can actually push end up here. .mjs / .cjs are technically text but\n// they're not on the backend whitelist (and not in DEFAULT_SCRIPT_EXTENSIONS),\n// so offering merge_markers for them would lead the user through a manual\n// resolve only to hit pre-flight rejection on push. Drop them to match\n// the pre-flight's reality.\nconst KNOWN_TEXT_EXTENSIONS: ReadonlySet<string> = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.html',\n '.css',\n '.scss',\n '.yaml',\n '.yml',\n '.xml',\n '.py',\n '.csv',\n]);\n\nexport function isLikelyTextFile(filePath: string, content?: Buffer): boolean {\n const ext = path.extname(filePath).toLowerCase();\n if (KNOWN_TEXT_EXTENSIONS.has(ext)) return true;\n if (!content) return false;\n // Sample first 8KB for a NUL byte. Binary formats (PDF, PNG, ZIP,\n // XLSX, \u2026) have one almost immediately; text files practically never.\n const slice = content.subarray(0, 8 * 1024);\n return !slice.includes(0);\n}\n\nexport function hasUnresolvedConflictMarkers(content: string | Buffer): boolean {\n const text = Buffer.isBuffer(content) ? content.toString('utf-8') : content;\n // OR (not AND) across the unique sentinels: a half-resolved file where\n // the user kept only the LOCAL or REMOTE marker still uploads broken\n // text. The `=======` separator is omitted on purpose \u2014 RST headings\n // and ASCII tables use bare `=======` lines and would false-positive.\n return CONFLICT_MARKER_LOCAL.test(text) || CONFLICT_MARKER_REMOTE.test(text);\n}\n\n/**\n * Same algorithm the backend uses (`tail(name.split('.'))`): split on `.`\n * and take the last segment, lowercased. This means:\n * - `foo.ts` \u2192 `ts`\n * - `Foo.TS` \u2192 `ts` (case-insensitive \u2014 backend folds case before lookup)\n * - `.gitignore` \u2192 `gitignore` (rejected, not in whitelist)\n * - `Makefile` \u2192 `makefile` (rejected \u2014 no `.`, returns the basename lowercased)\n * - `archive.tar.gz` \u2192 `gz` (rejected)\n */\nexport function getBackendExtension(fileName: string): string {\n const base = path.basename(fileName);\n const parts = base.split('.');\n return parts[parts.length - 1].toLowerCase();\n}\n\nexport function isExtensionAllowed(fileName: string): boolean {\n return BACKEND_EXTENSION_WHITELIST.has(getBackendExtension(fileName));\n}\n\nexport interface ValidatedFile {\n filePath: string;\n size: number;\n /**\n * Optional file content. When provided, the validator additionally\n * checks for unresolved git-style conflict markers (left behind by a\n * `merge_markers` pull resolution that the user hasn't cleaned up).\n * Push pre-flight passes content; tests/abstract callers can omit it.\n */\n content?: Buffer;\n}\n\n/**\n * Validate a single file the CLI is about to upload. Returns null when the\n * file would pass the backend's create/update validation, otherwise a\n * `ValidationFailure` describing the rule that would reject it.\n *\n * `size` is required so we can also flag empty files: the backend's\n * multipart parser tends to surface a content-less request as the cryptic\n * `{\"code\":\"BadRequest\"}` body that field reports point to.\n */\nexport function validateFileForUpload(file: ValidatedFile): ValidationFailure | null {\n const baseName = path.basename(file.filePath);\n const trimmed = baseName.trim();\n\n if (trimmed.length === 0) {\n return {\n filePath: file.filePath,\n reason: 'name_empty',\n detail: 'Filename is empty after trimming whitespace',\n hint: 'Rename the file to a non-empty name before pushing.',\n };\n }\n\n if (trimmed.length > MAX_FILE_NAME_LENGTH) {\n return {\n filePath: file.filePath,\n reason: 'name_too_long',\n detail: `Filename is ${trimmed.length} characters; backend rejects names longer than ${MAX_FILE_NAME_LENGTH}`,\n hint: 'Shorten the filename and try again.',\n };\n }\n\n if (!isExtensionAllowed(baseName)) {\n const ext = getBackendExtension(baseName);\n return {\n filePath: file.filePath,\n reason: 'extension_not_allowed',\n detail: `Extension \".${ext}\" is not in the backend whitelist`,\n hint: `Allowed: ${[...BACKEND_EXTENSION_WHITELIST]\n .map((e) => '.' + e)\n .sort()\n .join(', ')}`,\n };\n }\n\n if (file.size === 0) {\n return {\n filePath: file.filePath,\n reason: 'empty_content',\n detail: 'File is empty (0 bytes)',\n hint: 'Empty files often come back as opaque \"BadRequest\" from the upload endpoint. Add at least one byte before pushing.',\n };\n }\n\n if (file.content && hasUnresolvedConflictMarkers(file.content)) {\n return {\n filePath: file.filePath,\n reason: 'unresolved_conflict_markers',\n detail: 'File contains unresolved git-style conflict markers (<<<<<<< LOCAL / ======= / >>>>>>> REMOTE)',\n hint: \"Open the file, pick which version to keep, remove the marker lines, then 'farseer push' again.\",\n };\n }\n\n return null;\n}\n\n/**\n * Validate a batch and split into pushable + rejected. The push command uses\n * this to render a single grouped message (\"4 file(s) skipped: \u2026\") and exit\n * cleanly without sending any request that we know will fail.\n */\nexport function partitionForUpload(files: ValidatedFile[]): {\n valid: ValidatedFile[];\n rejected: ValidationFailure[];\n} {\n const valid: ValidatedFile[] = [];\n const rejected: ValidationFailure[] = [];\n for (const file of files) {\n const failure = validateFileForUpload(file);\n if (failure) rejected.push(failure);\n else valid.push(file);\n }\n return { valid, rejected };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAsB;AAoBf,MAAM,8BAAmD,oBAAI,IAAI;AAAA;AAAA,EAEpE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACJ,CAAC;AAEM,MAAM,uBAAuB;AAwBpC,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAyB/B,MAAM,wBAA6C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAEM,SAAS,iBAAiB,UAAkB,SAA2B;AAC1E,QAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAC/C,MAAI,sBAAsB,IAAI,GAAG,EAAG,QAAO;AAC3C,MAAI,CAA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B;AAAA,EACJ;AAEA,MAAI,KAAK,SAAS,GAAG;AACjB,WAAO;AAAA,MACH,UAAU,KAAK;AAAA,MACf,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,MAAM;AAAA,IACV;AAAA,EACJ;AAEA,MAAI,KAAK,WAAW,6BAA6B,KAAK,OAAO,GAAG;AAC5D,WAAO;AAAA,MACH,UAAU,KAAK;AAAA,MACf,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,MAAM;AAAA,IACV;AAAA,EACJ;AAEA,SAAO;AACX;AAOO,SAAS,mBAAmB,OAGjC;AACE,QAAM,QAAyB,CAAC;AAChC,QAAM,WAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACtB,UAAM,UAAU,sBAAsB,IAAI;AAC1C,QAAI,QAAS,UAAS,KAAK,OAAO;AAAA,QAC7B,OAAM,KAAK,IAAI;AAAA,EACxB;AACA,SAAO,EAAE,OAAO,SAAS;AAC7B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -28,14 +28,14 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
28
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
29
|
var packageManager_exports = {};
|
|
30
30
|
__export(packageManager_exports, {
|
|
31
|
-
FARSEER_CLIENT_URL: () => FARSEER_CLIENT_URL,
|
|
31
|
+
FARSEER_CLIENT_URL: () => import_constants.FARSEER_CLIENT_URL,
|
|
32
32
|
ensurePackageJson: () => ensurePackageJson,
|
|
33
33
|
parsePackageSpec: () => parsePackageSpec
|
|
34
34
|
});
|
|
35
35
|
module.exports = __toCommonJS(packageManager_exports);
|
|
36
36
|
var fs = __toESM(require("fs"));
|
|
37
37
|
var path = __toESM(require("path"));
|
|
38
|
-
|
|
38
|
+
var import_constants = require("./constants");
|
|
39
39
|
function ensurePackageJson(tenantDir, tenant) {
|
|
40
40
|
const packageJsonPath = path.join(tenantDir, "package.json");
|
|
41
41
|
const addedPackages = [];
|
|
@@ -54,7 +54,7 @@ function ensurePackageJson(tenantDir, tenant) {
|
|
|
54
54
|
}
|
|
55
55
|
pkg.dependencies = pkg.dependencies || {};
|
|
56
56
|
if (!pkg.dependencies["farseer-client"]) {
|
|
57
|
-
pkg.dependencies["farseer-client"] = FARSEER_CLIENT_URL;
|
|
57
|
+
pkg.dependencies["farseer-client"] = import_constants.FARSEER_CLIENT_URL;
|
|
58
58
|
addedPackages.push("farseer-client");
|
|
59
59
|
}
|
|
60
60
|
fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + "\n");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/packageManager.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Package Manager Utilities\n *\n * Shared logic for managing tenant package.json files and farseer-client dependency.\n * Used by both CLI install command and MCP farseer_install tool.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,SAAoB;AACpB,WAAsB;
|
|
4
|
+
"sourcesContent": ["/**\n * Package Manager Utilities\n *\n * Shared logic for managing tenant package.json files and farseer-client dependency.\n * Used by both CLI install command and MCP farseer_install tool.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { FARSEER_CLIENT_URL } from './constants';\n\nexport { FARSEER_CLIENT_URL };\n\n/**\n * Ensure the tenant directory has a package.json with farseer-client.\n * Creates package.json if it doesn't exist, adds farseer-client if missing.\n * Returns list of packages that were added.\n */\nexport function ensurePackageJson(tenantDir: string, tenant: string): string[] {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const addedPackages: string[] = [];\n\n let pkg: any;\n if (fs.existsSync(packageJsonPath)) {\n pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n } else {\n pkg = {\n name: `farseer-apps-${tenant}`,\n version: '1.0.0',\n private: true,\n description: `Farseer scripts for tenant ${tenant}`,\n dependencies: {},\n };\n addedPackages.push('package.json (created)');\n }\n\n pkg.dependencies = pkg.dependencies || {};\n\n if (!pkg.dependencies['farseer-client']) {\n pkg.dependencies['farseer-client'] = FARSEER_CLIENT_URL;\n addedPackages.push('farseer-client');\n }\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n return addedPackages;\n}\n\n/**\n * Parse an npm package specifier into name and version.\n * Handles scoped packages: @scope/name@version \u2192 { name: \"@scope/name\", version: \"version\" }\n */\nexport function parsePackageSpec(spec: string): { name: string; version: string } {\n const isScoped = spec.startsWith('@');\n const lastAt = spec.lastIndexOf('@');\n const hasVersion = lastAt > 0 && (!isScoped || lastAt > spec.indexOf('/'));\n\n return {\n name: hasVersion ? spec.substring(0, lastAt) : spec,\n version: hasVersion ? spec.substring(lastAt + 1) : '*',\n };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,SAAoB;AACpB,WAAsB;AACtB,uBAAmC;AAS5B,SAAS,kBAAkB,WAAmB,QAA0B;AAC3E,QAAM,kBAAkB,KAAK,KAAK,WAAW,cAAc;AAC3D,QAAM,gBAA0B,CAAC;AAEjC,MAAI;AACJ,MAAI,GAAG,WAAW,eAAe,GAAG;AAChC,UAAM,KAAK,MAAM,GAAG,aAAa,iBAAiB,OAAO,CAAC;AAAA,EAC9D,OAAO;AACH,UAAM;AAAA,MACF,MAAM,gBAAgB,MAAM;AAAA,MAC5B,SAAS;AAAA,MACT,SAAS;AAAA,MACT,aAAa,8BAA8B,MAAM;AAAA,MACjD,cAAc,CAAC;AAAA,IACnB;AACA,kBAAc,KAAK,wBAAwB;AAAA,EAC/C;AAEA,MAAI,eAAe,IAAI,gBAAgB,CAAC;AAExC,MAAI,CAAC,IAAI,aAAa,gBAAgB,GAAG;AACrC,QAAI,aAAa,gBAAgB,IAAI;AACrC,kBAAc,KAAK,gBAAgB;AAAA,EACvC;AAEA,KAAG,cAAc,iBAAiB,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,IAAI;AACrE,SAAO;AACX;AAMO,SAAS,iBAAiB,MAAiD;AAC9E,QAAM,WAAW,KAAK,WAAW,GAAG;AACpC,QAAM,SAAS,KAAK,YAAY,GAAG;AACnC,QAAM,aAAa,SAAS,MAAM,CAAC,YAAY,SAAS,KAAK,QAAQ,GAAG;AAExE,SAAO;AAAA,IACH,MAAM,aAAa,KAAK,UAAU,GAAG,MAAM,IAAI;AAAA,IAC/C,SAAS,aAAa,KAAK,UAAU,SAAS,CAAC,IAAI;AAAA,EACvD;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|