Skip to content

refactor: scripts code for better code quality #3851

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

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

Conversation

JeelRajodiya
Copy link
Contributor

@JeelRajodiya JeelRajodiya commented Mar 9, 2025

closes #3764

Tasks to be completed in this issue

Summary by CodeRabbit

  • Bug Fixes / Enhancements

    • Improved HTML entity decoding in RSS feeds using a dedicated library.
    • Enhanced error handling for missing environment variables and file existence.
    • Strengthened robustness in dashboard discussion processing and finance data handling.
    • Added validation for environment variables in calendar integration.
    • Improved error handling and sorting logic in tool combination processes.
  • New Features

    • Added numerous test fixtures and constants for documentation, navigation, finance, tools, and meetings.
    • Introduced new test cases covering error scenarios, data validation, environment variable checks, and edge cases across multiple modules.
  • Refactor

    • Migrated codebase and tests from CommonJS to ES module syntax for improved compatibility.
    • Updated type definitions and interfaces to support optional properties and enhanced type safety.
    • Removed coverage-ignore comments to increase test coverage visibility.
    • Improved JSON output formatting and error logging for better maintainability.
  • Tests

    • Expanded test coverage with new suites and enhanced existing tests for error handling and data validation.
    • Modernized test imports and mocks, improving clarity and reliability.
    • Removed obsolete tests and helper files while adding new tests for environment variable validation and data processing.

Copy link
Contributor

coderabbitai bot commented Mar 9, 2025

Walkthrough

The changes refactor and modernize the codebase across multiple modules. Updates include dependency management and configuration improvements in package.json, enhanced error handling and type safety in various scripts, removal of deprecated coverage ignore comments, and comprehensive migration of test and fixture files from CommonJS to ES module syntax. New helper functions have been added, and obsolete files removed. Overall, the modifications focus on improving robustness, consistency, and maintainability.

Changes

Files Change Summary
package.json, tailwind.config.ts, jest.config.js, tests/babel.test.config.cts Updated dependencies and configurations; added Babel config for ESM TypeScript support; changed string delimiters and Jest transform path.
scripts/* (e.g. build-docs.ts, build-rss.ts, dashboard/build-dashboard.ts, finance/index.ts, tools/combine-tools.ts, tools/extract-tools-github.ts, tools/tools-object.ts, markdown/check-edit-links.ts, markdown/check-markdown.ts, build-post-list.ts, build-pages.ts, build-meetings.ts, utils/readAndWriteJson.ts, types/scripts/tools.ts) Improved error handling, added environment variable validation, simplified logic (e.g. removal of redundant try-catch and coverage comments), and updated type definitions.
tests/** (all test files in adopters, dashboard, build-docs, build-meetings, build-newsroom-videos, build-pages, build-post-list, build-rss, build-tools, casestudies, finance, index, markdown, readAndWriteJson, tools, utils) Converted from CommonJS to ES module syntax; added new tests for error and invalid data scenarios; enhanced type safety and expanded test coverage.
tests/fixtures/** (all fixture files) Transitioned export syntax from CommonJS to ES6 modules; improved formatting and consistent structure; introduced new fixture data.
tests/helper/** (e.g. buildPostListSetup.ts, toolsObjectData.ts) Introduced new helper functions with ES6 exports and updated implementations; removed deprecated CommonJS helper.
Removed Files Deleted tests/helper/buildPostListSetup.js and tests/readAndWriteJson.test.js as redundant/deprecated.
types/scripts/dashboard.ts Updated interface properties to be optional, enhancing type safety and data structure flexibility.

Sequence Diagram(s)

sequenceDiagram
    participant Env as Environment
    participant BM as BuildMeetings Function
    participant GA as GoogleAuth

    Env->>BM: Provide CALENDAR_SERVICE_ACCOUNT & CALENDAR_ID
    alt All variables set
      BM->>GA: Parse credentials & authenticate
      GA-->>BM: Return credentials
      BM->>BM: Process meetings data
      BM-->>Env: Output meetings list
    else Missing variable
      BM-->>Env: Throw error "Environment variable not set"
    end
Loading
sequenceDiagram
    participant App as Application
    participant RW as writeJSON Function
    participant FS as File System

    App->>RW: Call writeJSON(filePath, content)
    RW->>FS: Attempt to read file
    alt Read Success
      RW->>FS: Write JSON file with formatted output
      FS-->>RW: Write successful
      RW-->>App: Return success
    else Error occurs
      RW-->>App: Throw detailed error message
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
ESM Migration & Test File Compatibility ([#3764])
Update Jest Configuration for TypeScript Imports ([#3764])
Check for missing GitHub token & environment variable validation ([#3764])
Improve error message construction, type safety, and remove unnecessary try-catch/coverage ignores ([#3764])
Consider sanitizing more aggressively / using a template engine ([#3764]) No changes implemented for aggressive sanitization or template engine adoption.

Possibly related PRs

Suggested labels

ready-to-merge

Suggested reviewers

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

Poem

Oh, I hop with glee through lines of code,
Refactored paths and tests bestowed.
Errors tamed with gentle care,
Type-safe hops fill up the air.
From CommonJS to ES — what a sight!
With every change my heart feels light 🐰✨
Keep on coding, day and night!

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81fd483 and 97b662f.

📒 Files selected for processing (2)
  • tests/helper/toolsObjectData.ts (5 hunks)
  • tests/tools/tools-object.test.ts (11 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/tools/tools-object.test.ts
  • tests/helper/toolsObjectData.ts

🪧 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.
  • @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 Mar 9, 2025

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 97b662f
🔍 Latest deploy log https://app.netlify.com/sites/asyncapi-website/deploys/67fe2f4defc417000805c046
😎 Deploy Preview https://deploy-preview-3851--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.

@JeelRajodiya JeelRajodiya marked this pull request as ready for review March 12, 2025 16:41
Copy link

codecov bot commented Mar 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (af03da7) to head (97b662f).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #3851   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           21        21           
  Lines          667       722   +55     
  Branches       113       141   +28     
=========================================
+ Hits           667       722   +55     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

🧹 Nitpick comments (5)
types/scripts/tools.ts (1)

90-90: Good simplification of the ToolsData type

Changing ToolsData from an object with an items property to a direct array of ToolItem is a clean refactoring. This simplifies the API and makes the code more straightforward to work with.

Make sure to update all consumers of this type to handle the array directly rather than accessing the items property.

tests/fixtures/newsroomData.js (1)

53-53: Consider migrating to ES module syntax.

Since the PR objective includes "migration to ECMAScript Modules (ESM)", consider updating this export to use ES module syntax instead of CommonJS.

-module.exports = { mockApiResponse, expectedResult };
+export { mockApiResponse, expectedResult };
tests/dashboard/build-dashboard.test.js (1)

233-242: Good error handling test for missing GITHUB_TOKEN.

This test ensures appropriate errors are thrown when environment variables are missing, which aligns with the PR objective of enhancing error handling.

Consider using assignment to undefined instead of the delete operator:

-    delete process.env.GITHUB_TOKEN;
+    process.env.GITHUB_TOKEN = undefined;

This approach is generally more performant than using the delete operator.

🧰 Tools
🪛 Biome (1.9.4)

[error] 234-234: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

tests/build-rss.test.js (1)

1-4: LGTM: Successfully migrated to ES modules for imports.

The conversion to ES module syntax for imports is correct. Note that line 7 still uses CommonJS require - consider converting this to an import statement as well for consistency.

-const { mockRssData, title, type, desc, missingDateMockData, incompletePostMockData } = require('./fixtures/rssData');
+import { mockRssData, title, type, desc, missingDateMockData, incompletePostMockData } from './fixtures/rssData';
tests/index.test.js (1)

1-7: Clean migration to ESM syntax.

All CommonJS require statements have been properly converted to ES6 import syntax, which is consistent with the PR objectives.

Since the imported functions (particularly rssFeed and buildFinanceInfoList) have been enhanced with better error handling and HTML entity decoding, consider adding specific test cases to verify these new behaviors function correctly.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 74d716f and 9af2472.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (46)
  • package.json (2 hunks)
  • scripts/build-docs.ts (1 hunks)
  • scripts/build-rss.ts (2 hunks)
  • scripts/dashboard/build-dashboard.ts (3 hunks)
  • scripts/finance/index.ts (2 hunks)
  • scripts/tools/combine-tools.ts (1 hunks)
  • scripts/tools/extract-tools-github.ts (1 hunks)
  • scripts/tools/tools-object.ts (1 hunks)
  • tests/adopters/index.test.js (1 hunks)
  • tests/build-docs/addDocButtons.test.js (1 hunks)
  • tests/build-docs/buildNavTree.test.js (2 hunks)
  • tests/build-docs/convertDocPosts.test.js (1 hunks)
  • tests/build-meetings.test.js (1 hunks)
  • tests/build-newsroom-videos.test.js (1 hunks)
  • tests/build-pages.test.js (1 hunks)
  • tests/build-post-list.test.js (1 hunks)
  • tests/build-rss.test.js (1 hunks)
  • tests/build-tools.test.js (1 hunks)
  • tests/casestudies/index.test.js (1 hunks)
  • tests/dashboard/build-dashboard.test.js (5 hunks)
  • tests/finance/index.test.js (1 hunks)
  • tests/fixtures/addDocButtonsData.js (1 hunks)
  • tests/fixtures/buildNavTreeData.js (1 hunks)
  • tests/fixtures/buildPostListData.js (1 hunks)
  • tests/fixtures/buildToolsData.js (1 hunks)
  • tests/fixtures/caseStudyData.js (1 hunks)
  • tests/fixtures/combineToolsData.js (1 hunks)
  • tests/fixtures/convertDocPostData.js (2 hunks)
  • tests/fixtures/dashboardData.js (1 hunks)
  • tests/fixtures/financeData.js (1 hunks)
  • tests/fixtures/markdown/check-edit-links-data.js (1 hunks)
  • tests/fixtures/meetingsData.js (1 hunks)
  • tests/fixtures/newsroomData.js (1 hunks)
  • tests/fixtures/rssData.js (3 hunks)
  • tests/fixtures/utilsData.js (1 hunks)
  • tests/helper/buildPostListSetup.js (1 hunks)
  • tests/helper/toolsObjectData.js (2 hunks)
  • tests/index.test.js (1 hunks)
  • tests/markdown/check-edit-links.test.js (1 hunks)
  • tests/markdown/check-markdown.test.js (1 hunks)
  • tests/readAndWriteJson.test.js (1 hunks)
  • tests/tools/combine-tools.test.js (2 hunks)
  • tests/tools/extract-tools-github.test.js (5 hunks)
  • tests/tools/tools-object.test.js (1 hunks)
  • tests/utils.test.js (1 hunks)
  • types/scripts/tools.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
tests/dashboard/build-dashboard.test.js

[error] 234-234: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (66)
package.json (2)

79-79: Good addition of HTML entity encoding/decoding library

Adding he for HTML entity handling is a good improvement for code quality. This should make the HTML entity handling more robust and maintainable than custom solutions.


138-138: Appropriate addition of TypeScript type definitions

Including TypeScript type definitions for the he library enhances type safety and developer experience when using the library, which aligns well with your code quality improvement goals.

tests/markdown/check-markdown.test.js (1)

1-11: Good migration to ES module syntax

Converting from CommonJS require to ES module import is a great improvement and aligns with the PR objective of migrating to ESM.

tests/fixtures/buildToolsData.js (2)

2-9: Improved code formatting

The improved indentation and spacing makes the code more consistent and readable. Good code quality improvement.

Also applies to: 13-24, 28-49, 53-76


79-79: Good migration to ES module exports

Converting from CommonJS module.exports to ES module export syntax is a great improvement and aligns with the PR objective of migrating to ESM.

tests/adopters/index.test.js (1)

1-3: Nice work on the ES module migration!

The conversion from CommonJS require() statements to ES6 import statements is clean and maintains the same functionality while modernizing the codebase as mentioned in the PR objectives.

tests/build-docs/addDocButtons.test.js (1)

1-2: Clean ES module migration

The conversion from CommonJS imports to ES module imports is well-executed and aligns with the project's goal of migrating to ECMAScript Modules (ESM).

scripts/tools/tools-object.ts (1)

93-93:

❓ Verification inconclusive

Good code simplification

The refactoring to map directly over data rather than creating an intermediate dataArray variable improves code cleanliness. This change aligns with the type update for ToolsData in the types/scripts/tools.ts file, which now appears to be a direct array type rather than an object with an items property.


🏁 Script executed:

#!/bin/bash
# Verify that all code calling convertTools passes the correct data structure
rg -A 1 "convertTools\(" --exclude "tools-object.ts"

Length of output: 464


Review Directive: Verify Data Structure in convertTools Usage

The refactoring to map directly over data is a solid improvement and aligns with the updated ToolsData type. However, the original verification command using rg --exclude "tools-object.ts" failed due to an unsupported flag. Please manually re-run verification (or update the script) with a corrected command such as:

rg -A 1 "convertTools\(" -g '!tools-object.ts'

This will help ensure that all calls to convertTools pass the correct data structure.

tests/build-meetings.test.js (1)

1-5: Well-executed ES module migration

The conversion from CommonJS to ES modules is clean and consistent with the pattern applied across the codebase. The specific imports for fs functions (rather than importing the entire module) is a good practice that improves code clarity.

tests/fixtures/combineToolsData.js (1)

209-227: Good job migrating to ESM syntax!

The change from CommonJS module.exports to ES6 export aligns well with the PR objective of migrating to ECMAScript Modules. This modernization improves consistency across the codebase.

tests/fixtures/buildPostListData.js (2)

2-26: Clean formatting improvements

The improved indentation and formatting make the test content more readable while preserving functionality.


29-29:

✅ Verification successful

Switched to default export

Good change from CommonJS to ES module syntax using default export instead of named export. Note that this change means importers will need to use import TEST_CONTENT from '...' instead of destructuring.


🏁 Script executed:

#!/bin/bash
# Search for any imports of this fixture to ensure they're updated for the default export
rg "TEST_CONTENT.*buildPostListData" --type js --type ts

Length of output: 151


Default Export Verified – No Further Changes Needed

The update to use a default export in tests/fixtures/buildPostListData.js has been confirmed. The consuming file (tests/helper/buildPostListSetup.js) correctly imports using the default import syntax (import TEST_CONTENT from '../fixtures/buildPostListData';).

tests/build-newsroom-videos.test.js (1)

1-5: Good job converting to ESM imports

The change from CommonJS require to ES6 import statements aligns with the PR objective of migrating to ECMAScript Modules. The use of named imports where appropriate is a good practice that enables better tree-shaking.

scripts/build-rss.ts (2)

2-2: Good addition of the 'he' library

Adding the HTML entities library is a good improvement, replacing custom HTML entity handling with a standard library solution.


94-94: Improved HTML entity handling with standard library

Replacing a custom clean function with the standardized he.decode method enhances code quality by:

  1. Using a well-maintained library instead of custom code
  2. Improving robustness in handling HTML entities
  3. Reducing maintenance burden

This change contributes to the PR objective of better code quality.

tests/fixtures/meetingsData.js (1)

25-25: LGTM! Module syntax modernization

Successfully updated the export syntax from CommonJS to ES modules, which aligns with the PR objectives to migrate to ECMAScript Modules (ESM).

tests/tools/extract-tools-github.test.js (5)

1-3: LGTM! Module import modernization

Successfully updated the import syntax from CommonJS to ES modules, which aligns with the PR objectives for ESM migration.


12-12: Improved test isolation with beforeEach

Good change from beforeAll to beforeEach, ensuring the environment is correctly set up before each test case.


38-38: Updated assertion to match new implementation

Correctly updated the assertion to match the new return structure of the getData function, which now returns items directly.


80-80: Updated length assertion for flattened structure

Correctly updated to check result.length instead of result.items.length, reflecting the flattened structure returned by getData.


89-96: Great addition of error handling test

Good addition of a test case for when the GitHub token is not set, enhancing error handling test coverage.

🧰 Tools
🪛 Biome (1.9.4)

[error] 91-91: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

scripts/finance/index.ts (1)

35-37: Great addition of file existence checks

Adding checks to verify that the files exist before attempting to read them enhances error handling and prevents potential runtime errors. The use of Promise.all efficiently checks both files concurrently.

This change aligns well with the PR objectives of adding path validation and existence checks and enhancing error handling for file operations.

tests/build-pages.test.js (1)

1-3: Successfully migrated to ES Modules.

The change from CommonJS require() statements to ES module import syntax is well implemented and aligns with the PR objective of migrating to ECMAScript Modules.

scripts/build-docs.ts (1)

204-215: Improved error handling for navigation construction.

The additional condition check (index + 2 < countDocPages) ensures the code safely handles edge cases when constructing the nextPage object. This prevents potential undefined property access if there aren't enough items in the array, aligning with the PR objective of enhancing error handling.

tests/fixtures/buildNavTreeData.js (1)

1-229: Well-structured ES module conversion with improved formatting.

The file has been successfully converted from CommonJS to ES module syntax with export default. Additionally, the code has been reformatted for better readability with consistent indentation, making it more maintainable while preserving the same data structure.

tests/fixtures/utilsData.js (1)

1-4: Clean conversion to named ES Module exports.

The file has been successfully converted from CommonJS to ES module syntax, using individual named exports for each constant. This approach provides better flexibility for importers, allowing them to selectively import only the needed constants.

tests/fixtures/markdown/check-edit-links-data.js (1)

85-85: ES Module export syntax properly implemented.

The change from CommonJS module.exports to ES Modules export syntax aligns with the PR objective of migrating to ECMAScript Modules (ESM). All exported variables are correctly maintained.

tests/utils.test.js (1)

1-2: Import statements correctly updated to ES Module syntax.

The conversion from CommonJS require() to ES Modules import syntax is correctly implemented, maintaining the same imports while adapting to the new module system.

tests/fixtures/dashboardData.js (1)

73-73: ES Module export syntax properly implemented.

The change from CommonJS module.exports to ES Modules export syntax is correct and aligns with the PR objective of migrating to ECMAScript Modules (ESM). All exported variables are maintained in the updated syntax.

tests/build-docs/convertDocPosts.test.js (1)

1-7: Import statements correctly updated to ES Module syntax.

The migration from CommonJS require() statements to ES Modules import syntax is correctly implemented, maintaining the same imports while aligning with the project's move to ECMAScript Modules.

tests/fixtures/newsroomData.js (2)

2-31: Code formatting improvements look good.

The reformatting of the mockApiResponse object structure improves readability without changing functionality.


34-51: Consistent JSON stringification formatting.

The expectedResult JSON stringification has been formatted consistently with proper indentation parameters.

scripts/dashboard/build-dashboard.ts (4)

61-65: Good improvement for GitHub token validation.

Adding explicit validation for the GitHub token before making API calls helps prevent runtime errors and provides clearer error messages.


108-112: Consistent error handling for token validation.

The consistent pattern for token validation across different functions improves code reliability.


118-118: Improved token reference.

Using the local token variable instead of directly accessing the environment variable is more consistent with the validation pattern.


157-157: Enhanced type safety with optional chaining.

Using optional chaining (?.) and nullish coalescing (??) operators improves type safety by handling potential undefined values, addressing the PR objective of "removing non-null assertions for better type safety."

tests/build-docs/buildNavTree.test.js (2)

1-3: Successfully migrated to ES module syntax.

The transition from CommonJS require() to ES module import syntax aligns with the PR objective of "migration to ECMAScript Modules (ESM)".


12-12: Updated variable source reference.

The destructuring assignment now correctly references the imported navData variable instead of the previous require statement.

tests/casestudies/index.test.js (1)

1-4: Successfully migrated to ES module syntax.

The transition from CommonJS require() to ES module import syntax for all dependencies aligns with the PR objective of "migration to ECMAScript Modules (ESM)".

tests/fixtures/addDocButtonsData.js (1)

39-39: Module syntax updated correctly to ES modules.

The export statement has been properly migrated from CommonJS (module.exports) to ES module syntax (export), which aligns with the PR objective of migrating to ECMAScript Modules.

tests/readAndWriteJson.test.js (1)

1-4: Module imports correctly updated to ES modules.

The imports have been properly migrated from CommonJS require statements to ES module import statements, aligning with the PR objective of migrating to ECMAScript Modules.

tests/fixtures/rssData.js (1)

93-93: Module syntax updated correctly to ES modules.

The export statement has been properly migrated from CommonJS (module.exports) to ES module syntax (export), which aligns with the PR objective of migrating to ECMAScript Modules.

tests/dashboard/build-dashboard.test.js (4)

1-5: Module imports correctly updated to ES modules.

The imports have been properly migrated from CommonJS require statements to ES module import statements, aligning with the PR objective of migrating to ECMAScript Modules.

Also applies to: 13-13, 15-22


38-38: Good test setup improvement.

Setting the GITHUB_TOKEN environment variable in the beforeAll hook ensures a consistent test environment, which improves test reliability.


147-173: Great addition of a comprehensive test case for mapGoodFirstIssues.

This test case thoroughly validates the mapping functionality with complete mock data, ensuring that all fields are correctly processed. This aligns with the PR objective of adding explicit unit tests for the mapGoodFirstIssues function.


198-210: Good defensive programming test case.

Testing the handling of undefined values in reviews.nodes addresses the PR objective of removing non-null assertions for better type safety. This test ensures that the code gracefully handles potential null or undefined values.

scripts/tools/combine-tools.ts (2)

195-205: Good defensive programming to handle potential null titles.

Adding null checks before accessing properties prevents potential runtime errors when sorting tools. This addresses edge cases where tools might be missing titles, improving the code's robustness.


208-228: Improved error handling for file operations.

The added try-catch block with detailed error messages provides better debugging information when file operations fail. Including file paths in the error message makes troubleshooting much easier.

The formatted JSON output (with indentation) is also a nice touch for readability.

tests/finance/index.test.js (1)

1-4: LGTM: Successfully migrated to ES modules.

The conversion from CommonJS require() to ES import statements aligns with the PR objective of migrating to ECMAScript Modules (ESM).

tests/helper/buildPostListSetup.js (3)

1-3: LGTM: Successfully migrated to ES modules.

The conversion from CommonJS to ES module import syntax is correct.


6-13: Performance improvement with concurrent directory operations.

Refactoring to use Promise.all with map() instead of a sequential loop improves performance by allowing directory creation and file writing operations to run concurrently. This is a good practice for handling asynchronous operations.


20-20: LGTM: Updated export syntax to match ES module standards.

The change from CommonJS module.exports to ES export statement completes the module syntax migration.

tests/fixtures/financeData.js (1)

1-4: Clean migration to ESM syntax.

The conversion from CommonJS to ES6 module exports is well-implemented and maintains the original data structure. This change aligns perfectly with the PR objective of migrating to ECMAScript Modules.

tests/tools/combine-tools.test.js (1)

1-23: Well-implemented migration to ESM syntax.

All CommonJS require statements have been properly converted to ES6 import syntax. This change is consistent with the PR objective of migrating to ECMAScript Modules and maintains all the test functionality.

tests/fixtures/convertDocPostData.js (3)

2-7: LGTM! Improved code formatting

The formatting changes make the code more consistent by removing trailing commas and adjusting spacing.


19-23: LGTM! Consistent formatting applied

The formatting adjustments here match the style changes applied to the previous object, creating a more consistent codebase.


26-26: Successfully migrated to ES modules

Changed export syntax from CommonJS (module.exports) to ES module syntax (export), which aligns with the PR objective of migrating to ECMAScript Modules.

tests/build-post-list.test.js (1)

1-4: Successfully migrated imports to ES module syntax

The file has been updated to use ES module import syntax instead of CommonJS require statements. This change is consistent with the PR objective of migrating to ESM.

tests/fixtures/caseStudyData.js (4)

1-4: Successfully migrated to ES module exports

Changed from CommonJS exports to ES module export syntax with improved template literal formatting.


6-9: LGTM! Consistent ES module export pattern

The ES module export pattern is applied consistently and the template formatting is improved.


11-14: Successfully migrated JSON object exports to ES module syntax

Object export pattern is now using the ES module format, maintaining the same data while improving code structure.


16-19: LGTM! Consistent ES module export pattern for JSON objects

The export pattern matches other exports in the file, creating consistency throughout the codebase.

tests/build-tools.test.js (1)

1-6: Successfully migrated imports to ES module syntax

The file now uses ES module import syntax instead of CommonJS require statements, which aligns with the PR objective of migrating to ESM. All necessary dependencies and test fixtures are correctly imported.

tests/helper/toolsObjectData.js (2)

58-63: Good refactoring of the createMockData function.

The simplification to directly return the result of tools.map() instead of wrapping it in an object improves code readability and removes an unnecessary layer of nesting. This makes the function more straightforward and its purpose clearer.


79-79: Appropriate migration to ES module syntax.

Changing from CommonJS (module.exports) to ES6 module syntax (export) aligns with the PR objective of migrating to ECMAScript Modules (ESM). This modernization improves code consistency across the codebase.

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

1-12: Successfully migrated imports to ES module syntax.

The conversion from CommonJS require() statements to ES6 import statements is implemented correctly. Good job including file extensions for local imports (especially .ts files), which is required for proper ESM resolution. This change fulfills the PR objective of migrating to ECMAScript Modules.

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 (5)
scripts/utils/readAndWriteJson.ts (1)

40-44: Minor formatting inconsistency

There's an extra blank line before the final throw statement that isn't present in the other error handling blocks.

  if (err instanceof Error) {
    throw new Error(`Error while writing file\nError: ${err.message}`);
  }
-
  throw new Error('Error while writing file\nError: Unknown error');
tests/dashboard/build-dashboard.test.ts (1)

254-264: Avoid using the delete operator for performance reasons.

Using the delete operator can impact performance. Consider using assignment to undefined instead.

-    delete process.env.GITHUB_TOKEN;
+    process.env.GITHUB_TOKEN = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 255-255: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

tests/tools/tools-object.test.ts (1)

11-11: Consider migrating logger import to ES modules

While most imports have been updated to ES modules, the logger is still imported using CommonJS require. For consistency, consider updating this import to also use ES module syntax.

-const { logger } = require('../../scripts/utils/logger');
+import { logger } from '../../scripts/utils/logger';
tests/build-meetings.test.ts (2)

136-150: Good addition of environment variable validation test

This test properly verifies that an error is thrown when the CALENDAR_SERVICE_ACCOUNT environment variable is not set, enhancing error handling.

Consider using undefined assignment instead of delete for better performance:

-    delete process.env.CALENDAR_SERVICE_ACCOUNT;
+    process.env.CALENDAR_SERVICE_ACCOUNT = undefined;

This avoids the performance impact of the delete operator as flagged by the static analysis.

🧰 Tools
🪛 Biome (1.9.4)

[error] 140-140: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


152-164: Good addition of environment variable validation test

This test properly verifies that an error is thrown when the CALENDAR_ID environment variable is not set, enhancing error handling.

Consider using undefined assignment instead of delete for better performance:

-    delete process.env.CALENDAR_ID;
+    process.env.CALENDAR_ID = undefined;

This avoids the performance impact of the delete operator as flagged by the static analysis.

🧰 Tools
🪛 Biome (1.9.4)

[error] 156-156: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34ec09a and 0e3fd13.

📒 Files selected for processing (46)
  • jest.config.js (1 hunks)
  • scripts/build-docs.ts (4 hunks)
  • scripts/dashboard/build-dashboard.ts (5 hunks)
  • scripts/markdown/check-markdown.ts (2 hunks)
  • scripts/utils/readAndWriteJson.ts (1 hunks)
  • tests/adopters/index.test.ts (1 hunks)
  • tests/babel.test.config.cts (1 hunks)
  • tests/build-docs/addDocButtons.test.ts (1 hunks)
  • tests/build-docs/buildNavTree.test.ts (6 hunks)
  • tests/build-docs/convertDocPosts.test.ts (4 hunks)
  • tests/build-meetings.test.ts (5 hunks)
  • tests/build-newsroom-videos.test.ts (5 hunks)
  • tests/build-pages.test.ts (3 hunks)
  • tests/build-post-list.test.ts (7 hunks)
  • tests/build-rss.test.ts (7 hunks)
  • tests/build-tools.test.ts (4 hunks)
  • tests/casestudies/index.test.ts (4 hunks)
  • tests/dashboard/build-dashboard.test.ts (1 hunks)
  • tests/finance/index.test.ts (5 hunks)
  • tests/fixtures/addDocButtonsData.ts (1 hunks)
  • tests/fixtures/buildNavTreeData.ts (1 hunks)
  • tests/fixtures/buildPostListData.ts (1 hunks)
  • tests/fixtures/buildToolsData.ts (1 hunks)
  • tests/fixtures/caseStudyData.ts (1 hunks)
  • tests/fixtures/combineToolsData.ts (1 hunks)
  • tests/fixtures/convertDocPostData.ts (1 hunks)
  • tests/fixtures/dashboardData.ts (4 hunks)
  • tests/fixtures/financeData.ts (1 hunks)
  • tests/fixtures/markdown/check-edit-links-data.ts (1 hunks)
  • tests/fixtures/meetingsData.ts (1 hunks)
  • tests/fixtures/newsroomData.ts (1 hunks)
  • tests/fixtures/rssData.ts (3 hunks)
  • tests/fixtures/utilsData.ts (1 hunks)
  • tests/helper/buildPostListSetup.js (0 hunks)
  • tests/helper/buildPostListSetup.ts (1 hunks)
  • tests/helper/toolsObjectData.ts (2 hunks)
  • tests/index.test.ts (2 hunks)
  • tests/markdown/check-edit-links.test.ts (8 hunks)
  • tests/markdown/check-markdown.test.ts (7 hunks)
  • tests/readAndWriteJson.test.js (0 hunks)
  • tests/readAndWriteJson.test.ts (1 hunks)
  • tests/tools/combine-tools.test.ts (10 hunks)
  • tests/tools/extract-tools-github.test.ts (5 hunks)
  • tests/tools/tools-object.test.ts (5 hunks)
  • tests/utils.test.ts (2 hunks)
  • types/scripts/dashboard.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • tests/readAndWriteJson.test.js
  • tests/helper/buildPostListSetup.js
✅ Files skipped from review due to trivial changes (10)
  • tests/adopters/index.test.ts
  • tests/fixtures/buildPostListData.ts
  • tests/fixtures/caseStudyData.ts
  • tests/fixtures/financeData.ts
  • tests/fixtures/newsroomData.ts
  • tests/babel.test.config.cts
  • tests/fixtures/utilsData.ts
  • tests/fixtures/meetingsData.ts
  • tests/fixtures/buildToolsData.ts
  • tests/fixtures/addDocButtonsData.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • scripts/dashboard/build-dashboard.ts
  • scripts/markdown/check-markdown.ts
🧰 Additional context used
🧬 Code Definitions (9)
tests/readAndWriteJson.test.ts (1)
tests/fixtures/utilsData.ts (2)
  • yamlString (2-2)
  • jsonObject (3-3)
tests/dashboard/build-dashboard.test.ts (3)
tests/fixtures/dashboardData.ts (5)
  • fullDiscussionDetails (83-83)
  • discussionWithMoreComments (83-83)
  • mockRateLimitResponse (83-83)
  • mockDiscussion (83-83)
  • issues (83-83)
scripts/dashboard/build-dashboard.ts (7)
  • getHotDiscussions (281-281)
  • getDiscussions (280-280)
  • start (285-285)
  • getLabel (282-282)
  • mapGoodFirstIssues (283-283)
  • getDiscussionByID (279-279)
  • writeToFile (286-286)
types/scripts/dashboard.ts (2)
  • GoodFirstIssues (87-87)
  • HotDiscussionsIssuesNode (89-94)
tests/build-tools.test.ts (1)
tests/fixtures/buildToolsData.ts (1)
  • mockExtractData (79-79)
tests/build-newsroom-videos.test.ts (1)
tests/fixtures/newsroomData.ts (2)
  • mockApiResponse (53-53)
  • expectedResult (53-53)
tests/fixtures/dashboardData.ts (1)
types/scripts/dashboard.ts (1)
  • GoodFirstIssues (87-87)
tests/tools/tools-object.test.ts (1)
tests/helper/toolsObjectData.ts (2)
  • createMockData (79-79)
  • createToolFileContent (79-79)
tests/build-docs/convertDocPosts.test.ts (2)
scripts/build-docs.ts (1)
  • convertDocPosts (258-258)
tests/fixtures/convertDocPostData.ts (3)
  • docObject (28-28)
  • singlePostDocObject (28-28)
  • nestedChildrenDocObject (28-28)
tests/markdown/check-edit-links.test.ts (2)
tests/fixtures/markdown/check-edit-links-data.ts (2)
  • determineEditLinkData (85-85)
  • testPaths (85-85)
scripts/markdown/check-markdown.ts (1)
  • main (192-192)
tests/markdown/check-markdown.test.ts (1)
scripts/markdown/check-markdown.ts (5)
  • FrontMatter (30-38)
  • validateBlogs (192-192)
  • validateDocs (192-192)
  • checkMarkdownFiles (192-192)
  • main (192-192)
🪛 Biome (1.9.4)
tests/dashboard/build-dashboard.test.ts

[error] 255-255: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

tests/build-meetings.test.ts

[error] 140-140: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 156-156: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (124)
tests/utils.test.ts (2)

1-2: Good migration to ESM syntax!

Import statements have been properly updated from CommonJS to ES module syntax, which aligns with the PR objective of migrating to ECMAScript Modules. The imports are also better organized with test fixtures now coming from a dedicated file.


21-26: Excellent improvement to error handling!

The enhanced error handling with proper type checking using instanceof Error is a significant improvement for type safety. Adding the specific error thrown for unexpected error types also improves debugging and test robustness.

This change directly addresses the PR's objective of removing non-null assertions for better type safety and enhancing error handling.

tests/index.test.ts (3)

1-8: Great job modernizing import statements!

The transition from CommonJS require() to ES module import syntax is a positive change that aligns with modern JavaScript/TypeScript best practices. This makes the codebase more maintainable and consistent with current standards.


39-39: Good improvement to test readability

Storing the spy in a named variable (readdirSyncSpy) improves code clarity and makes the test's intention more explicit. This is better than directly spying without capturing the reference.


45-45: Clean spy restoration

Using the stored spy variable for restoration is more explicit and maintainable than alternative approaches like jest.restoreAllMocks(). This ensures only the specific mock is restored and prevents potential side effects.

tests/fixtures/rssData.ts (2)

8-8: Consistent formatting applied with trailing comma removal.

The removal of trailing commas from the last properties in all objects makes the code format more consistent. While trailing commas can be beneficial for cleaner git diffs when adding new properties, this change aligns with a consistent code style across the codebase.

Also applies to: 16-17, 24-25, 32-33, 40-41, 47-48, 54-56, 65-66, 72-74, 83-86


93-93: Great modernization with ES module syntax.

The change from CommonJS (module.exports) to ES module syntax (export) aligns perfectly with the PR objective of migrating to ECMAScript Modules. Additionally, the exports are alphabetically sorted, which improves readability and maintainability.

tests/fixtures/combineToolsData.ts (1)

209-227: LGTM! Successful migration from CommonJS to ESM.

The change from CommonJS module exports to ES module exports aligns perfectly with the PR's objective of migrating to ECMAScript Modules. This modernization improves code maintainability, enables better tree-shaking, and enhances static analysis capabilities.

tests/tools/extract-tools-github.test.ts (8)

1-4: Good migration to ES modules!

The switch from CommonJS require statements to ES module import syntax aligns well with modern JavaScript practices and the PR objective of migrating to ECMAScript Modules. This change improves code consistency and maintainability.


13-15: Improved test isolation and type safety.

Two important improvements here:

  1. Adding a typed mock for axios (mockedAxios) improves type safety and provides better editor support
  2. Changing from beforeAll to beforeEach ensures each test runs with a clean environment, preventing potential test interdependencies

Both changes align with the PR objective of improving code quality and removing non-null assertions for better type safety.


37-37: Good use of typed mock.

Correctly updated to use the typed mock instance, which provides better type checking during testing.


41-41: Updated assertion matches implementation changes.

This assertion update reflects changes in the implementation of getData, which now directly returns the items array instead of an object containing items. The change helps simplify the API and makes the test more accurate.


71-71: Good use of chained mock implementations.

Correctly updated to use the typed mock with chained mock implementations for pagination testing.


83-83: Updated assertion for consistent return type.

This assertion is correctly updated to check the length of the result array directly, which aligns with the implementation changes in the getData function. This ensures the test remains accurate after refactoring.


89-89: Clean error test implementation.

The error handling test is implemented correctly using the typed mock.


94-94: Improved error message specificity.

The test now explicitly checks for the error message mentioning "GITHUB_TOKEN" rather than a generic message. This provides better clarity on what environment variable is missing and aligns with the PR objective of improving error handling.

tests/fixtures/markdown/check-edit-links-data.ts (1)

85-85: Well done on migrating to ES module syntax.

Replacing the CommonJS module.exports with ES6 export statement is consistent with the PR objective of migrating to ECMAScript Modules (ESM).

tests/markdown/check-edit-links.test.ts (4)

1-14: Good job on migrating to ES module imports.

The conversion from CommonJS require to ES module import syntax aligns well with the PR objective of migrating to ECMAScript Modules.


22-23: Improved type safety with typed mock.

Creating a typed variable mockFetch improves code clarity and type safety throughout the test file.


58-66: Good test coverage for edge case.

This new test case properly validates the behavior of determineEditLink when no matching target is found, enhancing error handling coverage.


90-107: Great addition for file filtering validation.

This test ensures that non-markdown files are properly skipped during path generation, improving validation of the core functionality. The mock implementation and cleanup are well-structured.

tests/markdown/check-markdown.test.ts (6)

1-14: Good job on ES module migration and type imports.

The conversion to ES module syntax and addition of proper type imports enhances code quality and type safety.


16-17: Improved mock implementation for logger.

The updated mock implementation ensures that the logger methods return functions, better matching the actual behavior of the logger in the application.


20-22: Enhanced type safety with explicit type annotations.

Adding explicit type annotations to variables makes the code more robust and easier to understand.


120-134: Good test for files outside reference/specification directory.

This test verifies that markdown files outside the excluded directory are correctly processed and validated.


181-187: Great addition of positive test case for valid frontmatter.

Testing the successful path (valid frontmatter) ensures the validation function works correctly for valid input, not just error cases.


189-195: Good edge case handling for non-markdown files.

This test ensures that non-markdown files are properly skipped without generating errors, improving robustness.

scripts/utils/readAndWriteJson.ts (2)

20-23: Great addition of proper error type checking

The improved error handling correctly differentiates between Error instances and other thrown values, providing more specific error messages.


30-33: Good consistency in error handling pattern

The same error handling pattern is applied consistently across all operations, making the code more maintainable.

tests/readAndWriteJson.test.ts (5)

1-15: Well-structured test file setup

The test setup includes proper imports, mocks, and fixtures. Type assertions for mocked functions are properly handled.


25-34: Comprehensive happy path testing

The test correctly verifies all aspects of successful execution, confirming that each function is called with expected arguments.


36-63: Thorough error case testing for standard Error objects

The tests properly validate error handling for all three potential failure points (reading, conversion, writing) with Error objects.


65-95: Complete coverage for non-Error exceptions

These tests ensure that non-Error thrown values are handled correctly across all operations. The ESLint disable comment in line 79 is appropriately used to allow throwing non-Error values in the test.


1-96: Overall excellent test coverage

The test suite comprehensively covers both success paths and error scenarios, including handling of different error types. This corresponds well with the error handling improvements in the implementation file.

tests/build-pages.test.ts (3)

1-4: LGTM: Solid migration to ES modules

The update from CommonJS require() to ES module import syntax is well-executed and aligns with the PR objective of migrating to ECMAScript modules.


53-65: Great test coverage addition for non-markdown files

This new test case fills an important gap by verifying that files with extensions other than .md are properly handled - copied but not renamed to .mdx. Good cleanup with unlinkSync() at the end.


67-87: Excellent edge case handling for non-standard fs entries

This test effectively covers an edge case where an entry is neither a file nor a directory. The mock fs.Dirent object is comprehensive, and the spy cleanup with mockRestore() ensures test isolation.

tests/tools/combine-tools.test.ts (3)

1-24: LGTM: Clean ES module import migration

The refactoring from CommonJS to ES module import syntax is well-structured. The imports are nicely organized, and the new imports (circularTool, finalToolWithMissingData, manualToolsToSort) are correctly added to support the new test cases.


254-272: Good defensive error logging test for missing tool titles

This test properly validates that an error is logged when tools lack a title property, improving error handling robustness. The mock data structure and expectation are well-defined.


274-296: Great addition for handling prototype inheritance

This test ensures that only own properties (not inherited) are processed, preventing potential issues with JavaScript's prototype chain. This is an important edge case that could lead to unexpected behavior.

types/scripts/dashboard.ts (3)

10-10: Improve type safety with optional property

Changing endCursor from a required property that could be null to an optional property is a better TypeScript pattern. This aligns with the PR objective of improving type safety.


60-60: Enhanced type flexibility for author property

Making author nullable improves the interface's ability to handle cases where an issue or PR may not have an associated author, enhancing type safety.


66-66: Better error handling for missing labels

Allowing the labels property to be null provides more flexibility and better error handling for cases where labels information may not be available.

jest.config.js (1)

3-3:

✅ Verification successful

Proper configuration update for TypeScript support

Updating the Babel configuration path from .cjs to .cts supports the migration to TypeScript modules, addressing issues with import-meta-url as mentioned in the PR summary.


🏁 Script executed:

#!/bin/bash
# Verify that the referenced config file exists
if [ -f "./tests/babel.test.config.cts" ]; then
  echo "✅ Configuration file exists"
  echo "Contents of babel.test.config.cts:"
  cat "./tests/babel.test.config.cts"
else
  echo "❌ Configuration file does not exist at ./tests/babel.test.config.cts"
fi

Length of output: 1077


Approved: Babel configuration update for TypeScript support

The update in the Jest configuration correctly points to ./tests/babel.test.config.cts, and verification confirms that the file exists with the appropriate Babel settings for transforming tests to TypeScript. This change aligns with the goal of resolving issues with import-meta-url as noted in the PR summary.

tests/helper/buildPostListSetup.ts (2)

11-26: Well-structured test setup with efficient concurrent operations

The setupTestDirectories function is implemented with good practices:

  • Uses Promise.all for concurrent directory and file creation which improves performance
  • Properly handles TypeScript type safety with as keyof typeof TEST_CONTENT
  • Clearly separates the creation of the subdirectory after the main directories are created

33-35: Good implementation of temporary directory path generation

The function generates unique paths using both timestamp and random string, which effectively prevents collisions in test environments where tests might run in parallel.

tests/fixtures/convertDocPostData.ts (1)

3-26: Well-structured test fixtures covering multiple scenarios

The test data is comprehensive and well-organized, covering:

  • Simple navigation tree with children
  • Empty object edge case
  • Single post scenario
  • Complex nested structure with multiple levels

This variety of test fixtures will enable thorough testing of the document conversion functionality.

scripts/build-docs.ts (5)

127-127: Expanded function parameter type improves flexibility

Adding NavTreeItem to the accepted parameter types makes the function more flexible and able to handle a wider range of document objects, which aligns with the PR objective to improve code quality.


148-153: Improved error handling follows TypeScript best practices

The enhanced error handling properly:

  • Types caught errors as unknown (TypeScript best practice)
  • Checks if the error is an instance of Error before accessing its properties
  • Provides a more informative fallback message for non-Error objects

This matches the improvements previously implemented in other functions and the test coverage has been added as confirmed in past review comments.


208-209: Use of istanbul ignore prevents coverage warnings

Adding the /* istanbul ignore else */ comment ensures that coverage tools don't flag uncovered branches for conditions that aren't practical to test, which improves the overall reporting accuracy without compromising code quality.


214-219: Enhanced nextPage logic improves navigation robustness

The additional condition index + 2 < countDocPages ensures that the navigation properties are only created when there are enough pages available, preventing potential undefined references and improving the overall robustness of the documentation navigation.


247-252: Improved error handling for addDocButtons follows best practices

The enhanced error handling for addDocButtons follows the same pattern as convertDocPosts:

  • Types caught errors as unknown
  • Properly checks if the error is an instance of Error before accessing properties
  • Provides a clear fallback error message for non-Error objects

As noted in past review comments, the tests for these error conditions have been implemented.

tests/build-docs/convertDocPosts.test.ts (3)

1-7: Modernized imports enhance maintainability

Switching from CommonJS require() to ES module import syntax:

  • Aligns with the PR objective to migrate to ECMAScript Modules
  • Improves code consistency across the codebase
  • Provides better TypeScript integration with explicit imports

46-46: Type assertions ensure test reliability

Adding as any type assertions when passing undefined or null to the convertDocPosts function ensures TypeScript doesn't raise type errors during test execution, which is necessary since the function signature was updated to be more specific.

Also applies to: 58-59


66-89: Comprehensive test for non-Error handling

This excellent test case:

  • Properly mocks the children property to throw a non-Error value
  • Verifies the error handling logic correctly formats the error message
  • Restores the original property after testing, preventing side effects

This ensures complete coverage of the enhanced error handling in the convertDocPosts function.

tests/build-docs/buildNavTree.test.ts (5)

1-2: Module syntax modernization looks good.

Nice job transitioning from CommonJS to ES module syntax. This change aligns with modern JavaScript standards and improves code maintainability.


82-84: Improved type safety with error handling.

Good addition of explicit type casting with (err as Error) before accessing the error message property. This ensures type safety and prevents potential runtime errors.


96-96: Type safety improvement for error handling.

Consistent application of error type assertion, enhancing type safety when accessing error properties.


108-110: Consistent error handling pattern.

The explicit type assertion and multi-line formatting improve both type safety and readability of the error message checks.


119-119: Consistent spacing improves readability.

Good attention to detail with consistent whitespace around array variable declarations, making the code more readable.

Also applies to: 125-125

tests/fixtures/buildNavTreeData.ts (2)

1-227: Well-structured test fixture data.

Excellent job extracting the navigation test data into a separate file. This separation of concerns improves maintainability by:

  1. Keeping test logic separate from test data
  2. Making the test file more focused and readable
  3. Organizing related test cases with clear category names

The comprehensive test cases cover various scenarios including basic navigation, section handling, orphaned items, missing fields, invalid parents, and complex nested structures.


229-229: Clean export pattern.

Using a default export for the navData object is appropriate here as it's the main export from this file.

tests/build-tools.test.ts (4)

1-7: Good modernization to ES modules.

Successfully converted CommonJS imports to ES module syntax, improving code consistency and maintainability.


10-11: Enhanced type safety for mocked axios.

Excellent addition of explicit typing for the mocked axios instance using jest.Mocked<typeof axios>. This improves type checking and IDE auto-completion support.


38-38: Consistent use of typed mock.

Good job consistently using the typed mockedAxios reference throughout the tests, improving type safety and making the mocking pattern more explicit.

Also applies to: 60-60, 81-81, 87-87


83-83: Simplified error handling in tests.

Great improvement using Jest's expect().rejects.toThrow() pattern instead of verbose try/catch blocks. This makes tests more concise and focused on the assertion, following Jest best practices.

Also applies to: 91-91

tests/build-newsroom-videos.test.ts (4)

1-7: Good migration to ES module syntax.

Successfully updated import statements from CommonJS to ES modules, maintaining consistency with the rest of the codebase modernization.


8-14: Improved mock setup pattern.

Good job explicitly creating a typed reference to the mocked fetch function using jest.mocked(). This pattern enhances type safety and makes the mocking more explicit.


31-31: Consistent use of mock reference.

Excellent job consistently using mockFetch instead of fetch throughout the tests. This clearly indicates we're working with a mock and improves code readability.

Also applies to: 34-36, 52-52, 59-60


65-69: Enhanced error type checking.

Great improvement adding proper type checking with if (err instanceof Error) before accessing error properties. This pattern:

  1. Ensures type safety in error handling
  2. Prevents potential runtime errors from accessing properties on non-Error objects
  3. Provides a clear fallback for unexpected error types

This follows TypeScript best practices for error handling.

Also applies to: 82-86, 100-104, 119-123

tests/fixtures/dashboardData.ts (5)

1-1: Good type import for improved type safety.

Adding the explicit GoodFirstIssues type import improves type safety and clarity in this fixture file.


18-22: Properly enhancing mock data structure.

Adding the timelineItems and reviews properties to the mock discussion object ensures it matches the expected interface structure for HotDiscussionsIssuesNode in the dashboard types.


40-44: Consistent mock data structure.

The same properties (timelineItems and reviews) are correctly added to the discussionWithMoreComments object, maintaining consistency with the first mock object.


81-81: Good type assertion for improved type safety.

Using the type assertion as GoodFirstIssues[] for the issues array enhances type safety and ensures the mock data conforms to the expected interface.


83-83: Great migration to ES module syntax.

Converting from CommonJS module.exports to ES module named exports improves code consistency and aligns with the project's migration to ECMAScript modules.

tests/build-docs/addDocButtons.test.ts (6)

1-2: Well-structured imports for test file.

The imports are clean and properly organized, using the ES module syntax. The test fixtures are imported as named imports, which is good practice.


4-46: Comprehensive test case for the happy path.

This test thoroughly verifies that the addDocButtons function correctly adds next and previous page information to document posts. The test includes detailed expected values and checks multiple aspects of the returned data structure.


48-54: Good specific test for root element handling.

This test isolates and tests a specific case where the next item is a root element, ensuring the function handles this edge case correctly.


56-78: Robust error handling tests.

These tests properly verify error handling when required parameters are missing. Using try/catch blocks and explicitly checking error messages is a good approach for testing error conditions.


80-91: Good test for invalid data structure.

This test ensures that the function properly handles invalid data structures in the treePosts parameter, enhancing robustness.


93-116: Excellent test for non-standard exceptions.

This test handles the case when a non-Error object is thrown (string exception). The use of Object.defineProperty to create a getter that throws a string is a clever approach to simulate this edge case.

tests/dashboard/build-dashboard.test.ts (11)

1-31: Well-structured imports and mocks.

Imports are properly organized, and the mocks for the logger and GraphQL API are well set up. The use of typed mocks with jest.Mock ensures type safety during testing.


33-57: Good test setup and teardown.

The use of temporary directories, environment variables, and console spies is well-structured. The beforeAll, afterAll, beforeEach, and afterEach hooks ensure proper setup and cleanup for each test.


59-81: Thorough test for paginated discussions.

This test verifies that the code can handle paginated discussions correctly by checking the GraphQL call parameters and validating the returned data structure.


83-116: Good tests for rate limits and pagination.

These tests verify that rate limit warnings are displayed correctly and that pagination is handled properly when fetching discussions.


117-125: Important failure handling test.

Testing the complete failure scenario ensures the code gracefully handles API errors and logs appropriate messages.


126-155: Good end-to-end and unit tests.

These tests verify both the end-to-end functionality (processing and writing data) and individual functions like getLabel. The checks are specific and verify the expected behavior.


157-188: Excellent detailed test for mapGoodFirstIssues.

This test thoroughly validates the data transformation in the mapGoodFirstIssues function with a complex input structure, ensuring all fields are properly mapped.


190-228: Good tests for specific functions and edge cases.

These tests verify the behavior of individual functions (getDiscussionByID, getHotDiscussions) and handle edge cases like undefined values in the data structure.


230-252: Important file writing and error handling tests.

Testing file writing functionality and error handling for parsing failures ensures the robustness of the dashboard generation process.


266-283: Good test for missing author edge case.

This test ensures the code can handle discussions without an author, which is an important edge case that might occur in real data.


285-305: Excellent test for score calculation logic.

This test verifies that the scoring algorithm correctly prioritizes recent discussions over older ones, which is essential for the hot discussions feature.

tests/finance/index.test.ts (4)

1-5: Good migration to ES module syntax.

Converting from CommonJS require statements to ES module import statements improves code consistency and aligns with the project's migration to ECMAScript modules.


67-67: Improved type safety with error handling.

Adding type assertion (error as Error) before accessing the message property enhances type safety by ensuring proper object type.


82-82: Consistent error type handling.

Same type assertion applied consistently across all error handlers.


104-104: Consistent error type handling throughout.

Type assertion applied consistently to all error handlers in the file.

tests/build-rss.test.ts (6)

1-5: Clean module import migration from CommonJS to ESM

The code now uses the modern ESM import style instead of CommonJS require, which is consistent with the PR's objective to migrate to ECMAScript Modules.


18-21: Improved error handling in beforeAll hook

The error handling now properly checks if the caught error is an instance of Error before accessing its message property, and provides a fallback error message for non-Error objects.


32-35: Improved error handling in afterAll hook

Similar to the beforeAll hook, the error handling has been enhanced to handle non-Error objects more gracefully.


65-65: Enhanced type safety with explicit annotations

Type annotations have been added to improve type safety when mapping over parsed RSS content items.

Also applies to: 85-85


151-167: Enhanced test for posts missing dates

The test has been significantly improved to:

  1. Test multiple posts missing dates
  2. Include a post with no title to verify slug fallback
  3. Provide more detailed error messages that include the specific posts with missing dates

This change provides better test coverage and more helpful error messages.


170-195: Added test for unsupported image extensions

This new test case verifies that the system correctly handles unsupported image extensions by using a default MIME type. This improves test coverage for edge cases.

tests/casestudies/index.test.ts (2)

1-5: Migrated imports to ES modules

The imports have been updated from CommonJS to ES module syntax, which aligns with the PR objective to migrate to ECMAScript Modules. The specific change to import from fs/promises directly is also a best practice.


52-52: Improved type safety in error handling

The error objects are now properly cast to the Error type before accessing the message property, which enhances type safety.

Also applies to: 77-77

tests/tools/tools-object.test.ts (4)

1-9: Migrated imports to ES modules

The imports have been updated from CommonJS to ES module syntax, which aligns with the PR objective to migrate to ECMAScript Modules.


194-209: Added test for non-Error exceptions

This new test case verifies that the system properly handles cases where non-Error objects are thrown by axios.get, returning a generic error message instead. This improves error handling robustness.


211-219: Added test for non-tool files

This test ensures that files not prefixed with .asyncapi-tool are properly skipped during processing, which prevents unintended inclusion of irrelevant files.


221-236: Added test for duplicate categories

This test verifies that tools with duplicate categories are only added once to each category, preventing duplication in the output.

tests/helper/toolsObjectData.ts (2)

58-63: Simplified createMockData function return value

The function now returns the mapped array directly instead of wrapping it in an object with an items property, which simplifies the usage of this function in tests.


79-79: Migrated exports to ES modules

The export statement has been updated from CommonJS to ES module syntax, which aligns with the PR objective to migrate to ECMAScript Modules.

tests/build-post-list.test.ts (13)

1-7: Great job migrating to ES modules!

The import statements have been successfully converted from CommonJS to ES Module syntax, and type imports have been properly added. This aligns with the PR objective of migrating to ECMAScript Modules.


10-12: Good addition of type annotations

Adding explicit type annotations to these variables improves type safety and code readability.


92-93: Improved type safety with explicit typing

Adding the Details type to the callback parameter enhances type checking and makes the code more robust.


107-108: Good use of type assertion

Asserting the JSON parse result as Result type improves type safety and makes subsequent operations on the data more reliable.


109-110: Improved type safety with explicit typing

Adding the Details type to the callback parameter enhances type checking and makes the code more robust.


126-127: Good use of type assertion

Asserting the JSON parse result as Result type improves type safety and makes subsequent operations on the data more reliable.


131-135: Removal of non-null assertions improves type safety

Removing the non-null assertions (!) aligns with the PR objective of removing non-null assertions for better type safety.


153-154: Good use of type assertion and explicit typing

The combination of type assertion for the output and explicit typing in the callback parameter enhances type safety.


169-173: Good use of type assertion and improved type safety

The combination of type assertion and explicit typing in the callback, along with removal of non-null assertions, enhances type safety significantly.


184-186: Good use of type assertion and improved type safety

The combination of type assertion and explicit typing in the callback, along with removal of non-null assertions, enhances type safety significantly.


245-252: Good test for edge case handling

This test verifies that the system handles directories without a second path element correctly by defaulting the sectionSlug to an empty string.


254-262: Good test for fallback behavior

This test verifies an important fallback mechanism where directory names are used as titles when front matter doesn't provide one.


292-298: Improved type checking with proper annotations

Adding TS-ignore comments while intentionally testing invalid input types is a good practice as it acknowledges the type violation is deliberate for testing purposes.

tests/build-meetings.test.ts (1)

1-7: Great job migrating to ES modules!

The import statements have been successfully converted from CommonJS to ES Module syntax, which aligns with the PR objective of migrating to ECMAScript Modules.

Comment on lines +227 to +243
it('does not add item when slug does not match any section', () => {
// Define finalResult
const finalResult = { blog: [], docs: [], about: [] };

// Get the initial state of finalResult
const initialBlogs = JSON.parse(JSON.stringify(finalResult.blog));
const initialDocs = JSON.parse(JSON.stringify(finalResult.docs));
const initialAbout = JSON.parse(JSON.stringify(finalResult.about));

// Add an item with a slug that doesn't match any section
addItem({ slug: '/unknown/path', title: 'Unknown Item' });

// Verify no changes were made to any section arrays
expect(finalResult.blog).toEqual(initialBlogs);
expect(finalResult.docs).toEqual(initialDocs);
expect(finalResult.about).toEqual(initialAbout);
});
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

Test logic might be incomplete

The test creates a finalResult object but doesn't pass it to the addItem function. This test might not be correctly verifying the intended behavior.


🏁 Script executed:

#!/bin/bash
# Check the addItem function signature and implementation to understand expected parameters

rg -A 5 -B 5 "function addItem" ../scripts/build-post-list.ts

Length of output: 133


I'll run another set of commands to search the repository for the definition and usage of the addItem function, and to locate the expected file. Please see the script below:

Once we have the output from these commands, we can better understand the context of addItem (whether the test is correctly verifying behavior or not) and update the review comment accordingly. Please provide the output of these commands for further analysis.


🏁 Script executed:

#!/bin/bash
# 1. Search for any file named build-post-list.ts
fd "build-post-list.ts"

# 2. Search for any instance of "function addItem" in the repository
rg -n "function addItem" .

# 3. Additionally check for exported definitions of addItem
rg -n "export function addItem" .

Length of output: 115


I'll run an additional shell script to search for an arrow function definition for addItem (e.g., defined as const addItem =) to better understand its signature and usage. This will help determine if the test logic is indeed incomplete or if addItem relies on a global state rather than an explicit parameter. Please execute the following command:

Once we have the output from this command, we can proceed with the final review comment.


🏁 Script executed:

#!/bin/bash
rg -n "const addItem =" .

Length of output: 106


Attention: Incomplete Test Verification for addItem's Behavior

The current test in tests/build-post-list.test.ts (lines 227-243) creates a local finalResult object and then calls addItem({ slug: '/unknown/path', title: 'Unknown Item' }); without passing this object. Since the addItem function (defined in scripts/build-post-list.ts as export const addItem = (details: Details) => { ... }) only accepts a details argument, it’s unclear how (or if) the local finalResult is affected.

  • Confirm whether addItem is intended to operate on a global or module-level finalResult.
  • If the design expects finalResult to be modified via an explicit parameter, update the function signature and test accordingly.
  • Otherwise, adjust the test to verify the correct state changes on the actual target object modified by addItem.

Comment on lines 32 to 38
date?: string;
type?: string;
tags?: string[];
cover?: string;
weight: number;
authors?: { name: string; link: string; photo: string }[];
}
Copy link
Member

Choose a reason for hiding this comment

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

Why all these parameters are made optional inside interface?

Comment on lines 196 to 198
logger.error(
`source: combine-tools.ts, tool title is missing. Tool: ${tool} \n AnotherTool: ${anotherTool}`
);
Copy link
Member

Choose a reason for hiding this comment

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

Logger should take the params of error in standard format, like message, detail & trace.

Comment on lines 40 to 44
if (err instanceof Error) {
throw new Error(`Error while writing file\nError: ${err.message}`);
}

throw new Error('Error while writing file\nError: Unknown error');
Copy link
Member

Choose a reason for hiding this comment

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

Since these are utils function, I think we shouldn't throw error here. These are async functions, so we can return Promise reject here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done!

Comment on lines 84 to 93
backgroundImage: {
ambassador: 'url(\'/img/homepage/ambassador.webp\')',
eventCover: 'url(\'/img/homepage/event-cover.webp\')',
channelCover: 'url(\'/img/homepage/slack-cover.webp\')',
usecases: 'url(\'/img/homepage/usecases.webp\')',
roadmapCover: 'url(\'/img/homepage/roadmap.webp\')',
confBg: 'url(\'/img/homepage/confBlurBg.webp\')',
ambassadorCover: 'url(\'/img/homepage/gathering.webp\')',
mapCover: 'url(\'/img/homepage/mapbase.webp\')'
ambassador: "url('/img/homepage/ambassador.webp')",
eventCover: "url('/img/homepage/event-cover.webp')",
channelCover: "url('/img/homepage/slack-cover.webp')",
usecases: "url('/img/homepage/usecases.webp')",
roadmapCover: "url('/img/homepage/roadmap.webp')",
confBg: "url('/img/homepage/confBlurBg.webp')",
ambassadorCover: "url('/img/homepage/gathering.webp')",
mapCover: "url('/img/homepage/mapbase.webp')"
},
Copy link
Member

Choose a reason for hiding this comment

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

Why these changes are done for tailwind config file?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

They are just eslint auto format, otherwise there were red lines in the file.

@@ -35,12 +36,12 @@ describe('start function', () => {
});

test('should throw an error if no finance data is found', async () => {
jest.spyOn(fs, 'readdirSync').mockReturnValue([]);
const readdirSyncSpy = jest.spyOn(fs, 'readdirSync').mockReturnValue([]);
Copy link
Member

Choose a reason for hiding this comment

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

Can we also assert over this spy, to check if it is called once or not.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure!

import path, { resolve } from 'path';

import { buildTools } from '../scripts/build-tools';
import { manualTools, mockConvertedData, mockExtractData, tagsData } from './fixtures/buildToolsData';

jest.mock('axios');
Copy link
Member

Choose a reason for hiding this comment

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

is there a need of this line, since you are mocking the axios library by type?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes we do, the other line is just there for type assertion.

jest.mock('axios'); // to mock the library 
const mockedAxios = axios as jest.Mocked<typeof axios>; // this is for type assertion 

@sambhavgupta0705
Copy link
Member

hey @JeelRajodiya are you still working on this MR

@JeelRajodiya
Copy link
Contributor Author

@sambhavgupta0705 Yes I am, is it just my exams are near so I haven't got time to update the PR.

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

🧹 Nitpick comments (2)
tests/tools/tools-object.test.ts (2)

78-79: Avoid using @ts-ignore

Using @ts-ignore suppresses type checking errors rather than fixing them properly. Consider addressing the underlying type issue instead. This might involve updating the expected type or adding appropriate type guards.

-    // @ts-ignore, ignore the error for missing properties
+    // Create a partial object with the properties we're testing
+    const partialExpected = expected as Partial<typeof expected>;
+    partialExpected.filters.isAsyncAPIOwner = '';

97-97: Consider alternatives to @ts-ignore

Multiple instances of @ts-ignore are used throughout the test file. While they provide explanations, consider refactoring to avoid suppressing type errors. This could involve creating type-safe utility functions or properly typing the test data.

Also applies to: 146-147, 174-175

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4baf12e and 4608857.

📒 Files selected for processing (7)
  • scripts/markdown/check-markdown.ts (2 hunks)
  • scripts/tools/combine-tools.ts (1 hunks)
  • tests/build-meetings.test.ts (6 hunks)
  • tests/markdown/check-markdown.test.ts (7 hunks)
  • tests/tools/combine-tools.test.ts (10 hunks)
  • tests/tools/tools-object.test.ts (11 hunks)
  • types/scripts/tools.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • scripts/markdown/check-markdown.ts
  • scripts/tools/combine-tools.ts
  • tests/tools/combine-tools.test.ts
🧰 Additional context used
🧬 Code Definitions (2)
tests/tools/tools-object.test.ts (2)
types/scripts/tools.ts (1)
  • AsyncAPITool (64-66)
tests/helper/toolsObjectData.ts (3)
  • createMockData (79-79)
  • createMalformedYAML (79-79)
  • createToolFileContent (79-79)
tests/build-meetings.test.ts (1)
tests/fixtures/meetingsData.ts (1)
  • mockEvents (25-25)
🪛 Biome (1.9.4)
tests/build-meetings.test.ts

[error] 148-148: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 164-164: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 180000ms (3)
  • GitHub Check: Redirect rules - asyncapi-website
  • GitHub Check: Header rules - asyncapi-website
  • GitHub Check: Pages changed - asyncapi-website
🔇 Additional comments (24)
tests/markdown/check-markdown.test.ts (9)

1-13: Excellent modernization to ES module syntax

The conversion from CommonJS to ES Module syntax improves code maintainability and aligns with modern TypeScript best practices. The type imports also enhance type safety throughout the tests.


20-22: Good addition of explicit type annotations

Adding explicit type annotations to variables improves type safety and code readability. This is a recommended practice in TypeScript and helps catch potential type-related issues at compile time.


59-59: Well-documented use of @ts-ignore

Each @ts-ignore comment is accompanied by an explanation of why it's being used (to simulate specific test scenarios), which is a good practice for maintainability. These are appropriate uses of type suppression for testing invalid inputs.

Also applies to: 86-86, 177-177, 184-184


102-102: Improved assertion for mocked logger

The assertion has been updated to correctly access the mock calls structure, ensuring the test properly verifies the logger's error reporting behavior.


120-134: Good test coverage for files outside special directories

This new test ensures that files outside the "reference/specification" folder are correctly processed and validated. The assertions properly check for both the file path and the specific validation error message.


157-157: Good practice: restoring mocks

Adding the mock restoration at the end of the test prevents test pollution and ensures that the mock doesn't affect subsequent tests. This is an important practice for maintaining test isolation.


181-188: Added positive test case for validation

This test ensures that valid frontmatter doesn't generate errors. Testing positive cases is important alongside negative cases to verify the complete behavior of the validation function.


190-196: Good edge case testing for non-markdown files

This test verifies that non-markdown files are properly ignored by the validation process, which is an important edge case to cover.


198-213: Comprehensive directory structure testing

This test ensures that markdown files in directories other than "reference/specification" are processed correctly. The test uses proper path handling and has clear assertions for the expected behavior.

tests/build-meetings.test.ts (7)

1-6: Good modernization of import statements.

The transition from CommonJS to ES module syntax improves code consistency and aligns with modern JavaScript practices. The imports are also well-organized alphabetically.


30-31: Excellent refactoring for improved readability.

Creating explicit variables for the mocked methods makes the test code more readable and maintainable. This approach also helps with TypeScript typing.


46-46: Good use of mock references.

Using the newly defined mock references (mockCalendar) instead of directly accessing nested properties enhances readability and maintenance.

Also applies to: 55-55


73-77: Improved error handling with type checking.

The addition of type checking for errors is a good practice that ensures type safety when accessing error properties. This prevents potential runtime errors if non-Error objects are thrown.


107-111: Good comprehensive error handling.

The error handling block properly handles both the Error case and non-Error case, ensuring test robustness.


144-158: Good addition of environment variable validation test.

This test ensures that the application properly validates the presence of the CALENDAR_SERVICE_ACCOUNT environment variable. The cleanup in the finally block is a good practice to ensure test isolation.

Regarding the static analysis warning about using delete, in this case it's actually correct since we need to completely remove the environment variable to test the error condition, not just set it to undefined.

🧰 Tools
🪛 Biome (1.9.4)

[error] 148-148: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


160-172: Good addition of CALENDAR_ID validation test.

This test properly verifies that the application validates the presence of the CALENDAR_ID environment variable. The pattern of saving, deleting, and restoring the environment variable is consistent with the previous test.

As with the previous comment, using delete is appropriate here despite the static analysis warning.

🧰 Tools
🪛 Biome (1.9.4)

[error] 164-164: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

tests/tools/tools-object.test.ts (6)

1-11: Good migration to ES modules for imports

The changes properly migrate from CommonJS require() to ES module import syntax, which aligns with the PR objective of migrating to ECMAScript Modules. The explicit type import for AsyncAPITool improves type safety as well.


28-29: Improved type safety and mocking approach

Good improvement in the test setup by adding explicit typing for axios mock using TypeScript's type assertion and updating the mock implementation. This enhances type safety and makes the test more robust.

Also applies to: 31-31, 38-38


35-35: Enhanced type safety with explicit typing

Adding explicit typing for the mockToolData function parameter improves type safety and makes the code more maintainable.


204-219: Good addition of error handling test case

This new test case effectively verifies that when a non-Error object is thrown, a generic error message is properly returned. This improves error handling robustness in the application.


221-229: Improved validation with file filtering test

The new test case for verifying that files not starting with .asyncapi-tool are skipped is valuable. It ensures that the system correctly filters input files, an important aspect that wasn't tested before.


231-246: Good test for duplicate category handling

This test ensures that a tool with duplicate categories is only added once to the corresponding category. This is an important edge case that helps maintain data integrity in the tool categorization system.

types/scripts/tools.ts (2)

7-7: Good modularity improvement with Category export

Making the Category type exported improves code reusability by allowing it to be imported in other modules.


91-91:

❓ Verification inconclusive

Breaking change in ToolsData structure

The type has been simplified from an object with an items array to a direct array. This is a breaking change that will require updates to any code using this type.


🏁 Script executed:

#!/bin/bash
# Look for usage of ToolsData type and potential access to .items property
rg "ToolsData" --type ts -A 3 -B 3

# Also look for places that might access .items property
rg "\.items" --type ts -A 3 -B 3

Length of output: 13679


Action Required: Verify Consumers of the Updated ToolsData Type
The type definition in types/scripts/tools.ts has been simplified from an object containing an items array to a direct array (Array<ToolItem>). Our search results indicate that there are no direct references accessing a non-existent .items property on instances of ToolsData within the codebase. However, note the following:

  • The API handling and related tests (e.g., in tests/tools/extract-tools-github.test.ts) continue to work with the raw API response structure (accessing data.items), so ensure these conversions are intentionally separated from the internal ToolsData type.
  • Any external consumers or documentation expecting the previous object shape ({ items: ToolItem[] }) must be reviewed and updated accordingly.

Please verify that all usages—both within and outside of this codebase—correctly treat ToolsData as an array and that no outdated assumptions remain.

Comment on lines +89 to +91
if (err instanceof Error) {
expect(err.message).toContain('Authentication failed');
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Missing error handling path.

The function doesn't handle the case where err is not an instance of Error, unlike other similar error handling blocks in the file.

  if (err instanceof Error) {
    expect(err.message).toContain('Authentication failed');
+  } else {
+    throw new Error('Unexpected error type');
  }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (err instanceof Error) {
expect(err.message).toContain('Authentication failed');
}
if (err instanceof Error) {
expect(err.message).toContain('Authentication failed');
} else {
throw new Error('Unexpected error type');
}

@@ -83,13 +84,11 @@ type ToolItem = {
name: string;
url: string;
path: string;
html_url: string;
html_url?: string;
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

Ensure nullable html_url is properly handled

Making html_url optional is reasonable if there are cases without URLs, but verify all code that accesses this property checks for its existence to prevent runtime errors.


🏁 Script executed:

#!/bin/bash
# Find all places where html_url is accessed to check for proper null handling
rg "\.html_url" --type ts -A 3 -B 3

Length of output: 1150


Address nullable html_url handling in tool accesses

The property html_url is declared as optional but is being accessed directly without a check in at least two locations:

  • In scripts/tools/tools-object.ts: const repositoryUrl = tool.repository.html_url;
  • In the warning log: Located in: ${tool.html_url} is used directly.

Please ensure that each access verifies the presence of html_url or safely handles its absence (for example, by using optional chaining or providing a fallback value) to avoid potential runtime errors.

@@ -43,6 +43,7 @@
technology?: Array<string>;
categories: Array<Category>;
hasCommercial?: boolean;
isAsyncAPIOwner?: boolean | string;
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

Verify handling of new type flexibility in isAsyncAPIOwner

The type change from boolean to boolean | string provides more flexibility but requires careful handling in consuming code.


🏁 Script executed:

#!/bin/bash
# Search for usage of isAsyncAPIOwner to verify proper type handling
rg "isAsyncAPIOwner" --type ts -A 3 -B 3

Length of output: 8733


Review and Confirm Handling of isAsyncAPIOwner Union Type

The change in types/scripts/tools.ts now defines isAsyncAPIOwner as boolean | string, which increases flexibility. However, our search indicates some inconsistencies in how this property is used across the codebase:

  • Type Discrepancies:

    • In types/components/tools/ToolDataType.ts, isAsyncAPIOwner is still defined as boolean.
    • In context/ToolFilterContext.tsx, the property is initialized and maintained as a boolean state.
    • Several components (e.g., in ToolsDashboard.tsx and Filters.tsx) include conditionals that assume a boolean value.
  • Test Expectations:

    • Some tests use a boolean value (e.g., true), while others expect an empty string ('') for isAsyncAPIOwner. This suggests that both types are in use, but the handling logic is not consistent.

Action Required:
Please ensure that all consumers of isAsyncAPIOwner either:

  • Update their type definitions and logic to account for the union type, or
  • Properly coerce or convert string values to booleans where a boolean check is expected.

This update will help prevent potential runtime issues arising from mismatched types.

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.

Refactor scripts code for better code quality
3 participants