From 5442d8fb8473ffb149f0da180138df371dad66ad Mon Sep 17 00:00:00 2001 From: Trevor McMaster Date: Thu, 14 Mar 2024 10:23:56 -0600 Subject: [PATCH 1/5] Fixed duplicate build:agent in build command --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ee0d20a5..31afaa3f 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "start:controller": "cd controller && npm run start", "start:agent": "cd agent && npm run start", "dev": "cd controller && npm run dev", - "build": "npm run lint && npm run build:common && npm run build:agent && npm-run-all --parallel build:agent build:controller", + "build": "npm run lint && npm run build:common && npm-run-all --parallel build:agent build:controller", "storybook": "cd controller && npm run storybook", "build-storybook": "cd controller && npm run build-storybook", "lint": "node --max_old_space_size=4096 ./node_modules/eslint/bin/eslint.js --fix . --ext .ts,.tsx", From d5a919c78a23758c5fa42c75a710719d15ad3341 Mon Sep 17 00:00:00 2001 From: Trevor McMaster Date: Thu, 14 Mar 2024 10:24:45 -0600 Subject: [PATCH 2/5] Added additional lint spacing rules --- .eslintrc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.eslintrc b/.eslintrc index 74e61e43..3bf36364 100644 --- a/.eslintrc +++ b/.eslintrc @@ -61,6 +61,8 @@ "space-before-function-paren": 1, "spaced-comment": ["error", "always", { "block": { "balanced": true } }], "space-infix-ops":"warn", + "space-before-blocks": "warn", + "keyword-spacing": "warn", "strict": 1, "comma-dangle": 1, "triple-equals": 0, From 71096a517f4bc2e6564af3574163f2bbe741efff Mon Sep 17 00:00:00 2001 From: Trevor McMaster Date: Thu, 14 Mar 2024 10:28:12 -0600 Subject: [PATCH 3/5] Fixed common, agent, and controller code for the new lint rules --- agent/acceptance/tests.spec.ts | 2 +- agent/createtest/pewpewtest.spec.ts | 2 +- agent/src/healthcheck.ts | 2 +- agent/src/pewpewtest.ts | 16 ++++++++-------- common/integration/s3.spec.ts | 4 ++-- common/integration/s3file.spec.ts | 6 +++--- common/src/ppaascommessage.ts | 2 +- common/src/ppaastestmessage.ts | 2 +- common/test/ppaasteststatus.spec.ts | 2 +- common/test/s3.spec.ts | 2 +- common/test/s3file.spec.ts | 4 ++-- controller/components/Calendar/index.tsx | 2 +- controller/components/StartTestForm/index.tsx | 2 +- controller/components/TestResults/charts.ts | 2 +- .../integration/ppaasencryptenvfile.spec.ts | 2 +- .../integration/ppaasencrypts3file.spec.ts | 2 +- controller/integration/testmanager.spec.ts | 2 +- controller/pages/api/auth.ts | 4 ++-- .../api/error/[yamlFile]/[dateString]/index.ts | 2 +- .../[yamlFile]/[dateString]/[resultsFile].ts | 2 +- controller/pages/api/login.ts | 2 +- controller/pages/api/logout.ts | 2 +- controller/pages/api/queuenames.ts | 2 +- controller/pages/api/queues.ts | 2 +- controller/pages/api/util/clientutil.ts | 2 +- controller/pages/api/util/healthcheck.ts | 2 +- controller/pages/api/util/testmanager.ts | 6 +++--- controller/pages/api/util/util.ts | 2 +- .../yaml/[yamlFile]/[dateString]/[filename].ts | 2 +- controller/test/ppaasencryptenvfile.spec.ts | 2 +- controller/test/testscheduler.spec.ts | 2 +- controller/test/util.spec.ts | 4 ++-- 32 files changed, 47 insertions(+), 47 deletions(-) diff --git a/agent/acceptance/tests.spec.ts b/agent/acceptance/tests.spec.ts index d6716347..b35c960f 100644 --- a/agent/acceptance/tests.spec.ts +++ b/agent/acceptance/tests.spec.ts @@ -27,7 +27,7 @@ describe("Tests Integration", () => { done(new Error("Should have returned a 404")); }).catch((error: unknown) => { log(integrationUrl + "/tests/ error", LogLevel.DEBUG, error, { status: (error as AxiosError)?.response?.status }); - if ((error as AxiosError)?.response?.status === 404){ + if ((error as AxiosError)?.response?.status === 404) { done(); } else { done(error); diff --git a/agent/createtest/pewpewtest.spec.ts b/agent/createtest/pewpewtest.spec.ts index 576223de..8f8f93d6 100644 --- a/agent/createtest/pewpewtest.spec.ts +++ b/agent/createtest/pewpewtest.spec.ts @@ -227,7 +227,7 @@ describe("PewPewTest Create Test", () => { await test!.launch(); // Should have thrown done(new Error("test.launch() should have failed with pewpew exited with kill")); - } catch(error) { + } catch (error) { // Kill should throw log("'Retrieve Test and launch, then kill should succeed' result", LogLevel.DEBUG, error); try { diff --git a/agent/src/healthcheck.ts b/agent/src/healthcheck.ts index 5f83c31c..88134c1d 100644 --- a/agent/src/healthcheck.ts +++ b/agent/src/healthcheck.ts @@ -65,7 +65,7 @@ export async function pingS3 (): Promise { config.lastS3Access = new Date(); log("Pinging S3 succeeded at " + new Date(), LogLevel.DEBUG); return true; - } catch(error) { + } catch (error) { log("pingS3 failed}", LogLevel.ERROR, error); // DO NOT REJECT. Just return false return false; diff --git a/agent/src/pewpewtest.ts b/agent/src/pewpewtest.ts index 78f12203..94a96957 100644 --- a/agent/src/pewpewtest.ts +++ b/agent/src/pewpewtest.ts @@ -305,7 +305,7 @@ export class PewPewTest { protected async writeTestStatus () { try { await this.ppaasTestStatus.writeStatus(); - } catch(error) { + } catch (error) { this.log("Could not write ppaasTestStatus", LogLevel.ERROR, error, { ppaasTestStatus: this.ppaasTestStatus }); } } @@ -316,7 +316,7 @@ export class PewPewTest { const { testId } = this.testMessage; const messageId = await new PpaasCommunicationsMessage({ testId, messageType, messageData }).send(); this.log(`Sent testStatus ${messageType}: " ${messageId}`, LogLevel.DEBUG, { messageData, messageId }); - } catch(error) { + } catch (error) { this.log("Could not send TestStatus", LogLevel.ERROR, error, { messageData }); } } @@ -325,7 +325,7 @@ export class PewPewTest { try { const messageId = await refreshTestScalingMessage(); this.log(`Sent refreshTestScalingMessage: " ${messageId}`, LogLevel.DEBUG, { messageId }); - } catch(error) { + } catch (error) { this.log("Error calling refreshTestScalingMessage", LogLevel.ERROR, error); } } @@ -334,7 +334,7 @@ export class PewPewTest { try { const messageId = await deleteTestScalingMessage(); this.log(`deleteTestScalingMessage: " ${messageId}`, LogLevel.DEBUG, { messageId }); - } catch(error) { + } catch (error) { this.log("Error calling deleteTestScalingMessage", LogLevel.ERROR, error); } } @@ -594,7 +594,7 @@ export class PewPewTest { this.log(errorMessage, LogLevel.ERROR, error); try { await this.internalStop(); - } catch(err) { + } catch (err) { this.log("Could not stop the pewpew process", LogLevel.ERROR, err); } // Send failed communications message and update teststatus @@ -758,7 +758,7 @@ export class PewPewTest { await this.sendTestStatus(); // Keep alive every loop await this.refreshTestScalingMessage(); - } catch(error) { + } catch (error) { this.log(`Polling PewPew Results Error. iteration: ${iteration}`, LogLevel.ERROR, error); } if (Date.now() < endLoop) { @@ -915,7 +915,7 @@ export class PewPewTest { this.writeTestStatus(), this.internalStop() ]); - } catch(err) { + } catch (err) { this.log("Could not stop the pewpew process", LogLevel.ERROR, err); } // Keep trying to check and kill the pewpew process? @@ -928,7 +928,7 @@ export class PewPewTest { if (this.pewpewRunning) { await sleep(10000); } - } catch(err) { + } catch (err) { this.log("Could not stop the pewpew process", LogLevel.ERROR, err); } } diff --git a/common/integration/s3.spec.ts b/common/integration/s3.spec.ts index 2c2b48e0..956d270d 100644 --- a/common/integration/s3.spec.ts +++ b/common/integration/s3.spec.ts @@ -243,7 +243,7 @@ describe("S3Util Integration", () => { const objects = await listObjects(s3FileKey!); return (objects && objects.Contents && objects.Contents.length > 0); }, MAX_POLL_WAIT, (errMsg: string) => `${errMsg} Could not find the ${s3FileKey} in s3`); - } catch(error) { + } catch (error) { log(`beforeEach error uploadFile(${UNIT_TEST_FILEPATH}, ${UNIT_TEST_KEY_PREFIX})`, LogLevel.ERROR, error); throw error; } @@ -416,7 +416,7 @@ describe("S3Util Integration", () => { afterEach (async () => { // Delete the local file - if(localFile) { + if (localFile) { await fs.unlink(localFile) .catch((error) => log("Could not delete " + localFile, LogLevel.WARN, error)); } diff --git a/common/integration/s3file.spec.ts b/common/integration/s3file.spec.ts index b5b17981..91055736 100644 --- a/common/integration/s3file.spec.ts +++ b/common/integration/s3file.spec.ts @@ -166,7 +166,7 @@ describe("PpaasS3File Integration", () => { testPpaasS3FileUpload.setLastModifiedLocal(0); testPpaasS3FileUpload.remoteUrl = ""; // As long as we don't throw, it passes - } catch(error) { + } catch (error) { throw error; } }); @@ -238,7 +238,7 @@ describe("PpaasS3File Integration", () => { log("testPpaasS3FileUpload.upload() succeeded", LogLevel.DEBUG); s3FileKey = testPpaasS3FileUpload.key; // As long as we don't throw, it passes - } catch(error) { + } catch (error) { throw error; } }); @@ -361,7 +361,7 @@ describe("PpaasS3File Integration", () => { afterEach (async () => { // Delete the local file - if(localFile) { + if (localFile) { await fs.unlink(localFile) .catch((error) => log("Could not delete " + localFile, LogLevel.WARN, error)); } diff --git a/common/src/ppaascommessage.ts b/common/src/ppaascommessage.ts index 9cba6c1f..953d7ca8 100644 --- a/common/src/ppaascommessage.ts +++ b/common/src/ppaascommessage.ts @@ -85,7 +85,7 @@ export class PpaasCommunicationsMessage implements CommunicationsMessage { continue; } else if (value.DataType === "String") { // "Number" also is stored as StringValue log(`messageAttributes[${key}].StringValue = ${value.StringValue}`, LogLevel.DEBUG); - switch(key) { + switch (key) { // If this is set, it isn't a real message and should be swallowed. It was from an integration test case "UnitTestMessage": unittestMessage = true; diff --git a/common/src/ppaastestmessage.ts b/common/src/ppaastestmessage.ts index e3a9829c..a9baa9a0 100644 --- a/common/src/ppaastestmessage.ts +++ b/common/src/ppaastestmessage.ts @@ -151,7 +151,7 @@ export class PpaasTestMessage implements TestMessage { continue; } else if (value.DataType === "String") { log(`messageAttributes[${key}].StringValue = ${value.StringValue}`, LogLevel.DEBUG); - switch(key) { + switch (key) { // If this is set, it isn't a real message and should be swallowed. It was from an integration test case "UnitTestMessage": unittestMessage = true; diff --git a/common/test/ppaasteststatus.spec.ts b/common/test/ppaasteststatus.spec.ts index 44a965ad..de0e8636 100644 --- a/common/test/ppaasteststatus.spec.ts +++ b/common/test/ppaasteststatus.spec.ts @@ -76,7 +76,7 @@ describe("PpaasTestStatus", () => { // should have all the TestStatus + lastModifiedRemote && testId && url expect(Object.keys(actualTestMessage).length, `Actual Keys: ${Object.keys(actualTestMessage).toString()}\nExpected Keys: ${Object.keys(testStatus).toString()}\nMessage keys length`).to.equal(Object.keys(testStatus).length + 3); for (const key in actualTestMessage) { - switch(key) { + switch (key) { case "lastModifiedRemote": expect(JSON.stringify(actualTestMessage.lastModifiedRemote), key).to.equal(JSON.stringify(new Date(0))); break; diff --git a/common/test/s3.spec.ts b/common/test/s3.spec.ts index eb9be6c2..a5cb7fc1 100644 --- a/common/test/s3.spec.ts +++ b/common/test/s3.spec.ts @@ -374,7 +374,7 @@ describe("S3Util", () => { afterEach (async () => { // Delete the local file - if(localFile) { + if (localFile) { await fs.unlink(localFile) .catch((error) => log("Could not delete " + localFile, LogLevel.WARN, error)); } diff --git a/common/test/s3file.spec.ts b/common/test/s3file.spec.ts index d0a91b4a..c63ca4a5 100644 --- a/common/test/s3file.spec.ts +++ b/common/test/s3file.spec.ts @@ -496,7 +496,7 @@ describe("PpaasS3File", () => { testPpaasS3FileUpload.setLastModifiedLocal(0); testPpaasS3FileUpload.remoteUrl = ""; // As long as we don't throw, it passes - } catch(error) { + } catch (error) { throw error; } }); @@ -564,7 +564,7 @@ describe("PpaasS3File", () => { afterEach (async () => { // Delete the local file - if(localFile) { + if (localFile) { await fs.unlink(localFile) .catch((error) => log("Could not delete " + localFile, LogLevel.WARN, error)); } diff --git a/controller/components/Calendar/index.tsx b/controller/components/Calendar/index.tsx index 58071307..e0bc2496 100644 --- a/controller/components/Calendar/index.tsx +++ b/controller/components/Calendar/index.tsx @@ -48,7 +48,7 @@ export const PPaaSCalendar = ({ ...calendarProps}: CalendarProps) => { // It has to be client rendered so we get the local browser time zone if (Array.isArray(calendarProps.events)) { for (const event of calendarProps.events) { - if(typeof event.startRecur === "number") { + if (typeof event.startRecur === "number") { event.startTime = getHourMinuteFromTimestamp(event.startRecur); event.endTime = typeof event.testRunTimeMn === "number" ? getHourMinuteFromTimestamp(event.startRecur + (60000 * event.testRunTimeMn)) diff --git a/controller/components/StartTestForm/index.tsx b/controller/components/StartTestForm/index.tsx index 4859ae1b..9734d1ec 100644 --- a/controller/components/StartTestForm/index.tsx +++ b/controller/components/StartTestForm/index.tsx @@ -247,7 +247,7 @@ export const StartTestForm = ({ ({ ...prevState, environmentVariables: [...environmentVariables, ...newEnvironmentVariables] }) ); } - } catch(error) { + } catch (error) { log(`Could not parse file: ${file.name}`, LogLevel.ERROR, error); setState({ error: `Could not parse file: ${file.name} - ${formatError(error)}` }); } diff --git a/controller/components/TestResults/charts.ts b/controller/components/TestResults/charts.ts index f7a7c806..d5eaafac 100644 --- a/controller/components/TestResults/charts.ts +++ b/controller/components/TestResults/charts.ts @@ -331,7 +331,7 @@ const afterBuildTicks = (chart: any) => { let lastLegendClick: [number, number, Chart] | undefined; Chart.defaults.plugins.legend.onClick = function ( - e: ChartEvent, + _e: ChartEvent, legendItem: LegendItem, legend: LegendElement ) { diff --git a/controller/integration/ppaasencryptenvfile.spec.ts b/controller/integration/ppaasencryptenvfile.spec.ts index 489cbccb..afede83e 100644 --- a/controller/integration/ppaasencryptenvfile.spec.ts +++ b/controller/integration/ppaasencryptenvfile.spec.ts @@ -168,7 +168,7 @@ describe("PpaasEncryptEnvironmentFile Integration", () => { log("testPpaasEncryptEnvironmentFileUpload.upload() succeeded", LogLevel.DEBUG); s3FileKey = testPpaasEncryptEnvironmentFileUpload.key; // As long as we don't throw, it passes - } catch(error) { + } catch (error) { throw error; } }); diff --git a/controller/integration/ppaasencrypts3file.spec.ts b/controller/integration/ppaasencrypts3file.spec.ts index 666cc2eb..d93c6ec3 100644 --- a/controller/integration/ppaasencrypts3file.spec.ts +++ b/controller/integration/ppaasencrypts3file.spec.ts @@ -128,7 +128,7 @@ describe("PpaasEncryptS3File Integration", () => { log("testPpaasEncryptS3FileUpload.upload() succeeded", LogLevel.DEBUG); s3FileKey = testPpaasEncryptS3FileUpload.key; // As long as we don't throw, it passes - } catch(error) { + } catch (error) { throw error; } }); diff --git a/controller/integration/testmanager.spec.ts b/controller/integration/testmanager.spec.ts index 41d87e85..1399fad3 100644 --- a/controller/integration/testmanager.spec.ts +++ b/controller/integration/testmanager.spec.ts @@ -1812,7 +1812,7 @@ describe("TestManager Integration", () => { expect(Array.isArray(tests.recentTests)).to.equal(true); // Requested should have at least one now expect(tests.runningTests.length + tests.recentTests.length, "tests.runningTests.length + tests.recentTests.length").to.be.greaterThan(0); - } catch(error) { + } catch (error) { log("afterEach error", LogLevel.ERROR, error); throw error; } diff --git a/controller/pages/api/auth.ts b/controller/pages/api/auth.ts index 83565934..e6be4812 100644 --- a/controller/pages/api/auth.ts +++ b/controller/pages/api/auth.ts @@ -24,7 +24,7 @@ export default async (req: NextApiRequest, res: NextApiResponse): Promise log(`${req.method} ${req.url} response: ${JSON.stringify(authPermissions)}`, LogLevel.DEBUG); res.status(200).json(authPermissions); } else if (req.query.refreshToken && !Array.isArray(req.query.refreshToken)) { - try{ + try { const tokenResponse: TokenResponse = await getTokenFromRefreshToken(req.query.refreshToken); log(`${req.method} ${req.url} returning token: ${JSON.stringify(tokenResponse)}`); res.status(200).json(tokenResponse); @@ -34,7 +34,7 @@ export default async (req: NextApiRequest, res: NextApiResponse): Promise } else { res.status(400).json({ message: `method ${req.method} must have a code or token queryparam` }); } - } catch(error) { + } catch (error) { log(`${req.method} ${req.url} failed: ${error}`, LogLevel.ERROR, error); res.status(500).json(createErrorResponse(req, error, LogLevel.ERROR)); } diff --git a/controller/pages/api/error/[yamlFile]/[dateString]/index.ts b/controller/pages/api/error/[yamlFile]/[dateString]/index.ts index defafce5..7b13f34b 100644 --- a/controller/pages/api/error/[yamlFile]/[dateString]/index.ts +++ b/controller/pages/api/error/[yamlFile]/[dateString]/index.ts @@ -55,7 +55,7 @@ export default async (request: NextApiRequest, response: NextApiResponse const authUrl: string = await getAuthUrl(req); log(`${req.method} ${req.url} authUrl response: ${authUrl}`, LogLevel.DEBUG); res.redirect(302, authUrl); - } catch(error) { + } catch (error) { log(`${req.method} ${req.url} failed: ${error}`, LogLevel.ERROR, error); res.status(500).json(createErrorResponse(req, error, LogLevel.ERROR)); } diff --git a/controller/pages/api/logout.ts b/controller/pages/api/logout.ts index a1f6efbc..08e5bc21 100644 --- a/controller/pages/api/logout.ts +++ b/controller/pages/api/logout.ts @@ -12,7 +12,7 @@ export default async (req: NextApiRequest, res: NextApiResponse): Promise const logoutUrl: string = await getLogoutUrl(req); log(`${req.method} ${req.url} logoutUrl response: ${logoutUrl}`, LogLevel.DEBUG); res.redirect(302, logoutUrl); - } catch(error) { + } catch (error) { log(`${req.method} ${req.url} failed: ${error}`, LogLevel.ERROR, error); res.status(500).json(createErrorResponse(req, error, LogLevel.ERROR)); } diff --git a/controller/pages/api/queuenames.ts b/controller/pages/api/queuenames.ts index 43fa6ccd..dbd8095f 100644 --- a/controller/pages/api/queuenames.ts +++ b/controller/pages/api/queuenames.ts @@ -8,7 +8,7 @@ export default (req: NextApiRequest, res: NextApiResponse): void => { try { const queueNames: string[] = PpaasTestMessage.getAvailableQueueNames(); res.status(200).json({ queueNames }); - } catch(error) { + } catch (error) { log(`${req.method} ${req.url} failed: ${error}`, LogLevel.ERROR, error); res.status(500).json(createErrorResponse(req, error)); } diff --git a/controller/pages/api/queues.ts b/controller/pages/api/queues.ts index 57860bd3..ffc01073 100644 --- a/controller/pages/api/queues.ts +++ b/controller/pages/api/queues.ts @@ -8,7 +8,7 @@ export default (req: NextApiRequest, res: NextApiResponse): void => { try { const queues: AgentQueueDescription = PpaasTestMessage.getAvailableQueueMap(); res.status(200).json(queues); - } catch(error) { + } catch (error) { log(`${req.method} ${req.url} failed: ${error}`, LogLevel.ERROR, error); res.status(500).json(createErrorResponse(req, error)); } diff --git a/controller/pages/api/util/clientutil.ts b/controller/pages/api/util/clientutil.ts index 8df4a3ed..d1234529 100644 --- a/controller/pages/api/util/clientutil.ts +++ b/controller/pages/api/util/clientutil.ts @@ -77,7 +77,7 @@ export function formatError (error: unknown): string { const methodText = `${axiosError.config?.method?.toUpperCase() || ""} ${axiosError.config?.url || "request"} failed`; if (axiosError.response) { let errorText: string; - if (typeof axiosError.response.data === "string"){ + if (typeof axiosError.response.data === "string") { // It's a string errorText = axiosError.response.data; } else if (typeof (axiosError.response.data as TestManagerError)?.message === "string") { diff --git a/controller/pages/api/util/healthcheck.ts b/controller/pages/api/util/healthcheck.ts index 7f6d039c..29d59e71 100644 --- a/controller/pages/api/util/healthcheck.ts +++ b/controller/pages/api/util/healthcheck.ts @@ -99,7 +99,7 @@ export async function pingS3 (): Promise { await listObjects({ prefix: "ping", maxKeys: 1 }); // Limit 1 so we can get back fast log("Pinging S3 succeeded at " + new Date(), LogLevel.DEBUG); return true; - } catch(error) { + } catch (error) { log("pingS3 failed", LogLevel.ERROR, error); // DO NOT REJECT. Just return false return false; diff --git a/controller/pages/api/util/testmanager.ts b/controller/pages/api/util/testmanager.ts index bb4cbf90..4ebeeec0 100644 --- a/controller/pages/api/util/testmanager.ts +++ b/controller/pages/api/util/testmanager.ts @@ -462,7 +462,7 @@ export async function validateYamlfile ( dummyEnvironmentVariables[splunkPath] = dummySplunkPath; } yamlParser = await YamlParser.parseYamlFile(yamlFile.filepath, dummyEnvironmentVariables); - } catch(error) { + } catch (error) { return { json: { message: `yamlFile: ${yamlFile.originalFilename || yamlFile.filepath} failed to parse`, error: formatError(error) }, status: 400 }; } @@ -1141,7 +1141,7 @@ export abstract class TestManager { } } log("parsed environmentVariables", LogLevel.DEBUG, Object.keys(environmentVariablesFile)); - } catch(error) { + } catch (error) { log("Could not parse environmentVariables", LogLevel.TRACE, error, fields.environmentVariables); // Don't log the actual error or environmentVariables since it could include passwords return { json: { message: "Could not parse environmentVariables", error: formatError(error) }, status: 400 }; @@ -1541,7 +1541,7 @@ export abstract class TestManager { } try { await YamlParser.parseYamlFile(yamlFile.filepath, environmentVariables); - } catch(error) { + } catch (error) { return { json: { message: `yamlFile: ${yamlFile.originalFilename || yamlFile.filepath} failed to parse`, error: formatError(error) }, status: 400 }; } } diff --git a/controller/pages/api/util/util.ts b/controller/pages/api/util/util.ts index 65b282d1..e78eb999 100644 --- a/controller/pages/api/util/util.ts +++ b/controller/pages/api/util/util.ts @@ -300,7 +300,7 @@ export async function parseZip (formFiles: Files): Promise { formFiles.yamlFile = yamlFiles.length > 1 ? yamlFiles : yamlFiles[0]; } // return formFiles; - } catch(error: any) { + } catch (error: any) { log ("Error parsing files in incoming test form files for zips: " + (error?.msg || error?.message || `${error}`), LogLevel.WARN, error); if (error instanceof Error && error.stack) { // eslint-disable-next-line no-console diff --git a/controller/pages/api/yaml/[yamlFile]/[dateString]/[filename].ts b/controller/pages/api/yaml/[yamlFile]/[dateString]/[filename].ts index 49aebf76..36e36c15 100644 --- a/controller/pages/api/yaml/[yamlFile]/[dateString]/[filename].ts +++ b/controller/pages/api/yaml/[yamlFile]/[dateString]/[filename].ts @@ -32,7 +32,7 @@ export default async (request: NextApiRequest, response: NextApiResponse { await testPpaasEncryptEnvironmentFileUpload.upload(true); lastModified = testPpaasEncryptEnvironmentFileUpload.getLastModifiedRemote(); log("testPpaasEncryptEnvironmentFileUpload.upload() succeeded", LogLevel.DEBUG); - } catch(error) { + } catch (error) { throw error; } }); diff --git a/controller/test/testscheduler.spec.ts b/controller/test/testscheduler.spec.ts index 2f559491..012b132f 100644 --- a/controller/test/testscheduler.spec.ts +++ b/controller/test/testscheduler.spec.ts @@ -547,7 +547,7 @@ describe("TestScheduler", () => { TestSchedulerIntegration.getCalendarEvents().then((events: EventInput[]) => { expect(events).to.not.equal(undefined); expect(events.length, "events.length").to.equal(sizeBefore); - for(const event of events) { + for (const event of events) { expect(event.id).to.equal(testId); expect(event.title).to.equal(yamlFile); expect(event.start).to.equal(scheduledTestData.scheduleDate); diff --git a/controller/test/util.spec.ts b/controller/test/util.spec.ts index 99069fe9..0aebc84c 100644 --- a/controller/test/util.spec.ts +++ b/controller/test/util.spec.ts @@ -34,7 +34,7 @@ describe("Util", () => { await fs.unlink(filepath).catch((error) => log("Could not delete unzipped file " + filename, LogLevel.ERROR, error)); } } - } catch(error) { + } catch (error) { log("Could not clean-up unzipped files", LogLevel.ERROR, error); } }); @@ -135,7 +135,7 @@ describe("Util", () => { await fs.unlink(filepath).catch((error) => log("Could not delete unzipped file " + filename, LogLevel.ERROR, error)); } } - } catch(error) { + } catch (error) { log("Could not clean-up unzipped files", LogLevel.ERROR, error); } }); From f044703815b9a815362dbdb19037ba4bf61cdedf Mon Sep 17 00:00:00 2001 From: Trevor McMaster Date: Thu, 14 Mar 2024 10:49:28 -0600 Subject: [PATCH 4/5] Added spacing and no-shadow lint rules to the guide results viewer --- guide/results-viewer-react/.eslintrc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/guide/results-viewer-react/.eslintrc b/guide/results-viewer-react/.eslintrc index 88261956..f5a20c45 100644 --- a/guide/results-viewer-react/.eslintrc +++ b/guide/results-viewer-react/.eslintrc @@ -9,8 +9,8 @@ ], "extends": [ "eslint:recommended", - "plugin:@typescript-eslint/recommended", - "plugin:@typescript-eslint/stylistic" + "plugin:@typescript-eslint/stylistic", + "plugin:@typescript-eslint/recommended" ], "ignorePatterns": ["lib/", "webpack.config.js"], "rules": { @@ -48,6 +48,8 @@ "space-before-function-paren": 1, "spaced-comment": ["error", "always", { "block": { "balanced": true } }], "space-infix-ops":"warn", + "space-before-blocks": "warn", + "keyword-spacing": "warn", "strict": 1, "comma-dangle": 1, "triple-equals": 0, @@ -55,6 +57,8 @@ "camelcase": 1, "no-irregular-whitespace": 1, "object-shorthand": 1, + "no-shadow": "off", + "@typescript-eslint/no-shadow": "warn", "@typescript-eslint/await-thenable": 1, "quotes": ["warn", "double"] } From 1abcceb636863cfb2dbfde0d09eaec312dbfad24 Mon Sep 17 00:00:00 2001 From: Trevor McMaster Date: Thu, 14 Mar 2024 10:50:35 -0600 Subject: [PATCH 5/5] Fixed lint issues in the guide - Fixed no-shadow issues to match the version from the controller --- .../src/components/TestResults/charts.ts | 9 +- .../src/components/TestResults/index.tsx | 4 +- .../src/components/YamlEndpoints/index.tsx | 26 ++-- .../src/components/YamlLoadPatterns/index.tsx | 34 +++--- .../src/components/YamlLoadPatterns/story.tsx | 6 +- .../components/YamlLoggers/LoggerModal.tsx | 52 ++++---- .../src/components/YamlLoggers/index.tsx | 40 +++---- .../src/components/YamlProviders/index.tsx | 24 ++-- .../src/components/YamlUrls/index.tsx | 61 +++++----- .../src/components/YamlVars/index.tsx | 82 ++++++------- .../src/components/YamlWriterForm/index.tsx | 112 ++++++++++-------- .../src/components/YamlWriterUpload/index.tsx | 63 +++++----- 12 files changed, 266 insertions(+), 247 deletions(-) diff --git a/guide/results-viewer-react/src/components/TestResults/charts.ts b/guide/results-viewer-react/src/components/TestResults/charts.ts index 013b08dc..39d7e939 100644 --- a/guide/results-viewer-react/src/components/TestResults/charts.ts +++ b/guide/results-viewer-react/src/components/TestResults/charts.ts @@ -79,6 +79,7 @@ export function RTT (el: HTMLCanvasElement, dataPoints: DataPoint[]): Chart { ? Math.round(dp.rttHistogram.getMean()) / MICROS_TO_MS : NaN })); + } else if (type === "min") { label = "Min"; data = dataPoints.map((dp) => ({ @@ -87,6 +88,7 @@ export function RTT (el: HTMLCanvasElement, dataPoints: DataPoint[]): Chart { ? Number(dp.rttHistogram.getMinNonZeroValue()) / MICROS_TO_MS : NaN })); + } else if (type === "max") { label = "Max"; data = dataPoints.map((dp) => ({ @@ -95,6 +97,7 @@ export function RTT (el: HTMLCanvasElement, dataPoints: DataPoint[]): Chart { ? Number(dp.rttHistogram.getMaxValue()) / MICROS_TO_MS : NaN })); + } else if (type === "std") { label = "Std Dev"; data = dataPoints.map((dp) => ({ @@ -312,11 +315,11 @@ const afterBuildTicks = (chart: any) => { let currLog = -Infinity; chart.ticks.reverse().forEach((tick: number) => { // Makes sure value is greater than 0 - const log = Math.max(0, Math.log(tick)); + const newLog = Math.max(0, Math.log(tick)); // If distance between points is greater than min separation, add it to the ticks - if (log - currLog > minLogSeparation) { + if (newLog - currLog > minLogSeparation) { myTicks.push(tick); - currLog = log; + currLog = newLog; } }); // Sets chart ticks to modified ticks diff --git a/guide/results-viewer-react/src/components/TestResults/index.tsx b/guide/results-viewer-react/src/components/TestResults/index.tsx index cf4c21e8..0567710b 100644 --- a/guide/results-viewer-react/src/components/TestResults/index.tsx +++ b/guide/results-viewer-react/src/components/TestResults/index.tsx @@ -301,13 +301,13 @@ export const TestResults = ({ resultsText }: TestResultProps) => { const updateState = (newState: Partial) => setState((oldState: TestResultState) => ({ ...oldState, ...newState })); - const updateResultsData = async (resultsText: string): Promise => { + const updateResultsData = async (resultsPath: string): Promise => { updateState({ defaultMessage: "Results Loading..." }); try { // if there are multiple jsons (new format), split them up and parse them separately - const results = resultsText.replace(/}{/g, "}\n{") + const results = resultsPath.replace(/}{/g, "}\n{") .split("\n") .map((s) => JSON.parse(s)); const model = await import("./model"); diff --git a/guide/results-viewer-react/src/components/YamlEndpoints/index.tsx b/guide/results-viewer-react/src/components/YamlEndpoints/index.tsx index fe076145..5eb3e20d 100644 --- a/guide/results-viewer-react/src/components/YamlEndpoints/index.tsx +++ b/guide/results-viewer-react/src/components/YamlEndpoints/index.tsx @@ -1,5 +1,14 @@ import { CSSTransition, TransitionGroup } from "react-transition-group"; import { Checkbox, InputsDiv, Label, NonFlexSpan } from "../YamlStyles"; +import { + HIT_RATE_REGEX, + UrlProps, + Urls, + getAuthorizationHeader, + getDefaultHeaders, + getHitRateStyle, + getHitRateTitle +} from "../YamlUrls"; import { HarEndpoint, HarHeader, @@ -9,15 +18,6 @@ import { } from "../../util/yamlwriter"; import { LogLevel, log } from "../../util/log"; import React, { useEffect, useState } from "react"; -import { - UrlProps, - Urls, - getAuthorizationHeader, - getDefaultHeaders, - getHitRateStyle, - getHitRateTitle, - hitReg -} from "../YamlUrls"; import { QuestionBubble } from "../YamlQuestionBubble"; import styled from "styled-components"; import { uniqueId } from "../../util/clientutil"; @@ -73,15 +73,15 @@ export interface EndpointsState { } export const newUrl = (deaultHeaders: boolean, authenticated: boolean, point?: HarEndpoint): PewPewAPI => { - const headers: PewPewHeader[] = point?.headers.map(({ name, value }: HarHeader): PewPewHeader => ({ id: uniqueId(), name, value })) || []; - const defaultHeaders: PewPewHeader[] = deaultHeaders + const pointHeaders: PewPewHeader[] = point?.headers.map(({ name, value }: HarHeader): PewPewHeader => ({ id: uniqueId(), name, value })) || []; + const pewpewHeaders: PewPewHeader[] = deaultHeaders ? getDefaultHeaders(authenticated) : (authenticated ? [getAuthorizationHeader()] : []); return { id: uniqueId(), url: point?.url || "", hitRate: "1hpm", - headers: [...defaultHeaders, ...headers], + headers: [...pewpewHeaders, ...pointHeaders], method: point?.method || "GET", authorization: null }; @@ -139,7 +139,7 @@ export const Endpoints = ({ urls, ...props }: EndpointsProps) => { } }; - const invalidHitRate = !hitReg.test(state.hitRate); + const invalidHitRate = !HIT_RATE_REGEX.test(state.hitRate); const hitRateStyle: React.CSSProperties = getHitRateStyle(invalidHitRate); const hitRateTitle: string | undefined = state.hitRate === "" ? "Please enter a Hit Rate" : (getHitRateTitle(invalidHitRate) || "Update all hit rates"); return ( diff --git a/guide/results-viewer-react/src/components/YamlLoadPatterns/index.tsx b/guide/results-viewer-react/src/components/YamlLoadPatterns/index.tsx index 4f7cc0ae..75f139d2 100644 --- a/guide/results-viewer-react/src/components/YamlLoadPatterns/index.tsx +++ b/guide/results-viewer-react/src/components/YamlLoadPatterns/index.tsx @@ -20,15 +20,15 @@ interface LoadPatternState { defaultPatterns: boolean; } -export const overReg = new RegExp("^((((\\d+)\\s?(h|hr|hrs|hour|hours))\\s?)?(((\\d+)\\s?(m|min|mins|minute|minutes))\\s?)?(((\\d+)\\s?(s|sec|secs|second|seconds)))?)$"); -export const numReg = new RegExp("^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$"); -export const patterns = "patterns"; -export const rampPattern = "rampPattern"; -export const loadPattern = "loadPattern"; +export const OVER_REGEX = new RegExp("^((((\\d+)\\s?(h|hr|hrs|hour|hours))\\s?)?(((\\d+)\\s?(m|min|mins|minute|minutes))\\s?)?(((\\d+)\\s?(s|sec|secs|second|seconds)))?)$"); +export const NUMBER_REGEX = new RegExp("^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$"); +export const PATTERNS = "patterns"; +export const RAMP_PATTERN = "rampPattern"; +export const LOAD_PATTERN = "loadPattern"; export const newLoadPattern = (patternId: string = uniqueId()): PewPewLoadPattern => ({ id: patternId, from: "", to: "", over: "" }); -export const newRampLoadPattern = (): PewPewLoadPattern => ({ id: rampPattern, from: "10", to: "100", over: "15m" }); -export const newLoadLoadPattern = (): PewPewLoadPattern => ({ id: loadPattern, from: "100", to: "100", over: "15m" }); +export const newRampLoadPattern = (): PewPewLoadPattern => ({ id: RAMP_PATTERN, from: "10", to: "100", over: "15m" }); +export const newLoadLoadPattern = (): PewPewLoadPattern => ({ id: LOAD_PATTERN, from: "100", to: "100", over: "15m" }); const errorColor: React.CSSProperties = { color: "red" }; @@ -52,19 +52,19 @@ export function LoadPatterns ({ defaultYaml, patterns, ...props }: LoadPatternPr }; const switchDefault = (newChecked: boolean) => { - if (newChecked && !loadPatternsMap.has(rampPattern)) { + if (newChecked && !loadPatternsMap.has(RAMP_PATTERN)) { // Add it (will update the map when it comes back in via props) props.addPattern(newRampLoadPattern()); - } else if (!newChecked && loadPatternsMap.has(rampPattern)) { + } else if (!newChecked && loadPatternsMap.has(RAMP_PATTERN)) { // Remove it (will update the map when it comes back in via props) - props.deletePattern(rampPattern); + props.deletePattern(RAMP_PATTERN); } - if (newChecked && !loadPatternsMap.has(loadPattern)) { + if (newChecked && !loadPatternsMap.has(LOAD_PATTERN)) { // Add it (will update the map when it comes back in via props) props.addPattern(newLoadLoadPattern()); - } else if (!newChecked && loadPatternsMap.has(loadPattern)) { + } else if (!newChecked && loadPatternsMap.has(LOAD_PATTERN)) { // Remove it (will update the map when it comes back in via props) - props.deletePattern(loadPattern); + props.deletePattern(LOAD_PATTERN); } updateState({ defaultPatterns: newChecked }); }; @@ -75,7 +75,7 @@ export function LoadPatterns ({ defaultYaml, patterns, ...props }: LoadPatternPr }; const deletePattern = (patternId: string) => { - if (patternId === rampPattern || patternId === loadPattern) { + if (patternId === RAMP_PATTERN || patternId === LOAD_PATTERN) { updateState({ defaultPatterns: false }); } props.deletePattern(patternId); @@ -104,9 +104,9 @@ export function LoadPatterns ({ defaultYaml, patterns, ...props }: LoadPatternPr {Array.from(loadPatternsMap.values()).map((pewpewPattern: PewPewLoadPattern) => { // TODO: Do we want to check if they're greater than 0? - const validFrom: boolean = !pewpewPattern.from || numReg.test(pewpewPattern.from); - const validTo: boolean = numReg.test(pewpewPattern.to); - const validOver: boolean = overReg.test(pewpewPattern.over); + const validFrom: boolean = !pewpewPattern.from || NUMBER_REGEX.test(pewpewPattern.from); + const validTo: boolean = NUMBER_REGEX.test(pewpewPattern.to); + const validOver: boolean = OVER_REGEX.test(pewpewPattern.over); return
diff --git a/guide/results-viewer-react/src/components/YamlLoadPatterns/story.tsx b/guide/results-viewer-react/src/components/YamlLoadPatterns/story.tsx index 741c25c4..7f72b3ee 100644 --- a/guide/results-viewer-react/src/components/YamlLoadPatterns/story.tsx +++ b/guide/results-viewer-react/src/components/YamlLoadPatterns/story.tsx @@ -1,5 +1,5 @@ import { DisplayDivBody, DisplayDivMain } from "../YamlWriterForm"; -import LoadPatterns, { LoadPatternProps, loadPattern, rampPattern } from "."; +import LoadPatterns, { LOAD_PATTERN, LoadPatternProps, RAMP_PATTERN } from "."; import { GlobalStyle } from "../Global"; import { PewPewLoadPattern } from "../../util/yamlwriter"; import React from "react"; @@ -28,8 +28,8 @@ const props: LoadPatternProps = { const propsDefault: LoadPatternProps = { ...props, defaultYaml: true, patterns: [ - { id: rampPattern, from: "10", to: "100", over: "15m" }, - { id: loadPattern, from: "100", to: "100", over: "15m" } + { id: RAMP_PATTERN, from: "10", to: "100", over: "15m" }, + { id: LOAD_PATTERN, from: "100", to: "100", over: "15m" } ] }; diff --git a/guide/results-viewer-react/src/components/YamlLoggers/LoggerModal.tsx b/guide/results-viewer-react/src/components/YamlLoggers/LoggerModal.tsx index fd4b6738..a03249a2 100644 --- a/guide/results-viewer-react/src/components/YamlLoggers/LoggerModal.tsx +++ b/guide/results-viewer-react/src/components/YamlLoggers/LoggerModal.tsx @@ -35,10 +35,10 @@ interface LoggerModalProps { data: PewPewLogger; } -const loggerType = "loggerSelect"; -const request = "request"; -const response = "response"; -const timing = "timing"; +const LOGGER_SELECT = "loggerSelect"; +const REQUEST = "request"; +const RESPONSE = "response"; +const TIMING = "timing"; type HeaderLoggerType = "request" | "response" | "timing"; type RequestLoggerName = "request" | "method" | "url" | "requestHeaders" | "requestHeadersAll" | "requestBody"; @@ -71,14 +71,14 @@ const timingLoggers: TimingLogger = { "rtt": { display: "stats.rtt", name: "rtt", value: "stats.rtt" } }; -const getLoggerSelectEntryByName = (name: LoggerName): LoggerSelectEntry => { +const getLoggerSelectEntryByName = (loggerName: LoggerName): LoggerSelectEntry => { let displayLogger: LoggerSelectEntryDisplay | undefined; - if (name in requestLoggers) { - displayLogger = requestLoggers[name as RequestLoggerName]; - } else if (name in responseLoggers) { - displayLogger = responseLoggers[name as ResponseLoggerName]; - } else if (name in timingLoggers) { - displayLogger = timingLoggers[name as TimingLoggerName]; + if (loggerName in requestLoggers) { + displayLogger = requestLoggers[loggerName as RequestLoggerName]; + } else if (loggerName in responseLoggers) { + displayLogger = responseLoggers[loggerName as ResponseLoggerName]; + } else if (loggerName in timingLoggers) { + displayLogger = timingLoggers[loggerName as TimingLoggerName]; } if (displayLogger) { const { name, value } = displayLogger; @@ -86,8 +86,8 @@ const getLoggerSelectEntryByName = (name: LoggerName): LoggerSelectEntry => { log("getLoggerSelectEntryByName", LogLevel.DEBUG, { name, loggerEntry }); return loggerEntry; } else { - log("Unknown LoggerSelectEntry name " + name, LogLevel.ERROR); - throw new Error ("Unknown LoggerSelectEntry name " + name); + log("Unknown LoggerSelectEntry name " + loggerName, LogLevel.ERROR); + throw new Error ("Unknown LoggerSelectEntry name " + loggerName); } }; @@ -108,19 +108,19 @@ export const loggerOptions: { }[] = [ // Here is all of the Request information (loggerOptions[0]) { - type: request, + type: REQUEST, stateVariable: "defaultRequest", returnTypeArray: Object.values(requestLoggers) }, // Here is all of the Response information (loggerOptions[1]) { - type: response, + type: RESPONSE, stateVariable: "defaultResponse", returnTypeArray: Object.values(responseLoggers) }, // Here is all of the Timing information (loggerOptions[2]) { - type: timing, + type: TIMING, stateVariable: "defaultTiming", returnTypeArray: Object.values(timingLoggers) } @@ -318,9 +318,9 @@ export const LoggerModal = forwardRef(({ onClose, changeLogger, data }: LoggerMo const listClick = (headerType: HeaderLoggerType, name: LoggerName, value: string, newChecked: boolean, dontDelete?: boolean) => { let stateType: RequestState | ResponseState | TimingState | undefined; let stateValue: boolean | undefined; - if (headerType === request) { stateType = state.request; stateValue = state.request[name as RequestLoggerName]; } - if (headerType === response) { stateType = state.response; stateValue = state.response[name as ResponseLoggerName]; } - if (headerType === timing) { stateType = state.timing; stateValue = state.timing[name as TimingLoggerName]; } + if (headerType === REQUEST) { stateType = state.request; stateValue = state.request[name as RequestLoggerName]; } + if (headerType === RESPONSE) { stateType = state.response; stateValue = state.response[name as ResponseLoggerName]; } + if (headerType === TIMING) { stateType = state.timing; stateValue = state.timing[name as TimingLoggerName]; } if (stateValue === undefined || stateValue === newChecked) { // Nothing needed log("listClick no change", LogLevel.DEBUG, { headerType, name, value, newChecked, stateValue, current: stateType }); @@ -343,11 +343,11 @@ export const LoggerModal = forwardRef(({ onClose, changeLogger, data }: LoggerMo closeText="Close" onClose={onClose} > - {loggerOptions.map((header, index: number) => { - const stateVariable = header.type === request ? state.defaultRequest : header.type === response ? state.defaultResponse : state.defaultTiming; - const itemType = header.type === request ? state.request : header.type === response ? state.response : state.timing; + {loggerOptions.map((header, optionsIndex: number) => { + const stateVariable = header.type === REQUEST ? state.defaultRequest : header.type === RESPONSE ? state.defaultResponse : state.defaultTiming; + const itemType = header.type === REQUEST ? state.request : header.type === RESPONSE ? state.response : state.timing; return ( - + {header.type} - {header.returnTypeArray.map((item, index: number) => { + {header.returnTypeArray.map((item, returnTypeIndex: number) => { return ( - + {item.display}           - diff --git a/guide/results-viewer-react/src/components/YamlLoggers/index.tsx b/guide/results-viewer-react/src/components/YamlLoggers/index.tsx index bf5b2273..00890175 100644 --- a/guide/results-viewer-react/src/components/YamlLoggers/index.tsx +++ b/guide/results-viewer-react/src/components/YamlLoggers/index.tsx @@ -19,11 +19,11 @@ const EditListButton = styled.button` width: 100px; `; -export const loggers = "loggers"; -const debugLogger = "debugLogger"; -const errorLogger = "errorLogger"; -const killLogger = "killLogger"; -const defaultLoggers = "defaultLoggers"; +export const LOGGERS = "loggers"; +const DEBUG_LOGGER = "debugLogger"; +const ERROR_LOGGER = "errorLogger"; +const KILL_LOGGER = "killLogger"; +const DEFAULT_LOGGERS = "defaultLoggers"; export type DefaultLoggerTypeAll = DefaultVariablesType | "defaultLoggers"; export type PewPewLoggerBooleanType = "kill" | "pretty"; @@ -55,7 +55,7 @@ export const newLogger = (loggerId: string = uniqueId()): PewPewLogger => ({ }); export const debugLoggerVar = (): PewPewLogger => ({ - id: debugLogger, + id: DEBUG_LOGGER, name: "httpAll", where: "", to: "stdout", @@ -65,7 +65,7 @@ export const debugLoggerVar = (): PewPewLogger => ({ kill: false }); export const errorLoggerVar = (): PewPewLogger => ({ - id: errorLogger, + id: ERROR_LOGGER, name: "httpErrors", where: "response.status >= 400", to: "stderr", @@ -75,7 +75,7 @@ export const errorLoggerVar = (): PewPewLogger => ({ kill: false }); export const killLoggerVar = (): PewPewLogger => ({ - id: killLogger, + id: KILL_LOGGER, name: "testEnd", where: "response.status >= 500", to: "stderr", @@ -87,11 +87,11 @@ export const killLoggerVar = (): PewPewLogger => ({ function getDefaultLogger (loggerName: DefaultVariablesType): PewPewLogger { switch (loggerName) { - case debugLogger: + case DEBUG_LOGGER: return debugLoggerVar(); - case errorLogger: + case ERROR_LOGGER: return errorLoggerVar(); - case killLogger: + case KILL_LOGGER: return killLoggerVar(); default: throw new Error("getDefaultLogger Invalid loggerName: " + loggerName); @@ -150,7 +150,7 @@ export function Loggers ({ defaultYaml, ...props }: LoggerProps) { const id = target.id as DefaultLoggerTypeAll; const checked = target.checked; log("handleClickDefault", LogLevel.DEBUG, { id, checked }); - if (id === defaultLoggers) { + if (id === DEFAULT_LOGGERS) { switchAllDefaults(checked); } else { switchDefault(id, checked); @@ -230,21 +230,21 @@ export function Loggers ({ defaultYaml, ...props }: LoggerProps) {       - + - +
- + - + - + - + - + - +
{Array.from(loggerMap.values()).map((logger: PewPewLogger) => ( diff --git a/guide/results-viewer-react/src/components/YamlProviders/index.tsx b/guide/results-viewer-react/src/components/YamlProviders/index.tsx index 180c2fe7..bd3f9532 100644 --- a/guide/results-viewer-react/src/components/YamlProviders/index.tsx +++ b/guide/results-viewer-react/src/components/YamlProviders/index.tsx @@ -22,11 +22,11 @@ export interface ProviderMainProps { providers: PewPewProvider[]; } -export const providers = "providers"; -export const providerFile = "providerFile"; -export const providerResponse = "providerResponse"; -export const providerRange = "providerRange"; -export const providerList = "providerList"; +export const PROVIDERS = "providers"; +export const PROVIDER_FILE = "providerFile"; +export const PROVIDER_RESPONSE = "providerResponse"; +export const PROVIDER_RANGE = "providerRange"; +export const PROVIDER_LIST = "providerList"; export const newProviderFile = (providerId: string = uniqueId()): PewPewProvider => ({ id: providerId, type: "file", name: "", file: "", repeat: true, random: false }); export const newProviderResponse = (providerId: string = uniqueId()): PewPewProvider => ({ id: providerId, type: "response", name: "", response: {} }); @@ -43,11 +43,11 @@ export const newProvider = (providerType: ProviderType) => { case ProviderType.list: return newProviderList(); default: - throw new Error("Unknown ProviderType: " + providerFile); + throw new Error("Unknown ProviderType: " + PROVIDER_FILE); } }; -export default function Providers ({ providers, ...props }: ProviderMainProps) { +export function Providers ({ providers, ...props }: ProviderMainProps) { const providersMap = new Map(providers.map((pewpewPattern) => ([pewpewPattern.id, pewpewPattern]))); const [display, setDisplay] = useState(false); @@ -125,16 +125,16 @@ export default function Providers ({ providers, ...props }: ProviderMainProps) {
{display && - - - -    @@ -155,3 +155,5 @@ export default function Providers ({ providers, ...props }: ProviderMainProps) { ); } + +export default Providers; diff --git a/guide/results-viewer-react/src/components/YamlUrls/index.tsx b/guide/results-viewer-react/src/components/YamlUrls/index.tsx index 3ec66290..d11064d6 100644 --- a/guide/results-viewer-react/src/components/YamlUrls/index.tsx +++ b/guide/results-viewer-react/src/components/YamlUrls/index.tsx @@ -43,37 +43,36 @@ export interface UrlState { passed: boolean; } -export const hitReg: RegExp = new RegExp("^(\\d+)hp(h|m|s)$"); -export const urls = "urls"; -// export const authenticated = "authenticated"; -const emptyHeader = "emptyHeader"; -const defaultHeaders = "defaultHeaders"; -export const authenticated = "authenticated"; -const acceptLanguage = "acceptLanguage"; -const contentType = "contentType"; +export const HIT_RATE_REGEX: RegExp = new RegExp("^(\\d+)hp(h|m|s)$"); +export const URLS = "urls"; +const EMPTY_HEADER = "emptyHeader"; +const DEFAULT_HEADERS = "defaultHeaders"; +export const AUTHENTICATED = "authenticated"; +const ACCEPT_LANGUAGE = "acceptLanguage"; +const CONTENT_TYPE = "contentType"; type HeaderType = "defaultHeaders" | "authenticated" | "acceptLanguage" | "contentType"; type PewPewApiStringType = "url" | "method" | "hitRate"; type PewPewHeaderStringType = "name" | "value"; export const newHeader = () => ({ id: uniqueId(), name: "", value: "" }); -export const getAuthorizationHeader = (): PewPewHeader => ({ id: authenticated, name: "Authorization", value: "Bearer ${sessionId}" }); -const getAcceptLanguageHeader = (): PewPewHeader => ({ id: acceptLanguage, name: "Accept-Language", value: "en-us"}); -const getContentTypedHeader = (): PewPewHeader => ({ id: contentType, name: "Content-Type", value: "application/json"}); +export const getAuthorizationHeader = (): PewPewHeader => ({ id: AUTHENTICATED, name: "Authorization", value: "Bearer ${sessionId}" }); +const getAcceptLanguageHeader = (): PewPewHeader => ({ id: ACCEPT_LANGUAGE, name: "Accept-Language", value: "en-us"}); +const getContentTypedHeader = (): PewPewHeader => ({ id: CONTENT_TYPE, name: "Content-Type", value: "application/json"}); export const getDefaultHeaders = (authenticated?: boolean): PewPewHeader[] => [ ...(authenticated ? [getAuthorizationHeader()] : []), getAcceptLanguageHeader(), getContentTypedHeader() ]; -function getHeader (headerType: HeaderType | "emptyHeader" = emptyHeader): PewPewHeader { +function getHeader (headerType: HeaderType | "emptyHeader" = EMPTY_HEADER): PewPewHeader { switch (headerType) { - case authenticated: + case AUTHENTICATED: return getAuthorizationHeader(); - case acceptLanguage: + case ACCEPT_LANGUAGE: return getAcceptLanguageHeader(); - case contentType: + case CONTENT_TYPE: return getContentTypedHeader(); - case emptyHeader: + case EMPTY_HEADER: return newHeader(); default: throw new Error("getHeader Invalid headerType: " + headerType); @@ -110,31 +109,31 @@ export function Urls ({ data: { headers, ...data }, ...props }: UrlProps) { // Changes the state of authenticated button when default is checked or unchecked useEffect(() => { // Add/delete from headersMap/headers - if (props.authenticated && !headersMap.has(authenticated)) { + if (props.authenticated && !headersMap.has(AUTHENTICATED)) { // Add it (will update the map when it comes back in via props) - addHeader(authenticated); - } else if (!props.authenticated && headersMap.has(authenticated)) { + addHeader(AUTHENTICATED); + } else if (!props.authenticated && headersMap.has(AUTHENTICATED)) { // Remove it (will update the map when it comes back in via props) - removeHeader(authenticated); + removeHeader(AUTHENTICATED); } }, [props.authenticated]); useEffect(() => { // Add/delete from headersMap/headers - const hasAcceptLanguage = headersMap.has(acceptLanguage); - const hasContentType = headersMap.has(contentType); + const hasAcceptLanguage = headersMap.has(ACCEPT_LANGUAGE); + const hasContentType = headersMap.has(CONTENT_TYPE); // If we need to change both, we need to group them into a single "defaultHeaders" transaction if (props.defaultHeaders && (!hasAcceptLanguage || !hasContentType)) { // Add it (will update the map when it comes back in via props) const headerToAdd: HeaderType = !hasAcceptLanguage && !hasContentType - ? defaultHeaders - : !hasAcceptLanguage ? acceptLanguage : contentType; + ? DEFAULT_HEADERS + : !hasAcceptLanguage ? ACCEPT_LANGUAGE : CONTENT_TYPE; addHeader(headerToAdd); } else if (!props.defaultHeaders && (hasAcceptLanguage || hasAcceptLanguage)) { // Remove it (will update the map when it comes back in via props) const headerToRemove: HeaderType = hasAcceptLanguage && hasContentType - ? defaultHeaders - : hasAcceptLanguage ? acceptLanguage : contentType; + ? DEFAULT_HEADERS + : hasAcceptLanguage ? ACCEPT_LANGUAGE : CONTENT_TYPE; removeHeader(headerToRemove); } }, [props.defaultHeaders]); @@ -204,7 +203,7 @@ export function Urls ({ data: { headers, ...data }, ...props }: UrlProps) { const addHeader = (headerType?: HeaderType) => { log("addHeader " + headerType, LogLevel.DEBUG); // Adding header when Authenticated option is checked - if (headerType === defaultHeaders) { + if (headerType === DEFAULT_HEADERS) { // add all props.addHeaders(data.id, getDefaultHeaders()); } else { @@ -218,10 +217,10 @@ export function Urls ({ data: { headers, ...data }, ...props }: UrlProps) { const removeHeader = (headerId: string) => { // Removing header when X button is pressed in urls modal log("removeHeader " + headerId, LogLevel.DEBUG); - if (headerId === defaultHeaders) { + if (headerId === DEFAULT_HEADERS) { // Remove both! - props.deleteHeader(data.id, acceptLanguage); - props.deleteHeader(data.id, contentType); + props.deleteHeader(data.id, ACCEPT_LANGUAGE); + props.deleteHeader(data.id, CONTENT_TYPE); } else { props.deleteHeader(data.id, headerId); } @@ -245,7 +244,7 @@ export function Urls ({ data: { headers, ...data }, ...props }: UrlProps) { const invalidUrl: boolean = !isValidUrl(data.url); const urlStyle: React.CSSProperties = getUrlStyle(invalidUrl); const urlTitle: string | undefined = getUrlTitle(invalidUrl); - const invalidHitRate = !hitReg.test(data.hitRate); + const invalidHitRate = !HIT_RATE_REGEX.test(data.hitRate); return (
diff --git a/guide/results-viewer-react/src/components/YamlVars/index.tsx b/guide/results-viewer-react/src/components/YamlVars/index.tsx index ddcc7a7f..e90eefae 100644 --- a/guide/results-viewer-react/src/components/YamlVars/index.tsx +++ b/guide/results-viewer-react/src/components/YamlVars/index.tsx @@ -51,32 +51,32 @@ interface VarsState extends DefaultVariables { defaultVars: boolean; environment: string; } -export const vars = "vars"; -const sessionId = "sessionId"; -const rampTime = "rampTime"; -const loadTime = "loadTime"; -const peakLoad = "peakLoad"; -const devKey = "devKey"; -const defaultVars = "defaultVars"; +export const VARS = "vars"; +const SESSION_ID = "sessionId"; +const RAMP_TIME = "rampTime"; +const LOAD_TIME = "loadTime"; +const PEAK_LOAD = "peakLoad"; +const DEV_KEY = "devKey"; +const DEFAULT_VARS = "defaultVars"; -export const newVar = (varId: string = uniqueId()): PewPewVars => ({ id: varId, name: "", value: "" }); -export const devKeyVar = (environment: string): PewPewVars => ({ id: devKey, name: devKey, value: environment }); -export const rampTimeVar = (): PewPewVars => ({ id: rampTime, name: rampTime, value: RAMP_TIME_DEFAULT }); -export const loadTimeVar = (): PewPewVars => ({ id: loadTime, name: loadTime, value: LOAD_TIME_DEFAULT }); -export const peakLoadVar = (): PewPewVars => ({ id: peakLoad, name: peakLoad, value: PEAK_LOAD_DEFAULT }); -export const sessionIdVar = (): PewPewVars => ({ id: sessionId, name: sessionId, value: SESSION_ID_DEFAULT }); +export const emptyVar = (varId: string = uniqueId()): PewPewVars => ({ id: varId, name: "", value: "" }); +export const devKeyVar = (environment: string): PewPewVars => ({ id: DEV_KEY, name: DEV_KEY, value: environment }); +export const rampTimeVar = (): PewPewVars => ({ id: RAMP_TIME, name: RAMP_TIME, value: RAMP_TIME_DEFAULT }); +export const loadTimeVar = (): PewPewVars => ({ id: LOAD_TIME, name: LOAD_TIME, value: LOAD_TIME_DEFAULT }); +export const peakLoadVar = (): PewPewVars => ({ id: PEAK_LOAD, name: PEAK_LOAD, value: PEAK_LOAD_DEFAULT }); +export const sessionIdVar = (): PewPewVars => ({ id: SESSION_ID, name: SESSION_ID, value: SESSION_ID_DEFAULT }); function getDefaultVar (varName: DefaultVariablesType, environment: string): PewPewVars { switch (varName) { - case sessionId: + case SESSION_ID: return sessionIdVar(); - case rampTime: + case RAMP_TIME: return rampTimeVar(); - case loadTime: + case LOAD_TIME: return loadTimeVar(); - case peakLoad: + case PEAK_LOAD: return peakLoadVar(); - case devKey: + case DEV_KEY: return devKeyVar(environment); default: throw new Error("getDefaultVar Invalid varName: " + varName); @@ -125,15 +125,15 @@ export function Vars ({ authenticated, defaultYaml, ...props }: VarsProps) { }; const switchSessionId = (newChecked: boolean) => { - switchDefault(sessionId, newChecked); + switchDefault(SESSION_ID, newChecked); }; // Switching the default should remove the vars or add all of them to the vars // Can be called via a click, or via a prop from the defaultYaml checkbox from the parent const switchAllDefaults = (newChecked: boolean) => { - switchDefault(loadTime, newChecked); - switchDefault(rampTime, newChecked); - switchDefault(peakLoad, newChecked); + switchDefault(LOAD_TIME, newChecked); + switchDefault(RAMP_TIME, newChecked); + switchDefault(PEAK_LOAD, newChecked); updateState({ defaultVars: newChecked }); }; @@ -142,8 +142,8 @@ export function Vars ({ authenticated, defaultYaml, ...props }: VarsProps) { // Add/delete from varsMap/vars if (newChecked && !varsMap.has(varsType)) { // Add it (will update the map when it comes back in via props) - const newVar = getDefaultVar(varsType, state.environment); - props.addVar(newVar); + const defaultVar = getDefaultVar(varsType, state.environment); + props.addVar(defaultVar); } else if (!newChecked && varsMap.has(varsType)) { // Remove it (will update the map when it comes back in via props) props.deleteVar(varsType); @@ -171,10 +171,10 @@ export function Vars ({ authenticated, defaultYaml, ...props }: VarsProps) { const changeEnvironment = (event: React.ChangeEvent) => { updateState({ environment: event.target.value }); - const devKeyVar = varsMap.get(devKey); - if (devKeyVar) { - devKeyVar.value = event.target.value; - props.changeVar(devKeyVar); + const devKey = varsMap.get(DEV_KEY); + if (devKey) { + devKey.value = event.target.value; + props.changeVar(devKey); } else { log("Environment changed without devKey variable existing", LogLevel.WARN); } @@ -182,7 +182,7 @@ export function Vars ({ authenticated, defaultYaml, ...props }: VarsProps) { return ( - - + - handleClick(defaults, event.target.checked)} checked={state.default} /> + ) => handleClick(DEFAULT, event.target.checked)} checked={state.default} /> - + - handleClick(authenticated, event.target.checked)} checked={state.authenticated} /> + ) => handleClick(AUTHENTICATED, event.target.checked)} checked={state.authenticated} /> clearInput(urls)} - deleteUrl={(urlId: string) => removeInput(urlId, urls)} + clearAllUrls={() => clearInput(URLS)} + deleteUrl={(urlId: string) => removeInput(urlId, URLS)} changeUrl={changeUrl} addHeaders={addHeaders} deleteHeader={deleteHeader} @@ -425,8 +439,8 @@ export const YamlWriterForm = (props: YamlWriterFormProps) => { /> clearInput(vars)} - deleteVar={(varId: string) => removeInput(varId, vars)} + clearAllVars={() => clearInput(VARS)} + deleteVar={(varId: string) => removeInput(varId, VARS)} changeVar={changeVars} defaultYaml={state.default} authenticated={state.authenticated} @@ -434,23 +448,23 @@ export const YamlWriterForm = (props: YamlWriterFormProps) => { /> clearInput(patterns)} - deletePattern={(patternId: string) => removeInput(patternId, patterns)} + clearAllPatterns={() => clearInput(PATTERNS)} + deletePattern={(patternId: string) => removeInput(patternId, PATTERNS)} changePattern={changePattern} defaultYaml={state.default} patterns={state.patterns} /> clearInput(providers)} - deleteProvider={(patternId: string) => removeInput(patternId, providers)} + clearAllProviders={() => clearInput(PROVIDERS)} + deleteProvider={(patternId: string) => removeInput(patternId, PROVIDERS)} changeProvider={changeProvider} providers={state.providers} /> clearInput(loggers)} - deleteLogger={(loggerId: string) => removeInput(loggerId, loggers)} + clearAllLoggers={() => clearInput(LOGGERS)} + deleteLogger={(loggerId: string) => removeInput(loggerId, LOGGERS)} changeLogger={changeLogger} defaultYaml={state.default} loggers={state.loggers} diff --git a/guide/results-viewer-react/src/components/YamlWriterUpload/index.tsx b/guide/results-viewer-react/src/components/YamlWriterUpload/index.tsx index 37d730fc..bb3f4527 100644 --- a/guide/results-viewer-react/src/components/YamlWriterUpload/index.tsx +++ b/guide/results-viewer-react/src/components/YamlWriterUpload/index.tsx @@ -14,7 +14,6 @@ import DropFile from "../DropFile"; import { Span } from "../YamlStyles"; import styled from "styled-components"; import { uniqueId } from "../../util/clientutil"; -import update from "immutability-helper"; export const HeaderMain = styled.div` width: 100%; @@ -173,8 +172,8 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { output: {} }; - const fileName: string = ""; - const [name, setName] = useState(fileName); + const defaultFilename: string = ""; + const [filename, setFilename] = useState(defaultFilename); const [state, setState] = useState(defaultState); const fileModalRef = useRef(null); useEffectModal(fileModalRef); @@ -235,7 +234,7 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { // Sends endpoints to App.js to send to Content.js const finalizeEndpoints = () => { props.sendEndpoints( - (state.output[name]?.endpoints || []) + (state.output[filename]?.endpoints || []) // Convert a ParsedEndpoint to a HarEndpoint .map(({ url, ...parsedEndpoint }: ParsedEndpoint): HarEndpoint => ({ ...parsedEndpoint, url: url.href })) ); @@ -245,7 +244,7 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { // Used if file is removed from upload list const clearFile = () => { setState((prevState: YamlWriterUploadState): YamlWriterUploadState => ({ ...prevState, file: undefined })); - setName(""); + setFilename(""); }; // Checks both current state, and parent state to see if file has already been uploaded @@ -290,7 +289,7 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { if (urls[hostUrl] !== undefined) { urls[hostUrl]!.index.push({ iter: i, id }); } else { - urls[hostUrl] = { index: [{ iter: i, id }], selected: "no" }; + urls[hostUrl] = { index: [{ iter: i, id }], selected: "yes"}; } endpoints.push({ selected: "yes", url, type: mimeType, id, method: entry.request.method, headers: [...entry.request.headers] }); } @@ -311,7 +310,7 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { else { typesTemp[key]!.selected = "partial"; } } const output: Record = { - [name]: { + [filename]: { types, urls, endpoints @@ -322,11 +321,12 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { // This is in the Cutomize HAR File pop up window // Any time an item is clicked in the choose endpoints, update all objects for if they are selected const handleChange = (type: string, ident: string | ParsedEndpoint) => { - const outputName: Output | undefined = state.output[name]; + const outputName: Output | undefined = state.output[filename]; if (!outputName) { - log("No output found for " + name, LogLevel.WARN, state.output); + log("No output found for " + filename, LogLevel.WARN, state.output); return; } + // TODO: Should all of this be inside the setState() function? const indices = [...outputName.endpoints]; const urlTypeIdent = ident as string; switch (type) { @@ -341,9 +341,9 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { } // If the item clicked was a type header, make all endpoints with references in given type checked or unchecked case "type": { - outputName.types[urlTypeIdent]?.index.forEach((type: IndexType) => { + outputName.types[urlTypeIdent]?.index.forEach((indexType: IndexType) => { indices.forEach(item => { - if (type.id === item.id) { item.selected = outputName.types[urlTypeIdent]?.selected === "no" ? "yes" : "no"; } + if (indexType.id === item.id) { item.selected = outputName.types[urlTypeIdent]?.selected === "no" ? "yes" : "no"; } }); }); break; @@ -380,27 +380,28 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { for (const key of typeKeys) { let typeCheck = 0; - const type = outputName.types[key]; + const outputType = outputName.types[key]; const typeTemp = typesTemp[key]; - if (!type || !typeTemp) { continue; } - for (const typeIndex of type.index) { + if (!outputType || !typeTemp) { continue; } + for (const typeIndex of outputType.index) { if (indices[typeIndex.iter].selected === "yes") { typeCheck++; } } - if (typeCheck === type.index.length) { typeTemp.selected = "yes"; } + if (typeCheck === outputType.index.length) { typeTemp.selected = "yes"; } else if (typeCheck === 0) { typeTemp.selected = "no"; } else { typeTemp.selected = "partial"; } } - const newState: YamlWriterUploadState = update(state, { - output: { - [name]: { - types: { $set: typesTemp }, - urls: { $set: urlsTemp }, - endpoints: { $set: indices } - } - } + const newOutput: Output = { + types: typesTemp, + urls: urlsTemp, + endpoints: indices + }; + setState(({ output, ...prevState }: YamlWriterUploadState) => { + return { + ...prevState, + output: { ...output, [filename]: newOutput } + }; }); - setState(newState); }; return ( @@ -456,8 +457,8 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => {

Urls

    - {state.output[name]?.urls && Object.keys(state.output[name]!.urls).map((key, index) => { - const url: OutputRecord = state.output[name]!.urls[key]!; + {state.output[filename]?.urls && Object.keys(state.output[filename]!.urls).map((key, index) => { + const url: OutputRecord = state.output[filename]!.urls[key]!; return ( @@ -482,8 +483,8 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { - {state.output[name] && url.index.map((inx: IndexType, i: number) => { - const point = state.output[name]!.endpoints.find((obj: ParsedEndpoint) => obj.id === inx.id); + {state.output[filename] && url.index.map((inx: IndexType, i: number) => { + const point = state.output[filename]!.endpoints.find((obj: ParsedEndpoint) => obj.id === inx.id); return ( point &&

{

Return Types

- {state.output[name]?.types && Object.keys(state.output[name]!.types).map((key, index) => { - const type = state.output[name]!.types[key]; + {state.output[filename]?.types && Object.keys(state.output[filename]!.types).map((key, index) => { + const type = state.output[filename]!.types[key]; return ( type && @@ -529,7 +530,7 @@ export const YamlWriterUpload = (props: YamlWriterUploadProps) => { {type.index.map((inx: IndexType, i: number) => { - const point = state.output[name]?.endpoints.find((obj: ParsedEndpoint) => obj.id === inx.id); + const point = state.output[filename]?.endpoints.find((obj: ParsedEndpoint) => obj.id === inx.id); return ( point &&