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: migrate build script to typescript #3423

Open
wants to merge 257 commits into
base: master
Choose a base branch
from

Conversation

JeelRajodiya
Copy link
Contributor

@JeelRajodiya JeelRajodiya commented Nov 22, 2024

Description

  • The PR migrates the build scripts to Typescript

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/678b5e3ee3013d00087ed64b
😎 Deploy Preview https://deploy-preview-3423--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Related issue(s)
Related to #3187

Summary by CodeRabbit

  • New Features

    • Introduced a new configuration for internationalization settings, supporting multiple locales.
    • Added a flexible override in ESLint configuration for improved coding practices.
    • Enhanced document processing and navigation tree construction for better user experience.
    • Implemented a logging utility for improved error tracking and reporting.
    • Added new functionality for generating structured lists of posts and handling case studies.
  • Refactor & Chores

    • Transitioned codebase to ES module syntax for improved compatibility.
    • Updated testing framework to utilize TypeScript and centralized logging for consistency and clarity.
    • Modernized package management and build scripts for better performance and maintainability.
    • Improved error handling and type safety across various modules and functions.
    • Reorganized and updated import paths to reflect TypeScript file extensions.

Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

Walkthrough

This pull request introduces extensive refactoring, migrating many scripts and configurations from JavaScript to TypeScript while transitioning to ES module syntax. Key changes include updates to ESLint rules and internationalization configuration, modifications in package.json scripts and dependencies, and improvements in error handling and logging across build, utility, and test files. New type definitions and declaration files are added, and numerous test imports and mocks are updated to align with TypeScript. Overall, the PR enhances type safety and standardizes module formats throughout the project.

Changes

File(s) Change Summary
.eslintrc Added an override for scripts/**/* to disable import/no-extraneous-dependencies and disabled max-len rule for components/logos/*.
next-i18next.config.cjs, next-i18next.config.js, pages/_document.ts Introduced a new internationalization config file in CJS, removed the old JS file, and updated import paths accordingly.
package.json Added "type": "module", updated scripts to use tsx, replaced and updated TypeScript versions, and added new dependencies/devDependencies.
scripts/adopters/index.js / scripts/adopters/index.ts Removed the JS version and added a TypeScript implementation for building the adopters list with improved path resolution.
Build scripts: build-docs.ts, build-meetings.ts, build-newsroom-videos.js/.ts, build-pages.ts, build-post-list.js/.ts, build-rss.js/.ts, build-tools.js/.ts Migrated various build scripts to TypeScript, updated to ES module syntax, enhanced type safety and error handling, and renamed files accordingly.
scripts/casestudies/index.js / scripts/casestudies/index.ts, scripts/compose.ts, scripts/dashboard/*, scripts/finance/index.js / scripts/finance/index.ts, scripts/index.ts Updated from JS to TS with improved import paths, ES module syntax, and refined control flow/error handling.
Markdown utilities: scripts/markdown/check-markdown.js / .ts Replaced the JS version with a TypeScript implementation that enhances frontmatter validation and integrates a logger utility.
Tools modules: Files under scripts/tools/ (e.g. categorylist, combine-tools, extract-tools-github, tags-color, tools-object) Removed JS versions and added corresponding TypeScript files; updated JSON schema and enhanced error handling and data validation.
Utils: scripts/utils.js / scripts/utils.ts, scripts/utils/readAndWriteJson.js / .ts Refactored utility functions to TypeScript, improved error handling, added new functionality (e.g. a pause function) and standardized module exports.
Configuration & Type Declarations: tsconfig.json and multiple *.d.ts files Updated tsconfig with "target": "ES2022" and reorganized type declarations for external modules and project-specific scripts.
Test files (various in tests/) Updated import paths from JS to TS, integrated a new logger utility into tests, standardized mocks, and adjusted formatting for consistency.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant BM as buildMeetings Function
    participant GA as Google API
    participant FS as File System

    U->>BM: Call buildMeetings(writePath)
    BM->>GA: Authenticate & fetch calendar events
    GA-->>BM: Return events list
    BM->>BM: Process and validate events
    BM->>FS: Write events to specified writePath
    FS-->>BM: Confirm file write
    BM-->>U: Return success or error response
Loading

Possibly related PRs

  • feat: add workflow and script to check edit links on docs #3557: The changes in the main PR, which involve modifications to the ESLint configuration for handling markdown files, are related to the retrieved PR that introduces a workflow for checking edit links in documentation, as both involve enhancements to the handling and validation of markdown-related files.

Suggested labels

ready-to-merge, gsoc

Suggested reviewers

  • derberg
  • magicmatatjahu
  • akshatnema
  • anshgoyalevil
  • devilkiller-ag
  • sambhavgupta0705
  • Mayaleeeee
  • asyncapi-bot-eve

Poem

Hop along, I’m a coding bunny,
Scurrying through scripts so funny.
TypeScript leaps and modules soar,
Logging and tests—who could ask for more?
I nibble on clean code with delight,
Happy hops in every merge tonight!
🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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

netlify bot commented Nov 22, 2024

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit e75e746
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/67a5bef0c05d200008047f3f
😎 Deploy Preview https://deploy-preview-3423--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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: 0

🧹 Nitpick comments (1)
scripts/markdown/check-edit-links.ts (1)

186-187: Log errors using logger.error before throwing in the main function

In the main function, if an error occurs, you throw a new error without logging it. It's a good practice to log errors before throwing them to aid in debugging and monitoring.

Apply this diff to improve error logging:

} catch (error) {
-    throw new Error(`Failed to check edit links: ${error}`);
+    logger.error(`Failed to check edit links: ${error}`);
+    throw new Error(`Failed to check edit links: ${error}`);
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cfad022 and c5928da.

📒 Files selected for processing (3)
  • package.json (5 hunks)
  • scripts/markdown/check-edit-links.ts (5 hunks)
  • tests/markdown/check-edit-links.test.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🔇 Additional comments (3)
scripts/markdown/check-edit-links.ts (1)

2-2: ⚠️ Potential issue

Correct the module name for 'node-fetch' import

On line 2, the module 'node-fetch-2' is being imported. The standard package name is 'node-fetch'. Please verify the module name and ensure it matches the installed dependency in your project.

Apply this diff to correct the import statement:

-import fetch from 'node-fetch-2';
+import fetch from 'node-fetch';

If you intended to use a different package named 'node-fetch-2', please ensure it's properly installed and compatible with your codebase.

tests/markdown/check-edit-links.test.js (2)

10-12: Ensure compatibility when requiring TypeScript files in JavaScript tests

You're requiring TypeScript files directly in your JavaScript test file. This can cause runtime errors if your testing environment doesn't support importing TypeScript modules directly. Consider one of the following:

  • Compile the TypeScript files before running tests.
  • Convert your test file to TypeScript for consistency.
  • Adjust your test environment to handle TypeScript modules.

Please ensure that your test environment is configured to handle TypeScript modules appropriately.


Line range hint 2-2: Correct the module name for 'node-fetch' import

On line 2, the module 'node-fetch-2' is being required. The correct package name is 'node-fetch'. Ensure that the package name matches the installed dependency to prevent runtime errors.

Apply this diff to correct the require statement:

-const fetch = require('node-fetch-2');
+const fetch = require('node-fetch');

If a different package named 'node-fetch-2' is intended, verify that it's installed and compatible with your test environment.

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: 0

🧹 Nitpick comments (7)
scripts/markdown/check-edit-links.ts (7)

1-8: Consider using a more modern HTTP client.

The node-fetch-2 package is outdated. Consider using undici (Node.js built-in fetch) or node-fetch v3 for better maintenance and security.

-import fetch from 'node-fetch-2';
+import { fetch } from 'undici';

16-20: Enhance interface documentation.

The PathObject interface could benefit from JSDoc comments describing each property's purpose.

+/**
+ * Represents a markdown file's paths and its corresponding edit link
+ */
 interface PathObject {
+  /** The file system path to the markdown file */
   filePath: string;
+  /** The URL path where the file will be served */
   urlPath: string;
+  /** The GitHub edit link for the file, null if not applicable */
   editLink: string | null;
 }

Line range hint 27-52: Improve error handling in processBatch.

The error handling could be improved in several ways:

  1. The error is rejected without being logged
  2. The timeout logic could be extracted into a reusable utility

Consider this refactor:

+const checkWithTimeout = async (url: string, timeout: number) => {
+  const controller = new AbortController();
+  const timeoutId = setTimeout(() => controller.abort(), timeout);
+  try {
+    const response = await fetch(url, {
+      method: 'HEAD',
+      signal: controller.signal
+    });
+    return response;
+  } finally {
+    clearTimeout(timeoutId);
+  }
+};

 async function processBatch(batch: PathObject[]): Promise<(PathObject | null)[]> {
   const TIMEOUT_MS = Number(process.env.DOCS_LINK_CHECK_TIMEOUT) || 5000;

   return Promise.all(
     batch.map(async ({ filePath, urlPath, editLink }) => {
       try {
         if (!editLink || ignoreFiles.some((ignorePath) => filePath.endsWith(ignorePath))) return null;

-        const controller = new AbortController();
-        const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
-        const response = await fetch(editLink, {
-          method: 'HEAD',
-          signal: controller.signal
-        });
-
-        clearTimeout(timeout);
+        const response = await checkWithTimeout(editLink, TIMEOUT_MS);
         if (response.status === 404) {
           return { filePath, urlPath, editLink };
         }

         return null;
       } catch (error) {
+        logger.error(`Error checking ${editLink}:`, error);
         return Promise.reject(new Error(`Error checking ${editLink}: ${error}`));
       }
     })
   );
 }

60-86: Improve type safety in checkUrls.

The function could benefit from stronger typing and better error handling:

  1. The batch size should be validated
  2. The pause duration should be configurable

Consider this enhancement:

+const DEFAULT_BATCH_SIZE = 5;
+const DEFAULT_PAUSE_DURATION = 1000;

-async function checkUrls(paths: PathObject[]): Promise<PathObject[]> {
+async function checkUrls(
+  paths: PathObject[],
+  options?: {
+    batchSize?: number;
+    pauseDuration?: number;
+  }
+): Promise<PathObject[]> {
   const result: PathObject[] = [];
-  const batchSize = Number(process.env.DOCS_LINK_CHECK_BATCH_SIZE) || 5;
+  const batchSize = Math.max(1, Number(process.env.DOCS_LINK_CHECK_BATCH_SIZE) || options?.batchSize || DEFAULT_BATCH_SIZE);
+  const pauseDuration = Math.max(0, Number(process.env.DOCS_LINK_CHECK_PAUSE_DURATION) || options?.pauseDuration || DEFAULT_PAUSE_DURATION);

   // ... rest of the function ...

-      await pause(1000);
+      await pause(pauseDuration);

95-113: Improve type safety in determineEditLink.

The function could benefit from a custom type for edit options and better null handling:

+interface EditOption {
+  /** The path segment to match against */
+  value: string;
+  /** The base URL for edit links */
+  href: string;
+}

 function determineEditLink(
   urlPath: string,
   filePath: string,
-  editOptions: { value: string; href: string }[]
+  editOptions: EditOption[]
 ): string | null {
   // Remove leading 'docs/' if present for matching
   const pathForMatching = urlPath.startsWith('docs/') ? urlPath.slice(5) : urlPath;

-  const target = editOptions.find((edit) => pathForMatching.includes(edit.value));
+  const target = editOptions.find((edit) => 
+    edit.value === '' || pathForMatching.includes(edit.value)
+  );

-  // Handle the empty value case (fallback)
-  if (target?.value === '') {
+  if (!target) {
+    return null;
+  }
+
+  if (target.value === '') {
     return `${target.href}/docs/${urlPath}.md`;
   }

-  // For other cases with specific targets
-  /* istanbul ignore next */
-  return target ? `${target.href}/${path.basename(filePath)}` : null;
+  return `${target.href}/${path.basename(filePath)}`;
 }

144-145: Remove unnecessary istanbul ignore.

The /* istanbul ignore else */ comment seems unnecessary as the else branch is covered by the subsequent else if condition.

-        /* istanbul ignore else */
-
         if (stats.isDirectory()) {

166-192: Improve main function configuration and error handling.

The main function could benefit from:

  1. Configuration options for batch size and pause duration
  2. Better error logging before throwing
+interface CheckLinksOptions {
+  batchSize?: number;
+  pauseDuration?: number;
+  timeout?: number;
+}

-async function main() {
+async function main(options?: CheckLinksOptions) {
   const editOptions = editUrls;

   try {
     const currentFilePath = fileURLToPath(import.meta.url);
     const currentDirPath = dirname(currentFilePath);
     const docsFolderPath = path.resolve(currentDirPath, '../../markdown/docs');
     const paths = await generatePaths(docsFolderPath, editOptions);

     logger.info('Starting URL checks...');
-    const invalidUrls = await checkUrls(paths);
+    const invalidUrls = await checkUrls(paths, {
+      batchSize: options?.batchSize,
+      pauseDuration: options?.pauseDuration
+    });

     if (invalidUrls.length > 0) {
       logger.info('\nURLs returning 404:\n');
       invalidUrls.forEach((url) => logger.info(`- ${url.editLink} generated from ${url.filePath}\n`));
       logger.info(`\nTotal invalid URLs found: ${invalidUrls.length}`);
     } else {
       logger.info('All URLs are valid.');
     }
   } catch (error) {
+    logger.error('Failed to check edit links:', error);
     throw new Error(`Failed to check edit links: ${error}`);
   }
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c5928da and 1cb5862.

📒 Files selected for processing (1)
  • scripts/markdown/check-edit-links.ts (5 hunks)

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: 1

🧹 Nitpick comments (2)
.github/workflows/validate-case-studies-structures.yaml (2)

4-4: Fix trailing spaces.

Remove trailing spaces after push: to maintain consistent code style.

-  push: 
+  push:
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 4-4: trailing spaces

(trailing-spaces)


4-4: Consider adding path filters to the push trigger.

The current configuration will run on all pushes, which could be inefficient. Consider adding path filters to only run when relevant files are changed:

push:
  paths:
    - 'config/casestudies/*.yml'
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 4-4: trailing spaces

(trailing-spaces)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1cb5862 and cc194a6.

📒 Files selected for processing (1)
  • .github/workflows/validate-case-studies-structures.yaml (1 hunks)
🧰 Additional context used
🪛 YAMLlint (1.35.1)
.github/workflows/validate-case-studies-structures.yaml

[error] 4-4: trailing spaces

(trailing-spaces)

.github/workflows/validate-case-studies-structures.yaml Outdated Show resolved Hide resolved
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: 1

🧹 Nitpick comments (1)
scripts/build-docs.ts (1)

115-117: Improve error handling for better type safety.

The error handling could be more type-safe and informative.

-    throw new Error(`Failed to build navigation tree: ${err}`);
+    throw new Error(`Failed to build navigation tree: ${err instanceof Error ? err.message : String(err)}`);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc194a6 and 8dec363.

📒 Files selected for processing (1)
  • scripts/build-docs.ts (1 hunks)
🔇 Additional comments (5)
scripts/build-docs.ts (5)

1-7: LGTM! Clean imports with good practices.

The imports are well-organized, using named imports for better tree-shaking, and properly importing TypeScript types.


149-150: Fix error message construction and improve type safety.

The error message construction is incorrect and the type assertion could be handled better.


244-245: Improve error message construction in addDocButtons.

Similar to the previous error handling issue, the error message construction could be improved.


250-251: LGTM! Clean exports.

The named exports are well-organized and follow TypeScript best practices.


201-215: ⚠️ Potential issue

Add bounds checking for array access in navigation logic.

When constructing the next page title, ensure index + 2 is within bounds.

 if (index + 1 < countDocPages) {
   if (!structuredPosts[index + 1].isRootElement && !structuredPosts[index + 1].isSection) {
     nextPage = {
       title: structuredPosts[index + 1].title,
       href: structuredPosts[index + 1].slug
     };
   } else {
+    if (index + 2 < countDocPages) {
       nextPage = {
         title: `${structuredPosts[index + 1].title} - ${structuredPosts[index + 2].title}`,
         href: structuredPosts[index + 2].slug
       };
+    }
   }

Likely invalid or redundant comment.

Comment on lines +107 to +109
if (rootKey === 'reference' && key === 'specification') {
allChildren[key].item.href = childrenOfAllChildren.find((c) => c.isPrerelease === undefined)!.slug;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Add fallback for specification version lookup.

The non-null assertion on the find result could be unsafe if no matching specification version is found.


🏁 Script executed:

#!/bin/bash
# Check if there are any specification versions without isPrerelease
rg -l "isPrerelease.*undefined" --type ts

Length of output: 65


Potential Runtime Error in Specification Version Lookup

The code at lines 107–109 in scripts/build-docs.ts is still using a non-null assertion on the result of the find operation. If no matching specification version is found (i.e., if childrenOfAllChildren.find((c) => c.isPrerelease === undefined) returns undefined), accessing .slug will trigger a runtime error. Please add a conditional check or default fallback value to avoid this unsafe dereference.

  • Check if the find result is defined before accessing .slug or implement a fallback value.

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: 1

♻️ Duplicate comments (4)
scripts/tools/combine-tools.ts (3)

67-112: 🛠️ Refactor suggestion

Extract shared tag processing logic.

The language and technology processing logic is still duplicated. Consider extracting this into a shared function.

type TagType = 'language' | 'technology';
interface TagConfig {
  defaultColor: string;
  defaultBorderColor: string;
  fuseInstance: Fuse<LanguageColorItem>;
  tagList: LanguageColorItem[];
}

async function processTag(
  tag: string,
  config: TagConfig
): Promise<LanguageColorItem> {
  const search = await config.fuseInstance.search(tag);
  if (search.length > 0) {
    return search[0].item;
  }
  
  const tagObject = {
    name: tag,
    color: config.defaultColor,
    borderColor: config.defaultBorderColor
  };
  
  config.tagList.push(tagObject);
  config.fuseInstance = new Fuse(config.tagList, options);
  return tagObject;
}

Also applies to: 113-138


195-197: ⚠️ Potential issue

Remove non-null assertions from sort comparison.

The sort comparison still uses non-null assertions which could lead to runtime errors.

-        finalTools[key].toolsList = [...automatedResults, ...manualResults].sort((tool, anotherTool) =>
-          tool!.title.localeCompare(anotherTool!.title)
-        ) as FinalAsyncAPITool[];
+        finalTools[key].toolsList = [...automatedResults, ...manualResults].sort((tool, anotherTool) => {
+          if (!tool?.title || !anotherTool?.title) return 0;
+          return tool.title.localeCompare(anotherTool.title);
+        }) as FinalAsyncAPITool[];

200-204: 🛠️ Refactor suggestion

Enhance error handling for file operations.

The file operations error handling could be more informative.

-    fs.writeFileSync(toolsPath, JSON.stringify(finalTools));
-    fs.writeFileSync(tagsPath, JSON.stringify({ languages: languageList, technologies: technologyList }));
+    try {
+      fs.writeFileSync(toolsPath, JSON.stringify(finalTools, null, 2));
+      fs.writeFileSync(tagsPath, JSON.stringify({ 
+        languages: languageList, 
+        technologies: technologyList 
+      }, null, 2));
+    } catch (error) {
+      throw new Error(
+        `Failed to write output files:\n` +
+        `Tools path: ${toolsPath}\n` +
+        `Tags path: ${tagsPath}\n` +
+        `Error: ${error.message}`
+      );
+    }
scripts/tools/extract-tools-github.ts (1)

56-58: ⚠️ Potential issue

Fix incorrect merging of items.

Line 56 incorrectly pushes all items into result.data.items, which already includes the first page of items, causing duplication.

-    result.data.items.push(...allItems);
+    result.data.items = allItems;
🧹 Nitpick comments (4)
scripts/tools/combine-tools.ts (2)

20-23: Add error handling for schema validation setup.

The schema validation setup could fail silently. Consider adding error handling:

-const ajv = new Ajv();
-addFormats(ajv, ['uri']);
-const validate = ajv.compile(schema);
+const ajv = new Ajv();
+try {
+  addFormats(ajv, ['uri']);
+  const validate = ajv.compile(schema);
+} catch (error) {
+  throw new Error(`Failed to initialize schema validation: ${error.message}`);
+}

35-40: Consider making Fuse configuration values configurable.

The threshold value of 0.39 is hardcoded. Consider making it configurable for better flexibility:

+const FUSE_THRESHOLD = process.env.FUSE_THRESHOLD ? parseFloat(process.env.FUSE_THRESHOLD) : 0.39;
+
 const options = {
   includeScore: true,
   shouldSort: true,
-  threshold: 0.39,
+  threshold: FUSE_THRESHOLD,
   keys: ['name', 'color', 'borderColor']
 };
scripts/tools/extract-tools-github.ts (2)

12-18: Add usage example to JSDoc.

Consider adding an @example section to make the usage clearer for other developers.

 /**
  * Fetches tool data from the GitHub API.
  *
  * @returns {Promise<ToolsData>} The data from the GitHub API.
  * @throws {Error} If there is an error fetching the data.
+ * @example
+ * const toolsData = await getData();
+ * console.log(`Found ${toolsData.total_count} tools`);
  */

19-21: Enhance error message with setup instructions.

The error message could be more helpful by including setup instructions.

-    throw new Error('GITHUB_TOKEN environment variable is required');
+    throw new Error(
+      'GITHUB_TOKEN environment variable is required. Please set it in your .env file or environment variables. ' +
+      'You can create a token at https://github.com/settings/tokens with `public_repo` scope.'
+    );
🧰 Tools
🪛 GitHub Actions: PR testing - if Node project

[error] 20-20: GITHUB_TOKEN environment variable is required


[error] 20-20: GITHUB_TOKEN environment variable is required


[error] 20-20: GITHUB_TOKEN environment variable is required

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8dec363 and 4bd3f9c.

📒 Files selected for processing (2)
  • scripts/tools/combine-tools.ts (1 hunks)
  • scripts/tools/extract-tools-github.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
scripts/tools/extract-tools-github.ts

[error] 60-60: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

🪛 GitHub Actions: PR testing - if Node project
scripts/tools/extract-tools-github.ts

[error] 20-20: GITHUB_TOKEN environment variable is required


[error] 20-20: GITHUB_TOKEN environment variable is required


[error] 20-20: GITHUB_TOKEN environment variable is required

🔇 Additional comments (4)
scripts/tools/combine-tools.ts (2)

68-68: Add optional chaining for filters access.

This is still vulnerable to undefined filters.

-if (toolObject.filters.language) {
+if (toolObject.filters?.language) {

142-166: LGTM! Well-structured error handling.

The function has proper error handling, type safety, and clear logging of validation failures.

scripts/tools/extract-tools-github.ts (2)

1-10: LGTM! Imports and type declarations are well organized.

The ESLint disable for no-await-in-loop is justified here since we need sequential pagination to avoid rate limits.


37-55: LGTM! Pagination handling is well implemented.

Good practices implemented:

  • Proper pagination based on total count
  • Rate limiting protection with 1-second pause
  • Progress logging

scripts/tools/extract-tools-github.ts Show resolved Hide resolved
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: 0

🧹 Nitpick comments (1)
scripts/tools/extract-tools-github.ts (1)

12-17: Enhance JSDoc documentation.

Consider adding @requires tag to document the required environment variables.

 /**
  * Fetches tool data from the GitHub API.
  *
+ * @requires {string} process.env.GITHUB_TOKEN - GitHub API token for authentication
  * @returns {Promise<ToolsData>} The data from the GitHub API.
  * @throws {Error} If there is an error fetching the data.
  */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 43014fa and 21f0157.

📒 Files selected for processing (1)
  • scripts/tools/extract-tools-github.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
scripts/tools/extract-tools-github.ts

[error] 57-57: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

⏰ Context from checks skipped due to timeout of 180000ms (5)
  • GitHub Check: Redirect rules - asyncapi-website
  • GitHub Check: Header rules - asyncapi-website
  • GitHub Check: Pages changed - asyncapi-website
  • GitHub Check: Test NodeJS PR - windows-latest
  • GitHub Check: Lighthouse CI
🔇 Additional comments (4)
scripts/tools/extract-tools-github.ts (4)

1-10: LGTM! Well-organized imports and configuration.

The imports are properly organized and typed. The ESLint disable comment for no-await-in-loop is justified as we need to wait between API calls to avoid rate limiting.


18-18: Add environment variable validation.

Add validation for the required GITHUB_TOKEN environment variable at the start of the function.

 export async function getData(): Promise<ToolsData> {
+  if (!process.env.GITHUB_TOKEN) {
+    throw new Error('GITHUB_TOKEN environment variable is required');
+  }

19-58: Improve error handling.

The current try-catch block only rethrows errors without adding value. Let's enhance it with proper error handling.

-  // eslint-disable-next-line no-useless-catch
-  try {
+  try {
     const allItems = [];
     let page = 1;
     // ... rest of the code ...
   } catch (error) {
-    throw err;
+    if (axios.isAxiosError(error)) {
+      if (error.response?.status === 403) {
+        throw new Error('GitHub API rate limit exceeded. Please try again later.');
+      }
+      if (error.response?.status === 401) {
+        throw new Error('Invalid GitHub token. Please check your GITHUB_TOKEN.');
+      }
+      throw new Error(`GitHub API error: ${error.response?.data?.message || error.message}`);
+    }
+    throw error;
   }
🧰 Tools
🪛 Biome (1.9.4)

[error] 57-57: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)


53-53: Fix incorrect merging of items.

There's a bug in how items are merged. The line result.data.items.push(...allItems) is incorrect as allItems already contains all items including those from the first page.

-result.data.items.push(...allItems);
+result.data.items = allItems;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants