-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathcollection-watcher.js
More file actions
967 lines (809 loc) · 30.8 KB
/
collection-watcher.js
File metadata and controls
967 lines (809 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');
const {
hasRequestExtension,
isWSLPath,
normalizeAndResolvePath,
sizeInMB,
getCollectionFormat,
clearCollectionFormatCache
} = require('../utils/filesystem');
const {
parseEnvironment,
parseRequest,
parseRequestViaWorker,
parseCollection,
parseFolder
} = require('@usebruno/filestore');
const { uuid } = require('../utils/common');
const { getRequestUid } = require('../cache/requestUids');
const { decryptStringSafe } = require('../utils/encryption');
const { setBrunoConfig } = require('../store/bruno-config');
const EnvironmentSecretsStore = require('../store/env-secrets');
const UiStateSnapshot = require('../store/ui-state-snapshot');
const { parseFileMeta, hydrateRequestWithUuid } = require('../utils/collection');
const { parseLargeRequestWithRedaction } = require('../utils/parse');
const { transformBrunoConfigAfterRead } = require('../utils/transformBrunoConfig');
const dotEnvWatcher = require('./dotenv-watcher');
const MAX_FILE_SIZE = 2.5 * 1024 * 1024;
const environmentSecretsStore = new EnvironmentSecretsStore();
const isBrunoConfigFile = (pathname, collectionPath) => {
const dirname = path.dirname(pathname);
const basename = path.basename(pathname);
return path.normalize(dirname) === path.normalize(collectionPath) && basename === 'bruno.json';
};
const isEnvironmentsFolder = (pathname, collectionPath) => {
const dirname = path.dirname(pathname);
const envDirectory = path.join(collectionPath, 'environments');
return path.normalize(dirname) === path.normalize(envDirectory);
};
const isFolderRootFile = (pathname, collectionPath) => {
const basename = path.basename(pathname);
try {
const format = getCollectionFormat(collectionPath);
if (format === 'yml') {
return basename === 'folder.yml';
} else if (format === 'bru') {
return basename === 'folder.bru';
}
} catch (err) {
// Collection config file may have been deleted, can't determine format
return false;
}
return false;
};
const isCollectionRootFile = (pathname, collectionPath) => {
const dirname = path.dirname(pathname);
const basename = path.basename(pathname);
// return if we are not at the root of the collection
if (path.normalize(dirname) !== path.normalize(collectionPath)) {
return false;
}
return basename === 'collection.bru' || basename === 'opencollection.yml';
};
const envHasSecrets = (environment = {}) => {
const secrets = _.filter(environment.variables, (v) => v.secret);
return secrets && secrets.length > 0;
};
const hydrateCollectionRootWithUuid = (collectionRoot) => {
const params = _.get(collectionRoot, 'request.params', []);
const headers = _.get(collectionRoot, 'request.headers', []);
const requestVars = _.get(collectionRoot, 'request.vars.req', []);
const responseVars = _.get(collectionRoot, 'request.vars.res', []);
params.forEach((param) => (param.uid = uuid()));
headers.forEach((header) => (header.uid = uuid()));
requestVars.forEach((variable) => (variable.uid = uuid()));
responseVars.forEach((variable) => (variable.uid = uuid()));
return collectionRoot;
};
const addEnvironmentFile = async (win, pathname, collectionUid, collectionPath) => {
try {
const basename = path.basename(pathname);
const file = {
meta: {
collectionUid,
pathname,
name: basename
}
};
const format = getCollectionFormat(collectionPath);
let content = fs.readFileSync(pathname, 'utf8');
file.data = await parseEnvironment(content, { format });
// Extract name by removing the extension
const ext = path.extname(basename);
file.data.name = basename.substring(0, basename.length - ext.length);
file.data.uid = getRequestUid(pathname);
_.each(_.get(file, 'data.variables', []), (variable) => (variable.uid = uuid()));
// hydrate environment variables with secrets
if (envHasSecrets(file.data)) {
const envSecrets = environmentSecretsStore.getEnvSecrets(collectionPath, file.data);
_.each(envSecrets, (secret) => {
const variable = _.find(file.data.variables, (v) => v.name === secret.name);
if (variable && secret.value) {
const decryptionResult = decryptStringSafe(secret.value);
variable.value = decryptionResult.value;
}
});
}
win.webContents.send('main:collection-tree-updated', 'addEnvironmentFile', file);
} catch (err) {
console.error('Error processing environment file: ', err);
}
};
const changeEnvironmentFile = async (win, pathname, collectionUid, collectionPath) => {
try {
const basename = path.basename(pathname);
const file = {
meta: {
collectionUid,
pathname,
name: basename
}
};
const format = getCollectionFormat(collectionPath);
const content = fs.readFileSync(pathname, 'utf8');
file.data = await parseEnvironment(content, { format });
// Extract name by removing the extension
const ext = path.extname(basename);
file.data.name = basename.substring(0, basename.length - ext.length);
file.data.uid = getRequestUid(pathname);
_.each(_.get(file, 'data.variables', []), (variable) => (variable.uid = uuid()));
// hydrate environment variables with secrets
if (envHasSecrets(file.data)) {
const envSecrets = environmentSecretsStore.getEnvSecrets(collectionPath, file.data);
_.each(envSecrets, (secret) => {
const variable = _.find(file.data.variables, (v) => v.name === secret.name);
if (variable && secret.value) {
const decryptionResult = decryptStringSafe(secret.value);
variable.value = decryptionResult.value;
}
});
}
// we are reusing the addEnvironmentFile event itself
// this is because the uid of the pathname remains the same
// and the collection tree will be able to update the existing environment
win.webContents.send('main:collection-tree-updated', 'addEnvironmentFile', file);
} catch (err) {
console.error(err);
}
};
const unlinkEnvironmentFile = async (win, pathname, collectionUid) => {
try {
const file = {
meta: {
collectionUid,
pathname,
name: path.basename(pathname)
},
data: {
uid: getRequestUid(pathname),
name: path.basename(pathname).substring(0, path.basename(pathname).length - 4)
}
};
win.webContents.send('main:collection-tree-updated', 'unlinkEnvironmentFile', file);
} catch (err) {
console.error(err);
}
};
const add = async (win, pathname, collectionUid, collectionPath, useWorkerThread, watcher) => {
console.log(`watcher add: ${pathname}`);
if (isBrunoConfigFile(pathname, collectionPath)) {
try {
const content = fs.readFileSync(pathname, 'utf8');
let brunoConfig = JSON.parse(content);
// Transform the config to add exists metadata for protobuf files and import paths
brunoConfig = await transformBrunoConfigAfterRead(brunoConfig, collectionPath);
setBrunoConfig(collectionUid, brunoConfig);
const payload = {
collectionUid,
brunoConfig: brunoConfig
};
win.webContents.send('main:bruno-config-update', payload);
} catch (err) {
console.error(err);
}
}
if (isEnvironmentsFolder(pathname, collectionPath)) {
return addEnvironmentFile(win, pathname, collectionUid, collectionPath);
}
if (isCollectionRootFile(pathname, collectionPath)) {
try {
const format = getCollectionFormat(collectionPath);
const file = {
meta: {
collectionUid,
pathname,
name: path.basename(pathname),
collectionRoot: true
}
};
let content = fs.readFileSync(pathname, 'utf8');
let parsed = await parseCollection(content, { format });
let collectionRoot, brunoConfig;
if (format === 'yml') {
collectionRoot = parsed.collectionRoot;
brunoConfig = parsed.brunoConfig;
} else {
collectionRoot = parsed;
brunoConfig = undefined;
}
file.data = collectionRoot;
hydrateCollectionRootWithUuid(file.data);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
// in yml format, opencollection.yml also contains the bruno config
if (format === 'yml') {
// Transform the config to add exists metadata for protobuf files and import paths
brunoConfig = await transformBrunoConfigAfterRead(brunoConfig, collectionPath);
setBrunoConfig(collectionUid, brunoConfig);
const payload = {
collectionUid,
brunoConfig: brunoConfig
};
win.webContents.send('main:bruno-config-update', payload);
}
} catch (err) {
console.error(err);
}
return;
}
if (isFolderRootFile(pathname, collectionPath)) {
const file = {
meta: {
collectionUid,
pathname,
name: path.basename(pathname),
folderRoot: true
}
};
try {
let format = getCollectionFormat(collectionPath);
let content = fs.readFileSync(pathname, 'utf8');
file.data = await parseFolder(content, { format });
hydrateCollectionRootWithUuid(file.data);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
return;
} catch (err) {
console.error(err);
return;
}
}
try {
const format = getCollectionFormat(collectionPath);
if (hasRequestExtension(pathname, format)) {
watcher.addFileToProcessing(collectionUid, pathname);
const file = {
meta: {
collectionUid,
pathname,
name: path.basename(pathname)
}
};
const fileStats = fs.statSync(pathname);
let content = fs.readFileSync(pathname, 'utf8');
// If worker thread is not used, we can directly parse the file
if (!useWorkerThread) {
try {
file.data = await parseRequest(content, { format });
file.partial = false;
file.loading = false;
file.size = sizeInMB(fileStats?.size);
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
} catch (error) {
console.error(error);
} finally {
watcher.markFileAsProcessed(win, collectionUid, pathname);
}
return;
}
try {
// we need to send a partial file info to the UI
// so that the UI can display the file in the collection tree
file.data = {
name: path.basename(pathname),
type: 'http-request'
};
const metaJson = parseFileMeta(content, format);
file.data = metaJson;
file.partial = true;
file.loading = false;
file.size = sizeInMB(fileStats?.size);
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
if (fileStats.size < MAX_FILE_SIZE) {
// This is to update the loading indicator in the UI
file.data = metaJson;
file.partial = false;
file.loading = true;
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
// This is to update the file info in the UI
file.data = await parseRequestViaWorker(content, {
format,
filename: pathname
});
file.partial = false;
file.loading = false;
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
}
} catch (error) {
file.data = {
name: path.basename(pathname),
type: 'http-request'
};
file.error = {
message: error?.message
};
file.partial = true;
file.loading = false;
file.size = sizeInMB(fileStats?.size);
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file);
} finally {
watcher.markFileAsProcessed(win, collectionUid, pathname);
}
}
} catch (err) {
console.error(`Error in add handler for ${pathname}:`, err);
}
};
const addDirectory = async (win, pathname, collectionUid, collectionPath) => {
try {
const envDirectory = path.join(collectionPath, 'environments');
if (path.normalize(pathname) === path.normalize(envDirectory)) {
return;
}
let name = path.basename(pathname);
let seq;
const format = getCollectionFormat(collectionPath);
const folderFilePath = path.join(pathname, `folder.${format}`);
try {
if (fs.existsSync(folderFilePath)) {
let folderFileContent = fs.readFileSync(folderFilePath, 'utf8');
let folderData = await parseFolder(folderFileContent, { format });
name = folderData?.meta?.name || name;
seq = folderData?.meta?.seq;
}
} catch (error) {
console.error(`Error occured while parsing folder.${format} file`);
console.error(error);
}
const directory = {
meta: {
collectionUid,
pathname,
name,
seq,
uid: getRequestUid(pathname)
}
};
win.webContents.send('main:collection-tree-updated', 'addDir', directory);
} catch (error) {
console.error(`Error in addDirectory handler for ${pathname}:`, error);
}
};
const change = async (win, pathname, collectionUid, collectionPath) => {
if (isBrunoConfigFile(pathname, collectionPath)) {
try {
const content = fs.readFileSync(pathname, 'utf8');
let brunoConfig = JSON.parse(content);
// Transform the config to add file existence checks for protobuf files and import paths
brunoConfig = await transformBrunoConfigAfterRead(brunoConfig, collectionPath);
setBrunoConfig(collectionUid, brunoConfig);
const payload = {
collectionUid,
brunoConfig: brunoConfig
};
win.webContents.send('main:bruno-config-update', payload);
} catch (err) {
console.error(err);
}
return;
}
if (isEnvironmentsFolder(pathname, collectionPath)) {
return changeEnvironmentFile(win, pathname, collectionUid, collectionPath);
}
if (isCollectionRootFile(pathname, collectionPath)) {
const file = {
meta: {
collectionUid,
pathname,
name: path.basename(pathname),
collectionRoot: true
}
};
try {
let content = fs.readFileSync(pathname, 'utf8');
let format = getCollectionFormat(collectionPath);
let parsed = await parseCollection(content, { format });
let collectionRoot, brunoConfig;
if (format === 'yml') {
collectionRoot = parsed.collectionRoot;
brunoConfig = parsed.brunoConfig;
} else {
collectionRoot = parsed;
brunoConfig = undefined;
}
file.data = collectionRoot;
hydrateCollectionRootWithUuid(file.data);
win.webContents.send('main:collection-tree-updated', 'change', file);
// in yml format, opencollection.yml also contains the bruno config
if (format === 'yml') {
// Transform the config to add exists metadata for protobuf files and import paths
brunoConfig = await transformBrunoConfigAfterRead(brunoConfig, collectionPath);
setBrunoConfig(collectionUid, brunoConfig);
const payload = {
collectionUid,
brunoConfig: brunoConfig
};
win.webContents.send('main:bruno-config-update', payload);
}
} catch (err) {
console.error(err);
}
return;
}
if (isFolderRootFile(pathname, collectionPath)) {
const file = {
meta: {
collectionUid,
pathname,
name: path.basename(pathname),
folderRoot: true
}
};
try {
let format = getCollectionFormat(collectionPath);
let content = fs.readFileSync(pathname, 'utf8');
file.data = await parseFolder(content, { format });
hydrateCollectionRootWithUuid(file.data);
win.webContents.send('main:collection-tree-updated', 'change', file);
return;
} catch (err) {
console.error(err);
return;
}
}
try {
const format = getCollectionFormat(collectionPath);
if (hasRequestExtension(pathname, format)) {
const file = {
meta: {
collectionUid,
pathname,
name: path.basename(pathname)
}
};
const content = fs.readFileSync(pathname, 'utf8');
const fileStats = fs.statSync(pathname);
if (fileStats.size >= MAX_FILE_SIZE && format === 'bru') {
file.data = await parseLargeRequestWithRedaction(content, 'bru');
} else {
file.data = await parseRequest(content, { format });
}
file.size = sizeInMB(fileStats?.size);
hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'change', file);
}
} catch (err) {
console.error(err);
}
};
const unlink = (win, pathname, collectionUid, collectionPath) => {
console.log(`watcher unlink: ${pathname}`);
try {
if (isEnvironmentsFolder(pathname, collectionPath)) {
return unlinkEnvironmentFile(win, pathname, collectionUid);
}
console.log(`watcher unlink: ${pathname}`);
const format = getCollectionFormat(collectionPath);
if (hasRequestExtension(pathname, format)) {
const basename = path.basename(pathname);
const dirname = path.dirname(pathname);
if (basename === 'opencollection.yml' && path.normalize(dirname) === path.normalize(collectionPath)) {
return;
}
const file = {
meta: {
collectionUid,
pathname,
name: basename
}
};
win.webContents.send('main:collection-tree-updated', 'unlink', file);
}
} catch (error) {
console.error(`Error in unlink handler for ${pathname}:`, error);
}
};
const unlinkDir = async (win, pathname, collectionUid, collectionPath) => {
try {
const envDirectory = path.join(collectionPath, 'environments');
if (path.normalize(pathname) === path.normalize(envDirectory)) {
return;
}
let name = path.basename(pathname);
const format = getCollectionFormat(collectionPath);
const folderFilePath = path.join(pathname, `folder.${format}`);
if (fs.existsSync(folderFilePath)) {
let folderFileContent = fs.readFileSync(folderFilePath, 'utf8');
let folderData = await parseFolder(folderFileContent, { format });
name = folderData?.meta?.name || name;
}
const directory = {
meta: {
collectionUid,
pathname,
name
}
};
win.webContents.send('main:collection-tree-updated', 'unlinkDir', directory);
// Clear format cache when collection root is deleted
if (path.normalize(pathname) === path.normalize(collectionPath)) {
clearCollectionFormatCache(collectionPath);
}
} catch (error) {
console.error(`Error in unlinkDir handler for ${pathname}:`, error);
}
};
const onWatcherSetupComplete = (win, watchPath, collectionUid, watcher) => {
// Mark discovery as complete
watcher.completeCollectionDiscovery(win, collectionUid);
const UiStateSnapshotStore = new UiStateSnapshot();
const collectionsSnapshotState = UiStateSnapshotStore.getCollections();
const collectionSnapshotState = collectionsSnapshotState?.find((c) => c?.pathname && path.normalize(c.pathname) === path.normalize(watchPath));
win.webContents.send('main:hydrate-app-with-ui-state-snapshot', collectionSnapshotState);
};
class CollectionWatcher {
constructor() {
this.watchers = {};
this.loadingStates = {};
this.tempDirectoryMap = {};
}
// Initialize loading state tracking for a collection
initializeLoadingState(collectionUid) {
if (!this.loadingStates[collectionUid]) {
this.loadingStates[collectionUid] = {
isDiscovering: false, // Initial discovery phase
isProcessing: false, // Processing discovered files
pendingFiles: new Set() // Files that need processing
};
}
}
startCollectionDiscovery(win, collectionUid) {
this.initializeLoadingState(collectionUid);
const state = this.loadingStates[collectionUid];
state.isDiscovering = true;
state.pendingFiles.clear();
win.webContents.send('main:collection-loading-state-updated', {
collectionUid,
isLoading: true
});
}
addFileToProcessing(collectionUid, filepath) {
this.initializeLoadingState(collectionUid);
const state = this.loadingStates[collectionUid];
state.pendingFiles.add(filepath);
}
markFileAsProcessed(win, collectionUid, filepath) {
if (!this.loadingStates[collectionUid]) return;
const state = this.loadingStates[collectionUid];
state.pendingFiles.delete(filepath);
// If discovery is complete and no pending files, mark as not loading
if (!state.isDiscovering && state.pendingFiles.size === 0 && state.isProcessing) {
state.isProcessing = false;
win.webContents.send('main:collection-loading-state-updated', {
collectionUid,
isLoading: false
});
}
}
completeCollectionDiscovery(win, collectionUid) {
if (!this.loadingStates[collectionUid]) return;
const state = this.loadingStates[collectionUid];
state.isDiscovering = false;
// If there are pending files, start processing phase
if (state.pendingFiles.size > 0) {
state.isProcessing = true;
} else {
// No pending files, collection is fully loaded
win.webContents.send('main:collection-loading-state-updated', {
collectionUid,
isLoading: false
});
}
}
cleanupLoadingState(collectionUid) {
delete this.loadingStates[collectionUid];
}
addWatcher(win, watchPath, collectionUid, brunoConfig, forcePolling = false, useWorkerThread) {
if (this.watchers[watchPath]) {
this.watchers[watchPath].close();
}
this.initializeLoadingState(collectionUid);
this.startCollectionDiscovery(win, collectionUid);
// Always ignore node_modules and .git, regardless of user config
// This prevents infinite loops with symlinked directories (e.g., npm workspaces)
const defaultIgnores = ['node_modules', '.git'];
const userIgnores = brunoConfig?.ignore || [];
const ignores = [...new Set([...defaultIgnores, ...userIgnores])];
setTimeout(() => {
const watcher = chokidar.watch(watchPath, {
ignoreInitial: false,
usePolling: isWSLPath(watchPath) || forcePolling ? true : false,
ignored: (filepath) => {
const normalizedPath = normalizeAndResolvePath(filepath);
const relativePath = path.relative(watchPath, normalizedPath);
const basename = path.basename(filepath);
// Ignore .env files - handled by dotenv-watcher
if (basename === '.env' || basename.startsWith('.env.')) {
return true;
}
// Check if any path segment matches a default ignore pattern (handles symlinks)
const pathSegments = relativePath.split(path.sep);
if (pathSegments.some((segment) => defaultIgnores.includes(segment))) {
return true;
}
return ignores.some((ignorePattern) => {
return relativePath === ignorePattern || relativePath.startsWith(ignorePattern);
});
},
persistent: true,
ignorePermissionErrors: true,
awaitWriteFinish: {
stabilityThreshold: 80,
pollInterval: 10
},
depth: 20,
disableGlobbing: true
});
let startedNewWatcher = false;
watcher
.on('ready', () => onWatcherSetupComplete(win, watchPath, collectionUid, this))
.on('add', (pathname) => add(win, pathname, collectionUid, watchPath, useWorkerThread, this))
.on('addDir', (pathname) => addDirectory(win, pathname, collectionUid, watchPath))
.on('change', (pathname) => change(win, pathname, collectionUid, watchPath))
.on('unlink', (pathname) => unlink(win, pathname, collectionUid, watchPath))
.on('unlinkDir', (pathname) => unlinkDir(win, pathname, collectionUid, watchPath))
.on('error', (error) => {
// `EMFILE` is an error code thrown when to many files are watched at the same time see: https://github.com/usebruno/bruno/issues/627
// `ENOSPC` stands for "Error No space" but is also thrown if the file watcher limit is reached.
// To prevent loops `!forcePolling` is checked.
if ((error.code === 'ENOSPC' || error.code === 'EMFILE') && !startedNewWatcher && !forcePolling) {
// This callback is called for every file the watcher is trying to watch. To prevent a spam of messages and
// Multiple watcher being started `startedNewWatcher` is set to prevent this.
startedNewWatcher = true;
watcher.close();
console.error(
`\nCould not start watcher for ${watchPath}:`,
'ENOSPC: System limit for number of file watchers reached!',
'Trying again with polling, this will be slower!\n',
'Update your system config to allow more concurrently watched files with:',
'"echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p"'
);
this.addWatcher(win, watchPath, collectionUid, brunoConfig, true, useWorkerThread);
} else {
console.error(`An error occurred in the watcher for: ${watchPath}`, error);
}
});
this.watchers[watchPath] = watcher;
dotEnvWatcher.addCollectionWatcher(win, watchPath, collectionUid);
}, 100);
}
hasWatcher(watchPath) {
return this.watchers[watchPath];
}
removeWatcher(watchPath, win, collectionUid) {
if (this.watchers[watchPath]) {
this.watchers[watchPath].close();
this.watchers[watchPath] = null;
}
dotEnvWatcher.removeCollectionWatcher(watchPath);
const tempDirectoryPath = this.tempDirectoryMap[watchPath];
if (tempDirectoryPath && this.watchers[tempDirectoryPath]) {
this.watchers[tempDirectoryPath].close();
delete this.watchers[tempDirectoryPath];
delete this.tempDirectoryMap[watchPath];
}
if (collectionUid) {
this.cleanupLoadingState(collectionUid);
}
}
getWatcherByItemPath(itemPath) {
const paths = Object.keys(this.watchers);
const watcherPath = paths?.find((collectionPath) => {
const absCollectionPath = path.resolve(collectionPath);
const absItemPath = path.resolve(itemPath);
return absItemPath.startsWith(absCollectionPath);
});
return watcherPath ? this.watchers[watcherPath] : null;
}
unlinkItemPathInWatcher(itemPath) {
const watcher = this.getWatcherByItemPath(itemPath);
if (watcher) {
watcher.unwatch(itemPath);
}
}
addItemPathInWatcher(itemPath) {
const watcher = this.getWatcherByItemPath(itemPath);
if (watcher && !watcher?.has?.(itemPath)) {
watcher?.add?.(itemPath);
}
}
// Helper function to get collection path from temp directory metadata
getCollectionPathFromTempDirectory(tempDirectoryPath) {
const metadataPath = path.join(tempDirectoryPath, 'metadata.json');
try {
const metadataContent = fs.readFileSync(metadataPath, 'utf8');
const metadata = JSON.parse(metadataContent);
return metadata.collectionPath;
} catch (error) {
console.error(`Error reading metadata from temp directory ${tempDirectoryPath}:`, error);
return null;
}
}
// Add watcher for transient directory
// The tempDirectoryPath is stored in this.tempDirectoryMap[collectionPath] so removeWatcher can clean it up
addTempDirectoryWatcher(win, tempDirectoryPath, collectionUid, collectionPath) {
if (this.watchers[tempDirectoryPath]) {
this.watchers[tempDirectoryPath].close();
}
// Store the mapping from collectionPath to tempDirectoryPath for cleanup in removeWatcher
this.tempDirectoryMap[collectionPath] = tempDirectoryPath;
// Ignore metadata.json file
const ignored = (filepath) => {
const basename = path.basename(filepath);
return basename === 'metadata.json';
};
const watcher = chokidar.watch(tempDirectoryPath, {
ignoreInitial: true, // Don't process existing files
usePolling: isWSLPath(tempDirectoryPath) ? true : false,
ignored,
persistent: true,
ignorePermissionErrors: true,
awaitWriteFinish: {
stabilityThreshold: 80,
pollInterval: 10
},
depth: 1, // Only watch the temp directory itself, not subdirectories
disableGlobbing: true
});
// Wrapper function to handle temp directory files
const addTempFile = async (pathname) => {
// Skip metadata.json
if (path.basename(pathname) === 'metadata.json') {
return;
}
// Get the actual collection path from metadata
const actualCollectionPath = this.getCollectionPathFromTempDirectory(tempDirectoryPath);
if (!actualCollectionPath) {
console.error(`Could not determine collection path for temp directory: ${tempDirectoryPath}`);
return;
}
// Use the collection format from the actual collection
const format = getCollectionFormat(actualCollectionPath);
// Only process request files
if (hasRequestExtension(pathname, format)) {
// Call the regular add function with the actual collection path
// This will hydrate and send the file to the renderer
await add(win, pathname, collectionUid, actualCollectionPath, false, this);
}
};
const unlinkTempFile = async (pathname) => {
// Skip metadata.json
if (path.basename(pathname) === 'metadata.json') {
return;
}
// Get the actual collection path from metadata
const actualCollectionPath = this.getCollectionPathFromTempDirectory(tempDirectoryPath);
if (!actualCollectionPath) {
console.error(`Could not determine collection path for temp directory: ${tempDirectoryPath}`);
return;
}
// Use the collection format from the actual collection
const format = getCollectionFormat(actualCollectionPath);
// Only process request files
if (hasRequestExtension(pathname, format)) {
// Call the regular unlink function with the actual collection path
await unlink(win, pathname, collectionUid, actualCollectionPath);
}
};
watcher
.on('add', (pathname) => addTempFile(pathname))
.on('unlink', (pathname) => unlinkTempFile(pathname))
.on('error', (error) => {
console.error(`An error occurred in the temp directory watcher for: ${tempDirectoryPath}`, error);
});
this.watchers[tempDirectoryPath] = watcher;
}
getAllWatcherPaths() {
return Object.entries(this.watchers)
.filter(([path, watcher]) => !!watcher)
.map(([path, _watcher]) => path);
}
}
const collectionWatcher = new CollectionWatcher();
module.exports = collectionWatcher;