-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathcollection.js
More file actions
2449 lines (2102 loc) · 88.6 KB
/
collection.js
File metadata and controls
2449 lines (2102 loc) · 88.6 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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const _ = require('lodash');
const fs = require('fs');
const fsExtra = require('fs-extra');
const os = require('os');
const path = require('path');
const archiver = require('archiver');
const extractZip = require('extract-zip');
const AdmZip = require('adm-zip');
const { ipcMain, shell, dialog, app } = require('electron');
const {
parseRequest,
stringifyRequest,
parseRequestViaWorker,
stringifyRequestViaWorker,
parseCollection,
stringifyCollection,
parseFolder,
stringifyFolder,
stringifyEnvironment,
parseEnvironment,
DEFAULT_COLLECTION_FORMAT
} = require('@usebruno/filestore');
const { dotenvToJson } = require('@usebruno/lang');
const { utils } = require('@usebruno/common');
const brunoConverters = require('@usebruno/converters');
const { postmanToBruno } = brunoConverters;
const { cookiesStore } = require('../store/cookies');
const { parseLargeRequestWithRedaction } = require('../utils/parse');
const { wsClient } = require('../ipc/network/ws-event-handlers');
const { hasSubDirectories } = require('../utils/filesystem');
const {
DEFAULT_GITIGNORE,
writeFile,
hasBruExtension,
isDirectory,
createDirectory,
sanitizeName,
isWSLPath,
safeToRename,
isWindowsOS,
hasRequestExtension,
getCollectionFormat,
searchForRequestFiles,
validateName,
getCollectionStats,
sizeInMB,
safeWriteFileSync,
copyPath,
removePath,
getPaths,
generateUniqueName,
isDotEnvFile,
isValidDotEnvFilename,
isBrunoConfigFile,
isBruEnvironmentConfig,
isCollectionRootBruFile,
scanForBrunoFiles
} = require('../utils/filesystem');
const { openCollectionDialog, openCollectionsByPathname, registerScratchCollectionPath } = require('../app/collections');
const { generateUidBasedOnHash, stringifyJson, safeStringifyJSON, safeParseJSON } = require('../utils/common');
const { moveRequestUid, deleteRequestUid, syncExampleUidsCache } = require('../cache/requestUids');
const { deleteCookiesForDomain, getDomainsWithCookies, addCookieForDomain, modifyCookieForDomain, parseCookieString, createCookieString, deleteCookie } = require('../utils/cookies');
const EnvironmentSecretsStore = require('../store/env-secrets');
const CollectionSecurityStore = require('../store/collection-security');
const UiStateSnapshotStore = require('../store/ui-state-snapshot');
const interpolateVars = require('./network/interpolate-vars');
const { interpolateString } = require('./network/interpolate-string');
const { getEnvVars, getTreePathFromCollectionToItem, mergeVars, parseBruFileMeta, hydrateRequestWithUuid, transformRequestToSaveToFilesystem } = require('../utils/collection');
const { getProcessEnvVars } = require('../store/process-env');
const { getOAuth2TokenUsingAuthorizationCode, getOAuth2TokenUsingClientCredentials, getOAuth2TokenUsingPasswordCredentials, getOAuth2TokenUsingImplicitGrant, refreshOauth2Token } = require('../utils/oauth2');
const { getCertsAndProxyConfig } = require('./network/cert-utils');
const collectionWatcher = require('../app/collection-watcher');
const { transformBrunoConfigBeforeSave } = require('../utils/transformBrunoConfig');
const { REQUEST_TYPES } = require('../utils/constants');
const { cancelOAuth2AuthorizationRequest, isOauth2AuthorizationRequestInProgress } = require('../utils/oauth2-protocol-handler');
const { findUniqueFolderName } = require('../utils/collection-import');
const { saveSpecAndUpdateMetadata, cleanupSpecFilesForCollection } = require('./openapi-sync');
const environmentSecretsStore = new EnvironmentSecretsStore();
const collectionSecurityStore = new CollectionSecurityStore();
const uiStateSnapshotStore = new UiStateSnapshotStore();
// size and file count limits to determine whether the bru files in the collection should be loaded asynchronously or not.
const MAX_COLLECTION_SIZE_IN_MB = 20;
const MAX_SINGLE_FILE_SIZE_IN_COLLECTION_IN_MB = 5;
const MAX_COLLECTION_FILES_COUNT = 2000;
// Get the base directory for transient request files (stored in app data directory)
const getTransientDirectoryBase = () => {
return path.join(app.getPath('userData'), 'tmp', 'transient');
};
// Get the prefix used for transient collection directories
const getTransientCollectionPrefix = () => {
return path.join(getTransientDirectoryBase(), 'bruno-');
};
// Get the prefix used for scratch collection directories
const getTransientScratchPrefix = () => {
return path.join(getTransientDirectoryBase(), 'bruno-scratch-');
};
// Check if a path is within the transient directory
const isTransientPath = (filePath) => {
const transientBase = getTransientDirectoryBase();
return filePath.startsWith(transientBase + path.sep) || filePath.startsWith(transientBase);
};
const envHasSecrets = (environment = {}) => {
const secrets = _.filter(environment.variables, (v) => v.secret);
return secrets && secrets.length > 0;
};
const findCollectionPathByItemPath = (filePath) => {
const parts = filePath.split(path.sep);
const index = parts.findIndex((part) => part.startsWith('bruno-'));
if (isTransientPath(filePath) && index !== -1) {
const transientDirPath = parts.slice(0, index + 1).join(path.sep);
const metadataPath = path.join(transientDirPath, 'metadata.json');
try {
const metadataContent = fs.readFileSync(metadataPath, 'utf8');
const metadata = JSON.parse(metadataContent);
if (metadata.type === 'scratch') {
return transientDirPath;
}
if (metadata.collectionPath) {
return metadata.collectionPath;
}
} catch (error) {
return null;
}
return null;
}
const allCollectionPaths = collectionWatcher.getAllWatcherPaths();
// Find the collection path that contains this file
// Sort by length descending to find the most specific (deepest) match first
const sortedPaths = allCollectionPaths.sort((a, b) => b.length - a.length);
// Normalize the file path for comparison
const normalizedFilePath = path.normalize(filePath);
for (const collectionPath of sortedPaths) {
const normalizedCollectionPath = path.normalize(collectionPath);
if (normalizedFilePath.startsWith(normalizedCollectionPath + path.sep) || normalizedFilePath === normalizedCollectionPath) {
return collectionPath;
}
}
return null;
};
const validatePathIsInsideCollection = (filePath) => {
const collectionPath = findCollectionPathByItemPath(filePath);
if (!collectionPath) {
throw new Error(`Path: ${filePath} should be inside a collection`);
}
};
const registerRendererEventHandlers = (mainWindow, watcher) => {
// create collection
ipcMain.handle(
'renderer:create-collection',
async (event, collectionName, collectionFolderName, collectionLocation, options = {}) => {
try {
const format = options.format || DEFAULT_COLLECTION_FORMAT;
collectionFolderName = sanitizeName(collectionFolderName);
const dirPath = path.join(collectionLocation, collectionFolderName);
if (fs.existsSync(dirPath)) {
const files = fs.readdirSync(dirPath);
if (files.length > 0) {
throw new Error(`collection: ${dirPath} already exists and is not empty`);
}
}
if (!validateName(path.basename(dirPath))) {
throw new Error(`collection: invalid pathname - ${dirPath}`);
}
if (!fs.existsSync(dirPath)) {
await createDirectory(dirPath);
}
const uid = generateUidBasedOnHash(dirPath);
let brunoConfig = {
version: '1',
name: collectionName,
type: 'collection',
ignore: ['node_modules', '.git']
};
if (format === 'yml') {
const collectionRoot = {
meta: {
name: collectionName
}
};
// For YAML collections, set opencollection instead of version
brunoConfig = {
opencollection: '1.0.0',
name: collectionName,
type: 'collection',
ignore: ['node_modules', '.git']
};
const content = stringifyCollection(collectionRoot, brunoConfig, { format });
await writeFile(path.join(dirPath, 'opencollection.yml'), content);
} else if (format === 'bru') {
const content = await stringifyJson(brunoConfig);
await writeFile(path.join(dirPath, 'bruno.json'), content);
} else {
throw new Error(`Invalid format: ${format}`);
}
await writeFile(path.join(dirPath, '.gitignore'), DEFAULT_GITIGNORE);
const { size, filesCount } = await getCollectionStats(dirPath);
brunoConfig.size = size;
brunoConfig.filesCount = filesCount;
mainWindow.webContents.send('main:collection-opened', dirPath, uid, brunoConfig);
ipcMain.emit('main:collection-opened', mainWindow, dirPath, uid, brunoConfig);
} catch (error) {
return Promise.reject(error);
}
}
);
// clone collection
ipcMain.handle(
'renderer:clone-collection',
async (event, collectionName, collectionFolderName, collectionLocation, previousPath) => {
collectionFolderName = sanitizeName(collectionFolderName);
const dirPath = path.join(collectionLocation, collectionFolderName);
if (fs.existsSync(dirPath)) {
throw new Error(`collection: ${dirPath} already exists`);
}
if (!validateName(path.basename(dirPath))) {
throw new Error(`collection: invalid pathname - ${dirPath}`);
}
// create dir
await createDirectory(dirPath);
const uid = generateUidBasedOnHash(dirPath);
const format = getCollectionFormat(previousPath);
let brunoConfig;
if (format === 'yml') {
const configFilePath = path.join(previousPath, 'opencollection.yml');
const content = fs.readFileSync(configFilePath, 'utf8');
const {
brunoConfig: parsedBrunoConfig,
collectionRoot
} = parseCollection(content, { format });
brunoConfig = parsedBrunoConfig;
brunoConfig.name = collectionName;
const newContent = stringifyCollection(collectionRoot, brunoConfig, { format });
await writeFile(path.join(dirPath, 'opencollection.yml'), newContent);
} else if (format === 'bru') {
const configFilePath = path.join(previousPath, 'bruno.json');
const content = fs.readFileSync(configFilePath, 'utf8');
brunoConfig = JSON.parse(content);
brunoConfig.name = collectionName;
const newContent = await stringifyJson(brunoConfig);
await writeFile(path.join(dirPath, 'bruno.json'), newContent);
} else {
throw new Error(`Invalid collectionformat: ${format}`);
}
// Now copy all the files matching the collection's filetype along with the dir
const files = searchForRequestFiles(previousPath);
for (const sourceFilePath of files) {
const relativePath = path.relative(previousPath, sourceFilePath);
const newFilePath = path.join(dirPath, relativePath);
// skip if the file is opencollection.yml or bruno.json at the root of the collection
const isRootConfigFile = (path.basename(sourceFilePath) === 'opencollection.yml' || path.basename(sourceFilePath) === 'bruno.json')
&& path.dirname(sourceFilePath) === previousPath;
if (isRootConfigFile) {
continue;
}
// handle dir of files
fs.mkdirSync(path.dirname(newFilePath), { recursive: true });
// copy each files
fs.copyFileSync(sourceFilePath, newFilePath);
}
const { size, filesCount } = await getCollectionStats(dirPath);
brunoConfig.size = size;
brunoConfig.filesCount = filesCount;
mainWindow.webContents.send('main:collection-opened', dirPath, uid, brunoConfig);
ipcMain.emit('main:collection-opened', mainWindow, dirPath, uid);
}
);
// rename collection
ipcMain.handle('renderer:rename-collection', async (event, newName, collectionPathname) => {
try {
const format = getCollectionFormat(collectionPathname);
if (format === 'yml') {
const configFilePath = path.join(collectionPathname, 'opencollection.yml');
const content = fs.readFileSync(configFilePath, 'utf8');
const {
brunoConfig,
collectionRoot
} = parseCollection(content, { format: 'yml' });
brunoConfig.name = newName;
const newContent = stringifyCollection(collectionRoot, brunoConfig, { format: 'yml' });
await writeFile(path.join(collectionPathname, 'opencollection.yml'), newContent);
} else if (format === 'bru') {
const configFilePath = path.join(collectionPathname, 'bruno.json');
const content = fs.readFileSync(configFilePath, 'utf8');
const brunoConfig = JSON.parse(content);
brunoConfig.name = newName;
const newContent = await stringifyJson(brunoConfig);
await writeFile(path.join(collectionPathname, 'bruno.json'), newContent);
} else {
throw new Error(`Invalid format: ${format}`);
}
mainWindow.webContents.send('main:collection-renamed', {
collectionPathname,
newName
});
} catch (error) {
return Promise.reject(error);
}
});
ipcMain.handle('renderer:save-folder-root', async (event, folder) => {
try {
const { name: folderName, root: folderRoot = {}, folderPathname, collectionPathname } = folder;
const format = getCollectionFormat(collectionPathname);
const folderFilePath = path.join(folderPathname, `folder.${format}`);
if (!folderRoot.meta) {
folderRoot.meta = {
name: folderName
};
}
const content = await stringifyFolder(folderRoot, { format });
await writeFile(folderFilePath, content);
} catch (error) {
return Promise.reject(error);
}
});
// save collection root
ipcMain.handle('renderer:save-collection-root', async (event, collectionPathname, collectionRoot, brunoConfig) => {
try {
const format = getCollectionFormat(collectionPathname);
const filename = format === 'yml' ? 'opencollection.yml' : 'collection.bru';
const content = await stringifyCollection(collectionRoot, brunoConfig, { format });
await writeFile(path.join(collectionPathname, filename), content);
} catch (error) {
console.error('Error in save-collection-root:', error);
return Promise.reject(error);
}
});
// new request
ipcMain.handle('renderer:new-request', async (event, pathname, request) => {
try {
if (fs.existsSync(pathname)) {
throw new Error(`path: ${pathname} already exists`);
}
const collectionPath = findCollectionPathByItemPath(pathname);
if (!collectionPath) {
throw new Error('Collection not found for the given pathname');
}
const format = getCollectionFormat(collectionPath);
// For the actual filename part, we want to be strict
const baseFilename = request?.filename?.replace(`.${format}`, '');
if (!validateName(baseFilename)) {
throw new Error(`${request.filename} is not a valid filename`);
}
validatePathIsInsideCollection(pathname);
const content = await stringifyRequestViaWorker(request, { format });
await writeFile(pathname, content);
} catch (error) {
return Promise.reject(error);
}
});
// save request
ipcMain.handle('renderer:save-request', async (event, pathname, request, format) => {
try {
if (!fs.existsSync(pathname)) {
throw new Error(`path: ${pathname} does not exist`);
}
// Sync example UIDs cache to maintain consistency when examples are added/deleted/reordered
syncExampleUidsCache(pathname, request.examples);
const content = await stringifyRequestViaWorker(request, { format });
await writeFile(pathname, content);
} catch (error) {
return Promise.reject(error);
}
});
ipcMain.handle('renderer:save-transient-request', async (event, { sourcePathname, targetDirname, targetFilename, request, format, sourceFormat }) => {
try {
if (!fs.existsSync(sourcePathname)) {
throw new Error(`Source path: ${sourcePathname} does not exist`);
}
if (!fs.existsSync(targetDirname)) {
throw new Error(`Target directory: ${targetDirname} does not exist`);
}
validatePathIsInsideCollection(targetDirname);
const collectionPath = findCollectionPathByItemPath(targetDirname);
if (!collectionPath) {
throw new Error('Could not determine collection for target directory');
}
const targetFormat = getCollectionFormat(collectionPath);
const filename = targetFilename || path.basename(sourcePathname);
const filenameWithoutExt = filename.replace(/\.(bru|yml)$/, '');
const finalFilename = `${filenameWithoutExt}.${targetFormat}`;
const targetPathname = path.join(targetDirname, finalFilename);
if (fs.existsSync(targetPathname)) {
throw new Error(`A file with the name "${finalFilename}" already exists in the target location`);
}
const actualSourceFormat = sourceFormat || 'yml';
const needsConversion = actualSourceFormat !== targetFormat;
let finalContent;
if (needsConversion) {
const { parseRequest, stringifyRequest } = require('@usebruno/filestore');
const sourceContent = await fs.promises.readFile(sourcePathname, 'utf8');
const parsedRequest = parseRequest(sourceContent, { format: actualSourceFormat });
const mergedRequest = { ...parsedRequest, ...request };
syncExampleUidsCache(sourcePathname, mergedRequest.examples);
finalContent = stringifyRequest(mergedRequest, { format: targetFormat });
} else {
syncExampleUidsCache(sourcePathname, request.examples);
finalContent = await stringifyRequestViaWorker(request, { format: targetFormat });
}
await writeFile(targetPathname, finalContent);
return { newPathname: targetPathname };
} catch (error) {
return Promise.reject(error);
}
});
// save multiple requests
ipcMain.handle('renderer:save-multiple-requests', async (event, requestsToSave) => {
try {
for (let r of requestsToSave) {
const request = r.item;
const pathname = r.pathname;
if (!fs.existsSync(pathname)) {
throw new Error(`path: ${pathname} does not exist`);
}
const content = await stringifyRequestViaWorker(request, { format: r.format });
await writeFile(pathname, content);
}
} catch (error) {
return Promise.reject(error);
}
});
// Helper: Parse file content based on scope type
const parseFileByType = async (fileContent, scopeType, format) => {
switch (scopeType) {
case 'request':
return await parseRequestViaWorker(fileContent, { format });
case 'folder':
return parseFolder(fileContent, { format });
case 'collection':
return parseCollection(fileContent, { format });
default:
throw new Error(`Invalid scope type: ${scopeType}`);
}
};
const stringifyByType = async (data, scopeType, collectionRoot, format) => {
switch (scopeType) {
case 'request':
return await stringifyRequestViaWorker(data, { format });
case 'folder':
return stringifyFolder(data, { format });
case 'collection':
return stringifyCollection(collectionRoot, data, { format });
default:
throw new Error(`Invalid scope type: ${scopeType}`);
}
};
// Helper: Update or create variable in array
const updateOrCreateVariable = (variables, variable) => {
const existingVar = variables.find((v) => v.name === variable.name);
if (existingVar) {
// Update existing variable
return variables.map((v) => (v.name === variable.name ? variable : v));
}
// Create new variable
return [...variables, variable];
};
// update variable in request/folder/collection file
ipcMain.handle('renderer:update-variable-in-file', async (event, pathname, variable, scopeType, collectionRoot, format) => {
try {
if (!fs.existsSync(pathname)) {
throw new Error(`path: ${pathname} does not exist`);
}
// Read and parse the file
const fileContent = fs.readFileSync(pathname, 'utf8');
const parsedData = await parseFileByType(fileContent, scopeType, format);
// Update the specific variable or create it if it doesn't exist
const varsPath = 'request.vars.req';
const variables = _.get(parsedData, varsPath, []);
const updatedVariables = updateOrCreateVariable(variables, variable);
_.set(parsedData, varsPath, updatedVariables);
const content = await stringifyByType(parsedData, scopeType, collectionRoot, format);
await writeFile(pathname, content);
} catch (error) {
return Promise.reject(error);
}
});
// create environment
ipcMain.handle('renderer:create-environment', async (event, collectionPathname, name, variables, color) => {
try {
const envDirPath = path.join(collectionPathname, 'environments');
if (!fs.existsSync(envDirPath)) {
await createDirectory(envDirPath);
}
const format = getCollectionFormat(collectionPathname);
// Get existing environment files to generate unique name
const existingFiles = fs.existsSync(envDirPath) ? fs.readdirSync(envDirPath) : [];
const existingEnvNames = existingFiles
.filter((file) => file.endsWith(`.${format}`))
.map((file) => path.basename(file, `.${format}`));
// Generate unique name based on existing environment files
const sanitizedName = sanitizeName(name);
const uniqueName = generateUniqueName(sanitizedName, (name) => existingEnvNames.includes(name));
const envFilePath = path.join(envDirPath, `${uniqueName}.${format}`);
const environment = {
name: uniqueName,
variables: variables || [],
color
};
if (envHasSecrets(environment)) {
environmentSecretsStore.storeEnvSecrets(collectionPathname, environment);
}
const content = await stringifyEnvironment(environment, { format });
await writeFile(envFilePath, content);
} catch (error) {
return Promise.reject(error);
}
});
// save environment
ipcMain.handle('renderer:save-environment', async (event, collectionPathname, environment) => {
try {
const envDirPath = path.join(collectionPathname, 'environments');
if (!fs.existsSync(envDirPath)) {
await createDirectory(envDirPath);
}
const format = getCollectionFormat(collectionPathname);
// Determine filetype from collection
const envFilePath = path.join(envDirPath, `${environment.name}.${format}`);
if (!fs.existsSync(envFilePath)) {
throw new Error(`environment: ${envFilePath} does not exist`);
}
if (envHasSecrets(environment)) {
environmentSecretsStore.storeEnvSecrets(collectionPathname, environment);
}
const content = await stringifyEnvironment(environment, { format });
await writeFile(envFilePath, content);
} catch (error) {
return Promise.reject(error);
}
});
// rename environment
ipcMain.handle('renderer:rename-environment', async (event, collectionPathname, environmentName, newName) => {
try {
const format = getCollectionFormat(collectionPathname);
const envDirPath = path.join(collectionPathname, 'environments');
const envFilePath = path.join(envDirPath, `${environmentName}.${format}`);
if (!fs.existsSync(envFilePath)) {
throw new Error(`environment: ${envFilePath} does not exist`);
}
const newEnvFilePath = path.join(envDirPath, `${newName}.${format}`);
if (!safeToRename(envFilePath, newEnvFilePath)) {
throw new Error(`environment: ${newEnvFilePath} already exists`);
}
moveRequestUid(envFilePath, newEnvFilePath);
fs.renameSync(envFilePath, newEnvFilePath);
environmentSecretsStore.renameEnvironment(collectionPathname, environmentName, newName);
} catch (error) {
return Promise.reject(error);
}
});
// delete environment
ipcMain.handle('renderer:delete-environment', async (event, collectionPathname, environmentName) => {
try {
const format = getCollectionFormat(collectionPathname);
const envDirPath = path.join(collectionPathname, 'environments');
const envFilePath = path.join(envDirPath, `${environmentName}.${format}`);
if (!fs.existsSync(envFilePath)) {
throw new Error(`environment: ${envFilePath} does not exist`);
}
fs.unlinkSync(envFilePath);
environmentSecretsStore.deleteEnvironment(collectionPathname, environmentName);
} catch (error) {
return Promise.reject(error);
}
});
// Save .env file variables for collection
ipcMain.handle('renderer:save-dotenv-variables', async (event, collectionPathname, variables, filename = '.env') => {
try {
if (!isValidDotEnvFilename(filename)) {
throw new Error('Invalid .env filename');
}
const dotEnvPath = path.join(collectionPathname, filename);
const content = utils.jsonToDotenv(variables);
await writeFile(dotEnvPath, content);
return { success: true };
} catch (error) {
console.error('Error saving .env file:', error);
return Promise.reject(error);
}
});
// Save .env file raw content for collection
ipcMain.handle('renderer:save-dotenv-raw', async (event, collectionPathname, content, filename = '.env') => {
try {
if (!isValidDotEnvFilename(filename)) {
throw new Error('Invalid .env filename');
}
const dotEnvPath = path.join(collectionPathname, filename);
await writeFile(dotEnvPath, content);
return { success: true };
} catch (error) {
console.error('Error saving .env file:', error);
return Promise.reject(error);
}
});
// Create .env file for collection
ipcMain.handle('renderer:create-dotenv-file', async (event, collectionPathname, filename = '.env') => {
try {
if (!isValidDotEnvFilename(filename)) {
throw new Error('Invalid .env filename');
}
const dotEnvPath = path.join(collectionPathname, filename);
if (fs.existsSync(dotEnvPath)) {
throw new Error(`${filename} file already exists`);
}
await writeFile(dotEnvPath, '');
return { success: true, filename };
} catch (error) {
console.error('Error creating .env file:', error);
return Promise.reject(error);
}
});
// Delete .env file for collection
ipcMain.handle('renderer:delete-dotenv-file', async (event, collectionPathname, filename = '.env') => {
try {
if (!isValidDotEnvFilename(filename)) {
throw new Error('Invalid .env filename');
}
const dotEnvPath = path.join(collectionPathname, filename);
if (!fs.existsSync(dotEnvPath)) {
throw new Error(`${filename} file does not exist`);
}
fs.unlinkSync(dotEnvPath);
return { success: true };
} catch (error) {
console.error('Error deleting .env file:', error);
return Promise.reject(error);
}
});
// update environment color
ipcMain.handle('renderer:update-environment-color', async (event, collectionPathname, environmentName, color) => {
try {
const format = getCollectionFormat(collectionPathname);
const envDirPath = path.join(collectionPathname, 'environments');
const envFilePath = path.join(envDirPath, `${environmentName}.${format}`);
if (!fs.existsSync(envFilePath)) {
throw new Error(`environment: ${envFilePath} does not exist`);
}
// Read, update color, and write back to file
const fileContent = fs.readFileSync(envFilePath, 'utf8');
const environment = parseEnvironment(fileContent, { format });
environment.color = color;
const updatedContent = stringifyEnvironment(environment, { format });
fs.writeFileSync(envFilePath, updatedContent, 'utf8');
} catch (error) {
return Promise.reject(error);
}
});
// Generic environment export handler
ipcMain.handle('renderer:export-environment', async (event, { environments, environmentType, filePath, exportFormat = 'folder' }) => {
try {
const { app } = require('electron');
const appVersion = app?.getVersion() || '2.0.0';
// For single environments and folder exports, include info in each environment
const environmentWithInfo = (environment) => ({
name: environment.name,
variables: environment.variables,
color: environment.color ?? undefined,
info: {
type: 'bruno-environment',
exportedAt: new Date().toISOString(),
exportedUsing: `Bruno/v${appVersion}`
}
});
if (exportFormat === 'folder') {
// separate environment json files in folder
const baseFolderName = `bruno-${environmentType}-environments`;
const uniqueFolderName = generateUniqueName(baseFolderName, (name) => fs.existsSync(path.join(filePath, name)));
const exportPath = path.join(filePath, uniqueFolderName);
fs.mkdirSync(exportPath, { recursive: true });
for (const environment of environments) {
const baseFileName = environment.name ? `${environment.name.replace(/[^a-zA-Z0-9-_]/g, '_')}` : 'environment';
const uniqueFileName = generateUniqueName(baseFileName, (name) => fs.existsSync(path.join(exportPath, `${name}.json`)));
const fullPath = path.join(exportPath, `${uniqueFileName}.json`);
const cleanEnv = environmentWithInfo(environment);
const jsonContent = JSON.stringify(cleanEnv, null, 2);
await fs.promises.writeFile(fullPath, jsonContent, 'utf8');
}
} else if (exportFormat === 'single-file') {
// all environments in a single file with top-level info and environments array
const baseFileName = `bruno-${environmentType}-environments`;
const uniqueFileName = generateUniqueName(baseFileName, (name) => fs.existsSync(path.join(filePath, `${name}.json`)));
const fullPath = path.join(filePath, `${uniqueFileName}.json`);
const exportData = {
info: {
type: 'bruno-environment',
exportedAt: new Date().toISOString(),
exportedUsing: `Bruno/v${appVersion}`
},
environments
};
const jsonContent = JSON.stringify(exportData, null, 2);
await fs.promises.writeFile(fullPath, jsonContent, 'utf8');
} else if (exportFormat === 'single-object') {
// single environment json file
if (environments.length !== 1) {
throw new Error('Single object export requires exactly one environment');
}
const environment = environments[0];
const baseFileName = environment.name ? `${environment.name.replace(/[^a-zA-Z0-9-_]/g, '_')}` : 'environment';
const uniqueFileName = generateUniqueName(baseFileName, (name) => fs.existsSync(path.join(filePath, `${name}.json`)));
const fullPath = path.join(filePath, `${uniqueFileName}.json`);
const jsonContent = JSON.stringify(environmentWithInfo(environment), null, 2);
await fs.promises.writeFile(fullPath, jsonContent, 'utf8');
} else {
throw new Error(`Unsupported export format: ${exportFormat}`);
}
} catch (error) {
return Promise.reject(error);
}
});
// rename item
ipcMain.handle('renderer:rename-item-name', async (event, { itemPath, newName, collectionPathname }) => {
try {
if (!fs.existsSync(itemPath)) {
throw new Error(`path: ${itemPath} does not exist`);
}
if (isDirectory(itemPath)) {
const format = getCollectionFormat(collectionPathname);
const folderFilePath = path.join(itemPath, `folder.${format}`);
let folderFileJsonContent;
if (fs.existsSync(folderFilePath)) {
const oldFolderFileContent = await fs.promises.readFile(folderFilePath, 'utf8');
folderFileJsonContent = await parseFolder(oldFolderFileContent, { format });
folderFileJsonContent.meta.name = newName;
} else {
folderFileJsonContent = {
meta: {
name: newName
}
};
}
const folderFileContent = await stringifyFolder(folderFileJsonContent, { format });
await writeFile(folderFilePath, folderFileContent);
return;
}
const format = getCollectionFormat(collectionPathname);
if (!hasRequestExtension(itemPath, format)) {
throw new Error(`path: ${itemPath} is not a valid request file`);
}
const data = fs.readFileSync(itemPath, 'utf8');
const jsonData = parseRequest(data, { format });
jsonData.name = newName;
const content = stringifyRequest(jsonData, { format });
await writeFile(itemPath, content);
} catch (error) {
return Promise.reject(error);
}
});
// rename item
ipcMain.handle('renderer:rename-item-filename', async (event, { oldPath, newPath, newName, newFilename, collectionPathname }) => {
const tempDir = path.join(os.tmpdir(), `temp-folder-${Date.now()}`);
const isWindowsOSAndNotWSLPathAndItemHasSubDirectories = isDirectory(oldPath) && isWindowsOS() && !isWSLPath(oldPath) && hasSubDirectories(oldPath);
try {
// Check if the old path exists
if (!fs.existsSync(oldPath)) {
throw new Error(`path: ${oldPath} does not exist`);
}
if (!safeToRename(oldPath, newPath)) {
throw new Error(`path: ${newPath} already exists`);
}
const format = getCollectionFormat(collectionPathname);
if (isDirectory(oldPath)) {
const folderFilePath = path.join(oldPath, `folder.${format}`);
let folderFileJsonContent;
if (fs.existsSync(folderFilePath)) {
const oldFolderFileContent = await fs.promises.readFile(folderFilePath, 'utf8');
folderFileJsonContent = await parseFolder(oldFolderFileContent, { format });
folderFileJsonContent.meta.name = newName;
} else {
folderFileJsonContent = {
meta: {
name: newName
}
};
}
const folderFileContent = await stringifyFolder(folderFileJsonContent, { format });
await writeFile(folderFilePath, folderFileContent);
const requestFilesAtSource = await searchForRequestFiles(oldPath, collectionPathname);
for (let requestFile of requestFilesAtSource) {
const newRequestFilePath = requestFile.replace(oldPath, newPath);
moveRequestUid(requestFile, newRequestFilePath);
}
/**
* If it is windows OS
* And it is not a WSL path (meaning it is not running in WSL (linux pathtype))
* And it has sub directories
* Only then we need to use the temp dir approach to rename the folder
*
* Windows OS would sometimes throw error when renaming a folder with sub directories
* This is an alternative approach to avoid that error
*/
if (isWindowsOSAndNotWSLPathAndItemHasSubDirectories) {
await fsExtra.copy(oldPath, tempDir);
await fsExtra.remove(oldPath);
await fsExtra.move(tempDir, newPath, { overwrite: true });
await fsExtra.remove(tempDir);
} else {
await fs.renameSync(oldPath, newPath);
}
return newPath;
}
if (!hasRequestExtension(oldPath, format)) {
throw new Error(`path: ${oldPath} is not a valid request file`);
}
if (!validateName(newFilename)) {
throw new Error(`path: ${newFilename} is not a valid filename`);
}
// update name in file and save new copy, then delete old copy
const data = await fs.promises.readFile(oldPath, 'utf8'); // Use async read
const jsonData = parseRequest(data, { format });
jsonData.name = newName;
moveRequestUid(oldPath, newPath);
const content = stringifyRequest(jsonData, { format });
await fs.promises.unlink(oldPath);
await writeFile(newPath, content);
return newPath;
} catch (error) {
// in case the rename file operations fails, and we see that the temp dir exists
// and the old path does not exist, we need to restore the data from the temp dir to the old path
if (isWindowsOSAndNotWSLPathAndItemHasSubDirectories) {
if (fsExtra.pathExistsSync(tempDir) && !fsExtra.pathExistsSync(oldPath)) {
try {
await fsExtra.copy(tempDir, oldPath);
await fsExtra.remove(tempDir);
} catch (err) {
console.error('Failed to restore data to the old path:', err);
}
}
}
return Promise.reject(error);
}
});
// new folder
ipcMain.handle('renderer:new-folder', async (event, { pathname, folderData, format }) => {
const resolvedFolderName = sanitizeName(path.basename(pathname));
pathname = path.join(path.dirname(pathname), resolvedFolderName);
try {
if (!fs.existsSync(pathname)) {
fs.mkdirSync(pathname);
const folderFilePath = path.join(pathname, `folder.${format}`);
const content = await stringifyFolder(folderData, { format });
await writeFile(folderFilePath, content);
} else {
return Promise.reject(new Error('The directory already exists'));
}
} catch (error) {
return Promise.reject(error);
}
});
// delete file/folder