Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor ( website-builder ): Refactor website-builder to typescript #5

Open
wants to merge 1 commit into
base: the-one
Choose a base branch
from

Conversation

Hamza-Asif99
Copy link

The index.js file is now refactored to index.ts and a tsconfig.json has been added along with required type packages as dev dependencies

closes #1054

The Pull Request is ready

  • fixes #1054

Overview

index.js is now refactored to index.ts, tsconfig.json has been added for the typescript compiler

Website Builder

  • the change breaks no interface
  • default behaviour did not change
  • tests have been added (if required)
  • documentation has been adjusted (if required)
  • shared code has been extracted in a different file

The index.js file is now refactored to index.ts and a tsconfig.json has
been added along with required type packages as dev dependencies

closes #1054
Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for contributing!
Please make sure the actions pass. Once your pull request has been merged, you will automatically be added to the contributor's list on the website.
If you want to be shouted out on Linkedin, have a look for the shoutout issue of the specific version.

You can also find us on slack at idrinth-api-bench.

Copy link
Contributor

coderabbitai bot commented May 21, 2024

Walkthrough

The overall changes involve converting import statements to use require, adding explicit type annotations to variables and function signatures, updating return values, removing the type field from package.json, adding TypeScript dependencies, and configuring TypeScript compiler options.

Changes

Files Change Summary
index.ts Converted import statements to require, added type annotations to variables and functions, updated return values.
package.json Removed "type": "module", added TypeScript and type definitions for Express and Node as dev dependencies.
tsconfig.json Introduced compiler options for TypeScript including strict type-checking and module settings.

In code we trust, with TypeScript's might,
Our imports changed, from day to night.
The types are strong, the future bright,
CodeRabbit's drone, in endless flight.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

Note: Auto-reply has been disabled for this repository by the repository owner. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between 13180b5 and e9b8460.
Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
Files selected for processing (3)
  • index.ts (2 hunks)
  • package.json (2 hunks)
  • tsconfig.json (1 hunks)
Files skipped from review due to trivial changes (2)
  • package.json
  • tsconfig.json
Additional Context Used
Path-based Instructions (1)
index.ts (1)

Pattern **/*.ts: Review the code for conformity with the .eslintrc files in / and /*/.

Additional comments not posted (3)
index.ts (3)

1-4: CodeRabbit observes that the import syntax has been changed from ES modules to CommonJS. This is consistent with the removal of "type": "module" in package.json. Ensure that all dependent modules and build configurations are compatible with CommonJS to avoid runtime issues.


11-17: CodeRabbit notes the addition of explicit type annotations for boolean and number types. This enhances type safety and is in line with TypeScript best practices.


79-106: CodeRabbit notes the logic in buildProject function handles various build conditions. Ensure that the logic correctly reflects the intended behaviour, especially the conditions under which each build is triggered.

};

const initiateBuild = async (command, projectPath, destPath) => {
const initiateBuild = async (command: string, projectPath: string, destPath: string) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeRabbit suggests refactoring the initiateBuild function to reduce redundancy and potential errors in command execution paths.

-  await executeCmd(`cd ${projectPath}/ && git pull`);
-  await executeCmd(`cd ${projectPath}/ && npm ci`);
-  await executeCmd(`cd ${projectPath}/ && ${command}`);
-  await executeCmd(`cp -r ${projectPath}/dist/ ${destPath}/`);
+  const commands = ['git pull', 'npm ci', `${command}`, `cp -r dist/ ${destPath}/`];
+  for (const cmd of commands) {
+    await executeCmd(`cd ${projectPath}/ && ${cmd}`);
+  }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const initiateBuild = async (command: string, projectPath: string, destPath: string) => {
const initiateBuild = async (command: string, projectPath: string, destPath: string) => {
const commands = ['git pull', 'npm ci', `${command}`, `cp -r dist/ ${destPath}/`];
for (const cmd of commands) {
await executeCmd(`cd ${projectPath}/ && ${cmd}`);
}

Comment on lines +56 to +63
const getBranchStatus = async (req: any) => {
console.log("Webhook received successfully");

const branchName = req.body?.ref?.split("/").pop();
if (!branchName) {
return 400, "Branch name not found in the request.";
return {result: 400, respMessage: "Branch name not found in the request."};
}
return branchName === process.env.BRANCH_NAME ? await buildProject() : 202, "Build not required.";
return branchName === process.env.BRANCH_NAME ? await buildProject() : {result: 202, respMessage: "Build not required."};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeRabbit suggests improving the type safety of the req parameter in getBranchStatus. Currently, it is typed as any, which defeats the purpose of using TypeScript for type safety.

- const getBranchStatus = async (req: any) => {
+ const getBranchStatus = async (req: express.Request) => {

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const getBranchStatus = async (req: any) => {
console.log("Webhook received successfully");
const branchName = req.body?.ref?.split("/").pop();
if (!branchName) {
return 400, "Branch name not found in the request.";
return {result: 400, respMessage: "Branch name not found in the request."};
}
return branchName === process.env.BRANCH_NAME ? await buildProject() : 202, "Build not required.";
return branchName === process.env.BRANCH_NAME ? await buildProject() : {result: 202, respMessage: "Build not required."};
const getBranchStatus = async (req: express.Request) => {
console.log("Webhook received successfully");
const branchName = req.body?.ref?.split("/").pop();
if (!branchName) {
return {result: 400, respMessage: "Branch name not found in the request."};
}
return branchName === process.env.BRANCH_NAME ? await buildProject() : {result: 202, respMessage: "Build not required."};

Comment on lines +21 to +30
app.post("/webhook", async (req: express.Request, res: express.Response) => {
console.log("req receieved");
const signature = req.headers["x-hub-signature"];
const payload = JSON.stringify(req.body);

const hmac = crypto.createHmac("sha1", process.env.GITHUB_SECRET);
const hmac = crypto.createHmac("sha1", process.env.GITHUB_SECRET as string);
const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`;

if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) {
const { result, respMessage } = await getBranchStatus();
if (crypto.timingSafeEqual(Buffer.from(signature as string), Buffer.from(calculatedSignature))) {
const { result, respMessage } = await getBranchStatus(null);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeRabbit identifies a potential security risk. The signature from req.headers["x-hub-signature"] should be validated for existence before being used. This prevents potential runtime errors when the header is missing.

-  if (crypto.timingSafeEqual(Buffer.from(signature as string), Buffer.from(calculatedSignature))) {
+  if (signature && crypto.timingSafeEqual(Buffer.from(signature as string), Buffer.from(calculatedSignature))) {

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
app.post("/webhook", async (req: express.Request, res: express.Response) => {
console.log("req receieved");
const signature = req.headers["x-hub-signature"];
const payload = JSON.stringify(req.body);
const hmac = crypto.createHmac("sha1", process.env.GITHUB_SECRET);
const hmac = crypto.createHmac("sha1", process.env.GITHUB_SECRET as string);
const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`;
if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(calculatedSignature))) {
const { result, respMessage } = await getBranchStatus();
if (crypto.timingSafeEqual(Buffer.from(signature as string), Buffer.from(calculatedSignature))) {
const { result, respMessage } = await getBranchStatus(null);
app.post("/webhook", async (req: express.Request, res: express.Response) => {
console.log("req receieved");
const signature = req.headers["x-hub-signature"];
const payload = JSON.stringify(req.body);
const hmac = crypto.createHmac("sha1", process.env.GITHUB_SECRET as string);
const calculatedSignature = `sha1=${hmac.update(payload).digest("hex")}`;
if (signature && crypto.timingSafeEqual(Buffer.from(signature as string), Buffer.from(calculatedSignature))) {
const { result, respMessage } = await getBranchStatus(null);

Comment on lines +42 to +48
const executeCmd = async (cmd: string) => {
let stdout;
let stderr;
try {
const { stdout, stderr } = await exec(cmd);
const cmdResp = await exec(cmd);
stderr = cmdResp.stderr;
stdout = cmdResp.stdout
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeRabbit detects an issue with error handling. The error thrown in the catch block should include more contextual information to aid in debugging. Additionally, consider logging the command that failed.

-    throw new Error(stderr + "\n" + stdout);
+    throw new Error(`Command failed: ${cmd}\nError: ${stderr}\nOutput: ${stdout}`);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const executeCmd = async (cmd: string) => {
let stdout;
let stderr;
try {
const { stdout, stderr } = await exec(cmd);
const cmdResp = await exec(cmd);
stderr = cmdResp.stderr;
stdout = cmdResp.stdout
const executeCmd = async (cmd: string) => {
let stdout;
let stderr;
try {
const cmdResp = await exec(cmd);
stderr = cmdResp.stderr;
stdout = cmdResp.stdout;
} catch (error) {
throw new Error(`Command failed: ${cmd}\nError: ${stderr}\nOutput: ${stdout}`);
}
};

Comment on lines +67 to +72
const currentTime: number = Date.now();
let mindmapUpdateTimeInterval = parseInt(process.env.MINDMAP_UPDATE_TIME_INTERVAL as string)
let docWebsiteUpdateTimeInterval = parseInt(process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL as string)

isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindmapUpdateTimeInterval ? true : false;
isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > docWebsiteUpdateTimeInterval ? true : false;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

CodeRabbit observes the use of environment variables without documentation or validation. Ensure these variables are documented and validated to prevent runtime errors due to missing or incorrect configurations.

  • MINDMAP_UPDATE_TIME_INTERVAL
  • DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL
  • CONTRIBUTORS_UPDATE_TIME_INTERVAL
Analysis chain

CodeRabbit observes the use of environment variables for configuration. Ensure these variables are documented and validated to prevent runtime errors due to missing or incorrect configurations.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all required environment variables are documented.

# Test: Search for documentation of environment variables. Expect: Documentation entries for each variable used.
rg --type markdown 'MINDMAP_UPDATE_TIME_INTERVAL|DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL|CONTRIBUTORS_UPDATE_TIME_INTERVAL'

Length of output: 128



Script:

#!/bin/bash
# Description: Verify the usage and validation of environment variables in the codebase.

# Search for the usage of the environment variables in the codebase.
rg 'process\.env\.MINDMAP_UPDATE_TIME_INTERVAL|process\.env\.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL|process\.env\.CONTRIBUTORS_UPDATE_TIME_INTERVAL'

# Search for validation logic related to these environment variables.
rg 'if\s*\(.*process\.env\.MINDMAP_UPDATE_TIME_INTERVAL.*\)|if\s*\(.*process\.env\.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL.*\)|if\s*\(.*process\.env\.CONTRIBUTORS_UPDATE_TIME_INTERVAL.*\)'

Length of output: 681

@Hamza-Asif99 Hamza-Asif99 marked this pull request as ready for review May 23, 2024 09:42
Comment on lines +1 to +4
import express = require("express");
import {exec} from "child_process";
import crypto from "crypto";
import dotenv from "dotenv";
import crypto = require("crypto");
import dotenv = require("dotenv");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

proper imports please, no requires.

Comment on lines +46 to +48
const cmdResp = await exec(cmd);
stderr = cmdResp.stderr;
stdout = cmdResp.stdout
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please revert the structural change, the extra lines for splitting are unnecessary :)

return stderr + "\n" + stdout;
} catch (error) {
console.error(`exec error: ${error}`);
throw new Error(stderr + "\n" + stdout);
}
};

const getBranchStatus = async (req) => {
const getBranchStatus = async (req: any) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no use of any please. Create an interface for the github token please

let mindmapUpdateTimeInterval = parseInt(process.env.MINDMAP_UPDATE_TIME_INTERVAL as string)
let docWebsiteUpdateTimeInterval = parseInt(process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL as string)

isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindmapUpdateTimeInterval ? true : false;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the ? true : false, it doesn't serve a benefit

let docWebsiteUpdateTimeInterval = parseInt(process.env.DOCUMENTATION_WEBSITE_UPDATE_TIME_INTERVAL as string)

isMindmapUpdated = (currentTime - mindmapBuildTime) / 1000 / 60 > mindmapUpdateTimeInterval ? true : false;
isDocumentationWebsiteUpdated = (currentTime - documentationWebsiteBuildTime) / 1000 / 60 > docWebsiteUpdateTimeInterval ? true : false;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the ? true : false, it doesn't serve a benefit

@@ -3,7 +3,6 @@
"version": "1.0.0",
"description": "This repository is our website deploy and update tool to minimize github api queries.",
"main": "index.js",
"type" : "module",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please restore

@@ -0,0 +1,111 @@
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this does not follow our usual tsconfigs, please take the one from the framework as baseline.

return isMindmapUpdated || isDocumentationWebsiteUpdated;
};

const buildProject = async () => {
const currentTime = Date.now();
if (!isUpdateRequired()) {
if (contributorsBuildRequired || (currentTime - contributorsBuildTime) / 1000 / 60 > process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL) {
let contUpdateTimeInterval = parseInt(process.env.CONTRIBUTORS_UPDATE_TIME_INTERVAL as string)

Check notice

Code scanning / CodeQL

Semicolon insertion Note

Avoid automated semicolon insertion (94% of all statements in
the enclosing function
have an explicit semicolon).
try {
const { stdout, stderr } = await exec(cmd);
const cmdResp = await exec(cmd);

Check warning

Code scanning / CodeQL

Indirect uncontrolled command line Medium

This command depends on an unsanitized
environment variable
.
This command depends on an unsanitized
environment variable
.
This command depends on an unsanitized
environment variable
.
This command depends on an unsanitized
environment variable
.
This command depends on an unsanitized
environment variable
.
This command depends on an unsanitized
environment variable
.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants