Skip to content

fix: address review comments on PR #4823#1

Closed
biplavbarua wants to merge 3 commits into
BBleae:codex/pr-4714-followupfrom
biplavbarua:codex/pr-4714-followup
Closed

fix: address review comments on PR #4823#1
biplavbarua wants to merge 3 commits into
BBleae:codex/pr-4714-followupfrom
biplavbarua:codex/pr-4714-followup

Conversation

@biplavbarua

@biplavbarua biplavbarua commented Mar 4, 2026

Copy link
Copy Markdown

This PR addresses the recent review feedback on anuraghazra#4823.

  • Fixed floating point precision on calculateRank.test.js
  • Mapped GraphQL error correctly in repo.js
  • Avoided ESM SyntaxError with JSON imports in gist.js and wakatime.js by reverting to createRequire.

Summary by Sourcery

根据评审反馈,修正错误处理、JSON 导入以及测试预期。

Bug 修复:

  • 修复 GraphQL 仓库获取器,使其使用错误类型而不是 HTTP 状态文本来映射 GraphQL 错误。
  • 调整排名计算测试,对百分位数预期使用合适的浮点数容差。
  • 使用 createRequire 恢复在 gist 和 Wakatime 卡片中以 Node 兼容方式加载语言颜色的 JSON。
Original summary in English

Summary by Sourcery

Address review feedback by correcting error handling, JSON imports, and test expectations.

Bug Fixes:

  • Fix GraphQL repository fetcher to map GraphQL errors using the error type instead of HTTP status text.
  • Adjust rank calculation test to use an appropriate floating point tolerance for percentile expectations.
  • Restore Node-compatible JSON loading for language colors in gist and Wakatime cards using createRequire.

biplavbarua and others added 3 commits December 25, 2025 12:12
…oad worker routes

- http.js: use native fetch for non-test envs to avoid axios adapter issues;
  add normalizeJsonPayload helper for consistent response parsing
- retryer.js: normalize non-GraphQL message payloads (e.g. Bad credentials)
  into GraphQL-like error shape in both success and catch paths
- repo.js: add missing imports and handle GraphQL errors from retryer response
- worker.js: lazy-load route handlers so process.env is populated before
  module evaluation; replace switch with route-map lookup; guard
  process.env from being undefined
- tests/pat-info.test.js: preserve NODE_ENV when resetting process.env in
  beforeAll so http.js continues to use axios mock adapter in tests
@sourcery-ai

sourcery-ai Bot commented Mar 4, 2026

Copy link
Copy Markdown
审阅者指南(在小型 PR 上折叠显示)

审阅者指南

通过以下方式落实 PR anuraghazra#4823 的审阅意见:修正排名测试中的浮点断言容差、在仓库获取逻辑中正确映射 GraphQL 错误类型,以及将卡片组件中的 JSON 导入恢复为基于 createRequire 的方式,以避免在当前 Node 运行时下出现 ESM SyntaxError。

fetchRepo 中更新后的 GraphQL 错误处理时序图

sequenceDiagram
  participant RepoConsumer
  participant RepoFetcher as fetchRepo
  participant GitHubAPI as GitHub_GraphQL_API
  participant CustomErrorClass as CustomError

  RepoConsumer->>RepoFetcher: fetchRepo(username, reponame)
  RepoFetcher->>GitHubAPI: POST GraphQL repo query
  GitHubAPI-->>RepoFetcher: HTTP response with data.errors
  alt GraphQL_error_with_message
    RepoFetcher->>RepoFetcher: extract message = res.data.errors[0].message
    RepoFetcher->>RepoFetcher: extract type = res.data.errors[0].type || GRAPHQL_ERROR
    RepoFetcher->>CustomErrorClass: new CustomError(message, type)
    CustomErrorClass-->>RepoFetcher: error_instance
    RepoFetcher-->>RepoConsumer: throw error_instance
  else Other_error_without_message
    RepoFetcher->>CustomErrorClass: new CustomError(HTTP_ERROR_MESSAGE, GRAPHQL_ERROR)
    CustomErrorClass-->>RepoFetcher: error_instance
    RepoFetcher-->>RepoConsumer: throw error_instance
  end
Loading

使用 createRequire 导入 languageColors 的流程图

flowchart TD
  A[Module_startup] --> B[Import_createRequire_from_module]
  B --> C[Call_createRequire_with_import_meta_url]
  C --> D[Assign_result_to_require_function]
  D --> E[Call_require_with_languageColors_json_path]
  E --> F[Assign_export_to_languageColors]
  F --> G[Use_languageColors_in_gist_or_wakatime_card]
Loading

文件级变更

变更 详情 文件
将 JSON 导入恢复为基于 createRequire 的加载方式,以避免在卡片模块中出现 ESM SyntaxError。
  • 用基于 createRequire 的 require 调用替换对 language colors JSON 的直接 ESM JSON 导入。
  • 从 module 包引入 createRequire,并实例化一个本地 require 函数用于 JSON 加载。
src/cards/gist.js
src/cards/wakatime.js
改进仓库获取逻辑中的 GraphQL 错误映射。
  • 当存在 GraphQL 错误消息时,如果可用,则使用错误的 type 字段来抛出 CustomError,而不是使用 HTTP status text。
  • 当 GraphQL 响应未提供错误类型时,回退为使用 CustomError.GRAPHQL_ERROR。
src/fetchers/repo.js
收紧排名计算测试中的浮点精度预期。
  • 将 Jest 中对 percentile 使用的 expect.closeTo 精度参数从 10 调整为 5,以更好地体现预期的浮点容差。
tests/calculateRank.test.js

使用提示与命令

与 Sourcery 交互

  • 触发新审阅: 在 pull request 中评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审阅评论。
  • 从审阅评论生成 GitHub issue: 在审阅评论下回复,请求 Sourcery 根据该评论创建 issue。你也可以直接回复 @sourcery-ai issue 来从该评论创建 issue。
  • 生成 pull request 标题: 在 pull request 标题中任意位置写上 @sourcery-ai,即可随时生成标题。你也可以在 pull request 中评论 @sourcery-ai title 来(重新)生成标题。
  • 生成 pull request 摘要: 在 pull request 正文任意位置写上 @sourcery-ai summary,即可在指定位置生成 PR 摘要。你也可以在 pull request 中评论 @sourcery-ai summary 来在任意时间(重新)生成摘要。
  • 生成审阅者指南: 在 pull request 中评论 @sourcery-ai guide,即可在任意时间(重新)生成审阅者指南。
  • 解决所有 Sourcery 评论: 在 pull request 中评论 @sourcery-ai resolve,即可解决所有 Sourcery 评论。适用于你已经处理完所有评论且不再希望看到它们时。
  • 撤销所有 Sourcery 审阅: 在 pull request 中评论 @sourcery-ai dismiss,即可撤销所有现有的 Sourcery 审阅。特别适合在你希望从一次全新的审阅开始时使用——别忘了随后评论 @sourcery-ai review 以触发新的审阅!

自定义你的体验

访问你的 控制面板 以:

  • 启用或禁用诸如 Sourcery 自动生成的 pull request 摘要、审阅者指南等审阅功能。
  • 更改审阅语言。
  • 添加、移除或编辑自定义审阅指令。
  • 调整其他审阅设置。

获取帮助

Original review guide in English
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Implements review feedback for PR anuraghazra#4823 by fixing floating-point assertion tolerance in rank tests, correctly mapping GraphQL error types in the repo fetcher, and reverting JSON imports in card components back to a createRequire-based approach to avoid ESM SyntaxError under the current Node runtime.

Sequence diagram for updated GraphQL error handling in fetchRepo

sequenceDiagram
  participant RepoConsumer
  participant RepoFetcher as fetchRepo
  participant GitHubAPI as GitHub_GraphQL_API
  participant CustomErrorClass as CustomError

  RepoConsumer->>RepoFetcher: fetchRepo(username, reponame)
  RepoFetcher->>GitHubAPI: POST GraphQL repo query
  GitHubAPI-->>RepoFetcher: HTTP response with data.errors
  alt GraphQL_error_with_message
    RepoFetcher->>RepoFetcher: extract message = res.data.errors[0].message
    RepoFetcher->>RepoFetcher: extract type = res.data.errors[0].type || GRAPHQL_ERROR
    RepoFetcher->>CustomErrorClass: new CustomError(message, type)
    CustomErrorClass-->>RepoFetcher: error_instance
    RepoFetcher-->>RepoConsumer: throw error_instance
  else Other_error_without_message
    RepoFetcher->>CustomErrorClass: new CustomError(HTTP_ERROR_MESSAGE, GRAPHQL_ERROR)
    CustomErrorClass-->>RepoFetcher: error_instance
    RepoFetcher-->>RepoConsumer: throw error_instance
  end
Loading

Flow diagram for languageColors import using createRequire

flowchart TD
  A[Module_startup] --> B[Import_createRequire_from_module]
  B --> C[Call_createRequire_with_import_meta_url]
  C --> D[Assign_result_to_require_function]
  D --> E[Call_require_with_languageColors_json_path]
  E --> F[Assign_export_to_languageColors]
  F --> G[Use_languageColors_in_gist_or_wakatime_card]
Loading

File-Level Changes

Change Details Files
Revert JSON imports to createRequire-based loading to avoid ESM SyntaxError in card modules.
  • Replace direct ESM JSON import with createRequire-based require call for the language colors JSON.
  • Introduce createRequire import from the module package and instantiate a local require function for JSON loading.
src/cards/gist.js
src/cards/wakatime.js
Improve GraphQL error mapping in repository fetcher.
  • When a GraphQL error message is present, throw CustomError with the error's type field if available instead of using HTTP status text.
  • Fallback to CustomError.GRAPHQL_ERROR when the error type is not provided by the GraphQL response.
src/fetchers/repo.js
Tighten floating-point precision expectations in rank calculation tests.
  • Adjust Jest expect.closeTo precision parameter for percentile from 10 to 5 to better reflect the intended floating-point tolerance.
tests/calculateRank.test.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses specific feedback from a previous review, focusing on enhancing the robustness and correctness of the application. It refines how JSON data is imported, improves the handling of GraphQL errors for better diagnostics, and fine-tunes test assertions to prevent flakiness related to floating-point arithmetic.

Highlights

  • JSON Import Fix: Reverted JSON imports in gist.js and wakatime.js to use createRequire to prevent ESM SyntaxErrors, ensuring compatibility with Node.js environments that do not fully support JSON modules.
  • GraphQL Error Handling: Updated the repo.js fetcher to correctly map GraphQL errors by utilizing the error type (res.data.errors[0].type) instead of the generic HTTP status text, improving error specificity.
  • Test Precision Adjustment: Adjusted the floating-point precision for percentile expectations in calculateRank.test.js from 10 to 5, resolving potential test failures due to minor precision differences.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/cards/gist.js
    • Reverted JSON import mechanism to use createRequire.
  • src/cards/wakatime.js
    • Reverted JSON import mechanism to use createRequire.
  • src/fetchers/repo.js
    • Modified GraphQL error mapping to use error type instead of status text.
  • tests/calculateRank.test.js
    • Adjusted floating-point precision for percentile expectation in test.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - 我在这里给出了一些高层次的反馈:

  • 由于现在有多个模块都在对 languageColors.json 使用 createRequire 这种变通方案,建议把这个导入集中到一个共享的 helper 中(例如 common/languageColors.js),以避免重复,并把 Node 对 JSON 导入的处理集中到一个地方。
  • fetchRepo 中,当访问 res.data.errors[0].type 时,最好使用可选链或条件保护,以避免在 errors 为空或缺失时出现潜在的运行时错误。
给 AI Agent 的提示
Please address the comments from this code review:

## Overall Comments
- Since multiple modules now use the `createRequire` workaround for `languageColors.json`, consider centralizing this import in a shared helper (e.g., `common/languageColors.js`) to avoid duplication and keep the Node JSON import handling in one place.
- In `fetchRepo`, it may be safer to use optional chaining or guards when accessing `res.data.errors[0].type` to avoid potential runtime errors if `errors` is empty or missing.

Sourcery 对开源项目免费——如果你喜欢我们的评审,请考虑帮我们分享 ✨
帮我变得更有用!请在每条评论上点 👍 或 👎,我会根据你的反馈改进后续的评审。
Original comment in English

Hey - I've left some high level feedback:

  • Since multiple modules now use the createRequire workaround for languageColors.json, consider centralizing this import in a shared helper (e.g., common/languageColors.js) to avoid duplication and keep the Node JSON import handling in one place.
  • In fetchRepo, it may be safer to use optional chaining or guards when accessing res.data.errors[0].type to avoid potential runtime errors if errors is empty or missing.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Since multiple modules now use the `createRequire` workaround for `languageColors.json`, consider centralizing this import in a shared helper (e.g., `common/languageColors.js`) to avoid duplication and keep the Node JSON import handling in one place.
- In `fetchRepo`, it may be safer to use optional chaining or guards when accessing `res.data.errors[0].type` to avoid potential runtime errors if `errors` is empty or missing.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This PR correctly addresses previous review feedback, with appropriate changes to fix JSON imports, GraphQL error handling, and test precision. No security vulnerabilities were found. However, I've suggested a refactor in gist.js and wakatime.js to remove duplicated JSON import code. Additionally, there's a potential bug in src/fetchers/repo.js at line 85 where error handling could lead to a TypeError with an empty errors array; a check for res.data.errors.length > 0 is recommended.

Comment thread src/cards/gist.js
Comment on lines +16 to +18
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const languageColors = require("../common/languageColors.json");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This createRequire logic for importing JSON is duplicated in src/cards/wakatime.js. To improve maintainability and adhere to the DRY (Don't Repeat Yourself) principle, consider abstracting this into a shared utility function within a common module. This would centralize the logic for loading JSON files in a Node.js ESM-compatible way.

Comment thread src/cards/wakatime.js
Comment on lines +10 to +12
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const languageColors = require("../common/languageColors.json");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

This createRequire logic for importing JSON is duplicated in src/cards/gist.js. To improve maintainability and adhere to the DRY (Don't Repeat Yourself) principle, consider abstracting this into a shared utility function within a common module. This would centralize the logic for loading JSON files in a Node.js ESM-compatible way.

@BBleae BBleae force-pushed the codex/pr-4714-followup branch from 727d211 to 4d72a71 Compare June 5, 2026 05:44
@BBleae

BBleae commented Jun 5, 2026

Copy link
Copy Markdown
Owner

Thanks @biplavbarua! All three of your changes have been taken — your commit was cherry-picked onto the rebased branch with authorship preserved (1fd5d22), which is why GitHub shows this PR as closed rather than merged.

One important finding from testing your fix on this fork, which is also relevant for the upstream PR anuraghazra#4823 discussion:

createRequire(import.meta.url) crashes Cloudflare workerd. This branch carries the Cloudflare Workers support, and in workerd import.meta.url is undefined, so createRequire(undefined) throws at module-evaluation time. Reproduced with wrangler dev --local:

GET /api/gist → HTTP 500
TypeError: The argument 'path' ... Received undefined
    at createRequire (node:module:34:15)
    at src/cards/wakatime.js:11:17
    at api/wakatime.js:3:1
    at src/worker.js:18:7

Note that wrangler deploy --dry-run does NOT catch this — both variants build successfully; the failure only appears at runtime.

Meanwhile the bare JSON import you replaced was equally broken in the other direction: on Node ≥22 it throws ERR_IMPORT_ATTRIBUTE_MISSING, killing /api/gist and /api/wakatime on Vercel (Jest's --experimental-vm-modules loader doesn't enforce import attributes, so tests pass either way — false confidence).

The follow-up commit (4d72a71) switches to standard import attributes, which works on both targets:

import languageColors from "../common/languageColors.json" with { type: "json" };

plus ecmaVersion: 2022 → 2025 in eslint.config.mjs so espree parses the syntax. Verified across the full matrix: Node 26 import ✅, full Jest suite (27 suites / 242 tests) ✅, eslint --max-warnings 0 ✅, wrangler build (JSON statically inlined, no runtime require) ✅, and wrangler dev --local serving both endpoints with HTTP 200 ✅.

For upstream anuraghazra#4823 (Vercel-only, no workerd) your createRequire form is fine and matches upstream convention — but if the Workers support ever lands upstream, import attributes are the safe universal form.

The GraphQL error-type mapping fix and the float-tolerance test fix were taken as-is. Thanks again!

@BBleae BBleae closed this Jun 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants