farseer-cli 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +102 -30
  2. package/dist/commands/checkout.js +3 -8
  3. package/dist/commands/checkout.js.map +2 -2
  4. package/dist/commands/model.js +0 -3
  5. package/dist/commands/model.js.map +2 -2
  6. package/dist/commands/pull.js +159 -46
  7. package/dist/commands/pull.js.map +2 -2
  8. package/dist/commands/push.js +185 -75
  9. package/dist/commands/push.js.map +2 -2
  10. package/dist/commands/run.js +31 -30
  11. package/dist/commands/run.js.map +2 -2
  12. package/dist/commands/status.js +26 -33
  13. package/dist/commands/status.js.map +2 -2
  14. package/dist/commands/variables.js +0 -3
  15. package/dist/commands/variables.js.map +2 -2
  16. package/dist/index.js +5 -3
  17. package/dist/index.js.map +2 -2
  18. package/dist/mcp/tools/appTools.js +6 -20
  19. package/dist/mcp/tools/appTools.js.map +2 -2
  20. package/dist/mcp/tools/authTools.js +2 -1
  21. package/dist/mcp/tools/authTools.js.map +2 -2
  22. package/dist/mcp/tools/cellTools.js +2 -10
  23. package/dist/mcp/tools/cellTools.js.map +2 -2
  24. package/dist/mcp/tools/dashboardTools.js +12 -23
  25. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  26. package/dist/mcp/tools/dataTools.js +5 -16
  27. package/dist/mcp/tools/dataTools.js.map +2 -2
  28. package/dist/mcp/tools/folderTools.js +3 -11
  29. package/dist/mcp/tools/folderTools.js.map +2 -2
  30. package/dist/mcp/tools/modelTools.js +14 -40
  31. package/dist/mcp/tools/modelTools.js.map +2 -2
  32. package/dist/mcp/tools/runTools.js +3 -8
  33. package/dist/mcp/tools/runTools.js.map +2 -2
  34. package/dist/mcp/tools/sheetTools.js +11 -22
  35. package/dist/mcp/tools/sheetTools.js.map +2 -2
  36. package/dist/mcp/tools/syncTools.js +132 -47
  37. package/dist/mcp/tools/syncTools.js.map +2 -2
  38. package/dist/mcp/utils/helpers.js +2 -2
  39. package/dist/mcp/utils/helpers.js.map +2 -2
  40. package/dist/services/appSyncService.js +3 -2
  41. package/dist/services/appSyncService.js.map +2 -2
  42. package/dist/services/farseerApi.js +16 -37
  43. package/dist/services/farseerApi.js.map +2 -2
  44. package/dist/services/farseerFactory.js +1 -1
  45. package/dist/services/farseerFactory.js.map +2 -2
  46. package/dist/services/farseerService.js +30 -17
  47. package/dist/services/farseerService.js.map +2 -2
  48. package/dist/services/syncService.js +322 -182
  49. package/dist/services/syncService.js.map +3 -3
  50. package/dist/utils/cliOptions.js +36 -0
  51. package/dist/utils/cliOptions.js.map +7 -0
  52. package/dist/utils/errorFormatter.js +152 -0
  53. package/dist/utils/errorFormatter.js.map +7 -0
  54. package/dist/utils/fileLogger.js +13 -0
  55. package/dist/utils/fileLogger.js.map +2 -2
  56. package/dist/utils/fileValidation.js +180 -0
  57. package/dist/utils/fileValidation.js.map +7 -0
  58. package/dist/utils/helpers.js +85 -14
  59. package/dist/utils/helpers.js.map +2 -2
  60. package/docs/cli-guide.md +49 -4
  61. package/package.json +1 -1
@@ -28,7 +28,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var syncService_exports = {};
30
30
  __export(syncService_exports, {
31
+ MERGE_MARKER_LOCAL_START: () => MERGE_MARKER_LOCAL_START,
32
+ MERGE_MARKER_REMOTE_END: () => MERGE_MARKER_REMOTE_END,
33
+ MERGE_MARKER_SEPARATOR: () => MERGE_MARKER_SEPARATOR,
31
34
  SyncService: () => SyncService,
35
+ isHiddenFile: () => import_helpers2.isHiddenFile,
36
+ isOsMetadataFile: () => import_helpers2.isOsMetadataFile,
32
37
  shouldIncludeFile: () => shouldIncludeFile
33
38
  });
34
39
  module.exports = __toCommonJS(syncService_exports);
@@ -38,19 +43,35 @@ var import_farseerFactory = require("./farseerFactory");
38
43
  var import_configService = require("./configService");
39
44
  var import_helpers = require("../utils/helpers");
40
45
  var import_logger = require("../utils/logger");
46
+ var import_fileValidation = require("../utils/fileValidation");
47
+ var import_errorFormatter = require("../utils/errorFormatter");
48
+ var import_helpers2 = require("../utils/helpers");
41
49
  function shouldIncludeFile(filePath, tenant, options) {
42
- if (options?.all) return true;
50
+ if ((0, import_helpers.isOsMetadataFile)(filePath)) return false;
43
51
  const ext = path.extname(filePath).toLowerCase();
52
+ const persistent = (0, import_configService.getSyncIncludes)(tenant);
53
+ const matchesIncludes = (options?.includeExtensions?.includes(ext) ?? false) || (options?.includeFolders?.some((f) => filePath.startsWith(f + "/") || filePath === f) ?? false) || (persistent?.extensions?.includes(ext) ?? false) || (persistent?.folders?.some((f) => filePath.startsWith(f + "/") || filePath === f) ?? false);
54
+ if ((0, import_helpers.isHiddenFile)(filePath)) return matchesIncludes;
55
+ if (options?.all) return true;
44
56
  if (import_farseerFactory.DEFAULT_SCRIPT_EXTENSIONS.includes(ext)) return true;
45
- if (options?.includeExtensions?.includes(ext)) return true;
46
- if (options?.includeFolders?.some((f) => filePath.startsWith(f + "/") || filePath === f)) return true;
47
- const includes = (0, import_configService.getSyncIncludes)(tenant);
48
- if (includes) {
49
- if (includes.extensions?.includes(ext)) return true;
50
- if (includes.folders?.some((f) => filePath.startsWith(f + "/") || filePath === f)) return true;
51
- }
52
- return false;
57
+ return matchesIncludes;
58
+ }
59
+ function emptyStatus(deepCompare) {
60
+ return {
61
+ addedLocally: [],
62
+ modifiedLocally: [],
63
+ deletedLocally: [],
64
+ addedRemotely: [],
65
+ modifiedRemotely: [],
66
+ deletedRemotely: [],
67
+ inSync: [],
68
+ conflicts: [],
69
+ deepCompare
70
+ };
53
71
  }
72
+ const MERGE_MARKER_LOCAL_START = "<<<<<<< LOCAL (your version)";
73
+ const MERGE_MARKER_SEPARATOR = "=======";
74
+ const MERGE_MARKER_REMOTE_END = ">>>>>>> REMOTE";
54
75
  class SyncService {
55
76
  constructor(tenant, farseerClient) {
56
77
  this.tenant = tenant;
@@ -80,97 +101,56 @@ class SyncService {
80
101
  fs.writeFileSync(syncFilePath, JSON.stringify(state, null, 2), "utf-8");
81
102
  }
82
103
  /**
83
- * Fast status check that uses sync state instead of downloading remote file content.
84
- * This is much faster than getStatus() but may miss changes made by others since last pull.
85
- * Use this for push operations where we trust the sync state.
104
+ * Single status engine used by both `farseer status` and the push
105
+ * preflight. By default (deep=false) we list remote files but don't
106
+ * download their content — fast on big tenants and accurate for adds,
107
+ * deletes, and *local* edits. Pass deep=true (or `farseer status --deep`)
108
+ * to also detect remote-side edits, which requires hashing every remote
109
+ * file.
110
+ *
111
+ * Output buckets are explicit (added/modified/deleted on each side) so
112
+ * the user never sees "M file.ts" for a file that's actually deleted on
113
+ * one side — a regular failure mode of the previous two-bucket layout.
86
114
  */
87
- async getStatusFast(options) {
88
- const syncState = this.loadSyncState();
89
- const filesDir = (0, import_helpers.getTenantFilesDir)(this.tenant);
90
- let localFiles = (0, import_helpers.getAllFilesInDir)(filesDir);
91
- if (!options?.all) {
92
- localFiles = localFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));
93
- }
94
- let remoteFiles = await this.farseerClient.listFiles();
95
- if (!options?.all) {
96
- remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));
97
- }
98
- const remoteFilePaths = new Set(remoteFiles.map((f) => f.path));
99
- const status = {
100
- modifiedLocally: [],
101
- modifiedRemotely: [],
102
- onlyLocal: [],
103
- onlyRemote: [],
104
- inSync: [],
105
- conflicts: []
106
- };
107
- for (const localFile of localFiles) {
108
- const localPath = path.join(filesDir, localFile);
109
- const content = fs.readFileSync(localPath);
110
- const localHash = (0, import_helpers.calculateHash)(content);
111
- const syncInfo = syncState.files[localFile];
112
- if (remoteFilePaths.has(localFile)) {
113
- if (syncInfo && localHash === syncInfo.localHash) {
114
- status.inSync.push(localFile);
115
- } else {
116
- status.modifiedLocally.push(localFile);
117
- }
118
- } else {
119
- if (syncInfo && syncInfo.remoteHash) {
120
- if (localHash !== syncInfo.localHash) {
121
- status.conflicts.push({
122
- filePath: localFile,
123
- type: "local_modified_remote_deleted",
124
- description: "File modified locally but deleted on remote"
125
- });
126
- } else {
127
- status.modifiedRemotely.push(localFile);
128
- }
129
- } else {
130
- status.onlyLocal.push(localFile);
131
- }
132
- }
133
- }
134
- for (const remoteFile of remoteFiles) {
135
- if (!localFiles.includes(remoteFile.path)) {
136
- const syncInfo = syncState.files[remoteFile.path];
137
- if (syncInfo && syncInfo.localHash) {
138
- status.modifiedLocally.push(remoteFile.path);
139
- } else {
140
- status.onlyRemote.push(remoteFile.path);
141
- }
142
- }
143
- }
144
- return status;
145
- }
146
115
  async getStatus(options) {
116
+ const deep = options?.deep === true;
147
117
  const syncState = this.loadSyncState();
148
118
  const filesDir = (0, import_helpers.getTenantFilesDir)(this.tenant);
149
- let localFiles = (0, import_helpers.getAllFilesInDir)(filesDir);
150
- if (!options?.all) {
151
- localFiles = localFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));
152
- }
119
+ const localFiles = (0, import_helpers.getAllFilesInDir)(filesDir).filter((f) => shouldIncludeFile(f, this.tenant, options));
153
120
  const localHashes = /* @__PURE__ */ new Map();
154
121
  for (const file of localFiles) {
155
- const fullPath = path.join(filesDir, file);
122
+ const fullPath = (0, import_helpers.safeResolveWithinBase)(filesDir, file);
156
123
  const content = fs.readFileSync(fullPath);
157
124
  localHashes.set(file, (0, import_helpers.calculateHash)(content));
158
125
  }
159
- let remoteFiles = await this.farseerClient.listFiles();
160
- if (!options?.all) {
161
- remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));
162
- }
126
+ const remoteFiles = (await this.farseerClient.listFiles()).filter((f) => !(0, import_helpers.isOsMetadataFile)(f.path)).filter((f) => shouldIncludeFile(f.path, this.tenant, options));
163
127
  const remoteHashes = /* @__PURE__ */ new Map();
164
- const fileContents = await (0, import_helpers.fetchWithConcurrency)(
165
- remoteFiles,
166
- async (file) => {
167
- const content = await this.farseerClient.getFileContentAsBuffer(file.reference);
168
- return { path: file.path, hash: (0, import_helpers.calculateHash)(content) };
169
- },
170
- 15
171
- );
172
- for (const { path: filePath, hash } of fileContents) {
173
- remoteHashes.set(filePath, hash);
128
+ if (deep) {
129
+ const fileContents = await (0, import_helpers.fetchWithConcurrency)(
130
+ remoteFiles,
131
+ async (file) => {
132
+ const content = await this.farseerClient.getFileContentAsBuffer(file.reference);
133
+ return { path: file.path, hash: (0, import_helpers.calculateHash)(content) };
134
+ },
135
+ 15
136
+ );
137
+ for (const { path: filePath, hash } of fileContents) {
138
+ remoteHashes.set(filePath, hash);
139
+ }
140
+ } else {
141
+ for (const file of remoteFiles) {
142
+ const baseline = syncState.files[file.path]?.remoteHash;
143
+ if (baseline) {
144
+ remoteHashes.set(file.path, baseline);
145
+ continue;
146
+ }
147
+ const localHash = localHashes.get(file.path);
148
+ if (localHash) {
149
+ remoteHashes.set(file.path, localHash);
150
+ continue;
151
+ }
152
+ remoteHashes.set(file.path, `__remote_present__:${file.path}`);
153
+ }
174
154
  }
175
155
  const comparisons = this.compareFiles({
176
156
  localHashes,
@@ -180,14 +160,10 @@ class SyncService {
180
160
  includeExtensions: options?.includeExtensions,
181
161
  includeFolders: options?.includeFolders
182
162
  });
183
- const status = {
184
- modifiedLocally: [],
185
- modifiedRemotely: [],
186
- onlyLocal: [],
187
- onlyRemote: [],
188
- inSync: [],
189
- conflicts: []
190
- };
163
+ const status = emptyStatus(deep);
164
+ if (deep) {
165
+ status.remoteHashes = remoteHashes;
166
+ }
191
167
  for (const c of comparisons) {
192
168
  switch (c.changeType) {
193
169
  case "unchanged":
@@ -200,16 +176,16 @@ class SyncService {
200
176
  status.modifiedRemotely.push(c.filePath);
201
177
  break;
202
178
  case "local_new":
203
- status.onlyLocal.push(c.filePath);
179
+ status.addedLocally.push(c.filePath);
204
180
  break;
205
181
  case "remote_new":
206
- status.onlyRemote.push(c.filePath);
182
+ status.addedRemotely.push(c.filePath);
207
183
  break;
208
184
  case "remote_deleted":
209
- status.modifiedRemotely.push(c.filePath);
185
+ status.deletedRemotely.push(c.filePath);
210
186
  break;
211
187
  case "local_deleted":
212
- status.modifiedLocally.push(c.filePath);
188
+ status.deletedLocally.push(c.filePath);
213
189
  break;
214
190
  default:
215
191
  status.conflicts.push(SyncService.buildConflicts([c])[0]);
@@ -222,10 +198,7 @@ class SyncService {
222
198
  const filesDir = (0, import_helpers.getTenantFilesDir)(this.tenant);
223
199
  (0, import_helpers.ensureDirectoryExists)(filesDir);
224
200
  const syncState = this.loadSyncState();
225
- let remoteFiles = await this.farseerClient.listFiles();
226
- if (!options?.all) {
227
- remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));
228
- }
201
+ let remoteFiles = (await this.farseerClient.listFiles()).filter((f) => !(0, import_helpers.isOsMetadataFile)(f.path)).filter((f) => shouldIncludeFile(f.path, this.tenant, options));
229
202
  remoteFiles = await this.fetchMetadataForFiles(remoteFiles);
230
203
  const result = {
231
204
  downloaded: [],
@@ -261,10 +234,10 @@ class SyncService {
261
234
  const localFiles = (0, import_helpers.getAllFilesInDir)(filesDir);
262
235
  const localHashes = /* @__PURE__ */ new Map();
263
236
  for (const localFile of localFiles) {
264
- if (!options?.all && !shouldIncludeFile(localFile, this.tenant, options)) {
237
+ if (!shouldIncludeFile(localFile, this.tenant, options)) {
265
238
  continue;
266
239
  }
267
- const localPath = path.join(filesDir, localFile);
240
+ const localPath = (0, import_helpers.safeResolveWithinBase)(filesDir, localFile);
268
241
  const content = fs.readFileSync(localPath);
269
242
  localHashes.set(localFile, (0, import_helpers.calculateHash)(content));
270
243
  }
@@ -279,12 +252,32 @@ class SyncService {
279
252
  const resolutions = options?.conflictResolutions ?? {};
280
253
  for (const comparison of comparisons) {
281
254
  const { filePath, changeType } = comparison;
282
- const localPath = path.join(filesDir, filePath);
255
+ const localPath = (0, import_helpers.safeResolveWithinBase)(filesDir, filePath);
283
256
  const remoteInfo = remoteContentMap.get(filePath);
284
257
  switch (changeType) {
285
258
  case "unchanged":
259
+ result.unchanged.push(filePath);
260
+ if (remoteInfo) {
261
+ const existingSync = syncState.files[filePath];
262
+ if (existingSync) {
263
+ existingSync.remoteHash = remoteInfo.hash;
264
+ existingSync.metadata = this.buildMetadata(remoteInfo.file);
265
+ }
266
+ }
267
+ break;
286
268
  case "local_modified":
287
269
  case "local_new":
270
+ if (options?.force && remoteInfo) {
271
+ (0, import_helpers.ensureDirectoryExists)(path.dirname(localPath));
272
+ fs.writeFileSync(localPath, remoteInfo.content);
273
+ result.downloaded.push(filePath);
274
+ syncState.files[filePath] = {
275
+ localHash: remoteInfo.hash,
276
+ remoteHash: remoteInfo.hash,
277
+ metadata: this.buildMetadata(remoteInfo.file)
278
+ };
279
+ break;
280
+ }
288
281
  result.unchanged.push(filePath);
289
282
  if (remoteInfo) {
290
283
  const existingSync = syncState.files[filePath];
@@ -295,6 +288,17 @@ class SyncService {
295
288
  }
296
289
  break;
297
290
  case "local_deleted":
291
+ if (options?.force && remoteInfo) {
292
+ (0, import_helpers.ensureDirectoryExists)(path.dirname(localPath));
293
+ fs.writeFileSync(localPath, remoteInfo.content);
294
+ result.downloaded.push(filePath);
295
+ syncState.files[filePath] = {
296
+ localHash: remoteInfo.hash,
297
+ remoteHash: remoteInfo.hash,
298
+ metadata: this.buildMetadata(remoteInfo.file)
299
+ };
300
+ break;
301
+ }
298
302
  result.unchanged.push(filePath);
299
303
  break;
300
304
  case "remote_modified":
@@ -381,7 +385,7 @@ class SyncService {
381
385
  const ext = path.extname(filePath);
382
386
  const base = filePath.slice(0, -ext.length || void 0);
383
387
  const conflictFileName = `${base}.remote${ext}`;
384
- const conflictPath = path.join(filesDir, conflictFileName);
388
+ const conflictPath = (0, import_helpers.safeResolveWithinBase)(filesDir, conflictFileName);
385
389
  (0, import_helpers.ensureDirectoryExists)(path.dirname(conflictPath));
386
390
  fs.writeFileSync(conflictPath, remoteInfo.content);
387
391
  result.conflictFilesWritten.push(conflictFileName);
@@ -397,6 +401,50 @@ class SyncService {
397
401
  }
398
402
  result.unchanged.push(filePath);
399
403
  break;
404
+ case "merge_markers":
405
+ if (remoteInfo && fs.existsSync(localPath)) {
406
+ const localBuf = fs.readFileSync(localPath);
407
+ const remoteBuf = remoteInfo.content;
408
+ if (!(0, import_fileValidation.isLikelyTextFile)(filePath, localBuf) || !(0, import_fileValidation.isLikelyTextFile)(filePath, remoteBuf)) {
409
+ const ext = path.extname(filePath);
410
+ const base = filePath.slice(0, -ext.length || void 0);
411
+ const conflictFileName = `${base}.remote${ext}`;
412
+ const conflictPath = (0, import_helpers.safeResolveWithinBase)(filesDir, conflictFileName);
413
+ (0, import_helpers.ensureDirectoryExists)(path.dirname(conflictPath));
414
+ fs.writeFileSync(conflictPath, remoteBuf);
415
+ const localHash = (0, import_helpers.calculateHash)(localBuf);
416
+ syncState.files[filePath] = {
417
+ localHash,
418
+ remoteHash: comparison.currentRemoteHash ?? "",
419
+ metadata: this.buildMetadata(remoteInfo.file)
420
+ };
421
+ result.conflictFilesWritten.push(
422
+ `${conflictFileName} (binary \u2014 merge markers not safe; wrote .remote alongside)`
423
+ );
424
+ result.unchanged.push(filePath);
425
+ break;
426
+ }
427
+ const localContent = localBuf.toString("utf-8");
428
+ const remoteContent = remoteBuf.toString("utf-8");
429
+ const merged = `${MERGE_MARKER_LOCAL_START}
430
+ ${localContent}${localContent.endsWith("\n") ? "" : "\n"}${MERGE_MARKER_SEPARATOR}
431
+ ${remoteContent}${remoteContent.endsWith("\n") ? "" : "\n"}${MERGE_MARKER_REMOTE_END}
432
+ `;
433
+ fs.writeFileSync(localPath, merged);
434
+ const newHash = (0, import_helpers.calculateHash)(Buffer.from(merged));
435
+ syncState.files[filePath] = {
436
+ localHash: newHash,
437
+ remoteHash: comparison.currentRemoteHash ?? "",
438
+ metadata: this.buildMetadata(remoteInfo.file)
439
+ };
440
+ result.conflictFilesWritten.push(`${filePath} (merge markers)`);
441
+ } else if (!remoteInfo && fs.existsSync(localPath)) {
442
+ const localContent = fs.readFileSync(localPath);
443
+ const localHash = (0, import_helpers.calculateHash)(localContent);
444
+ syncState.files[filePath] = { localHash, remoteHash: "" };
445
+ }
446
+ result.unchanged.push(filePath);
447
+ break;
400
448
  }
401
449
  break;
402
450
  }
@@ -423,49 +471,73 @@ class SyncService {
423
471
  updated: [],
424
472
  deleted: [],
425
473
  unchanged: [],
426
- conflicts: []
474
+ conflicts: [],
475
+ rejected: [],
476
+ // Per-file failures from create/update/delete API calls. We don't
477
+ // abort the whole push on the first failure — each item is its
478
+ // own atomic operation, and `syncState` is saved in `finally` so
479
+ // already-successful items aren't re-uploaded next run. The
480
+ // caller surfaces this list and exits non-zero on non-empty.
481
+ failed: []
427
482
  };
428
- const remoteFiles = await this.farseerClient.listFiles();
483
+ const remoteFiles = (await this.farseerClient.listFiles()).filter((f) => !(0, import_helpers.isOsMetadataFile)(f.path));
429
484
  const remoteFileMap = /* @__PURE__ */ new Map();
430
485
  for (const file of remoteFiles) {
431
486
  remoteFileMap.set(file.path, file);
432
487
  }
433
- const localFiles = (0, import_helpers.getAllFilesInDir)(filesDir);
434
- const localHashes = /* @__PURE__ */ new Map();
488
+ const allLocalFiles = (0, import_helpers.getAllFilesInDir)(filesDir);
489
+ const localPresenceSet = new Set(allLocalFiles);
490
+ const inScopeFiles = allLocalFiles.filter((f) => shouldIncludeFile(f, this.tenant, options));
435
491
  const localContents = /* @__PURE__ */ new Map();
492
+ for (const file of inScopeFiles) {
493
+ const fullPath = (0, import_helpers.safeResolveWithinBase)(filesDir, file);
494
+ localContents.set(file, fs.readFileSync(fullPath));
495
+ }
496
+ const validationInputs = inScopeFiles.map((filePath) => {
497
+ const content = localContents.get(filePath);
498
+ return {
499
+ filePath,
500
+ size: content.length,
501
+ content
502
+ };
503
+ });
504
+ const { valid: pushableValidatedFiles, rejected } = (0, import_fileValidation.partitionForUpload)(validationInputs);
505
+ result.rejected = rejected;
506
+ const localFiles = pushableValidatedFiles.map((f) => f.filePath);
507
+ const localHashes = /* @__PURE__ */ new Map();
436
508
  for (const localFile of localFiles) {
437
- const localPath = path.join(filesDir, localFile);
438
- const content = fs.readFileSync(localPath);
439
- localHashes.set(localFile, (0, import_helpers.calculateHash)(content));
440
- localContents.set(localFile, content);
509
+ localHashes.set(localFile, (0, import_helpers.calculateHash)(localContents.get(localFile)));
441
510
  }
442
511
  const candidateFiles = [];
443
512
  for (const localFile of localFiles) {
444
513
  const syncInfo = syncState.files[localFile];
445
514
  const localHash = localHashes.get(localFile);
446
- if (!syncInfo || localHash !== syncInfo.localHash) {
447
- if (remoteFileMap.has(localFile)) {
448
- candidateFiles.push(localFile);
449
- }
515
+ const baselineDiverged = !syncInfo || localHash !== syncInfo.remoteHash;
516
+ if (!remoteFileMap.has(localFile)) continue;
517
+ if (baselineDiverged || options?.mirror) {
518
+ candidateFiles.push(localFile);
450
519
  }
451
520
  }
521
+ const inScope = (f) => shouldIncludeFile(f, this.tenant, options);
452
522
  const locallyDeletedFiles = Object.keys(syncState.files).filter(
453
- (f) => !localFiles.includes(f) && remoteFileMap.has(f)
523
+ (f) => !localPresenceSet.has(f) && remoteFileMap.has(f) && inScope(f)
454
524
  );
455
525
  const filesToFetchRemote = [.../* @__PURE__ */ new Set([...candidateFiles, ...locallyDeletedFiles])];
456
- const remoteHashes = /* @__PURE__ */ new Map();
457
- if (filesToFetchRemote.length > 0 && !options?.force) {
458
- const toFetch = filesToFetchRemote.filter((f) => remoteFileMap.has(f)).map((f) => remoteFileMap.get(f));
459
- const fetched = await (0, import_helpers.fetchWithConcurrency)(
460
- toFetch,
461
- async (file) => {
462
- const content = await this.farseerClient.getFileContentAsBuffer(file.reference);
463
- return { file, hash: (0, import_helpers.calculateHash)(content) };
464
- },
465
- 15
466
- );
467
- for (const { file, hash } of fetched) {
468
- remoteHashes.set(file.path, hash);
526
+ const remoteHashes = new Map(options?.precomputedRemoteHashes ?? []);
527
+ if (filesToFetchRemote.length > 0 && (!options?.force || options?.mirror)) {
528
+ const toFetch = filesToFetchRemote.filter((f) => remoteFileMap.has(f) && !remoteHashes.has(f)).map((f) => remoteFileMap.get(f));
529
+ if (toFetch.length > 0) {
530
+ const fetched = await (0, import_helpers.fetchWithConcurrency)(
531
+ toFetch,
532
+ async (file) => {
533
+ const content = await this.farseerClient.getFileContentAsBuffer(file.reference);
534
+ return { file, hash: (0, import_helpers.calculateHash)(content) };
535
+ },
536
+ 15
537
+ );
538
+ for (const { file, hash } of fetched) {
539
+ remoteHashes.set(file.path, hash);
540
+ }
469
541
  }
470
542
  }
471
543
  const comparisons = this.compareFiles({ localHashes, remoteHashes, syncState, all: true });
@@ -479,77 +551,137 @@ class SyncService {
479
551
  }
480
552
  }
481
553
  }
482
- for (const localFile of localFiles) {
483
- if (conflictPaths.has(localFile)) continue;
484
- const localPath = path.join(filesDir, localFile);
485
- const content = localContents.get(localFile);
486
- const localHash = localHashes.get(localFile);
487
- const remoteFile = remoteFileMap.get(localFile);
488
- const syncInfo = syncState.files[localFile];
489
- if (remoteFile) {
490
- if (syncInfo && localHash === syncInfo.localHash) {
491
- result.unchanged.push(localFile);
492
- } else {
493
- await this.farseerClient.updateFile(remoteFile.reference, content, path.basename(localFile));
494
- result.updated.push(localFile);
495
- syncState.files[localFile] = {
496
- localHash,
497
- remoteHash: localHash
498
- };
499
- }
500
- } else {
501
- if (syncInfo && localHash === syncInfo.localHash) {
502
- result.unchanged.push(localFile);
554
+ try {
555
+ for (const localFile of localFiles) {
556
+ if (conflictPaths.has(localFile)) continue;
557
+ const content = localContents.get(localFile);
558
+ const localHash = localHashes.get(localFile);
559
+ const remoteFile = remoteFileMap.get(localFile);
560
+ const syncInfo = syncState.files[localFile];
561
+ if (remoteFile) {
562
+ const currentRemoteHash = remoteHashes.get(localFile);
563
+ const mirrorWantsRecreate = options?.mirror && currentRemoteHash !== void 0 && currentRemoteHash !== localHash;
564
+ if (syncInfo && localHash === syncInfo.remoteHash && !mirrorWantsRecreate) {
565
+ result.unchanged.push(localFile);
566
+ } else {
567
+ if (!options?.force && syncInfo && currentRemoteHash !== void 0 && currentRemoteHash !== syncInfo.remoteHash) {
568
+ result.conflicts.push({
569
+ filePath: localFile,
570
+ type: "both_modified",
571
+ description: "Remote changed since last sync \u2014 pull first or use --force to overwrite"
572
+ });
573
+ continue;
574
+ }
575
+ try {
576
+ await this.farseerClient.updateFile(
577
+ remoteFile.reference,
578
+ content,
579
+ path.basename(localFile)
580
+ );
581
+ result.updated.push(localFile);
582
+ syncState.files[localFile] = {
583
+ localHash,
584
+ remoteHash: localHash
585
+ };
586
+ } catch (err) {
587
+ result.failed.push({
588
+ filePath: localFile,
589
+ operation: "update",
590
+ reason: await (0, import_errorFormatter.formatClientError)(err)
591
+ });
592
+ }
593
+ }
503
594
  } else {
504
- const pathParts = localFile.split("/");
505
- const fileName = pathParts.pop();
506
- const folderPath = ["Files", ...pathParts];
507
- await this.farseerClient.createFile(content, fileName, folderPath);
508
- result.uploaded.push(localFile);
509
- syncState.files[localFile] = {
510
- localHash,
511
- remoteHash: localHash
512
- };
595
+ if (syncInfo && localHash === syncInfo.remoteHash && !options?.mirror) {
596
+ result.unchanged.push(localFile);
597
+ } else {
598
+ const pathParts = localFile.split("/");
599
+ const fileName = pathParts.pop();
600
+ const folderPath = ["Files", ...pathParts];
601
+ try {
602
+ await this.farseerClient.createFile(content, fileName, folderPath);
603
+ result.uploaded.push(localFile);
604
+ syncState.files[localFile] = {
605
+ localHash,
606
+ remoteHash: localHash
607
+ };
608
+ } catch (err) {
609
+ result.failed.push({
610
+ filePath: localFile,
611
+ operation: "create",
612
+ reason: await (0, import_errorFormatter.formatClientError)(err)
613
+ });
614
+ }
615
+ }
513
616
  }
514
617
  }
515
- }
516
- const localFileSet = new Set(localFiles);
517
- for (const [remotePath, remoteFile] of remoteFileMap) {
518
- if (!localFileSet.has(remotePath) && !conflictPaths.has(remotePath)) {
618
+ for (const [remotePath, remoteFile] of remoteFileMap) {
619
+ if (localPresenceSet.has(remotePath) || conflictPaths.has(remotePath)) continue;
620
+ if (!inScope(remotePath)) continue;
519
621
  const syncInfo = syncState.files[remotePath];
520
- if (syncInfo) {
622
+ const shouldDelete = syncInfo ? true : Boolean(options?.mirror);
623
+ if (!shouldDelete) continue;
624
+ try {
521
625
  await this.farseerClient.deleteFile(remoteFile.reference);
522
626
  result.deleted.push(remotePath);
523
627
  delete syncState.files[remotePath];
628
+ } catch (err) {
629
+ result.failed.push({
630
+ filePath: remotePath,
631
+ operation: "delete",
632
+ reason: await (0, import_errorFormatter.formatClientError)(err)
633
+ });
524
634
  }
525
635
  }
636
+ } finally {
637
+ syncState.lastSync = (/* @__PURE__ */ new Date()).toISOString();
638
+ this.saveSyncState(syncState);
526
639
  }
527
- syncState.lastSync = (/* @__PURE__ */ new Date()).toISOString();
528
- this.saveSyncState(syncState);
529
640
  return result;
530
641
  }
642
+ /**
643
+ * Detect whether the remote has files we haven't seen yet (or recorded
644
+ * files no longer present on remote) within the current sync scope.
645
+ *
646
+ * Returns the set of paths that are causing drift so the command layer
647
+ * can show the user exactly what's blocking the push and suggest a
648
+ * matching `farseer pull` command. The previous boolean-only return
649
+ * gave the user just "Remote has changes" with no clue WHICH file —
650
+ * and `farseer pull` (without the same `--include-ext`/`--include-folder`)
651
+ * silently said "Already up to date" because it ran in a different
652
+ * scope, leaving the user stuck in an infinite "pull says clean, push
653
+ * says drift" loop.
654
+ */
531
655
  async checkRemoteChanges(options) {
532
656
  const syncState = this.loadSyncState();
533
657
  let remoteFiles = await this.farseerClient.listFiles();
534
658
  remoteFiles = remoteFiles.filter((f) => shouldIncludeFile(f.path, this.tenant, options));
659
+ const filesDir = (0, import_helpers.getTenantFilesDir)(this.tenant);
660
+ const localPresenceSet = new Set((0, import_helpers.getAllFilesInDir)(filesDir));
661
+ const addedRemotely = [];
662
+ const deletedRemotely = [];
535
663
  for (const file of remoteFiles) {
536
- const syncInfo = syncState.files[file.path];
537
- if (!syncInfo) {
538
- return true;
664
+ if (!syncState.files[file.path]) {
665
+ addedRemotely.push(file.path);
539
666
  }
540
667
  }
668
+ const remotePaths = new Set(remoteFiles.map((f) => f.path));
541
669
  for (const filePath of Object.keys(syncState.files)) {
542
670
  if (!shouldIncludeFile(filePath, this.tenant, options)) continue;
543
- const exists = remoteFiles.some((f) => f.path === filePath);
544
- if (!exists && syncState.files[filePath].remoteHash) {
545
- return true;
546
- }
671
+ if (remotePaths.has(filePath)) continue;
672
+ if (!syncState.files[filePath].remoteHash) continue;
673
+ if (!localPresenceSet.has(filePath)) continue;
674
+ deletedRemotely.push(filePath);
547
675
  }
548
- return false;
676
+ return {
677
+ drift: addedRemotely.length > 0 || deletedRemotely.length > 0,
678
+ addedRemotely,
679
+ deletedRemotely
680
+ };
549
681
  }
550
682
  async getFileDiff(filePath) {
551
683
  const filesDir = (0, import_helpers.getTenantFilesDir)(this.tenant);
552
- const localPath = path.join(filesDir, filePath);
684
+ const localPath = (0, import_helpers.safeResolveWithinBase)(filesDir, filePath);
553
685
  let localContent = null;
554
686
  let remoteContent = null;
555
687
  if (fs.existsSync(localPath)) {
@@ -596,12 +728,15 @@ class SyncService {
596
728
  } else {
597
729
  const localChanged = currentLocalHash !== baselineLocalHash;
598
730
  const remoteChanged = currentRemoteHash !== baselineRemoteHash;
731
+ const baselineDivergent = baselineLocalHash !== baselineRemoteHash;
599
732
  if (localChanged && remoteChanged) {
600
733
  changeType = "conflict_both_modified";
601
734
  } else if (localChanged) {
602
735
  changeType = "local_modified";
603
736
  } else if (remoteChanged) {
604
737
  changeType = "remote_modified";
738
+ } else if (baselineDivergent) {
739
+ changeType = "local_modified";
605
740
  } else {
606
741
  changeType = "unchanged";
607
742
  }
@@ -707,7 +842,12 @@ class SyncService {
707
842
  }
708
843
  // Annotate the CommonJS export names for ESM import in node:
709
844
  0 && (module.exports = {
845
+ MERGE_MARKER_LOCAL_START,
846
+ MERGE_MARKER_REMOTE_END,
847
+ MERGE_MARKER_SEPARATOR,
710
848
  SyncService,
849
+ isHiddenFile,
850
+ isOsMetadataFile,
711
851
  shouldIncludeFile
712
852
  });
713
853
  //# sourceMappingURL=syncService.js.map