chore(#197): ran prettier on packages/bruno-electron

This commit is contained in:
Anoop M D 2023-09-22 00:36:42 +05:30
parent ae692dde06
commit 67fe264494
18 changed files with 810 additions and 725 deletions

View File

@ -16,22 +16,24 @@ const configSchema = Yup.object({
name: Yup.string().nullable().max(256, 'name must be 256 characters or less'), name: Yup.string().nullable().max(256, 'name must be 256 characters or less'),
type: Yup.string().oneOf(['collection']).required('type is required'), type: Yup.string().oneOf(['collection']).required('type is required'),
version: Yup.string().oneOf(['1']).required('type is required') version: Yup.string().oneOf(['1']).required('type is required')
}).noUnknown(true).strict(); })
.noUnknown(true)
.strict();
const readConfigFile = async (pathname) => { const readConfigFile = async (pathname) => {
try { try {
const jsonData = fs.readFileSync(pathname, 'utf8'); const jsonData = fs.readFileSync(pathname, 'utf8');
return JSON.parse(jsonData); return JSON.parse(jsonData);
} catch (err) { } catch (err) {
return Promise.reject(new Error("Unable to parse json in bruno.json")); return Promise.reject(new Error('Unable to parse json in bruno.json'));
}
} }
};
const validateSchema = async (config) => { const validateSchema = async (config) => {
try { try {
await configSchema.validate(config); await configSchema.validate(config);
} catch (err) { } catch (err) {
return Promise.reject(new Error("bruno.json format is invalid")); return Promise.reject(new Error('bruno.json format is invalid'));
} }
}; };
@ -45,7 +47,7 @@ const getCollectionConfigFile = async (pathname) => {
await validateSchema(config); await validateSchema(config);
return config; return config;
} };
const openCollectionDialog = async (win, watcher) => { const openCollectionDialog = async (win, watcher) => {
const { filePaths } = await dialog.showOpenDialog(win, { const { filePaths } = await dialog.showOpenDialog(win, {
@ -60,14 +62,12 @@ const openCollectionDialog = async (win, watcher) => {
console.error(`[ERROR] Cannot open unknown folder: "${resolvedPath}"`); console.error(`[ERROR] Cannot open unknown folder: "${resolvedPath}"`);
} }
} }
} };
const openCollection = async (win, watcher, collectionPath, options = {}) => { const openCollection = async (win, watcher, collectionPath, options = {}) => {
if (!watcher.hasWatcher(collectionPath)) { if (!watcher.hasWatcher(collectionPath)) {
try { try {
const { const { name } = await getCollectionConfigFile(collectionPath);
name
} = await getCollectionConfigFile(collectionPath);
const uid = generateUidBasedOnHash(collectionPath); const uid = generateUidBasedOnHash(collectionPath);
win.webContents.send('main:collection-opened', collectionPath, uid, name); win.webContents.send('main:collection-opened', collectionPath, uid, name);

View File

@ -30,7 +30,7 @@ class LastOpenedCollections {
let collections = this.store.get('lastOpenedCollections') || []; let collections = this.store.get('lastOpenedCollections') || [];
if (collections.includes(collectionPath)) { if (collections.includes(collectionPath)) {
collections = _.filter(collections, c => c !== collectionPath); collections = _.filter(collections, (c) => c !== collectionPath);
this.store.set('lastOpenedCollections', collections); this.store.set('lastOpenedCollections', collections);
} }
} }
@ -38,6 +38,6 @@ class LastOpenedCollections {
removeAll() { removeAll() {
return this.store.set('lastOpenedCollections', []); return this.store.set('lastOpenedCollections', []);
} }
}; }
module.exports = LastOpenedCollections; module.exports = LastOpenedCollections;

View File

@ -38,16 +38,11 @@ const template = [
}, },
{ {
role: 'window', role: 'window',
submenu: [ submenu: [{ role: 'minimize' }, { role: 'close' }]
{ role: 'minimize'},
{ role: 'close'}
]
}, },
{ {
role: 'help', role: 'help',
submenu: [ submenu: [{ label: 'Learn More' }]
{ label: 'Learn More'}
]
} }
]; ];

View File

@ -14,11 +14,11 @@ let preferences = {};
const getPreferences = () => { const getPreferences = () => {
return preferences; return preferences;
} };
const setPreferences = (newPreferences) => { const setPreferences = (newPreferences) => {
preferences = newPreferences; preferences = newPreferences;
} };
module.exports = { module.exports = {
getPreferences, getPreferences,

View File

@ -3,19 +3,9 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
const chokidar = require('chokidar'); const chokidar = require('chokidar');
const { hasJsonExtension, hasBruExtension, writeFile } = require('../utils/filesystem'); const { hasJsonExtension, hasBruExtension, writeFile } = require('../utils/filesystem');
const { const { bruToEnvJson, envJsonToBru, bruToJson, jsonToBru } = require('../bru');
bruToEnvJson,
envJsonToBru,
bruToJson,
jsonToBru
} = require('../bru');
const { const { isLegacyEnvFile, migrateLegacyEnvFile, isLegacyBruFile, migrateLegacyBruFile } = require('../bru/migrate');
isLegacyEnvFile,
migrateLegacyEnvFile,
isLegacyBruFile,
migrateLegacyBruFile
} = require('../bru/migrate');
const { itemSchema } = require('@usebruno/schema'); const { itemSchema } = require('@usebruno/schema');
const { uuid } = require('../utils/common'); const { uuid } = require('../utils/common');
const { getRequestUid } = require('../cache/requestUids'); const { getRequestUid } = require('../cache/requestUids');
@ -46,16 +36,16 @@ const hydrateRequestWithUuid = (request, pathname) => {
const bodyFormUrlEncoded = _.get(request, 'request.body.formUrlEncoded', []); const bodyFormUrlEncoded = _.get(request, 'request.body.formUrlEncoded', []);
const bodyMultipartForm = _.get(request, 'request.body.multipartForm', []); const bodyMultipartForm = _.get(request, 'request.body.multipartForm', []);
params.forEach((param) => param.uid = uuid()); params.forEach((param) => (param.uid = uuid()));
headers.forEach((header) => header.uid = uuid()); headers.forEach((header) => (header.uid = uuid()));
requestVars.forEach((variable) => variable.uid = uuid()); requestVars.forEach((variable) => (variable.uid = uuid()));
responseVars.forEach((variable) => variable.uid = uuid()); responseVars.forEach((variable) => (variable.uid = uuid()));
assertions.forEach((assertion) => assertion.uid = uuid()); assertions.forEach((assertion) => (assertion.uid = uuid()));
bodyFormUrlEncoded.forEach((param) => param.uid = uuid()); bodyFormUrlEncoded.forEach((param) => (param.uid = uuid()));
bodyMultipartForm.forEach((param) => param.uid = uuid()); bodyMultipartForm.forEach((param) => (param.uid = uuid()));
return request; return request;
} };
const addEnvironmentFile = async (win, pathname, collectionUid) => { const addEnvironmentFile = async (win, pathname, collectionUid) => {
try { try {
@ -65,7 +55,7 @@ const addEnvironmentFile = async (win, pathname, collectionUid) => {
collectionUid, collectionUid,
pathname, pathname,
name: basename name: basename
}, }
}; };
let bruContent = fs.readFileSync(pathname, 'utf8'); let bruContent = fs.readFileSync(pathname, 'utf8');
@ -79,10 +69,10 @@ const addEnvironmentFile = async (win, pathname, collectionUid) => {
file.data.name = basename.substring(0, basename.length - 4); file.data.name = basename.substring(0, basename.length - 4);
file.data.uid = getRequestUid(pathname); file.data.uid = getRequestUid(pathname);
_.each(_.get(file, 'data.variables', []), (variable) => variable.uid = uuid()); _.each(_.get(file, 'data.variables', []), (variable) => (variable.uid = uuid()));
win.webContents.send('main:collection-tree-updated', 'addEnvironmentFile', file); win.webContents.send('main:collection-tree-updated', 'addEnvironmentFile', file);
} catch (err) { } catch (err) {
console.error(err) console.error(err);
} }
}; };
@ -101,14 +91,14 @@ const changeEnvironmentFile = async (win, pathname, collectionUid) => {
file.data = bruToEnvJson(bruContent); file.data = bruToEnvJson(bruContent);
file.data.name = basename.substring(0, basename.length - 4); file.data.name = basename.substring(0, basename.length - 4);
file.data.uid = getRequestUid(pathname); file.data.uid = getRequestUid(pathname);
_.each(_.get(file, 'data.variables', []), (variable) => variable.uid = uuid()); _.each(_.get(file, 'data.variables', []), (variable) => (variable.uid = uuid()));
// we are reusing the addEnvironmentFile event itself // we are reusing the addEnvironmentFile event itself
// this is because the uid of the pathname remains the same // this is because the uid of the pathname remains the same
// and the collection tree will be able to update the existing environment // and the collection tree will be able to update the existing environment
win.webContents.send('main:collection-tree-updated', 'addEnvironmentFile', file); win.webContents.send('main:collection-tree-updated', 'addEnvironmentFile', file);
} catch (err) { } catch (err) {
console.error(err) console.error(err);
} }
}; };
@ -118,17 +108,17 @@ const unlinkEnvironmentFile = async (win, pathname, collectionUid) => {
meta: { meta: {
collectionUid, collectionUid,
pathname, pathname,
name: path.basename(pathname), name: path.basename(pathname)
}, },
data: { data: {
uid: getRequestUid(pathname), uid: getRequestUid(pathname),
name: path.basename(pathname).substring(0, path.basename(pathname).length - 4), name: path.basename(pathname).substring(0, path.basename(pathname).length - 4)
} }
}; };
win.webContents.send('main:collection-tree-updated', 'unlinkEnvironmentFile', file); win.webContents.send('main:collection-tree-updated', 'unlinkEnvironmentFile', file);
} catch (err) { } catch (err) {
console.error(err) console.error(err);
} }
}; };
@ -191,9 +181,9 @@ const add = async (win, pathname, collectionUid, collectionPath) => {
meta: { meta: {
collectionUid, collectionUid,
pathname, pathname,
name: path.basename(pathname), name: path.basename(pathname)
}
} }
};
try { try {
let bruContent = fs.readFileSync(pathname, 'utf8'); let bruContent = fs.readFileSync(pathname, 'utf8');
@ -207,7 +197,7 @@ const add = async (win, pathname, collectionUid, collectionPath) => {
hydrateRequestWithUuid(file.data, pathname); hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'addFile', file); win.webContents.send('main:collection-tree-updated', 'addFile', file);
} catch (err) { } catch (err) {
console.error(err) console.error(err);
} }
} }
}; };
@ -223,7 +213,7 @@ const addDirectory = (win, pathname, collectionUid, collectionPath) => {
meta: { meta: {
collectionUid, collectionUid,
pathname, pathname,
name: path.basename(pathname), name: path.basename(pathname)
} }
}; };
win.webContents.send('main:collection-tree-updated', 'addDir', directory); win.webContents.send('main:collection-tree-updated', 'addDir', directory);
@ -240,7 +230,7 @@ const change = async (win, pathname, collectionUid, collectionPath) => {
meta: { meta: {
collectionUid, collectionUid,
pathname, pathname,
name: path.basename(pathname), name: path.basename(pathname)
} }
}; };
@ -249,10 +239,9 @@ const change = async (win, pathname, collectionUid, collectionPath) => {
hydrateRequestWithUuid(file.data, pathname); hydrateRequestWithUuid(file.data, pathname);
win.webContents.send('main:collection-tree-updated', 'change', file); win.webContents.send('main:collection-tree-updated', 'change', file);
} catch (err) { } catch (err) {
console.error(err) console.error(err);
} }
} }
}; };
const unlink = (win, pathname, collectionUid, collectionPath) => { const unlink = (win, pathname, collectionUid, collectionPath) => {
@ -270,7 +259,7 @@ const unlink = (win, pathname, collectionUid, collectionPath) => {
}; };
win.webContents.send('main:collection-tree-updated', 'unlink', file); win.webContents.send('main:collection-tree-updated', 'unlink', file);
} }
} };
const unlinkDir = (win, pathname, collectionUid, collectionPath) => { const unlinkDir = (win, pathname, collectionUid, collectionPath) => {
const envDirectory = path.join(collectionPath, 'environments'); const envDirectory = path.join(collectionPath, 'environments');
@ -287,7 +276,7 @@ const unlinkDir = (win, pathname, collectionUid, collectionPath) => {
} }
}; };
win.webContents.send('main:collection-tree-updated', 'unlinkDir', directory); win.webContents.send('main:collection-tree-updated', 'unlinkDir', directory);
} };
class Watcher { class Watcher {
constructor() { constructor() {
@ -309,7 +298,7 @@ class Watcher {
const watcher = chokidar.watch(watchPath, { const watcher = chokidar.watch(watchPath, {
ignoreInitial: false, ignoreInitial: false,
usePolling: false, usePolling: false,
ignored: path => ["node_modules", ".git", "bruno.json"].some(s => path.includes(s)), ignored: (path) => ['node_modules', '.git', 'bruno.json'].some((s) => path.includes(s)),
persistent: true, persistent: true,
ignorePermissionErrors: true, ignorePermissionErrors: true,
awaitWriteFinish: { awaitWriteFinish: {
@ -320,11 +309,11 @@ class Watcher {
}); });
watcher watcher
.on('add', pathname => add(win, pathname, collectionUid, watchPath)) .on('add', (pathname) => add(win, pathname, collectionUid, watchPath))
.on('addDir', pathname => addDirectory(win, pathname, collectionUid, watchPath)) .on('addDir', (pathname) => addDirectory(win, pathname, collectionUid, watchPath))
.on('change', pathname => change(win, pathname, collectionUid, watchPath)) .on('change', (pathname) => change(win, pathname, collectionUid, watchPath))
.on('unlink', pathname => unlink(win, pathname, collectionUid, watchPath)) .on('unlink', (pathname) => unlink(win, pathname, collectionUid, watchPath))
.on('unlinkDir', pathname => unlinkDir(win, pathname, collectionUid, watchPath)) .on('unlinkDir', (pathname) => unlinkDir(win, pathname, collectionUid, watchPath));
self.watchers[watchPath] = watcher; self.watchers[watchPath] = watcher;
}, 100); }, 100);
@ -340,6 +329,6 @@ class Watcher {
this.watchers[watchPath] = null; this.watchers[watchPath] = null;
} }
} }
}; }
module.exports = Watcher; module.exports = Watcher;

View File

@ -1,10 +1,5 @@
const _ = require('lodash'); const _ = require('lodash');
const { const { bruToJsonV2, jsonToBruV2, bruToEnvJsonV2, envJsonToBruV2 } = require('@usebruno/lang');
bruToJsonV2,
jsonToBruV2,
bruToEnvJsonV2,
envJsonToBruV2
} = require('@usebruno/lang');
const { each } = require('lodash'); const { each } = require('lodash');
const bruToEnvJson = (bru) => { const bruToEnvJson = (bru) => {
@ -15,14 +10,14 @@ const bruToEnvJson = (bru) => {
// this need to be evaulated and safely removed // this need to be evaulated and safely removed
// i don't see it being used in schema validation // i don't see it being used in schema validation
if (json && json.variables && json.variables.length) { if (json && json.variables && json.variables.length) {
each(json.variables, (v) => v.type = "text"); each(json.variables, (v) => (v.type = 'text'));
} }
return json; return json;
} catch (error) { } catch (error) {
return Promise.reject(e); return Promise.reject(e);
} }
} };
const envJsonToBru = (json) => { const envJsonToBru = (json) => {
try { try {
@ -31,7 +26,7 @@ const envJsonToBru = (json) => {
} catch (error) { } catch (error) {
return Promise.reject(e); return Promise.reject(e);
} }
} };
/** /**
* The transformer function for converting a BRU file to JSON. * The transformer function for converting a BRU file to JSON.
@ -46,35 +41,35 @@ const bruToJson = (bru) => {
try { try {
const json = bruToJsonV2(bru); const json = bruToJsonV2(bru);
let requestType = _.get(json, "meta.type"); let requestType = _.get(json, 'meta.type');
if(requestType === "http") { if (requestType === 'http') {
requestType = "http-request" requestType = 'http-request';
} else if(requestType === "graphql") { } else if (requestType === 'graphql') {
requestType = "graphql-request"; requestType = 'graphql-request';
} else { } else {
requestType = "http-request"; requestType = 'http-request';
} }
const sequence = _.get(json, "meta.seq") const sequence = _.get(json, 'meta.seq');
const transformedJson = { const transformedJson = {
"type": requestType, type: requestType,
"name": _.get(json, "meta.name"), name: _.get(json, 'meta.name'),
"seq": !isNaN(sequence) ? Number(sequence) : 1, seq: !isNaN(sequence) ? Number(sequence) : 1,
"request": { request: {
"method": _.upperCase(_.get(json, "http.method")), method: _.upperCase(_.get(json, 'http.method')),
"url": _.get(json, "http.url"), url: _.get(json, 'http.url'),
"params": _.get(json, "query", []), params: _.get(json, 'query', []),
"headers": _.get(json, "headers", []), headers: _.get(json, 'headers', []),
"body": _.get(json, "body", {}), body: _.get(json, 'body', {}),
"script": _.get(json, "script", {}), script: _.get(json, 'script', {}),
"vars": _.get(json, "vars", {}), vars: _.get(json, 'vars', {}),
"assertions": _.get(json, "assertions", []), assertions: _.get(json, 'assertions', []),
"tests": _.get(json, "tests", "") tests: _.get(json, 'tests', '')
} }
}; };
transformedJson.request.body.mode = _.get(json, "http.body", "none"); transformedJson.request.body.mode = _.get(json, 'http.body', 'none');
return transformedJson; return transformedJson;
} catch (e) { } catch (e) {
@ -93,18 +88,18 @@ const bruToJson = (bru) => {
const jsonToBru = (json) => { const jsonToBru = (json) => {
let type = _.get(json, 'type'); let type = _.get(json, 'type');
if (type === 'http-request') { if (type === 'http-request') {
type = "http"; type = 'http';
} else if (type === 'graphql-request') { } else if (type === 'graphql-request') {
type = "graphql"; type = 'graphql';
} else { } else {
type = "http"; type = 'http';
} }
const bruJson = { const bruJson = {
meta: { meta: {
name: _.get(json, 'name'), name: _.get(json, 'name'),
type: type, type: type,
seq: _.get(json, 'seq'), seq: _.get(json, 'seq')
}, },
http: { http: {
method: _.lowerCase(_.get(json, 'request.method')), method: _.lowerCase(_.get(json, 'request.method')),
@ -120,7 +115,7 @@ const jsonToBru = (json) => {
res: _.get(json, 'request.vars.res', []) res: _.get(json, 'request.vars.res', [])
}, },
assertions: _.get(json, 'request.assertions', []), assertions: _.get(json, 'request.assertions', []),
tests: _.get(json, 'request.tests', ''), tests: _.get(json, 'request.tests', '')
}; };
return jsonToBruV2(bruJson); return jsonToBruV2(bruJson);
@ -130,5 +125,5 @@ module.exports = {
bruToJson, bruToJson,
jsonToBru, jsonToBru,
bruToEnvJson, bruToEnvJson,
envJsonToBru, envJsonToBru
}; };

View File

@ -34,11 +34,11 @@ const isLegacyBruFile = (bruContent = '') => {
for (let line of lines) { for (let line of lines) {
line = line.trim(); line = line.trim();
if (line.startsWith("name")) { if (line.startsWith('name')) {
hasName = true; hasName = true;
} else if (line.startsWith("method")) { } else if (line.startsWith('method')) {
hasMethod = true; hasMethod = true;
} else if (line.startsWith("url")) { } else if (line.startsWith('url')) {
hasUrl = true; hasUrl = true;
} }
} }
@ -51,11 +51,11 @@ const migrateLegacyBruFile = async (bruContent, pathname) => {
let type = _.get(json, 'type'); let type = _.get(json, 'type');
if (type === 'http-request') { if (type === 'http-request') {
type = "http"; type = 'http';
} else if (type === 'graphql-request') { } else if (type === 'graphql-request') {
type = "graphql"; type = 'graphql';
} else { } else {
type = "http"; type = 'http';
} }
let script = {}; let script = {};
@ -70,7 +70,7 @@ const migrateLegacyBruFile = async (bruContent, pathname) => {
meta: { meta: {
name: _.get(json, 'name'), name: _.get(json, 'name'),
type: type, type: type,
seq: _.get(json, 'seq'), seq: _.get(json, 'seq')
}, },
http: { http: {
method: _.lowerCase(_.get(json, 'request.method')), method: _.lowerCase(_.get(json, 'request.method')),
@ -81,7 +81,7 @@ const migrateLegacyBruFile = async (bruContent, pathname) => {
headers: _.get(json, 'request.headers', []), headers: _.get(json, 'request.headers', []),
body: _.get(json, 'request.body', {}), body: _.get(json, 'request.body', {}),
script: script, script: script,
tests: _.get(json, 'request.tests', ''), tests: _.get(json, 'request.tests', '')
}; };
const newBruContent = jsonToBruV2(bruJson); const newBruContent = jsonToBruV2(bruJson);
@ -89,7 +89,7 @@ const migrateLegacyBruFile = async (bruContent, pathname) => {
await writeFile(pathname, newBruContent); await writeFile(pathname, newBruContent);
return newBruContent; return newBruContent;
} };
module.exports = { module.exports = {
isLegacyEnvFile, isLegacyEnvFile,

View File

@ -35,8 +35,8 @@ app.on('ready', async () => {
webPreferences: { webPreferences: {
nodeIntegration: true, nodeIntegration: true,
contextIsolation: true, contextIsolation: true,
preload: path.join(__dirname, "preload.js") preload: path.join(__dirname, 'preload.js')
}, }
}); });
const url = isDev const url = isDev

View File

@ -2,11 +2,7 @@ const _ = require('lodash');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const { ipcMain } = require('electron'); const { ipcMain } = require('electron');
const { const { envJsonToBru, bruToJson, jsonToBru } = require('../bru');
envJsonToBru,
bruToJson,
jsonToBru
} = require('../bru');
const { const {
isValidPathname, isValidPathname,
@ -21,7 +17,7 @@ const { stringifyJson } = require('../utils/common');
const { openCollectionDialog, openCollection } = require('../app/collections'); const { openCollectionDialog, openCollection } = require('../app/collections');
const { generateUidBasedOnHash } = require('../utils/common'); const { generateUidBasedOnHash } = require('../utils/common');
const { moveRequestUid, deleteRequestUid } = require('../cache/requestUids'); const { moveRequestUid, deleteRequestUid } = require('../cache/requestUids');
const { setPreferences } = require("../app/preferences"); const { setPreferences } = require('../app/preferences');
const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollections) => { const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollections) => {
// browse directory // browse directory
@ -36,7 +32,9 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
}); });
// create collection // create collection
ipcMain.handle('renderer:create-collection', async (event, collectionName, collectionFolderName, collectionLocation) => { ipcMain.handle(
'renderer:create-collection',
async (event, collectionName, collectionFolderName, collectionLocation) => {
try { try {
const dirPath = path.join(collectionLocation, collectionFolderName); const dirPath = path.join(collectionLocation, collectionFolderName);
if (fs.existsSync(dirPath)) { if (fs.existsSync(dirPath)) {
@ -64,7 +62,8 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
} catch (error) { } catch (error) {
return Promise.reject(error); return Promise.reject(error);
} }
}); }
);
// rename collection // rename collection
ipcMain.handle('renderer:rename-collection', async (event, newName, collectionPathname) => { ipcMain.handle('renderer:rename-collection', async (event, newName, collectionPathname) => {
@ -307,7 +306,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
// Recursive function to parse the collection items and create files/folders // Recursive function to parse the collection items and create files/folders
const parseCollectionItems = (items = [], currentPath) => { const parseCollectionItems = (items = [], currentPath) => {
items.forEach(item => { items.forEach((item) => {
if (['http-request', 'graphql-request'].includes(item.type)) { if (['http-request', 'graphql-request'].includes(item.type)) {
const content = jsonToBru(item); const content = jsonToBru(item);
const filePath = path.join(currentPath, `${item.name}.bru`); const filePath = path.join(currentPath, `${item.name}.bru`);
@ -330,7 +329,7 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
fs.mkdirSync(envDirPath); fs.mkdirSync(envDirPath);
} }
environments.forEach(env => { environments.forEach((env) => {
const content = envJsonToBru(env); const content = envJsonToBru(env);
const filePath = path.join(envDirPath, `${env.name}.bru`); const filePath = path.join(envDirPath, `${env.name}.bru`);
fs.writeFileSync(filePath, content); fs.writeFileSync(filePath, content);
@ -355,7 +354,6 @@ const registerRendererEventHandlers = (mainWindow, watcher, lastOpenedCollection
// create folder and files based on collection // create folder and files based on collection
await parseCollectionItems(collection.items, collectionPath); await parseCollectionItems(collection.items, collectionPath);
await parseEnvironments(collection.environments, collectionPath); await parseEnvironments(collection.environments, collectionPath);
} catch (error) { } catch (error) {
return Promise.reject(error); return Promise.reject(error);
} }
@ -449,12 +447,11 @@ const registerMainEventHandlers = (mainWindow, watcher, lastOpenedCollections) =
watcher.addWatcher(win, pathname, uid); watcher.addWatcher(win, pathname, uid);
lastOpenedCollections.add(pathname); lastOpenedCollections.add(pathname);
}); });
};
}
const registerCollectionsIpc = (mainWindow, watcher, lastOpenedCollections) => { const registerCollectionsIpc = (mainWindow, watcher, lastOpenedCollections) => {
registerRendererEventHandlers(mainWindow, watcher, lastOpenedCollections); registerRendererEventHandlers(mainWindow, watcher, lastOpenedCollections);
registerMainEventHandlers(mainWindow, watcher, lastOpenedCollections); registerMainEventHandlers(mainWindow, watcher, lastOpenedCollections);
} };
module.exports = registerCollectionsIpc; module.exports = registerCollectionsIpc;

View File

@ -1,8 +1,4 @@
const { const { each, filter } = require('lodash');
each,
filter
} = require('lodash');
const sortCollection = (collection) => { const sortCollection = (collection) => {
const items = collection.items || []; const items = collection.items || [];

View File

@ -53,7 +53,7 @@ const getEnvVars = (environment = {}) => {
return { return {
...envVars, ...envVars,
__name__: environment.name __name__: environment.name
} };
}; };
const getSize = (data) => { const getSize = (data) => {
@ -74,7 +74,9 @@ const getSize = (data) => {
const registerNetworkIpc = (mainWindow) => { const registerNetworkIpc = (mainWindow) => {
// handler for sending http request // handler for sending http request
ipcMain.handle('send-http-request', async (event, item, collectionUid, collectionPath, environment, collectionVariables) => { ipcMain.handle(
'send-http-request',
async (event, item, collectionUid, collectionPath, environment, collectionVariables) => {
const cancelTokenUid = uuid(); const cancelTokenUid = uuid();
const requestUid = uuid(); const requestUid = uuid();
@ -119,7 +121,13 @@ const registerNetworkIpc = (mainWindow) => {
const preRequestVars = get(request, 'vars.req', []); const preRequestVars = get(request, 'vars.req', []);
if (preRequestVars && preRequestVars.length) { if (preRequestVars && preRequestVars.length) {
const varsRuntime = new VarsRuntime(); const varsRuntime = new VarsRuntime();
const result = varsRuntime.runPreRequestVars(preRequestVars, request, envVars, collectionVariables, collectionPath); const result = varsRuntime.runPreRequestVars(
preRequestVars,
request,
envVars,
collectionVariables,
collectionPath
);
mainWindow.webContents.send('main:script-environment-update', { mainWindow.webContents.send('main:script-environment-update', {
envVariables: result.envVariables, envVariables: result.envVariables,
@ -133,7 +141,14 @@ const registerNetworkIpc = (mainWindow) => {
const requestScript = get(request, 'script.req'); const requestScript = get(request, 'script.req');
if (requestScript && requestScript.length) { if (requestScript && requestScript.length) {
const scriptRuntime = new ScriptRuntime(); const scriptRuntime = new ScriptRuntime();
const result = await scriptRuntime.runRequestScript(requestScript, request, envVars, collectionVariables, collectionPath, onConsoleLog); const result = await scriptRuntime.runRequestScript(
requestScript,
request,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:script-environment-update', { mainWindow.webContents.send('main:script-environment-update', {
envVariables: result.envVariables, envVariables: result.envVariables,
@ -172,10 +187,9 @@ const registerNetworkIpc = (mainWindow) => {
const httpsAgentRequestFields = {}; const httpsAgentRequestFields = {};
if (!sslVerification) { if (!sslVerification) {
httpsAgentRequestFields['rejectUnauthorized'] = false; httpsAgentRequestFields['rejectUnauthorized'] = false;
} } else {
else {
const cacertArray = [preferences['cacert'], process.env.SSL_CERT_FILE, process.env.NODE_EXTRA_CA_CERTS]; const cacertArray = [preferences['cacert'], process.env.SSL_CERT_FILE, process.env.NODE_EXTRA_CA_CERTS];
cacertFile = cacertArray.find(el => el); cacertFile = cacertArray.find((el) => el);
if (cacertFile && cacertFile.length > 1) { if (cacertFile && cacertFile.length > 1) {
try { try {
const fs = require('fs'); const fs = require('fs');
@ -199,7 +213,14 @@ const registerNetworkIpc = (mainWindow) => {
const postResponseVars = get(request, 'vars.res', []); const postResponseVars = get(request, 'vars.res', []);
if (postResponseVars && postResponseVars.length) { if (postResponseVars && postResponseVars.length) {
const varsRuntime = new VarsRuntime(); const varsRuntime = new VarsRuntime();
const result = varsRuntime.runPostResponseVars(postResponseVars, request, response, envVars, collectionVariables, collectionPath); const result = varsRuntime.runPostResponseVars(
postResponseVars,
request,
response,
envVars,
collectionVariables,
collectionPath
);
mainWindow.webContents.send('main:script-environment-update', { mainWindow.webContents.send('main:script-environment-update', {
envVariables: result.envVariables, envVariables: result.envVariables,
@ -213,7 +234,15 @@ const registerNetworkIpc = (mainWindow) => {
const responseScript = get(request, 'script.res'); const responseScript = get(request, 'script.res');
if (responseScript && responseScript.length) { if (responseScript && responseScript.length) {
const scriptRuntime = new ScriptRuntime(); const scriptRuntime = new ScriptRuntime();
const result = await scriptRuntime.runResponseScript(responseScript, request, response, envVars, collectionVariables, collectionPath, onConsoleLog); const result = await scriptRuntime.runResponseScript(
responseScript,
request,
response,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:script-environment-update', { mainWindow.webContents.send('main:script-environment-update', {
envVariables: result.envVariables, envVariables: result.envVariables,
@ -227,7 +256,14 @@ const registerNetworkIpc = (mainWindow) => {
const assertions = get(request, 'assertions'); const assertions = get(request, 'assertions');
if (assertions && assertions.length) { if (assertions && assertions.length) {
const assertRuntime = new AssertRuntime(); const assertRuntime = new AssertRuntime();
const results = assertRuntime.runAssertions(assertions, request, response, envVars, collectionVariables, collectionPath); const results = assertRuntime.runAssertions(
assertions,
request,
response,
envVars,
collectionVariables,
collectionPath
);
mainWindow.webContents.send('main:run-request-event', { mainWindow.webContents.send('main:run-request-event', {
type: 'assertion-results', type: 'assertion-results',
@ -242,7 +278,15 @@ const registerNetworkIpc = (mainWindow) => {
const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests'); const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests');
if (testFile && testFile.length) { if (testFile && testFile.length) {
const testRuntime = new TestRuntime(); const testRuntime = new TestRuntime();
const testResults = testRuntime.runTests(testFile, request, response, envVars, collectionVariables, collectionPath, onConsoleLog); const testResults = testRuntime.runTests(
testFile,
request,
response,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:run-request-event', { mainWindow.webContents.send('main:run-request-event', {
type: 'test-results', type: 'test-results',
@ -275,7 +319,7 @@ const registerNetworkIpc = (mainWindow) => {
deleteCancelToken(cancelTokenUid); deleteCancelToken(cancelTokenUid);
if (axios.isCancel(error)) { if (axios.isCancel(error)) {
let error = new Error("Request cancelled"); let error = new Error('Request cancelled');
error.isCancel = true; error.isCancel = true;
return Promise.reject(error); return Promise.reject(error);
} }
@ -285,7 +329,14 @@ const registerNetworkIpc = (mainWindow) => {
const assertions = get(request, 'assertions'); const assertions = get(request, 'assertions');
if (assertions && assertions.length) { if (assertions && assertions.length) {
const assertRuntime = new AssertRuntime(); const assertRuntime = new AssertRuntime();
const results = assertRuntime.runAssertions(assertions, request, error.response, envVars, collectionVariables, collectionPath); const results = assertRuntime.runAssertions(
assertions,
request,
error.response,
envVars,
collectionVariables,
collectionPath
);
mainWindow.webContents.send('main:run-request-event', { mainWindow.webContents.send('main:run-request-event', {
type: 'assertion-results', type: 'assertion-results',
@ -300,7 +351,15 @@ const registerNetworkIpc = (mainWindow) => {
const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests'); const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests');
if (testFile && testFile.length) { if (testFile && testFile.length) {
const testRuntime = new TestRuntime(); const testRuntime = new TestRuntime();
const testResults = testRuntime.runTests(testFile, request, error.response, envVars, collectionVariables, collectionPath, onConsoleLog); const testResults = testRuntime.runTests(
testFile,
request,
error.response,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:run-request-event', { mainWindow.webContents.send('main:run-request-event', {
type: 'test-results', type: 'test-results',
@ -323,12 +382,13 @@ const registerNetworkIpc = (mainWindow) => {
statusText: error.response.statusText, statusText: error.response.statusText,
headers: error.response.headers, headers: error.response.headers,
data: error.response.data data: error.response.data
}
}; };
}
return Promise.reject(error); return Promise.reject(error);
} }
}); }
);
ipcMain.handle('cancel-http-request', async (event, cancelTokenUid) => { ipcMain.handle('cancel-http-request', async (event, cancelTokenUid) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -337,7 +397,7 @@ const registerNetworkIpc = (mainWindow) => {
deleteCancelToken(cancelTokenUid); deleteCancelToken(cancelTokenUid);
resolve(); resolve();
} else { } else {
reject(new Error("cancel token not found")); reject(new Error('cancel token not found'));
} }
}); });
}); });
@ -371,14 +431,16 @@ const registerNetworkIpc = (mainWindow) => {
statusText: error.response.statusText, statusText: error.response.statusText,
headers: error.response.headers, headers: error.response.headers,
data: error.response.data data: error.response.data
}
}; };
}
return Promise.reject(error); return Promise.reject(error);
} }
}); });
ipcMain.handle('renderer:run-collection-folder', async (event, folder, collection, environment, collectionVariables, recursive) => { ipcMain.handle(
'renderer:run-collection-folder',
async (event, folder, collection, environment, collectionVariables, recursive) => {
const collectionUid = collection.uid; const collectionUid = collection.uid;
const collectionPath = collection.pathname; const collectionPath = collection.pathname;
const folderUid = folder ? folder.uid : null; const folderUid = folder ? folder.uid : null;
@ -465,7 +527,14 @@ const registerNetworkIpc = (mainWindow) => {
const requestScript = get(request, 'script.req'); const requestScript = get(request, 'script.req');
if (requestScript && requestScript.length) { if (requestScript && requestScript.length) {
const scriptRuntime = new ScriptRuntime(); const scriptRuntime = new ScriptRuntime();
const result = await scriptRuntime.runRequestScript(requestScript, request, envVars, collectionVariables, collectionPath, onConsoleLog); const result = await scriptRuntime.runRequestScript(
requestScript,
request,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:script-environment-update', { mainWindow.webContents.send('main:script-environment-update', {
envVariables: result.envVariables, envVariables: result.envVariables,
@ -509,7 +578,14 @@ const registerNetworkIpc = (mainWindow) => {
const postResponseVars = get(request, 'vars.res', []); const postResponseVars = get(request, 'vars.res', []);
if (postResponseVars && postResponseVars.length) { if (postResponseVars && postResponseVars.length) {
const varsRuntime = new VarsRuntime(); const varsRuntime = new VarsRuntime();
const result = varsRuntime.runPostResponseVars(postResponseVars, request, response, envVars, collectionVariables, collectionPath); const result = varsRuntime.runPostResponseVars(
postResponseVars,
request,
response,
envVars,
collectionVariables,
collectionPath
);
mainWindow.webContents.send('main:script-environment-update', { mainWindow.webContents.send('main:script-environment-update', {
envVariables: result.envVariables, envVariables: result.envVariables,
@ -522,7 +598,15 @@ const registerNetworkIpc = (mainWindow) => {
const responseScript = get(request, 'script.res'); const responseScript = get(request, 'script.res');
if (responseScript && responseScript.length) { if (responseScript && responseScript.length) {
const scriptRuntime = new ScriptRuntime(); const scriptRuntime = new ScriptRuntime();
const result = await scriptRuntime.runResponseScript(responseScript, request, response, envVars, collectionVariables, collectionPath, onConsoleLog); const result = await scriptRuntime.runResponseScript(
responseScript,
request,
response,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:script-environment-update', { mainWindow.webContents.send('main:script-environment-update', {
envVariables: result.envVariables, envVariables: result.envVariables,
@ -535,7 +619,14 @@ const registerNetworkIpc = (mainWindow) => {
const assertions = get(item, 'request.assertions'); const assertions = get(item, 'request.assertions');
if (assertions && assertions.length) { if (assertions && assertions.length) {
const assertRuntime = new AssertRuntime(); const assertRuntime = new AssertRuntime();
const results = assertRuntime.runAssertions(assertions, request, response, envVars, collectionVariables, collectionPath); const results = assertRuntime.runAssertions(
assertions,
request,
response,
envVars,
collectionVariables,
collectionPath
);
mainWindow.webContents.send('main:run-folder-event', { mainWindow.webContents.send('main:run-folder-event', {
type: 'assertion-results', type: 'assertion-results',
@ -549,7 +640,15 @@ const registerNetworkIpc = (mainWindow) => {
const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests'); const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests');
if (testFile && testFile.length) { if (testFile && testFile.length) {
const testRuntime = new TestRuntime(); const testRuntime = new TestRuntime();
const testResults = testRuntime.runTests(testFile, request, response, envVars, collectionVariables, collectionPath, onConsoleLog); const testResults = testRuntime.runTests(
testFile,
request,
response,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:run-folder-event', { mainWindow.webContents.send('main:run-folder-event', {
type: 'test-results', type: 'test-results',
@ -573,7 +672,7 @@ const registerNetworkIpc = (mainWindow) => {
headers: Object.entries(response.headers), headers: Object.entries(response.headers),
duration: timeEnd - timeStart, duration: timeEnd - timeStart,
size: response.headers['content-length'] || getSize(response.data), size: response.headers['content-length'] || getSize(response.data),
data: response.data, data: response.data
} }
}); });
} catch (error) { } catch (error) {
@ -591,14 +690,21 @@ const registerNetworkIpc = (mainWindow) => {
headers: Object.entries(error.response.headers), headers: Object.entries(error.response.headers),
duration: duration, duration: duration,
size: error.response.headers['content-length'] || getSize(error.response.data), size: error.response.headers['content-length'] || getSize(error.response.data),
data: error.response.data, data: error.response.data
} };
// run assertions // run assertions
const assertions = get(item, 'request.assertions'); const assertions = get(item, 'request.assertions');
if (assertions && assertions.length) { if (assertions && assertions.length) {
const assertRuntime = new AssertRuntime(); const assertRuntime = new AssertRuntime();
const results = assertRuntime.runAssertions(assertions, request, error.response, envVars, collectionVariables, collectionPath); const results = assertRuntime.runAssertions(
assertions,
request,
error.response,
envVars,
collectionVariables,
collectionPath
);
mainWindow.webContents.send('main:run-folder-event', { mainWindow.webContents.send('main:run-folder-event', {
type: 'assertion-results', type: 'assertion-results',
@ -612,7 +718,15 @@ const registerNetworkIpc = (mainWindow) => {
const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests'); const testFile = item.draft ? get(item.draft, 'request.tests') : get(item, 'request.tests');
if (testFile && testFile.length) { if (testFile && testFile.length) {
const testRuntime = new TestRuntime(); const testRuntime = new TestRuntime();
const testResults = testRuntime.runTests(testFile, request, error.response, envVars, collectionVariables, collectionPath, onConsoleLog); const testResults = testRuntime.runTests(
testFile,
request,
error.response,
envVars,
collectionVariables,
collectionPath,
onConsoleLog
);
mainWindow.webContents.send('main:run-folder-event', { mainWindow.webContents.send('main:run-folder-event', {
type: 'test-results', type: 'test-results',
@ -658,7 +772,8 @@ const registerNetworkIpc = (mainWindow) => {
error error
}); });
} }
}); }
);
}; };
module.exports = registerNetworkIpc; module.exports = registerNetworkIpc;

View File

@ -8,7 +8,7 @@ Mustache.escape = function (value) {
const interpolateVars = (request, envVars = {}, collectionVariables = {}) => { const interpolateVars = (request, envVars = {}, collectionVariables = {}) => {
const interpolate = (str) => { const interpolate = (str) => {
if(!str || !str.length || typeof str !== "string") { if (!str || !str.length || typeof str !== 'string') {
return str; return str;
} }
@ -27,29 +27,27 @@ const interpolateVars = (request, envVars = {}, collectionVariables ={}) => {
request.headers[key] = interpolate(value); request.headers[key] = interpolate(value);
}); });
if(request.headers["content-type"] === "application/json") { if (request.headers['content-type'] === 'application/json') {
if(typeof request.data === "object") { if (typeof request.data === 'object') {
try { try {
let parsed = JSON.stringify(request.data); let parsed = JSON.stringify(request.data);
parsed = interpolate(parsed); parsed = interpolate(parsed);
request.data = JSON.parse(parsed); request.data = JSON.parse(parsed);
} catch (err) { } catch (err) {}
}
} }
if(typeof request.data === "string") { if (typeof request.data === 'string') {
if (request.data.length) { if (request.data.length) {
request.data = interpolate(request.data); request.data = interpolate(request.data);
} }
} }
} else if(request.headers["content-type"] === "application/x-www-form-urlencoded") { } else if (request.headers['content-type'] === 'application/x-www-form-urlencoded') {
if(typeof request.data === "object") { if (typeof request.data === 'object') {
try { try {
let parsed = JSON.stringify(request.data); let parsed = JSON.stringify(request.data);
parsed = interpolate(parsed); parsed = interpolate(parsed);
request.data = JSON.parse(parsed); request.data = JSON.parse(parsed);
} catch (err) { } catch (err) {}
}
} }
} else { } else {
request.data = interpolate(request.data); request.data = interpolate(request.data);

View File

@ -19,7 +19,7 @@ const prepareGqlIntrospectionRequest = (endpoint, envVars) => {
method: 'POST', method: 'POST',
url: endpoint, url: endpoint,
headers: { headers: {
'Accept': 'application/json', Accept: 'application/json',
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
data: JSON.stringify(queryParams) data: JSON.stringify(queryParams)

View File

@ -2,11 +2,11 @@ const cancelTokens = {};
const saveCancelToken = (uid, axiosRequest) => { const saveCancelToken = (uid, axiosRequest) => {
cancelTokens[uid] = axiosRequest; cancelTokens[uid] = axiosRequest;
} };
const deleteCancelToken = (uid) => { const deleteCancelToken = (uid) => {
delete cancelTokens[uid]; delete cancelTokens[uid];
} };
module.exports = { module.exports = {
cancelTokens, cancelTokens,

View File

@ -15,7 +15,7 @@ const stringifyJson = async (str) => {
} catch (err) { } catch (err) {
return Promise.reject(err); return Promise.reject(err);
} }
} };
const parseJson = async (obj) => { const parseJson = async (obj) => {
try { try {
@ -23,7 +23,7 @@ const parseJson = async (obj) => {
} catch (err) { } catch (err) {
return Promise.reject(err); return Promise.reject(err);
} }
} };
const simpleHash = (str) => { const simpleHash = (str) => {
let hash = 0; let hash = 0;
@ -39,7 +39,7 @@ const generateUidBasedOnHash = (str) => {
const hash = simpleHash(str); const hash = simpleHash(str);
return `${hash}`.padEnd(21, '0'); return `${hash}`.padEnd(21, '0');
} };
module.exports = { module.exports = {
uuid, uuid,

View File

@ -4,7 +4,7 @@ const fsPromises = require('fs/promises');
const { dialog } = require('electron'); const { dialog } = require('electron');
const isValidPathname = require('is-valid-path'); const isValidPathname = require('is-valid-path');
const exists = async p => { const exists = async (p) => {
try { try {
await fsPromises.access(p); await fsPromises.access(p);
return true; return true;
@ -13,7 +13,7 @@ const exists = async p => {
} }
}; };
const isSymbolicLink = filepath => { const isSymbolicLink = (filepath) => {
try { try {
return fs.existsSync(filepath) && fs.lstatSync(filepath).isSymbolicLink(); return fs.existsSync(filepath) && fs.lstatSync(filepath).isSymbolicLink();
} catch (_) { } catch (_) {
@ -21,7 +21,7 @@ const isSymbolicLink = filepath => {
} }
}; };
const isFile = filepath => { const isFile = (filepath) => {
try { try {
return fs.existsSync(filepath) && fs.lstatSync(filepath).isFile(); return fs.existsSync(filepath) && fs.lstatSync(filepath).isFile();
} catch (_) { } catch (_) {
@ -29,7 +29,7 @@ const isFile = filepath => {
} }
}; };
const isDirectory = dirPath => { const isDirectory = (dirPath) => {
try { try {
return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
} catch (_) { } catch (_) {
@ -37,14 +37,14 @@ const isDirectory = dirPath => {
} }
}; };
const normalizeAndResolvePath = pathname => { const normalizeAndResolvePath = (pathname) => {
if (isSymbolicLink(pathname)) { if (isSymbolicLink(pathname)) {
const absPath = path.dirname(pathname); const absPath = path.dirname(pathname);
const targetPath = path.resolve(absPath, fs.readlinkSync(pathname)); const targetPath = path.resolve(absPath, fs.readlinkSync(pathname));
if (isFile(targetPath) || isDirectory(targetPath)) { if (isFile(targetPath) || isDirectory(targetPath)) {
return path.resolve(targetPath); return path.resolve(targetPath);
} }
console.error(`Cannot resolve link target "${pathname}" (${targetPath}).`) console.error(`Cannot resolve link target "${pathname}" (${targetPath}).`);
return ''; return '';
} }
return path.resolve(pathname); return path.resolve(pathname);
@ -53,22 +53,22 @@ const normalizeAndResolvePath = pathname => {
const writeFile = async (pathname, content) => { const writeFile = async (pathname, content) => {
try { try {
fs.writeFileSync(pathname, content, { fs.writeFileSync(pathname, content, {
encoding: "utf8" encoding: 'utf8'
}); });
} catch (err) { } catch (err) {
return Promise.reject(err); return Promise.reject(err);
} }
}; };
const hasJsonExtension = filename => { const hasJsonExtension = (filename) => {
if (!filename || typeof filename !== 'string') return false if (!filename || typeof filename !== 'string') return false;
return ['json'].some(ext => filename.toLowerCase().endsWith(`.${ext}`)) return ['json'].some((ext) => filename.toLowerCase().endsWith(`.${ext}`));
} };
const hasBruExtension = filename => { const hasBruExtension = (filename) => {
if (!filename || typeof filename !== 'string') return false if (!filename || typeof filename !== 'string') return false;
return ['bru'].some(ext => filename.toLowerCase().endsWith(`.${ext}`)) return ['bru'].some((ext) => filename.toLowerCase().endsWith(`.${ext}`));
} };
const createDirectory = async (dir) => { const createDirectory = async (dir) => {
if (!dir) { if (!dir) {
@ -108,7 +108,7 @@ const searchForFiles = (dir, extension) => {
} }
} }
return results; return results;
} };
const searchForBruFiles = (dir) => { const searchForBruFiles = (dir) => {
return searchForFiles(dir, '.bru'); return searchForFiles(dir, '.bru');