farseer-cli 1.5.0 → 1.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/commands/app.js +10 -2
- package/dist/commands/app.js.map +2 -2
- 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/commands/push.js +21 -4
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/run.js +2 -2
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/status.js +7 -4
- package/dist/commands/status.js.map +2 -2
- package/dist/mcp/tools/appTools.js +22 -8
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +2 -2
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/services/appSyncService.js +27 -12
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/farseerApi.js.map +2 -2
- package/dist/services/syncService.js +7 -2
- package/dist/services/syncService.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/helpers.js +18 -2
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/packageManager.js +3 -3
- package/dist/utils/packageManager.js.map +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/syncService.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { IFarseerClient, RemoteFile, DEFAULT_SCRIPT_EXTENSIONS } from './farseerFactory';\nimport { getSyncIncludes } from './configService';\nimport {\n calculateHash,\n getTenantFilesDir,\n getSyncFilePath,\n ensureDirectoryExists,\n getAllFilesInDir,\n fetchWithConcurrency,\n isHiddenFile,\n isOsMetadataFile,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { ValidationFailure, partitionForUpload, isLikelyTextFile } from '../utils/fileValidation';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Re-export so existing test imports (`from '../../src/services/syncService'`)\n// keep working \u2014 `isOsMetadataFile` moved to utils/helpers.ts so the file\n// listing helper can apply it as the default filter.\nexport { isOsMetadataFile, isHiddenFile } from '../utils/helpers';\n\nexport interface SyncOptions {\n all?: boolean;\n force?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n conflictResolutions?: ConflictResolutions;\n}\n\n/**\n * Determines if a file should be included in sync operations.\n *\n * Exclusion rules (run before any include rule):\n * - OS metadata (.DS_Store, Thumbs.db, ._foo, \u2026) \u2014 never synced.\n * - Hidden files / folders (any path segment starting with `.` \u2014 e.g.\n * .env, .git/, .vscode/) \u2014 synced only when explicitly listed in\n * `--include-ext` / `--include-folder` / persistent sync-includes\n * config. `--all` does NOT include them; the explicit-include path\n * is the single way to consent to syncing a credential / config /\n * VCS file.\n *\n * Inclusion rules (file must satisfy at least one):\n * 1. `--all` flag is passed (only for non-hidden files).\n * 2. Has a default script extension (.ts, .js).\n * 3. Has an extension from inline includeExtensions option.\n * 4. Lives under a folder from inline includeFolders option.\n * 5. Has an extension from persistent syncIncludes config.\n * 6. Lives under a folder from persistent syncIncludes config.\n */\nexport function shouldIncludeFile(\n filePath: string,\n tenant: string,\n options?: Pick<SyncOptions, 'all' | 'includeExtensions' | 'includeFolders'>,\n): boolean {\n // OS metadata is always excluded \u2014 `--all` should sync the user's work,\n // not their filesystem's bookkeeping.\n if (isOsMetadataFile(filePath)) return false;\n\n const ext = path.extname(filePath).toLowerCase();\n const persistent = getSyncIncludes(tenant);\n\n const matchesIncludes =\n (options?.includeExtensions?.includes(ext) ?? false) ||\n (options?.includeFolders?.some((f) => filePath.startsWith(f + '/') || filePath === f) ?? false) ||\n (persistent?.extensions?.includes(ext) ?? false) ||\n (persistent?.folders?.some((f) => filePath.startsWith(f + '/') || filePath === f) ?? false);\n\n // Hidden files (.env, .git, .vscode, \u2026) require explicit opt-in even\n // under --all. This stops a stray credential file in the working tree\n // from leaking on a force push. Users that genuinely want to sync a\n // hidden file add it via `--include-ext` / `--include-folder` or the\n // persistent `farseer config include` config.\n if (isHiddenFile(filePath)) return matchesIncludes;\n\n if (options?.all) return true;\n if (DEFAULT_SCRIPT_EXTENSIONS.includes(ext)) return true;\n return matchesIncludes;\n}\n\nexport interface SyncFileInfo {\n localHash: string;\n remoteHash: string;\n metadata?: {\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n lastFetched?: string;\n };\n}\n\nexport interface SyncState {\n lastSync: string;\n files: Record<string, SyncFileInfo>;\n}\n\n/**\n * A single status snapshot produced by `getStatus()`. Both `farseer status`\n * (preview) and `farseer push` (preflight) use this shape so the user sees\n * the same buckets in both commands.\n *\n * The legacy two-bucket layout (`modifiedLocally` / `modifiedRemotely`)\n * silently lumped deletions in with edits, which was the single biggest\n * source of \"why does status say M for a file that's actually deleted?\"\n * confusion. This shape splits the six combinatoric outcomes into their\n * own buckets and keeps `modifiedLocally` / `modifiedRemotely` as\n * derived aliases for back-compat with code that still reads them.\n */\nexport interface SyncStatus {\n addedLocally: string[];\n modifiedLocally: string[];\n deletedLocally: string[];\n addedRemotely: string[];\n modifiedRemotely: string[];\n deletedRemotely: string[];\n inSync: string[];\n conflicts: SyncConflict[];\n /**\n * True when the status was computed without fetching remote file\n * content. In `deep: false` mode the comparator can detect adds /\n * deletes / *local* modifications, but cannot distinguish a\n * remote-modified file from an in-sync one because that requires\n * downloading and hashing the remote content. Treat this flag as\n * \"remote-edit detection skipped\" rather than \"everything checked\".\n */\n deepCompare: boolean;\n /**\n * Real remote-content hashes keyed by file path. Only populated when\n * `deep: true` ran (the listing-only fast mode never downloads bytes).\n * Exposed so a follow-up `push({ precomputedRemoteHashes })` can skip\n * its own re-download for files already covered here \u2014 under\n * `push --force --mirror` these two operations would otherwise both\n * fetch the same set of remote contents back-to-back.\n */\n remoteHashes?: Map<string, string>;\n}\n\nexport interface GetStatusOptions extends SyncOptions {\n /**\n * When true, fetch and hash every remote file's content so we can\n * detect remote-side content edits made by other users. Slow on big\n * tenants. Default: false (list-only).\n */\n deep?: boolean;\n}\n\nfunction emptyStatus(deepCompare: boolean): SyncStatus {\n return {\n addedLocally: [],\n modifiedLocally: [],\n deletedLocally: [],\n addedRemotely: [],\n modifiedRemotely: [],\n deletedRemotely: [],\n inSync: [],\n conflicts: [],\n deepCompare,\n };\n}\n\n// Three-way comparison types\n\nexport type FileChangeType =\n | 'unchanged'\n | 'local_modified'\n | 'remote_modified'\n | 'remote_deleted'\n | 'local_deleted'\n | 'local_new'\n | 'remote_new'\n | 'conflict_both_modified'\n | 'conflict_local_modified_remote_deleted'\n | 'conflict_local_deleted_remote_modified'\n | 'conflict_both_new';\n\nexport interface FileCompareResult {\n filePath: string;\n changeType: FileChangeType;\n currentLocalHash: string | null;\n currentRemoteHash: string | null;\n baselineLocalHash: string | null;\n baselineRemoteHash: string | null;\n}\n\nexport interface SyncConflict {\n filePath: string;\n type: 'both_modified' | 'local_modified_remote_deleted' | 'local_deleted_remote_modified' | 'both_new';\n description: string;\n}\n\nexport interface PushFailure {\n filePath: string;\n operation: 'create' | 'update' | 'delete';\n reason: string;\n}\n\nexport type ConflictResolution = 'keep_local' | 'keep_remote' | 'keep_both' | 'merge_markers';\nexport type ConflictResolutions = Record<string, ConflictResolution>;\n\n/**\n * Markers we wrap a conflicted file with under the `merge_markers`\n * resolution \u2014 same convention as git so any IDE / editor picks them\n * up automatically and lets the user choose visually.\n *\n * The push pre-flight (utils/fileValidation.ts) refuses files that\n * still contain these markers \u2014 pushing an unresolved file would\n * upload broken syntax to the backend.\n */\nexport const MERGE_MARKER_LOCAL_START = '<<<<<<< LOCAL (your version)';\nexport const MERGE_MARKER_SEPARATOR = '=======';\nexport const MERGE_MARKER_REMOTE_END = '>>>>>>> REMOTE';\n\nexport class SyncService {\n private tenant: string;\n private farseerClient: IFarseerClient;\n\n constructor(tenant: string, farseerClient: IFarseerClient) {\n this.tenant = tenant;\n this.farseerClient = farseerClient;\n }\n\n loadSyncState(): SyncState {\n const syncFilePath = getSyncFilePath(this.tenant);\n\n if (!fs.existsSync(syncFilePath)) {\n return {\n lastSync: '',\n files: {},\n };\n }\n\n try {\n const content = fs.readFileSync(syncFilePath, 'utf-8');\n return JSON.parse(content) as SyncState;\n } catch {\n return {\n lastSync: '',\n files: {},\n };\n }\n }\n\n saveSyncState(state: SyncState): void {\n const syncFilePath = getSyncFilePath(this.tenant);\n ensureDirectoryExists(path.dirname(syncFilePath));\n fs.writeFileSync(syncFilePath, JSON.stringify(state, null, 2), 'utf-8');\n }\n\n /**\n * Single status engine used by both `farseer status` and the push\n * preflight. By default (deep=false) we list remote files but don't\n * download their content \u2014 fast on big tenants and accurate for adds,\n * deletes, and *local* edits. Pass deep=true (or `farseer status --deep`)\n * to also detect remote-side edits, which requires hashing every remote\n * file.\n *\n * Output buckets are explicit (added/modified/deleted on each side) so\n * the user never sees \"M file.ts\" for a file that's actually deleted on\n * one side \u2014 a regular failure mode of the previous two-bucket layout.\n */\n async getStatus(options?: GetStatusOptions): Promise<SyncStatus> {\n const deep = options?.deep === true;\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // shouldIncludeFile must run on every entry, even under --all: it\n // gates hidden paths (`.env`, `.vscode/`, `.git/`) which only get\n // synced when the user explicitly lists them via --include-ext or\n // --include-folder. Without the call here, --all would pick up a\n // local `.env` and either unlink it on pull --force or upload it.\n const localFiles = getAllFilesInDir(filesDir).filter((f) => shouldIncludeFile(f, this.tenant, options));\n\n const localHashes = new Map<string, string>();\n for (const file of localFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n const content = fs.readFileSync(fullPath);\n localHashes.set(file, calculateHash(content));\n }\n\n const remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n const remoteHashes = new Map<string, string>();\n if (deep) {\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { path: file.path, hash: calculateHash(content) };\n },\n 15,\n );\n for (const { path: filePath, hash } of fileContents) {\n remoteHashes.set(filePath, hash);\n }\n } else {\n // Fast mode: we never download remote content. The comparator\n // needs *some* hash, so we pick the value that makes its three-\n // way logic produce the \"trust syncState\" answer:\n //\n // \u2022 If we have a baseline remote hash, reuse it. This makes\n // `remoteChanged` always false in fast mode \u2014 the explicit\n // trade-off (we miss someone else's edits between pull and\n // push), surfaced via `status.deepCompare = false`.\n // \u2022 If there is no baseline but the file exists locally, use\n // the local hash. Without this, \"first-time both-sides\n // exist\" (fresh clone, no .farseer-sync.json) flips to\n // `conflict_both_new` even though the most likely truth is\n // \"this file is fine, we just lost the baseline\". `pull`\n // and `push` correctly re-validate before doing anything\n // destructive, so an over-optimistic preview here is safe.\n // \u2022 Otherwise emit a path-unique sentinel so the comparator\n // classifies this as `remote_new` (added remotely).\n for (const file of remoteFiles) {\n const baseline = syncState.files[file.path]?.remoteHash;\n if (baseline) {\n remoteHashes.set(file.path, baseline);\n continue;\n }\n const localHash = localHashes.get(file.path);\n if (localHash) {\n remoteHashes.set(file.path, localHash);\n continue;\n }\n remoteHashes.set(file.path, `__remote_present__:${file.path}`);\n }\n }\n\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n });\n\n const status = emptyStatus(deep);\n if (deep) {\n // Hand back the just-computed deep map so callers (e.g. push.ts\n // running a deep status before a mirror push) can pass it into\n // service.push() and avoid re-downloading every file body.\n status.remoteHashes = remoteHashes;\n }\n\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'unchanged':\n status.inSync.push(c.filePath);\n break;\n case 'local_modified':\n status.modifiedLocally.push(c.filePath);\n break;\n case 'remote_modified':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_new':\n status.addedLocally.push(c.filePath);\n break;\n case 'remote_new':\n status.addedRemotely.push(c.filePath);\n break;\n case 'remote_deleted':\n status.deletedRemotely.push(c.filePath);\n break;\n case 'local_deleted':\n status.deletedLocally.push(c.filePath);\n break;\n default:\n status.conflicts.push(SyncService.buildConflicts([c])[0]);\n break;\n }\n }\n\n return status;\n }\n\n async pull(options?: SyncOptions): Promise<{\n downloaded: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n conflictFilesWritten: string[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n ensureDirectoryExists(filesDir);\n\n const syncState = this.loadSyncState();\n // shouldIncludeFile must run even under --all so the hidden-file\n // gate (`.env`, `.vscode/`, `.git/`) stays in effect \u2014 these only\n // sync when explicitly listed in --include-ext / --include-folder.\n let remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // Batch fetch metadata for all files\n remoteFiles = await this.fetchMetadataForFiles(remoteFiles);\n\n const result = {\n downloaded: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n conflictFilesWritten: [] as string[],\n };\n\n // Download file contents in parallel with concurrency limit\n logger.dim(`Fetching ${remoteFiles.length} files in parallel...`);\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file, index) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n // Show progress every 10 files\n if ((index + 1) % 10 === 0 || index === remoteFiles.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteFiles.length} files`);\n }\n return { file, content };\n },\n 15,\n );\n // Clear progress line\n if (remoteFiles.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n // Build remote content map with hashes\n const remoteContentMap = new Map<string, { file: RemoteFile; content: Buffer; hash: string }>();\n const remoteHashes = new Map<string, string>();\n for (const { file, content } of fileContents) {\n const hash = calculateHash(content);\n remoteContentMap.set(file.path, { file, content, hash });\n remoteHashes.set(file.path, hash);\n }\n\n // Build local hashes. shouldIncludeFile runs on every entry so the\n // hidden-file gate stays in effect even under --all.\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n if (!shouldIncludeFile(localFile, this.tenant, options)) {\n continue;\n }\n const localPath = safeResolveWithinBase(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n });\n const resolutions = options?.conflictResolutions ?? {};\n\n for (const comparison of comparisons) {\n const { filePath, changeType } = comparison;\n const localPath = safeResolveWithinBase(filesDir, filePath);\n const remoteInfo = remoteContentMap.get(filePath);\n\n switch (changeType) {\n case 'unchanged':\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_modified':\n case 'local_new':\n if (options?.force && remoteInfo) {\n // --force on pull means \"make local match remote\".\n // Without this branch, local_modified silently went\n // into `unchanged` and the user's edit survived a\n // hard-reset \u2014 the opposite of what --force promises.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_deleted':\n if (options?.force && remoteInfo) {\n // Force: restore the file the user removed locally.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n break;\n\n case 'remote_modified':\n case 'remote_new':\n // Safe to write\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo!.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo!.hash,\n remoteHash: remoteInfo!.hash,\n metadata: this.buildMetadata(remoteInfo!.file),\n };\n break;\n\n case 'remote_deleted':\n // Safe to delete (local is unchanged)\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n }\n result.deleted.push(filePath);\n delete syncState.files[filePath];\n break;\n\n case 'conflict_both_modified':\n case 'conflict_local_modified_remote_deleted':\n case 'conflict_local_deleted_remote_modified':\n case 'conflict_both_new': {\n if (options?.force) {\n // Force: apply remote state\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted, force means delete local\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n }\n\n const resolution = resolutions[filePath];\n if (!resolution) {\n // No resolution provided - report conflict, skip file\n result.conflicts.push(SyncService.buildConflicts([comparison])[0]);\n break;\n }\n\n switch (resolution) {\n case 'keep_local':\n // Keep local as-is, update sync state to mark conflict resolved\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n } else {\n // Local was deleted, user wants to keep that decision\n delete syncState.files[filePath];\n }\n result.unchanged.push(filePath);\n break;\n\n case 'keep_remote':\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n\n case 'keep_both':\n if (remoteInfo) {\n // Write remote version as .remote file alongside local\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteInfo.content);\n result.conflictFilesWritten.push(conflictFileName);\n }\n // Keep local, update sync state\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n }\n result.unchanged.push(filePath);\n break;\n\n case 'merge_markers':\n // git-style inline merge. Wrap LOCAL and REMOTE\n // versions with markers so any editor / IDE\n // highlights them. After the user resolves the\n // file (manually picks the version they want and\n // strips the markers), a regular `farseer push`\n // uploads the cleaned-up content. The push\n // pre-flight refuses any file that still has\n // markers in it, so an accidentally-unfinished\n // resolve never reaches the backend as broken\n // syntax.\n if (remoteInfo && fs.existsSync(localPath)) {\n const localBuf = fs.readFileSync(localPath);\n const remoteBuf = remoteInfo.content;\n\n // Binary safety gate. Splicing UTF-8 markers\n // into a .png/.xlsx/.zip would corrupt it\n // (the toString('utf-8') round-trip flips\n // bytes). Fall back to keep_both \u2014 write\n // remote alongside local as <name>.remote.<ext>\n // and let the user diff with their tool of\n // choice. Without this gate the user's binary\n // got silently overwritten with garbage.\n if (!isLikelyTextFile(filePath, localBuf) || !isLikelyTextFile(filePath, remoteBuf)) {\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteBuf);\n const localHash = calculateHash(localBuf);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(\n `${conflictFileName} (binary \u2014 merge markers not safe; wrote .remote alongside)`,\n );\n result.unchanged.push(filePath);\n break;\n }\n\n const localContent = localBuf.toString('utf-8');\n const remoteContent = remoteBuf.toString('utf-8');\n const merged =\n `${MERGE_MARKER_LOCAL_START}\\n${localContent}` +\n `${localContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_SEPARATOR}\\n${remoteContent}` +\n `${remoteContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_REMOTE_END}\\n`;\n fs.writeFileSync(localPath, merged);\n // Update syncState so push sees this as\n // \"locally modified\" (localHash differs from\n // remoteHash). User pushes cleaned-up file\n // after manually resolving.\n const newHash = calculateHash(Buffer.from(merged));\n syncState.files[filePath] = {\n localHash: newHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(`${filePath} (merge markers)`);\n } else if (!remoteInfo && fs.existsSync(localPath)) {\n // Remote is gone \u2014 fall back to keep_local.\n // No useful merge for \"your version vs nothing\".\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = { localHash, remoteHash: '' };\n }\n result.unchanged.push(filePath);\n break;\n }\n break;\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n private buildMetadata(file: RemoteFile): SyncFileInfo['metadata'] {\n if (!file.metadata) return undefined;\n return {\n uploadTime: file.metadata.uploadTime,\n uploaderEmail: file.metadata.uploader?.email,\n uploaderName: file.metadata.uploader\n ? `${file.metadata.uploader.firstName} ${file.metadata.uploader.lastName}`.trim()\n : undefined,\n lastFetched: new Date().toISOString(),\n };\n }\n\n async push(options?: {\n force?: boolean;\n mirror?: boolean;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n /**\n * Pre-fetched remote-content hashes keyed by file path. Optional\n * optimisation for callers (push.ts) that already ran a deep\n * status \u2014 that pass already downloaded every remote file's body,\n * so we can skip the second remote fetch here when the entries\n * cover everything we'd otherwise refetch. Missing keys still\n * trigger a fetch as before, so it's safe to pass a partial map.\n */\n precomputedRemoteHashes?: Map<string, string>;\n }): Promise<{\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n rejected: ValidationFailure[];\n failed: PushFailure[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const syncState = this.loadSyncState();\n\n const result = {\n uploaded: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n rejected: [] as ValidationFailure[],\n // Per-file failures from create/update/delete API calls. We don't\n // abort the whole push on the first failure \u2014 each item is its\n // own atomic operation, and `syncState` is saved in `finally` so\n // already-successful items aren't re-uploaded next run. The\n // caller surfaces this list and exits non-zero on non-empty.\n failed: [] as PushFailure[],\n };\n\n // Get current remote files (just the list, not content). Filter out\n // OS metadata defensively in case anyone ever pushed one before.\n const remoteFiles = (await this.farseerClient.listFiles()).filter((f) => !isOsMetadataFile(f.path));\n const remoteFileMap = new Map<string, RemoteFile>();\n for (const file of remoteFiles) {\n remoteFileMap.set(file.path, file);\n }\n\n // OS metadata is stripped at the helper level (getAllFilesInDir),\n // so we never try to upload the user's filesystem bookkeeping \u2014\n // backend rejects those filenames and the user can't reasonably\n // remove them from the working tree.\n const allLocalFiles = getAllFilesInDir(filesDir);\n\n // Apply the user's declared sync scope BEFORE we treat anything as\n // an upload candidate. Without this filter, push iterates every\n // file the disk listing returned and any whitelisted-extension\n // bystander gets shipped to remote \u2014 e.g. a `.vscode/settings.json`\n // sitting next to scripts passes pre-flight (`.json` is on the\n // backend whitelist) and is silently uploaded under a default\n // `farseer push`. The status preview already filters by\n // `shouldIncludeFile`, so the user wouldn't even see it coming.\n // Pin the same scope here.\n //\n // `localPresenceSet` keeps the FULL on-disk listing, separately,\n // so the delete loop's \"is this file actually missing locally?\"\n // protection still works for any file the user has \u2014 including\n // out-of-scope ones we won't touch.\n const localPresenceSet = new Set(allLocalFiles);\n // Always route through shouldIncludeFile \u2014 under --all the function\n // returns true for non-hidden files under --all but still gates\n // hidden ones (.env, .vscode/, .git/) so they require explicit\n // --include-ext / --include-folder opt-in.\n const inScopeFiles = allLocalFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));\n\n const localContents = new Map<string, Buffer>();\n for (const file of inScopeFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n localContents.set(file, fs.readFileSync(fullPath));\n }\n\n // Pre-flight: refuse files the backend will refuse anyway. We do\n // this before any network call so the user sees a single grouped\n // verdict (\"3 file(s) skipped: extension not allowed, \u2026\") rather\n // than a half-finished push that errors mid-stream with an opaque\n // 400. Files that fail validation never reach the upload loop, but\n // they still count toward `result.rejected` so the caller can show\n // them to the user and exit non-zero.\n const validationInputs = inScopeFiles.map((filePath) => {\n const content = localContents.get(filePath)!;\n return {\n filePath,\n size: content.length,\n content,\n };\n });\n const { valid: pushableValidatedFiles, rejected } = partitionForUpload(validationInputs);\n result.rejected = rejected;\n // `localFiles` = files we'll consider for upload (in-scope, validated).\n const localFiles = pushableValidatedFiles.map((f) => f.filePath);\n\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n localHashes.set(localFile, calculateHash(localContents.get(localFile)!));\n }\n\n // Identify candidates that need remote content check for conflict detection.\n // Compare against syncInfo.remoteHash (not .localHash): a file is a\n // candidate whenever local diverges from what we last knew about remote,\n // which also covers keep_local / keep_both resolutions where localHash\n // matches baseline local but remoteHash points at the conflicting remote.\n //\n // Mirror exception: under `mirror: true` we treat EVERY locally-\n // present file that also exists on remote as a candidate, so we can\n // re-fetch the actual remote hash and detect content drift even on\n // files our baseline marks as \"in sync\". Without this, a user who\n // ran `push --force --mirror` after someone else edited a remote\n // file (with our recorded baseline still stale) would skip the\n // upload entirely and remote stays diverged.\n const candidateFiles: string[] = [];\n for (const localFile of localFiles) {\n const syncInfo = syncState.files[localFile];\n const localHash = localHashes.get(localFile)!;\n const baselineDiverged = !syncInfo || localHash !== syncInfo.remoteHash;\n if (!remoteFileMap.has(localFile)) continue;\n if (baselineDiverged || options?.mirror) {\n candidateFiles.push(localFile);\n }\n }\n // Also check files in sync state that no longer exist locally (local deletions).\n // Use `localPresenceSet` (not `localFiles`): rejected files DO exist\n // locally \u2014 they just can't be uploaded \u2014 so they must NOT count as\n // \"locally deleted\" and must NOT trigger remote deletion. Scope-filter\n // too: a `Data/foo.csv` previously synced under `--include-ext .csv`\n // shouldn't get deleted on a default push without the same flag \u2014\n // out-of-scope files are invisible this run. shouldIncludeFile\n // handles the --all gate plus the hidden-file gate together.\n const inScope = (f: string) => shouldIncludeFile(f, this.tenant, options);\n const locallyDeletedFiles = Object.keys(syncState.files).filter(\n (f) => !localPresenceSet.has(f) && remoteFileMap.has(f) && inScope(f),\n );\n const filesToFetchRemote = [...new Set([...candidateFiles, ...locallyDeletedFiles])];\n\n // Fetch remote content for conflict detection. We skip the fetch\n // under plain `force: true` (the user said 'overwrite, don't ask\n // questions') \u2014 but under `mirror: true` we DO need it: mirror\n // semantics rest on knowing the actual remote hash so we can decide\n // 'do we re-upload because remote drifted?'.\n //\n // Caller can pass `precomputedRemoteHashes` to skip the network\n // round-trip for entries already in hand (e.g. push.ts ran a deep\n // getStatus right before this and already paid for every fetch).\n // Files NOT in the map still get fetched here, so the fast-path\n // is safe with partial coverage.\n const remoteHashes = new Map<string, string>(options?.precomputedRemoteHashes ?? []);\n if (filesToFetchRemote.length > 0 && (!options?.force || options?.mirror)) {\n const toFetch = filesToFetchRemote\n .filter((f) => remoteFileMap.has(f) && !remoteHashes.has(f))\n .map((f) => remoteFileMap.get(f)!);\n\n if (toFetch.length > 0) {\n const fetched = await fetchWithConcurrency(\n toFetch,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { file, hash: calculateHash(content) };\n },\n 15,\n );\n\n for (const { file, hash } of fetched) {\n remoteHashes.set(file.path, hash);\n }\n }\n }\n\n // Three-way comparison for conflict detection\n const comparisons = this.compareFiles({ localHashes, remoteHashes, syncState, all: true });\n const conflictPaths = new Set<string>();\n\n if (!options?.force) {\n for (const c of comparisons) {\n if (c.changeType.startsWith('conflict_')) {\n const conflict = SyncService.buildConflicts([c])[0];\n result.conflicts.push(conflict);\n conflictPaths.add(c.filePath);\n }\n }\n }\n\n // Per-file try/catch around every backend call. A single 5xx (or\n // any other transient error) on file N must not lose progress on\n // files 1..N-1: we log into result.failed[], save syncState in the\n // outer `finally`, and let the user re-run. Without this, an\n // interrupted run would re-upload everything and risk creating\n // dupes for items the backend silently committed before failing.\n try {\n // Process non-conflicting files\n for (const localFile of localFiles) {\n if (conflictPaths.has(localFile)) continue;\n\n const content = localContents.get(localFile)!;\n const localHash = localHashes.get(localFile)!;\n\n const remoteFile = remoteFileMap.get(localFile);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFile) {\n // File exists on remote. Push when local diverges from what we\n // last recorded as the remote hash. Using remoteHash (not\n // localHash) means keep_local / keep_both conflict resolutions \u2014\n // where localHash gets updated to current local but remoteHash\n // still carries the conflicting remote hash \u2014 correctly trigger\n // an upload instead of being silently marked as unchanged.\n //\n // Mirror exception: under `mirror: true` the user explicitly\n // asked for \"remote == local\". Trusting our recorded\n // remoteHash here can mark the file unchanged even though\n // the real remote content drifted. Re-fetched currentRemoteHash\n // (when available \u2014 drift fetch step above runs even under\n // force/mirror for non-conflict candidates) lets us tell.\n // If we have a real remote hash and it matches local, skip\n // the upload (saves a roundtrip); otherwise overwrite.\n const currentRemoteHash = remoteHashes.get(localFile);\n const mirrorWantsRecreate =\n options?.mirror && currentRemoteHash !== undefined && currentRemoteHash !== localHash;\n if (syncInfo && localHash === syncInfo.remoteHash && !mirrorWantsRecreate) {\n result.unchanged.push(localFile);\n } else {\n // Drift check: before overwriting remote, make sure remote\n // still has the version we last recorded. If someone else\n // (or a still-pending background job) moved remote forward\n // since our baseline, and this isn't a forced push, refuse\n // to silently overwrite it. Without this, the keep_local\n // path can clobber a newer remote edit because the file's\n // changeType comes back as 'remote_modified' (not\n // conflict_*) and would otherwise sail through.\n // (currentRemoteHash already declared above for the\n // mirror-recreate check; reuse it here.)\n if (\n !options?.force &&\n syncInfo &&\n currentRemoteHash !== undefined &&\n currentRemoteHash !== syncInfo.remoteHash\n ) {\n result.conflicts.push({\n filePath: localFile,\n type: 'both_modified',\n description: 'Remote changed since last sync \u2014 pull first or use --force to overwrite',\n });\n continue;\n }\n try {\n await this.farseerClient.updateFile(\n remoteFile.reference,\n content,\n path.basename(localFile),\n );\n result.updated.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'update',\n reason: await formatClientError(err),\n });\n }\n }\n } else {\n // File doesn't exist on remote.\n //\n // Default push: respect the remote deletion (someone deleted\n // it via UI, we shouldn't undo their action just because\n // we still have the file locally and our baseline says it\n // used to be on remote). Mark unchanged.\n //\n // Mirror push (`mirror: true`): the user explicitly asked\n // for \"remote == local\". A local copy that's no longer on\n // remote means we need to RECREATE it on remote \u2014 falling\n // through to the upload branch below does that.\n if (syncInfo && localHash === syncInfo.remoteHash && !options?.mirror) {\n result.unchanged.push(localFile);\n } else {\n // New or modified local file - upload\n const pathParts = localFile.split('/');\n const fileName = pathParts.pop()!;\n const folderPath = ['Files', ...pathParts];\n try {\n await this.farseerClient.createFile(content, fileName, folderPath);\n result.uploaded.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'create',\n reason: await formatClientError(err),\n });\n }\n }\n }\n }\n\n // Delete files on remote that were deleted locally.\n //\n // Default: only delete files we previously pulled (`syncInfo` exists)\n // \u2014 that's how you express \"I just `rm`'d this file, please match\".\n // Mirror mode (`push --force` from the CLI surface): also delete\n // remote files that have no local counterpart at all, even if we\n // never pulled them. This is the \"make remote = local\" semantics\n // the CLI promises with --force, but it's destructive enough that\n // the command layer must confirm with the user before passing\n // `mirror: true`.\n // Honour the same `--include-ext` / `--include-folder` scope the\n // command layer used for the preview. Out-of-scope files are\n // invisible this run \u2014 even when syncState remembers them. Without\n // the gate on the syncInfo branch, a default `farseer push`\n // (no `--include-ext .csv`) after a previous `farseer push\n // --include-ext .csv` plus a local rm would silently nuke\n // Data/foo.csv on remote. Cross-scope side effects are exactly\n // what users don't expect from a default-flag run.\n for (const [remotePath, remoteFile] of remoteFileMap) {\n if (localPresenceSet.has(remotePath) || conflictPaths.has(remotePath)) continue;\n if (!inScope(remotePath)) continue;\n const syncInfo = syncState.files[remotePath];\n const shouldDelete = syncInfo ? true : Boolean(options?.mirror);\n if (!shouldDelete) continue;\n try {\n await this.farseerClient.deleteFile(remoteFile.reference);\n result.deleted.push(remotePath);\n delete syncState.files[remotePath];\n } catch (err) {\n result.failed.push({\n filePath: remotePath,\n operation: 'delete',\n reason: await formatClientError(err),\n });\n }\n }\n } finally {\n // Always persist progress, even on partial failure or if the\n // outer flow is cancelled with Ctrl-C between files. The next\n // run reads this state and skips items we already finished.\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n }\n\n return result;\n }\n\n /**\n * Detect whether the remote has files we haven't seen yet (or recorded\n * files no longer present on remote) within the current sync scope.\n *\n * Returns the set of paths that are causing drift so the command layer\n * can show the user exactly what's blocking the push and suggest a\n * matching `farseer pull` command. The previous boolean-only return\n * gave the user just \"Remote has changes\" with no clue WHICH file \u2014\n * and `farseer pull` (without the same `--include-ext`/`--include-folder`)\n * silently said \"Already up to date\" because it ran in a different\n * scope, leaving the user stuck in an infinite \"pull says clean, push\n * says drift\" loop.\n */\n async checkRemoteChanges(options?: SyncOptions): Promise<{\n drift: boolean;\n addedRemotely: string[];\n deletedRemotely: string[];\n }> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes to avoid false positives\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // We need local presence too: a syncState entry for a file that's\n // gone from BOTH local and remote is just stale baseline \u2014 neither\n // side can act on it, and flagging it as drift sends the user to a\n // pull that does nothing. Only count \"remote-deleted\" when local\n // still has the file (so the upcoming pull would clean it up).\n const filesDir = getTenantFilesDir(this.tenant);\n const localPresenceSet = new Set(getAllFilesInDir(filesDir));\n\n const addedRemotely: string[] = [];\n const deletedRemotely: string[] = [];\n\n // New files on remote that we don't have in sync state.\n for (const file of remoteFiles) {\n if (!syncState.files[file.path]) {\n addedRemotely.push(file.path);\n }\n }\n\n // Files deleted on remote that we have in sync state. Skip if local\n // is also missing (stale baseline \u2014 treat as already cleaned, the\n // next pull will drop it from syncState without any drift signal\n // confusing the user).\n const remotePaths = new Set(remoteFiles.map((f) => f.path));\n for (const filePath of Object.keys(syncState.files)) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) continue;\n if (remotePaths.has(filePath)) continue;\n if (!syncState.files[filePath].remoteHash) continue;\n if (!localPresenceSet.has(filePath)) continue;\n deletedRemotely.push(filePath);\n }\n\n // Note: we don't check for content changes here for performance.\n // After a pull, sync state is accurate. Content changes by others\n // between pull and push are surfaced through the per-file drift\n // check inside push() instead.\n return {\n drift: addedRemotely.length > 0 || deletedRemotely.length > 0,\n addedRemotely,\n deletedRemotely,\n };\n }\n\n async getFileDiff(filePath: string): Promise<{\n localContent: string | null;\n remoteContent: string | null;\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const localPath = safeResolveWithinBase(filesDir, filePath);\n\n let localContent: string | null = null;\n let remoteContent: string | null = null;\n\n if (fs.existsSync(localPath)) {\n // For diff, read as text (diff only makes sense for text files)\n localContent = fs.readFileSync(localPath, 'utf-8');\n }\n\n const remoteFile = await this.farseerClient.getFileByPath(filePath);\n if (remoteFile) {\n remoteContent = await this.farseerClient.getFileContent(remoteFile.reference);\n }\n\n return { localContent, remoteContent };\n }\n\n /**\n * Three-way comparison of all files.\n * Compares current local state, current remote state, and baseline from sync state.\n */\n compareFiles(options: {\n localHashes: Map<string, string>;\n remoteHashes: Map<string, string>;\n syncState: SyncState;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n }): FileCompareResult[] {\n const { localHashes, remoteHashes, syncState } = options;\n\n // Union of all known file paths\n const allPaths = new Set<string>([\n ...localHashes.keys(),\n ...remoteHashes.keys(),\n ...Object.keys(syncState.files),\n ]);\n\n const results: FileCompareResult[] = [];\n\n for (const filePath of allPaths) {\n // Filter files based on includes\n if (!options.all) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) {\n continue;\n }\n }\n\n const currentLocalHash = localHashes.get(filePath) ?? null;\n const currentRemoteHash = remoteHashes.get(filePath) ?? null;\n const baseline = syncState.files[filePath];\n const baselineLocalHash = baseline?.localHash ?? null;\n const baselineRemoteHash = baseline?.remoteHash ?? null;\n\n const localExists = currentLocalHash !== null;\n const remoteExists = currentRemoteHash !== null;\n const hadBaseline = baseline != null;\n\n let changeType: FileChangeType;\n\n if (localExists && remoteExists) {\n // Both exist\n if (currentLocalHash === currentRemoteHash) {\n changeType = 'unchanged';\n } else if (!hadBaseline) {\n changeType = 'conflict_both_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n const baselineDivergent = baselineLocalHash !== baselineRemoteHash;\n\n if (localChanged && remoteChanged) {\n changeType = 'conflict_both_modified';\n } else if (localChanged) {\n changeType = 'local_modified';\n } else if (remoteChanged) {\n changeType = 'remote_modified';\n } else if (baselineDivergent) {\n // Post `keep_local` / `keep_both` resolution: nothing\n // changed since baseline, but baseline already recorded\n // local diverged from remote on purpose. The user\n // chose local; we still need to push so remote\n // catches up. Without this branch, status & push\n // would both fall through to \"unchanged\" and the\n // local edit would silently never reach remote.\n changeType = 'local_modified';\n } else {\n changeType = 'unchanged';\n }\n }\n } else if (localExists && !remoteExists) {\n // Only local exists\n if (!hadBaseline) {\n changeType = 'local_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n if (localChanged) {\n changeType = 'conflict_local_modified_remote_deleted';\n } else {\n changeType = 'remote_deleted';\n }\n }\n } else if (!localExists && remoteExists) {\n // Only remote exists\n if (!hadBaseline) {\n changeType = 'remote_new';\n } else {\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n if (remoteChanged) {\n changeType = 'conflict_local_deleted_remote_modified';\n } else {\n changeType = 'local_deleted';\n }\n }\n } else {\n // Neither exists - both deleted since baseline, clean up\n continue;\n }\n\n results.push({\n filePath,\n changeType,\n currentLocalHash,\n currentRemoteHash,\n baselineLocalHash,\n baselineRemoteHash,\n });\n }\n\n return results;\n }\n\n /**\n * Extract SyncConflict[] from FileCompareResult[].\n */\n static buildConflicts(comparisons: FileCompareResult[]): SyncConflict[] {\n const conflicts: SyncConflict[] = [];\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'conflict_both_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_modified',\n description: 'Both local and remote versions modified since last sync',\n });\n break;\n case 'conflict_local_modified_remote_deleted':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n break;\n case 'conflict_local_deleted_remote_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_deleted_remote_modified',\n description: 'File deleted locally but modified on remote',\n });\n break;\n case 'conflict_both_new':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_new',\n description: 'File exists both locally and remotely with different content (no sync baseline)',\n });\n break;\n }\n }\n return conflicts;\n }\n\n /**\n * Batch fetch metadata for multiple files in parallel.\n * Fetches metadata in batches of 10 to avoid overwhelming the API.\n * Non-critical operation - failures are silently ignored.\n */\n private async fetchMetadataForFiles(files: RemoteFile[]): Promise<RemoteFile[]> {\n const batchSize = 10;\n\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const metadata = await this.farseerClient.getFileMetadata(file.reference);\n if (metadata) {\n file.metadata = metadata;\n }\n } catch {\n // Silently ignore metadata fetch errors - non-critical\n }\n }),\n );\n }\n\n return files;\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,4BAAsE;AACtE,2BAAgC;AAChC,qBAUO;AACP,oBAAuB;AACvB,4BAAwE;AACxE,4BAAkC;AAKlC,IAAAA,kBAA+C;AA8BxC,SAAS,kBACZ,UACA,QACA,SACO;AAGP,UAAI,iCAAiB,QAAQ,EAAG,QAAO;AAEvC,QAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAC/C,QAAM,iBAAa,sCAAgB,MAAM;AAEzC,QAAM,mBACD,SAAS,mBAAmB,SAAS,GAAG,KAAK,WAC7C,SAAS,gBAAgB,KAAK,CAAC,MAAM,SAAS,WAAW,IAAI,GAAG,KAAK,aAAa,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AAE,YAAY;AAAA,QAClB,KAAK;AACD,oBAAU,KAAK;AAAA,YACX,UAAU,EAAE;AAAA,YACZ,MAAM;AAAA,YACN,aAAa;AAAA,UACjB,CAAC;AACD;AAAA,QACJ,KAAK;AACD,oBAAU,KAAK;AAAA,YACX,UAAU,EAAE;AAAA,YACZ,MAAM;AAAA,YACN,aAAa;AAAA,UACjB,CAAC;AACD;AAAA,QACJ,KAAK;AACD,oBAAU,KAAK;AAAA,YACX,UAAU,EAAE;AAAA,YACZ,MAAM;AAAA,YACN,aAAa;AAAA,UACjB,CAAC;AACD;AAAA,QACJ,KAAK;AACD,oBAAU,KAAK;AAAA,YACX,UAAU,EAAE;AAAA,YACZ,MAAM;AAAA,YACN,aAAa;AAAA,UACjB,CAAC;AACD;AAAA,MACR;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,sBAAsB,OAA4C;AAC5E,UAAM,YAAY;AAElB,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAC9C,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAE1C,YAAM,QAAQ;AAAA,QACV,MAAM,IAAI,OAAO,SAAS;AACtB,cAAI;AACA,kBAAM,WAAW,MAAM,KAAK,cAAc,gBAAgB,KAAK,SAAS;AACxE,gBAAI,UAAU;AACV,mBAAK,WAAW;AAAA,YACpB;AAAA,UACJ,QAAQ;AAAA,UAER;AAAA,QACJ,CAAC;AAAA,MACL;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
|
|
4
|
+
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { IFarseerClient, RemoteFile, DEFAULT_SCRIPT_EXTENSIONS } from './farseerFactory';\nimport { getSyncIncludes } from './configService';\nimport {\n calculateHash,\n getTenantFilesDir,\n getSyncFilePath,\n ensureDirectoryExists,\n getAllFilesInDir,\n fetchWithConcurrency,\n isHiddenFile,\n isOsMetadataFile,\n safeResolveWithinBase,\n} from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { ValidationFailure, partitionForUpload, isLikelyTextFile } from '../utils/fileValidation';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Re-export so existing test imports (`from '../../src/services/syncService'`)\n// keep working \u2014 `isOsMetadataFile` moved to utils/helpers.ts so the file\n// listing helper can apply it as the default filter.\nexport { isOsMetadataFile, isHiddenFile } from '../utils/helpers';\n\nexport interface SyncOptions {\n all?: boolean;\n force?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n conflictResolutions?: ConflictResolutions;\n /**\n * Whitelist of file paths (relative to the tenant files dir).\n * When set, only listed paths participate in the sync \u2014 everything\n * else is treated as out-of-scope (not modified, not deleted, not\n * compared). Used by `farseer push --only` to push a single file\n * without touching unrelated drift in the working tree.\n */\n onlyFiles?: string[];\n}\n\n/**\n * Determines if a file should be included in sync operations.\n *\n * Exclusion rules (run before any include rule):\n * - OS metadata (.DS_Store, Thumbs.db, ._foo, \u2026) \u2014 never synced.\n * - Hidden files / folders (any path segment starting with `.` \u2014 e.g.\n * .env, .git/, .vscode/) \u2014 synced only when explicitly listed in\n * `--include-ext` / `--include-folder` / persistent sync-includes\n * config. `--all` does NOT include them; the explicit-include path\n * is the single way to consent to syncing a credential / config /\n * VCS file.\n *\n * Inclusion rules (file must satisfy at least one):\n * 1. `--all` flag is passed (only for non-hidden files).\n * 2. Has a default script extension (.ts, .js).\n * 3. Has an extension from inline includeExtensions option.\n * 4. Lives under a folder from inline includeFolders option.\n * 5. Has an extension from persistent syncIncludes config.\n * 6. Lives under a folder from persistent syncIncludes config.\n */\nexport function shouldIncludeFile(\n filePath: string,\n tenant: string,\n options?: Pick<SyncOptions, 'all' | 'includeExtensions' | 'includeFolders' | 'onlyFiles'>,\n): boolean {\n // OS metadata is always excluded \u2014 `--all` should sync the user's work,\n // not their filesystem's bookkeeping.\n if (isOsMetadataFile(filePath)) return false;\n\n // `--only` is a hard whitelist: when set, anything not listed is\n // out of scope regardless of other include rules. We compare on\n // exact relative path; the caller normalises before passing.\n if (options?.onlyFiles && options.onlyFiles.length > 0) {\n return options.onlyFiles.includes(filePath);\n }\n\n const ext = path.extname(filePath).toLowerCase();\n const persistent = getSyncIncludes(tenant);\n\n const matchesIncludes =\n (options?.includeExtensions?.includes(ext) ?? false) ||\n (options?.includeFolders?.some((f) => filePath.startsWith(f + '/') || filePath === f) ?? false) ||\n (persistent?.extensions?.includes(ext) ?? false) ||\n (persistent?.folders?.some((f) => filePath.startsWith(f + '/') || filePath === f) ?? false);\n\n // Hidden files (.env, .git, .vscode, \u2026) require explicit opt-in even\n // under --all. This stops a stray credential file in the working tree\n // from leaking on a force push. Users that genuinely want to sync a\n // hidden file add it via `--include-ext` / `--include-folder` or the\n // persistent `farseer config include` config.\n if (isHiddenFile(filePath)) return matchesIncludes;\n\n if (options?.all) return true;\n if (DEFAULT_SCRIPT_EXTENSIONS.includes(ext)) return true;\n return matchesIncludes;\n}\n\nexport interface SyncFileInfo {\n localHash: string;\n remoteHash: string;\n metadata?: {\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n lastFetched?: string;\n };\n}\n\nexport interface SyncState {\n lastSync: string;\n files: Record<string, SyncFileInfo>;\n}\n\n/**\n * A single status snapshot produced by `getStatus()`. Both `farseer status`\n * (preview) and `farseer push` (preflight) use this shape so the user sees\n * the same buckets in both commands.\n *\n * The legacy two-bucket layout (`modifiedLocally` / `modifiedRemotely`)\n * silently lumped deletions in with edits, which was the single biggest\n * source of \"why does status say M for a file that's actually deleted?\"\n * confusion. This shape splits the six combinatoric outcomes into their\n * own buckets and keeps `modifiedLocally` / `modifiedRemotely` as\n * derived aliases for back-compat with code that still reads them.\n */\nexport interface SyncStatus {\n addedLocally: string[];\n modifiedLocally: string[];\n deletedLocally: string[];\n addedRemotely: string[];\n modifiedRemotely: string[];\n deletedRemotely: string[];\n inSync: string[];\n conflicts: SyncConflict[];\n /**\n * True when the status was computed without fetching remote file\n * content. In `deep: false` mode the comparator can detect adds /\n * deletes / *local* modifications, but cannot distinguish a\n * remote-modified file from an in-sync one because that requires\n * downloading and hashing the remote content. Treat this flag as\n * \"remote-edit detection skipped\" rather than \"everything checked\".\n */\n deepCompare: boolean;\n /**\n * Real remote-content hashes keyed by file path. Only populated when\n * `deep: true` ran (the listing-only fast mode never downloads bytes).\n * Exposed so a follow-up `push({ precomputedRemoteHashes })` can skip\n * its own re-download for files already covered here \u2014 under\n * `push --force --mirror` these two operations would otherwise both\n * fetch the same set of remote contents back-to-back.\n */\n remoteHashes?: Map<string, string>;\n}\n\nexport interface GetStatusOptions extends SyncOptions {\n /**\n * When true, fetch and hash every remote file's content so we can\n * detect remote-side content edits made by other users. Slow on big\n * tenants. Default: false (list-only).\n */\n deep?: boolean;\n}\n\nfunction emptyStatus(deepCompare: boolean): SyncStatus {\n return {\n addedLocally: [],\n modifiedLocally: [],\n deletedLocally: [],\n addedRemotely: [],\n modifiedRemotely: [],\n deletedRemotely: [],\n inSync: [],\n conflicts: [],\n deepCompare,\n };\n}\n\n// Three-way comparison types\n\nexport type FileChangeType =\n | 'unchanged'\n | 'local_modified'\n | 'remote_modified'\n | 'remote_deleted'\n | 'local_deleted'\n | 'local_new'\n | 'remote_new'\n | 'conflict_both_modified'\n | 'conflict_local_modified_remote_deleted'\n | 'conflict_local_deleted_remote_modified'\n | 'conflict_both_new';\n\nexport interface FileCompareResult {\n filePath: string;\n changeType: FileChangeType;\n currentLocalHash: string | null;\n currentRemoteHash: string | null;\n baselineLocalHash: string | null;\n baselineRemoteHash: string | null;\n}\n\nexport interface SyncConflict {\n filePath: string;\n type: 'both_modified' | 'local_modified_remote_deleted' | 'local_deleted_remote_modified' | 'both_new';\n description: string;\n}\n\nexport interface PushFailure {\n filePath: string;\n operation: 'create' | 'update' | 'delete';\n reason: string;\n}\n\nexport type ConflictResolution = 'keep_local' | 'keep_remote' | 'keep_both' | 'merge_markers';\nexport type ConflictResolutions = Record<string, ConflictResolution>;\n\n/**\n * Markers we wrap a conflicted file with under the `merge_markers`\n * resolution \u2014 same convention as git so any IDE / editor picks them\n * up automatically and lets the user choose visually.\n *\n * The push pre-flight (utils/fileValidation.ts) refuses files that\n * still contain these markers \u2014 pushing an unresolved file would\n * upload broken syntax to the backend.\n */\nexport const MERGE_MARKER_LOCAL_START = '<<<<<<< LOCAL (your version)';\nexport const MERGE_MARKER_SEPARATOR = '=======';\nexport const MERGE_MARKER_REMOTE_END = '>>>>>>> REMOTE';\n\nexport class SyncService {\n private tenant: string;\n private farseerClient: IFarseerClient;\n\n constructor(tenant: string, farseerClient: IFarseerClient) {\n this.tenant = tenant;\n this.farseerClient = farseerClient;\n }\n\n loadSyncState(): SyncState {\n const syncFilePath = getSyncFilePath(this.tenant);\n\n if (!fs.existsSync(syncFilePath)) {\n return {\n lastSync: '',\n files: {},\n };\n }\n\n try {\n const content = fs.readFileSync(syncFilePath, 'utf-8');\n return JSON.parse(content) as SyncState;\n } catch {\n return {\n lastSync: '',\n files: {},\n };\n }\n }\n\n saveSyncState(state: SyncState): void {\n const syncFilePath = getSyncFilePath(this.tenant);\n ensureDirectoryExists(path.dirname(syncFilePath));\n fs.writeFileSync(syncFilePath, JSON.stringify(state, null, 2), 'utf-8');\n }\n\n /**\n * Single status engine used by both `farseer status` and the push\n * preflight. By default (deep=false) we list remote files but don't\n * download their content \u2014 fast on big tenants and accurate for adds,\n * deletes, and *local* edits. Pass deep=true (or `farseer status --deep`)\n * to also detect remote-side edits, which requires hashing every remote\n * file.\n *\n * Output buckets are explicit (added/modified/deleted on each side) so\n * the user never sees \"M file.ts\" for a file that's actually deleted on\n * one side \u2014 a regular failure mode of the previous two-bucket layout.\n */\n async getStatus(options?: GetStatusOptions): Promise<SyncStatus> {\n const deep = options?.deep === true;\n const syncState = this.loadSyncState();\n const filesDir = getTenantFilesDir(this.tenant);\n\n // shouldIncludeFile must run on every entry, even under --all: it\n // gates hidden paths (`.env`, `.vscode/`, `.git/`) which only get\n // synced when the user explicitly lists them via --include-ext or\n // --include-folder. Without the call here, --all would pick up a\n // local `.env` and either unlink it on pull --force or upload it.\n const localFiles = getAllFilesInDir(filesDir).filter((f) => shouldIncludeFile(f, this.tenant, options));\n\n const localHashes = new Map<string, string>();\n for (const file of localFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n const content = fs.readFileSync(fullPath);\n localHashes.set(file, calculateHash(content));\n }\n\n const remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n const remoteHashes = new Map<string, string>();\n if (deep) {\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { path: file.path, hash: calculateHash(content) };\n },\n 15,\n );\n for (const { path: filePath, hash } of fileContents) {\n remoteHashes.set(filePath, hash);\n }\n } else {\n // Fast mode: we never download remote content. The comparator\n // needs *some* hash, so we pick the value that makes its three-\n // way logic produce the \"trust syncState\" answer:\n //\n // \u2022 If we have a baseline remote hash, reuse it. This makes\n // `remoteChanged` always false in fast mode \u2014 the explicit\n // trade-off (we miss someone else's edits between pull and\n // push), surfaced via `status.deepCompare = false`.\n // \u2022 If there is no baseline but the file exists locally, use\n // the local hash. Without this, \"first-time both-sides\n // exist\" (fresh clone, no .farseer-sync.json) flips to\n // `conflict_both_new` even though the most likely truth is\n // \"this file is fine, we just lost the baseline\". `pull`\n // and `push` correctly re-validate before doing anything\n // destructive, so an over-optimistic preview here is safe.\n // \u2022 Otherwise emit a path-unique sentinel so the comparator\n // classifies this as `remote_new` (added remotely).\n for (const file of remoteFiles) {\n const baseline = syncState.files[file.path]?.remoteHash;\n if (baseline) {\n remoteHashes.set(file.path, baseline);\n continue;\n }\n const localHash = localHashes.get(file.path);\n if (localHash) {\n remoteHashes.set(file.path, localHash);\n continue;\n }\n remoteHashes.set(file.path, `__remote_present__:${file.path}`);\n }\n }\n\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n onlyFiles: options?.onlyFiles,\n });\n\n const status = emptyStatus(deep);\n if (deep) {\n // Hand back the just-computed deep map so callers (e.g. push.ts\n // running a deep status before a mirror push) can pass it into\n // service.push() and avoid re-downloading every file body.\n status.remoteHashes = remoteHashes;\n }\n\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'unchanged':\n status.inSync.push(c.filePath);\n break;\n case 'local_modified':\n status.modifiedLocally.push(c.filePath);\n break;\n case 'remote_modified':\n status.modifiedRemotely.push(c.filePath);\n break;\n case 'local_new':\n status.addedLocally.push(c.filePath);\n break;\n case 'remote_new':\n status.addedRemotely.push(c.filePath);\n break;\n case 'remote_deleted':\n status.deletedRemotely.push(c.filePath);\n break;\n case 'local_deleted':\n status.deletedLocally.push(c.filePath);\n break;\n default:\n status.conflicts.push(SyncService.buildConflicts([c])[0]);\n break;\n }\n }\n\n return status;\n }\n\n async pull(options?: SyncOptions): Promise<{\n downloaded: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n conflictFilesWritten: string[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n ensureDirectoryExists(filesDir);\n\n const syncState = this.loadSyncState();\n // shouldIncludeFile must run even under --all so the hidden-file\n // gate (`.env`, `.vscode/`, `.git/`) stays in effect \u2014 these only\n // sync when explicitly listed in --include-ext / --include-folder.\n let remoteFiles = (await this.farseerClient.listFiles())\n .filter((f) => !isOsMetadataFile(f.path))\n .filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // Batch fetch metadata for all files\n remoteFiles = await this.fetchMetadataForFiles(remoteFiles);\n\n const result = {\n downloaded: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n conflictFilesWritten: [] as string[],\n };\n\n // Download file contents in parallel with concurrency limit\n logger.dim(`Fetching ${remoteFiles.length} files in parallel...`);\n const fileContents = await fetchWithConcurrency(\n remoteFiles,\n async (file, index) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n // Show progress every 10 files\n if ((index + 1) % 10 === 0 || index === remoteFiles.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteFiles.length} files`);\n }\n return { file, content };\n },\n 15,\n );\n // Clear progress line\n if (remoteFiles.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n // Build remote content map with hashes\n const remoteContentMap = new Map<string, { file: RemoteFile; content: Buffer; hash: string }>();\n const remoteHashes = new Map<string, string>();\n for (const { file, content } of fileContents) {\n const hash = calculateHash(content);\n remoteContentMap.set(file.path, { file, content, hash });\n remoteHashes.set(file.path, hash);\n }\n\n // Build local hashes. shouldIncludeFile runs on every entry so the\n // hidden-file gate stays in effect even under --all.\n const localFiles = getAllFilesInDir(filesDir);\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n if (!shouldIncludeFile(localFile, this.tenant, options)) {\n continue;\n }\n const localPath = safeResolveWithinBase(filesDir, localFile);\n const content = fs.readFileSync(localPath);\n localHashes.set(localFile, calculateHash(content));\n }\n\n // Three-way comparison\n const comparisons = this.compareFiles({\n localHashes,\n remoteHashes,\n syncState,\n all: options?.all,\n includeExtensions: options?.includeExtensions,\n includeFolders: options?.includeFolders,\n onlyFiles: options?.onlyFiles,\n });\n const resolutions = options?.conflictResolutions ?? {};\n\n for (const comparison of comparisons) {\n const { filePath, changeType } = comparison;\n const localPath = safeResolveWithinBase(filesDir, filePath);\n const remoteInfo = remoteContentMap.get(filePath);\n\n switch (changeType) {\n case 'unchanged':\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_modified':\n case 'local_new':\n if (options?.force && remoteInfo) {\n // --force on pull means \"make local match remote\".\n // Without this branch, local_modified silently went\n // into `unchanged` and the user's edit survived a\n // hard-reset \u2014 the opposite of what --force promises.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n if (remoteInfo) {\n const existingSync = syncState.files[filePath];\n if (existingSync) {\n existingSync.remoteHash = remoteInfo.hash;\n existingSync.metadata = this.buildMetadata(remoteInfo.file);\n }\n }\n break;\n\n case 'local_deleted':\n if (options?.force && remoteInfo) {\n // Force: restore the file the user removed locally.\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n break;\n }\n result.unchanged.push(filePath);\n break;\n\n case 'remote_modified':\n case 'remote_new':\n // Safe to write\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo!.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo!.hash,\n remoteHash: remoteInfo!.hash,\n metadata: this.buildMetadata(remoteInfo!.file),\n };\n break;\n\n case 'remote_deleted':\n // Safe to delete (local is unchanged)\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n }\n result.deleted.push(filePath);\n delete syncState.files[filePath];\n break;\n\n case 'conflict_both_modified':\n case 'conflict_local_modified_remote_deleted':\n case 'conflict_local_deleted_remote_modified':\n case 'conflict_both_new': {\n if (options?.force) {\n // Force: apply remote state\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted, force means delete local\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n }\n\n const resolution = resolutions[filePath];\n if (!resolution) {\n // No resolution provided - report conflict, skip file\n result.conflicts.push(SyncService.buildConflicts([comparison])[0]);\n break;\n }\n\n switch (resolution) {\n case 'keep_local':\n // Keep local as-is, update sync state to mark conflict resolved\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n } else {\n // Local was deleted, user wants to keep that decision\n delete syncState.files[filePath];\n }\n result.unchanged.push(filePath);\n break;\n\n case 'keep_remote':\n if (remoteInfo) {\n ensureDirectoryExists(path.dirname(localPath));\n fs.writeFileSync(localPath, remoteInfo.content);\n result.downloaded.push(filePath);\n syncState.files[filePath] = {\n localHash: remoteInfo.hash,\n remoteHash: remoteInfo.hash,\n metadata: this.buildMetadata(remoteInfo.file),\n };\n } else {\n // Remote deleted\n if (fs.existsSync(localPath)) {\n fs.unlinkSync(localPath);\n result.deleted.push(filePath);\n }\n delete syncState.files[filePath];\n }\n break;\n\n case 'keep_both':\n if (remoteInfo) {\n // Write remote version as .remote file alongside local\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteInfo.content);\n result.conflictFilesWritten.push(conflictFileName);\n }\n // Keep local, update sync state\n if (fs.existsSync(localPath)) {\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: remoteInfo ? this.buildMetadata(remoteInfo.file) : undefined,\n };\n }\n result.unchanged.push(filePath);\n break;\n\n case 'merge_markers':\n // git-style inline merge. Wrap LOCAL and REMOTE\n // versions with markers so any editor / IDE\n // highlights them. After the user resolves the\n // file (manually picks the version they want and\n // strips the markers), a regular `farseer push`\n // uploads the cleaned-up content. The push\n // pre-flight refuses any file that still has\n // markers in it, so an accidentally-unfinished\n // resolve never reaches the backend as broken\n // syntax.\n if (remoteInfo && fs.existsSync(localPath)) {\n const localBuf = fs.readFileSync(localPath);\n const remoteBuf = remoteInfo.content;\n\n // Binary safety gate. Splicing UTF-8 markers\n // into a .png/.xlsx/.zip would corrupt it\n // (the toString('utf-8') round-trip flips\n // bytes). Fall back to keep_both \u2014 write\n // remote alongside local as <name>.remote.<ext>\n // and let the user diff with their tool of\n // choice. Without this gate the user's binary\n // got silently overwritten with garbage.\n if (!isLikelyTextFile(filePath, localBuf) || !isLikelyTextFile(filePath, remoteBuf)) {\n const ext = path.extname(filePath);\n const base = filePath.slice(0, -ext.length || undefined);\n const conflictFileName = `${base}.remote${ext}`;\n const conflictPath = safeResolveWithinBase(filesDir, conflictFileName);\n ensureDirectoryExists(path.dirname(conflictPath));\n fs.writeFileSync(conflictPath, remoteBuf);\n const localHash = calculateHash(localBuf);\n syncState.files[filePath] = {\n localHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(\n `${conflictFileName} (binary \u2014 merge markers not safe; wrote .remote alongside)`,\n );\n result.unchanged.push(filePath);\n break;\n }\n\n const localContent = localBuf.toString('utf-8');\n const remoteContent = remoteBuf.toString('utf-8');\n const merged =\n `${MERGE_MARKER_LOCAL_START}\\n${localContent}` +\n `${localContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_SEPARATOR}\\n${remoteContent}` +\n `${remoteContent.endsWith('\\n') ? '' : '\\n'}` +\n `${MERGE_MARKER_REMOTE_END}\\n`;\n fs.writeFileSync(localPath, merged);\n // Update syncState so push sees this as\n // \"locally modified\" (localHash differs from\n // remoteHash). User pushes cleaned-up file\n // after manually resolving.\n const newHash = calculateHash(Buffer.from(merged));\n syncState.files[filePath] = {\n localHash: newHash,\n remoteHash: comparison.currentRemoteHash ?? '',\n metadata: this.buildMetadata(remoteInfo.file),\n };\n result.conflictFilesWritten.push(`${filePath} (merge markers)`);\n } else if (!remoteInfo && fs.existsSync(localPath)) {\n // Remote is gone \u2014 fall back to keep_local.\n // No useful merge for \"your version vs nothing\".\n const localContent = fs.readFileSync(localPath);\n const localHash = calculateHash(localContent);\n syncState.files[filePath] = { localHash, remoteHash: '' };\n }\n result.unchanged.push(filePath);\n break;\n }\n break;\n }\n }\n }\n\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n\n return result;\n }\n\n private buildMetadata(file: RemoteFile): SyncFileInfo['metadata'] {\n if (!file.metadata) return undefined;\n return {\n uploadTime: file.metadata.uploadTime,\n uploaderEmail: file.metadata.uploader?.email,\n uploaderName: file.metadata.uploader\n ? `${file.metadata.uploader.firstName} ${file.metadata.uploader.lastName}`.trim()\n : undefined,\n lastFetched: new Date().toISOString(),\n };\n }\n\n async push(options?: {\n force?: boolean;\n mirror?: boolean;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n /**\n * Pre-fetched remote-content hashes keyed by file path. Optional\n * optimisation for callers (push.ts) that already ran a deep\n * status \u2014 that pass already downloaded every remote file's body,\n * so we can skip the second remote fetch here when the entries\n * cover everything we'd otherwise refetch. Missing keys still\n * trigger a fetch as before, so it's safe to pass a partial map.\n */\n precomputedRemoteHashes?: Map<string, string>;\n }): Promise<{\n uploaded: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n conflicts: SyncConflict[];\n rejected: ValidationFailure[];\n failed: PushFailure[];\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const syncState = this.loadSyncState();\n\n const result = {\n uploaded: [] as string[],\n updated: [] as string[],\n deleted: [] as string[],\n unchanged: [] as string[],\n conflicts: [] as SyncConflict[],\n rejected: [] as ValidationFailure[],\n // Per-file failures from create/update/delete API calls. We don't\n // abort the whole push on the first failure \u2014 each item is its\n // own atomic operation, and `syncState` is saved in `finally` so\n // already-successful items aren't re-uploaded next run. The\n // caller surfaces this list and exits non-zero on non-empty.\n failed: [] as PushFailure[],\n };\n\n // Get current remote files (just the list, not content). Filter out\n // OS metadata defensively in case anyone ever pushed one before.\n const remoteFiles = (await this.farseerClient.listFiles()).filter((f) => !isOsMetadataFile(f.path));\n const remoteFileMap = new Map<string, RemoteFile>();\n for (const file of remoteFiles) {\n remoteFileMap.set(file.path, file);\n }\n\n // OS metadata is stripped at the helper level (getAllFilesInDir),\n // so we never try to upload the user's filesystem bookkeeping \u2014\n // backend rejects those filenames and the user can't reasonably\n // remove them from the working tree.\n const allLocalFiles = getAllFilesInDir(filesDir);\n\n // Apply the user's declared sync scope BEFORE we treat anything as\n // an upload candidate. Without this filter, push iterates every\n // file the disk listing returned and any whitelisted-extension\n // bystander gets shipped to remote \u2014 e.g. a `.vscode/settings.json`\n // sitting next to scripts passes pre-flight (`.json` is on the\n // backend whitelist) and is silently uploaded under a default\n // `farseer push`. The status preview already filters by\n // `shouldIncludeFile`, so the user wouldn't even see it coming.\n // Pin the same scope here.\n //\n // `localPresenceSet` keeps the FULL on-disk listing, separately,\n // so the delete loop's \"is this file actually missing locally?\"\n // protection still works for any file the user has \u2014 including\n // out-of-scope ones we won't touch.\n const localPresenceSet = new Set(allLocalFiles);\n // Always route through shouldIncludeFile \u2014 under --all the function\n // returns true for non-hidden files under --all but still gates\n // hidden ones (.env, .vscode/, .git/) so they require explicit\n // --include-ext / --include-folder opt-in.\n const inScopeFiles = allLocalFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));\n\n const localContents = new Map<string, Buffer>();\n for (const file of inScopeFiles) {\n const fullPath = safeResolveWithinBase(filesDir, file);\n localContents.set(file, fs.readFileSync(fullPath));\n }\n\n // Pre-flight: refuse files the backend will refuse anyway. We do\n // this before any network call so the user sees a single grouped\n // verdict (\"3 file(s) skipped: extension not allowed, \u2026\") rather\n // than a half-finished push that errors mid-stream with an opaque\n // 400. Files that fail validation never reach the upload loop, but\n // they still count toward `result.rejected` so the caller can show\n // them to the user and exit non-zero.\n const validationInputs = inScopeFiles.map((filePath) => {\n const content = localContents.get(filePath)!;\n return {\n filePath,\n size: content.length,\n content,\n };\n });\n const { valid: pushableValidatedFiles, rejected } = partitionForUpload(validationInputs);\n result.rejected = rejected;\n // `localFiles` = files we'll consider for upload (in-scope, validated).\n const localFiles = pushableValidatedFiles.map((f) => f.filePath);\n\n const localHashes = new Map<string, string>();\n for (const localFile of localFiles) {\n localHashes.set(localFile, calculateHash(localContents.get(localFile)!));\n }\n\n // Identify candidates that need remote content check for conflict detection.\n // Compare against syncInfo.remoteHash (not .localHash): a file is a\n // candidate whenever local diverges from what we last knew about remote,\n // which also covers keep_local / keep_both resolutions where localHash\n // matches baseline local but remoteHash points at the conflicting remote.\n //\n // Mirror exception: under `mirror: true` we treat EVERY locally-\n // present file that also exists on remote as a candidate, so we can\n // re-fetch the actual remote hash and detect content drift even on\n // files our baseline marks as \"in sync\". Without this, a user who\n // ran `push --force --mirror` after someone else edited a remote\n // file (with our recorded baseline still stale) would skip the\n // upload entirely and remote stays diverged.\n const candidateFiles: string[] = [];\n for (const localFile of localFiles) {\n const syncInfo = syncState.files[localFile];\n const localHash = localHashes.get(localFile)!;\n const baselineDiverged = !syncInfo || localHash !== syncInfo.remoteHash;\n if (!remoteFileMap.has(localFile)) continue;\n if (baselineDiverged || options?.mirror) {\n candidateFiles.push(localFile);\n }\n }\n // Also check files in sync state that no longer exist locally (local deletions).\n // Use `localPresenceSet` (not `localFiles`): rejected files DO exist\n // locally \u2014 they just can't be uploaded \u2014 so they must NOT count as\n // \"locally deleted\" and must NOT trigger remote deletion. Scope-filter\n // too: a `Data/foo.csv` previously synced under `--include-ext .csv`\n // shouldn't get deleted on a default push without the same flag \u2014\n // out-of-scope files are invisible this run. shouldIncludeFile\n // handles the --all gate plus the hidden-file gate together.\n const inScope = (f: string) => shouldIncludeFile(f, this.tenant, options);\n const locallyDeletedFiles = Object.keys(syncState.files).filter(\n (f) => !localPresenceSet.has(f) && remoteFileMap.has(f) && inScope(f),\n );\n const filesToFetchRemote = [...new Set([...candidateFiles, ...locallyDeletedFiles])];\n\n // Fetch remote content for conflict detection. We skip the fetch\n // under plain `force: true` (the user said 'overwrite, don't ask\n // questions') \u2014 but under `mirror: true` we DO need it: mirror\n // semantics rest on knowing the actual remote hash so we can decide\n // 'do we re-upload because remote drifted?'.\n //\n // Caller can pass `precomputedRemoteHashes` to skip the network\n // round-trip for entries already in hand (e.g. push.ts ran a deep\n // getStatus right before this and already paid for every fetch).\n // Files NOT in the map still get fetched here, so the fast-path\n // is safe with partial coverage.\n const remoteHashes = new Map<string, string>(options?.precomputedRemoteHashes ?? []);\n if (filesToFetchRemote.length > 0 && (!options?.force || options?.mirror)) {\n const toFetch = filesToFetchRemote\n .filter((f) => remoteFileMap.has(f) && !remoteHashes.has(f))\n .map((f) => remoteFileMap.get(f)!);\n\n if (toFetch.length > 0) {\n const fetched = await fetchWithConcurrency(\n toFetch,\n async (file) => {\n const content = await this.farseerClient.getFileContentAsBuffer(file.reference);\n return { file, hash: calculateHash(content) };\n },\n 15,\n );\n\n for (const { file, hash } of fetched) {\n remoteHashes.set(file.path, hash);\n }\n }\n }\n\n // Three-way comparison for conflict detection\n const comparisons = this.compareFiles({ localHashes, remoteHashes, syncState, all: true });\n const conflictPaths = new Set<string>();\n\n if (!options?.force) {\n for (const c of comparisons) {\n if (c.changeType.startsWith('conflict_')) {\n const conflict = SyncService.buildConflicts([c])[0];\n result.conflicts.push(conflict);\n conflictPaths.add(c.filePath);\n }\n }\n }\n\n // Per-file try/catch around every backend call. A single 5xx (or\n // any other transient error) on file N must not lose progress on\n // files 1..N-1: we log into result.failed[], save syncState in the\n // outer `finally`, and let the user re-run. Without this, an\n // interrupted run would re-upload everything and risk creating\n // dupes for items the backend silently committed before failing.\n try {\n // Process non-conflicting files\n for (const localFile of localFiles) {\n if (conflictPaths.has(localFile)) continue;\n\n const content = localContents.get(localFile)!;\n const localHash = localHashes.get(localFile)!;\n\n const remoteFile = remoteFileMap.get(localFile);\n const syncInfo = syncState.files[localFile];\n\n if (remoteFile) {\n // File exists on remote. Push when local diverges from what we\n // last recorded as the remote hash. Using remoteHash (not\n // localHash) means keep_local / keep_both conflict resolutions \u2014\n // where localHash gets updated to current local but remoteHash\n // still carries the conflicting remote hash \u2014 correctly trigger\n // an upload instead of being silently marked as unchanged.\n //\n // Mirror exception: under `mirror: true` the user explicitly\n // asked for \"remote == local\". Trusting our recorded\n // remoteHash here can mark the file unchanged even though\n // the real remote content drifted. Re-fetched currentRemoteHash\n // (when available \u2014 drift fetch step above runs even under\n // force/mirror for non-conflict candidates) lets us tell.\n // If we have a real remote hash and it matches local, skip\n // the upload (saves a roundtrip); otherwise overwrite.\n const currentRemoteHash = remoteHashes.get(localFile);\n const mirrorWantsRecreate =\n options?.mirror && currentRemoteHash !== undefined && currentRemoteHash !== localHash;\n if (syncInfo && localHash === syncInfo.remoteHash && !mirrorWantsRecreate) {\n result.unchanged.push(localFile);\n } else {\n // Drift check: before overwriting remote, make sure remote\n // still has the version we last recorded. If someone else\n // (or a still-pending background job) moved remote forward\n // since our baseline, and this isn't a forced push, refuse\n // to silently overwrite it. Without this, the keep_local\n // path can clobber a newer remote edit because the file's\n // changeType comes back as 'remote_modified' (not\n // conflict_*) and would otherwise sail through.\n // (currentRemoteHash already declared above for the\n // mirror-recreate check; reuse it here.)\n if (\n !options?.force &&\n syncInfo &&\n currentRemoteHash !== undefined &&\n currentRemoteHash !== syncInfo.remoteHash\n ) {\n result.conflicts.push({\n filePath: localFile,\n type: 'both_modified',\n description: 'Remote changed since last sync \u2014 pull first or use --force to overwrite',\n });\n continue;\n }\n try {\n await this.farseerClient.updateFile(\n remoteFile.reference,\n content,\n path.basename(localFile),\n );\n result.updated.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'update',\n reason: await formatClientError(err),\n });\n }\n }\n } else {\n // File doesn't exist on remote.\n //\n // Default push: respect the remote deletion (someone deleted\n // it via UI, we shouldn't undo their action just because\n // we still have the file locally and our baseline says it\n // used to be on remote). Mark unchanged.\n //\n // Mirror push (`mirror: true`): the user explicitly asked\n // for \"remote == local\". A local copy that's no longer on\n // remote means we need to RECREATE it on remote \u2014 falling\n // through to the upload branch below does that.\n if (syncInfo && localHash === syncInfo.remoteHash && !options?.mirror) {\n result.unchanged.push(localFile);\n } else {\n // New or modified local file - upload\n const pathParts = localFile.split('/');\n const fileName = pathParts.pop()!;\n const folderPath = ['Files', ...pathParts];\n try {\n await this.farseerClient.createFile(content, fileName, folderPath);\n result.uploaded.push(localFile);\n syncState.files[localFile] = {\n localHash: localHash,\n remoteHash: localHash,\n };\n } catch (err) {\n result.failed.push({\n filePath: localFile,\n operation: 'create',\n reason: await formatClientError(err),\n });\n }\n }\n }\n }\n\n // Delete files on remote that were deleted locally.\n //\n // Default: only delete files we previously pulled (`syncInfo` exists)\n // \u2014 that's how you express \"I just `rm`'d this file, please match\".\n // Mirror mode (`push --force` from the CLI surface): also delete\n // remote files that have no local counterpart at all, even if we\n // never pulled them. This is the \"make remote = local\" semantics\n // the CLI promises with --force, but it's destructive enough that\n // the command layer must confirm with the user before passing\n // `mirror: true`.\n // Honour the same `--include-ext` / `--include-folder` scope the\n // command layer used for the preview. Out-of-scope files are\n // invisible this run \u2014 even when syncState remembers them. Without\n // the gate on the syncInfo branch, a default `farseer push`\n // (no `--include-ext .csv`) after a previous `farseer push\n // --include-ext .csv` plus a local rm would silently nuke\n // Data/foo.csv on remote. Cross-scope side effects are exactly\n // what users don't expect from a default-flag run.\n for (const [remotePath, remoteFile] of remoteFileMap) {\n if (localPresenceSet.has(remotePath) || conflictPaths.has(remotePath)) continue;\n if (!inScope(remotePath)) continue;\n const syncInfo = syncState.files[remotePath];\n const shouldDelete = syncInfo ? true : Boolean(options?.mirror);\n if (!shouldDelete) continue;\n try {\n await this.farseerClient.deleteFile(remoteFile.reference);\n result.deleted.push(remotePath);\n delete syncState.files[remotePath];\n } catch (err) {\n result.failed.push({\n filePath: remotePath,\n operation: 'delete',\n reason: await formatClientError(err),\n });\n }\n }\n } finally {\n // Always persist progress, even on partial failure or if the\n // outer flow is cancelled with Ctrl-C between files. The next\n // run reads this state and skips items we already finished.\n syncState.lastSync = new Date().toISOString();\n this.saveSyncState(syncState);\n }\n\n return result;\n }\n\n /**\n * Detect whether the remote has files we haven't seen yet (or recorded\n * files no longer present on remote) within the current sync scope.\n *\n * Returns the set of paths that are causing drift so the command layer\n * can show the user exactly what's blocking the push and suggest a\n * matching `farseer pull` command. The previous boolean-only return\n * gave the user just \"Remote has changes\" with no clue WHICH file \u2014\n * and `farseer pull` (without the same `--include-ext`/`--include-folder`)\n * silently said \"Already up to date\" because it ran in a different\n * scope, leaving the user stuck in an infinite \"pull says clean, push\n * says drift\" loop.\n */\n async checkRemoteChanges(options?: SyncOptions): Promise<{\n drift: boolean;\n addedRemotely: string[];\n deletedRemotely: string[];\n }> {\n const syncState = this.loadSyncState();\n let remoteFiles = await this.farseerClient.listFiles();\n\n // Filter files based on includes to avoid false positives\n remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));\n\n // We need local presence too: a syncState entry for a file that's\n // gone from BOTH local and remote is just stale baseline \u2014 neither\n // side can act on it, and flagging it as drift sends the user to a\n // pull that does nothing. Only count \"remote-deleted\" when local\n // still has the file (so the upcoming pull would clean it up).\n const filesDir = getTenantFilesDir(this.tenant);\n const localPresenceSet = new Set(getAllFilesInDir(filesDir));\n\n const addedRemotely: string[] = [];\n const deletedRemotely: string[] = [];\n\n // New files on remote that we don't have in sync state.\n for (const file of remoteFiles) {\n if (!syncState.files[file.path]) {\n addedRemotely.push(file.path);\n }\n }\n\n // Files deleted on remote that we have in sync state. Skip if local\n // is also missing (stale baseline \u2014 treat as already cleaned, the\n // next pull will drop it from syncState without any drift signal\n // confusing the user).\n const remotePaths = new Set(remoteFiles.map((f) => f.path));\n for (const filePath of Object.keys(syncState.files)) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) continue;\n if (remotePaths.has(filePath)) continue;\n if (!syncState.files[filePath].remoteHash) continue;\n if (!localPresenceSet.has(filePath)) continue;\n deletedRemotely.push(filePath);\n }\n\n // Note: we don't check for content changes here for performance.\n // After a pull, sync state is accurate. Content changes by others\n // between pull and push are surfaced through the per-file drift\n // check inside push() instead.\n return {\n drift: addedRemotely.length > 0 || deletedRemotely.length > 0,\n addedRemotely,\n deletedRemotely,\n };\n }\n\n async getFileDiff(filePath: string): Promise<{\n localContent: string | null;\n remoteContent: string | null;\n }> {\n const filesDir = getTenantFilesDir(this.tenant);\n const localPath = safeResolveWithinBase(filesDir, filePath);\n\n let localContent: string | null = null;\n let remoteContent: string | null = null;\n\n if (fs.existsSync(localPath)) {\n // For diff, read as text (diff only makes sense for text files)\n localContent = fs.readFileSync(localPath, 'utf-8');\n }\n\n const remoteFile = await this.farseerClient.getFileByPath(filePath);\n if (remoteFile) {\n remoteContent = await this.farseerClient.getFileContent(remoteFile.reference);\n }\n\n return { localContent, remoteContent };\n }\n\n /**\n * Three-way comparison of all files.\n * Compares current local state, current remote state, and baseline from sync state.\n */\n compareFiles(options: {\n localHashes: Map<string, string>;\n remoteHashes: Map<string, string>;\n syncState: SyncState;\n all?: boolean;\n includeExtensions?: string[];\n includeFolders?: string[];\n // Pass-through for `--only`: shouldIncludeFile honours it ahead of\n // ext/folder rules, but only if it's actually in `options`. Without\n // this, push --only would build a status that ignores the whitelist\n // (compareFiles re-runs shouldIncludeFile with only the ext/folder\n // fields above) and a non-.ts/.js whitelisted path would be filtered\n // out as out-of-scope.\n onlyFiles?: string[];\n }): FileCompareResult[] {\n const { localHashes, remoteHashes, syncState } = options;\n\n // Union of all known file paths\n const allPaths = new Set<string>([\n ...localHashes.keys(),\n ...remoteHashes.keys(),\n ...Object.keys(syncState.files),\n ]);\n\n const results: FileCompareResult[] = [];\n\n for (const filePath of allPaths) {\n // Filter files based on includes\n if (!options.all) {\n if (!shouldIncludeFile(filePath, this.tenant, options)) {\n continue;\n }\n }\n\n const currentLocalHash = localHashes.get(filePath) ?? null;\n const currentRemoteHash = remoteHashes.get(filePath) ?? null;\n const baseline = syncState.files[filePath];\n const baselineLocalHash = baseline?.localHash ?? null;\n const baselineRemoteHash = baseline?.remoteHash ?? null;\n\n const localExists = currentLocalHash !== null;\n const remoteExists = currentRemoteHash !== null;\n const hadBaseline = baseline != null;\n\n let changeType: FileChangeType;\n\n if (localExists && remoteExists) {\n // Both exist\n if (currentLocalHash === currentRemoteHash) {\n changeType = 'unchanged';\n } else if (!hadBaseline) {\n changeType = 'conflict_both_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n const baselineDivergent = baselineLocalHash !== baselineRemoteHash;\n\n if (localChanged && remoteChanged) {\n changeType = 'conflict_both_modified';\n } else if (localChanged) {\n changeType = 'local_modified';\n } else if (remoteChanged) {\n changeType = 'remote_modified';\n } else if (baselineDivergent) {\n // Post `keep_local` / `keep_both` resolution: nothing\n // changed since baseline, but baseline already recorded\n // local diverged from remote on purpose. The user\n // chose local; we still need to push so remote\n // catches up. Without this branch, status & push\n // would both fall through to \"unchanged\" and the\n // local edit would silently never reach remote.\n changeType = 'local_modified';\n } else {\n changeType = 'unchanged';\n }\n }\n } else if (localExists && !remoteExists) {\n // Only local exists\n if (!hadBaseline) {\n changeType = 'local_new';\n } else {\n const localChanged = currentLocalHash !== baselineLocalHash;\n if (localChanged) {\n changeType = 'conflict_local_modified_remote_deleted';\n } else {\n changeType = 'remote_deleted';\n }\n }\n } else if (!localExists && remoteExists) {\n // Only remote exists\n if (!hadBaseline) {\n changeType = 'remote_new';\n } else {\n const remoteChanged = currentRemoteHash !== baselineRemoteHash;\n if (remoteChanged) {\n changeType = 'conflict_local_deleted_remote_modified';\n } else {\n changeType = 'local_deleted';\n }\n }\n } else {\n // Neither exists - both deleted since baseline, clean up\n continue;\n }\n\n results.push({\n filePath,\n changeType,\n currentLocalHash,\n currentRemoteHash,\n baselineLocalHash,\n baselineRemoteHash,\n });\n }\n\n return results;\n }\n\n /**\n * Extract SyncConflict[] from FileCompareResult[].\n */\n static buildConflicts(comparisons: FileCompareResult[]): SyncConflict[] {\n const conflicts: SyncConflict[] = [];\n for (const c of comparisons) {\n switch (c.changeType) {\n case 'conflict_both_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_modified',\n description: 'Both local and remote versions modified since last sync',\n });\n break;\n case 'conflict_local_modified_remote_deleted':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_modified_remote_deleted',\n description: 'File modified locally but deleted on remote',\n });\n break;\n case 'conflict_local_deleted_remote_modified':\n conflicts.push({\n filePath: c.filePath,\n type: 'local_deleted_remote_modified',\n description: 'File deleted locally but modified on remote',\n });\n break;\n case 'conflict_both_new':\n conflicts.push({\n filePath: c.filePath,\n type: 'both_new',\n description: 'File exists both locally and remotely with different content (no sync baseline)',\n });\n break;\n }\n }\n return conflicts;\n }\n\n /**\n * Batch fetch metadata for multiple files in parallel.\n * Fetches metadata in batches of 10 to avoid overwhelming the API.\n * Non-critical operation - failures are silently ignored.\n */\n private async fetchMetadataForFiles(files: RemoteFile[]): Promise<RemoteFile[]> {\n const batchSize = 10;\n\n for (let i = 0; i < files.length; i += batchSize) {\n const batch = files.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const metadata = await this.farseerClient.getFileMetadata(file.reference);\n if (metadata) {\n file.metadata = metadata;\n }\n } catch {\n // Silently ignore metadata fetch errors - non-critical\n }\n }),\n );\n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X;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,sBAAsB,OAA4C;AAC5E,UAAM,YAAY;AAElB,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;AAC9C,YAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,SAAS;AAE1C,YAAM,QAAQ;AAAA,QACV,MAAM,IAAI,OAAO,SAAS;AACtB,cAAI;AACA,kBAAM,WAAW,MAAM,KAAK,cAAc,gBAAgB,KAAK,SAAS;AACxE,gBAAI,UAAU;AACV,mBAAK,WAAW;AAAA,YACpB;AAAA,UACJ,QAAQ;AAAA,UAER;AAAA,QACJ,CAAC;AAAA,MACL;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
|
|
6
6
|
"names": ["import_helpers"]
|
|
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.4.5";
|
|
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.4.5';\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,CAAC,QAAS,QAAO;AAGrB,QAAM,QAAQ,QAAQ,SAAS,GAAG,IAAI,IAAI;AAC1C,SAAO,CAAC,MAAM,SAAS,CAAC;AAC5B;AAEO,SAAS,6BAA6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AM;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
|
}
|
package/dist/utils/helpers.js
CHANGED
|
@@ -62,7 +62,8 @@ __export(helpers_exports, {
|
|
|
62
62
|
resolveTenantWithOrgMapping: () => resolveTenantWithOrgMapping,
|
|
63
63
|
safeResolveWithinBase: () => safeResolveWithinBase,
|
|
64
64
|
stripCredentials: () => stripCredentials,
|
|
65
|
-
stripCredentialsInDir: () => stripCredentialsInDir
|
|
65
|
+
stripCredentialsInDir: () => stripCredentialsInDir,
|
|
66
|
+
validateOnlyFilePaths: () => validateOnlyFilePaths
|
|
66
67
|
});
|
|
67
68
|
module.exports = __toCommonJS(helpers_exports);
|
|
68
69
|
var crypto = __toESM(require("crypto"));
|
|
@@ -112,6 +113,20 @@ function safeResolveWithinBase(baseDir, filePath) {
|
|
|
112
113
|
}
|
|
113
114
|
return resolved;
|
|
114
115
|
}
|
|
116
|
+
function validateOnlyFilePaths(baseDir, paths) {
|
|
117
|
+
const missing = [];
|
|
118
|
+
for (const p of paths) {
|
|
119
|
+
try {
|
|
120
|
+
const fullPath = safeResolveWithinBase(baseDir, p);
|
|
121
|
+
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
|
|
122
|
+
missing.push(p);
|
|
123
|
+
}
|
|
124
|
+
} catch {
|
|
125
|
+
missing.push(p);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return { missing };
|
|
129
|
+
}
|
|
115
130
|
const OS_METADATA_BASENAMES = /* @__PURE__ */ new Set([
|
|
116
131
|
".DS_Store",
|
|
117
132
|
// macOS Finder
|
|
@@ -478,6 +493,7 @@ function appendToAuditLog(tenant, entries) {
|
|
|
478
493
|
resolveTenantWithOrgMapping,
|
|
479
494
|
safeResolveWithinBase,
|
|
480
495
|
stripCredentials,
|
|
481
|
-
stripCredentialsInDir
|
|
496
|
+
stripCredentialsInDir,
|
|
497
|
+
validateOnlyFilePaths
|
|
482
498
|
});
|
|
483
499
|
//# sourceMappingURL=helpers.js.map
|