Skip to content

Introduce Promise Helpers #2102

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

Merged
merged 8 commits into from
Feb 25, 2025
Merged

Introduce Promise Helpers #2102

merged 8 commits into from
Feb 25, 2025

Conversation

ardatan
Copy link
Owner

@ardatan ardatan commented Feb 25, 2025

Create a helper package that collects all helpers and hacks related to Promise

Summary by CodeRabbit

  • New Features

    • Integrated an enhanced promise handling module to improve asynchronous operations and error management.
    • Added new dependencies for promise handling across various packages.
  • Refactor

    • Streamlined promise resolution and error handling flows for greater consistency.
    • Updated method signatures to utilize flexible return types accommodating both synchronous and asynchronous responses.
    • Removed custom promise handling implementations in favor of standardized external library functions.

Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Warning

Rate limit exceeded

@ardatan has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 4b50396 and b9fa745.

📒 Files selected for processing (1)
  • packages/server/src/utils.ts (4 hunks)

Walkthrough

This pull request introduces a new dependency, @whatwg-node/promise-helpers@^0.0.0, across multiple packages. Custom promise utilities and type aliases have been removed in favor of the standardized functions provided by the new package. Method signatures in classes such as CookieStore and PonyfillAsyncDisposableStack have been updated to utilize promise chaining instead of async/await. Additionally, the error handling in several server modules has been refactored to use handleMaybePromise, consolidating promise logic and improving consistency across the codebase.

Changes

File(s) Change Summary
.changeset/@whatwg-node_*
(cookie-store, disposablestack, node-fetch, server, green-rocks-bow)
Added new changeset files documenting dependency updates, including the patch and addition of @whatwg-node/promise-helpers@^0.0.0.
packages/*/package.json
(cookie-store, disposablestack, node-fetch, server)
Added @whatwg-node/promise-helpers with version ^0.0.0 to the dependencies section.
packages/cookie-store/src/CookieStore.ts Refactored methods (get, getAll, delete) to remove async and use promise chaining with fakePromise from the new dependency.
packages/disposablestack/src/AsyncDisposableStack.ts Updated type definitions to use MaybePromiseLike and delegated promise handling to handleMaybePromiseLike.
packages/disposablestack/src/utils.ts Removed the MaybePromise<T> type alias.
packages/node-fetch/src/utils.ts Removed custom implementations of isPromise and fakePromise; now importing fakePromise from @whatwg-node/promise-helpers.
packages/promise-helpers/package.json
packages/promise-helpers/src/index.ts
Introduced a new package providing promise utilities including types (MaybePromise, MaybePromiseLike), functions (isPromise, isPromiseLike, handleMaybePromiseLike, handleMaybePromise, fakePromise), and deferred promise utilities.
packages/server/src/createServerAdapter.ts
packages/server/src/plugins/useErrorHandling.ts
Refactored error handling by replacing isPromise checks with the handleMaybePromise function for streamlined asynchronous operations.
packages/server/src/utils.ts
packages/server/src/uwebsockets.ts
Removed local promise utility implementations and replaced them with imports from @whatwg-node/promise-helpers.
tsconfig.json Added a new path mapping for @whatwg-node/promise-helpers to resolve to its source file.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CookieStore
    participant PromiseHelpers

    Client->>CookieStore: get(init)
    CookieStore->>CookieStore: call getAll(init)
    CookieStore->>PromiseHelpers: fakePromise(cookies)
    PromiseHelpers-->>CookieStore: return promise-wrapped cookies
    CookieStore->>Client: return first cookie via .then()
Loading
sequenceDiagram
    participant Client
    participant ServerAdapter
    participant RequestHandler
    participant PromiseHelpers

    Client->>ServerAdapter: Send Request
    ServerAdapter->>PromiseHelpers: handleMaybePromise(requestHandler)
    PromiseHelpers->>RequestHandler: Invoke request handler
    RequestHandler-->>PromiseHelpers: Return response or error
    PromiseHelpers-->>ServerAdapter: Processed result
    ServerAdapter->>Client: Return final response
Loading

Possibly related PRs

  • Upcoming Release Changes #2098: The changes in the main PR, which involve adding a new dependency @whatwg-node/promise-helpers and modifying methods in the CookieStore class to utilize this dependency, are related to the retrieved PR as it also addresses updates and fixes in the @whatwg-node/fetch package, which is closely tied to the promise handling improvements introduced by the new dependency.

Poem

Oh, I’m a bunny on the run,
Hoping through changes in the code and fun.
Promises now dance with a friendly guide,
handleMaybePromise by our side.
With each new line, my ears stand high –
In this code garden, I joyfully fly! 🐇


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

github-actions bot commented Feb 25, 2025

🚀 Snapshot Release (alpha)

The latest changes of this PR are available as alpha on npm (based on the declared changesets):

Package Version Info
@whatwg-node/cookie-store 0.2.3-alpha-20250225122059-b9fa745cd0710ceae93952a89912c00202daf274 npm ↗︎ unpkg ↗︎
@whatwg-node/disposablestack 0.0.6-alpha-20250225122059-b9fa745cd0710ceae93952a89912c00202daf274 npm ↗︎ unpkg ↗︎
@whatwg-node/node-fetch 0.7.12-alpha-20250225122059-b9fa745cd0710ceae93952a89912c00202daf274 npm ↗︎ unpkg ↗︎
@whatwg-node/promise-helpers 0.0.1-alpha-20250225122059-b9fa745cd0710ceae93952a89912c00202daf274 npm ↗︎ unpkg ↗︎
@whatwg-node/server 0.9.70-alpha-20250225122059-b9fa745cd0710ceae93952a89912c00202daf274 npm ↗︎ unpkg ↗︎

Copy link
Contributor

github-actions bot commented Feb 25, 2025

@benchmarks/node-fetch results (consumeBody)

   ✓ active_handles.................: avg=140.868322 min=12      med=141     max=179     p(90)=158     p(95)=161    
     data_received..................: 20 MB  675 kB/s
     data_sent......................: 13 MB  433 kB/s
     http_req_blocked...............: avg=2.11µs     min=641ns   med=1.23µs  max=6.02ms  p(90)=1.99µs  p(95)=2.23µs 
     http_req_connecting............: avg=307ns      min=0s      med=0s      max=1.11ms  p(90)=0s      p(95)=0s     
     http_req_duration..............: avg=22.58ms    min=3.46ms  med=21.93ms max=1.19s   p(90)=28.15ms p(95)=29.78ms
       { expected_response:true }...: avg=22.58ms    min=3.46ms  med=21.93ms max=1.19s   p(90)=28.15ms p(95)=29.78ms
     http_req_failed................: 0.00%  ✓ 0           ✗ 132441
     http_req_receiving.............: avg=32.6µs     min=9.04µs  med=23.39µs max=11.93ms p(90)=37.31µs p(95)=43.38µs
     http_req_sending...............: avg=9.84µs     min=3.2µs   med=5.91µs  max=6.15ms  p(90)=9.55µs  p(95)=13.15µs
     http_req_tls_handshaking.......: avg=0s         min=0s      med=0s      max=0s      p(90)=0s      p(95)=0s     
     http_req_waiting...............: avg=22.54ms    min=3.43ms  med=21.89ms max=1.19s   p(90)=28.11ms p(95)=29.73ms
     http_reqs......................: 132441 4414.193255/s
     iteration_duration.............: avg=45.28ms    min=10.56ms med=43.64ms max=1.22s   p(90)=49.22ms p(95)=55.2ms 
     iterations.....................: 66207  2206.646679/s
     vus............................: 100    min=100       max=100 
     vus_max........................: 100    min=100       max=100 

Copy link
Contributor

github-actions bot commented Feb 25, 2025

@benchmarks/node-fetch results (noConsumeBody)

   ✓ active_handles.................: avg=140.48155 min=11     med=141     max=199     p(90)=160     p(95)=163    
     data_received..................: 21 MB  707 kB/s
     data_sent......................: 14 MB  458 kB/s
     http_req_blocked...............: avg=3.21µs    min=672ns  med=1.3µs   max=8.62ms  p(90)=2µs     p(95)=2.29µs 
     http_req_connecting............: avg=1.25µs    min=0s     med=0s      max=8.39ms  p(90)=0s      p(95)=0s     
     http_req_duration..............: avg=21.58ms   min=2.35ms med=20.99ms max=1.14s   p(90)=27.22ms p(95)=28.77ms
       { expected_response:true }...: avg=21.58ms   min=2.35ms med=20.99ms max=1.14s   p(90)=27.22ms p(95)=28.77ms
     http_req_failed................: 0.00%  ✓ 1           ✗ 138571
     http_req_receiving.............: avg=32.02µs   min=9.13µs med=22.53µs max=18.02ms p(90)=36.7µs  p(95)=43.88µs
     http_req_sending...............: avg=11.79µs   min=3.33µs med=5.96µs  max=8.13ms  p(90)=9.52µs  p(95)=13.81µs
     http_req_tls_handshaking.......: avg=0s        min=0s     med=0s      max=0s      p(90)=0s      p(95)=0s     
     http_req_waiting...............: avg=21.53ms   min=2.27ms med=20.95ms max=1.14s   p(90)=27.18ms p(95)=28.7ms 
     http_reqs......................: 138572 4618.42764/s
     iteration_duration.............: avg=43.26ms   min=9.5ms  med=41.71ms max=1.16s   p(90)=47.71ms p(95)=53.06ms
     iterations.....................: 69268  2308.613903/s
     vus............................: 0      min=0         max=100 
     vus_max........................: 100    min=100       max=100 

Copy link
Contributor

github-actions bot commented Feb 25, 2025

@benchmarks/server results (undici)

     ✓ no-errors
     ✓ expected-result

   ✓ checks.........................: 100.00% ✓ 214712      ✗ 0     
     data_received..................: 22 MB   719 kB/s
     data_sent......................: 8.6 MB  286 kB/s
     http_req_blocked...............: avg=1.41µs   min=892ns    med=1.19µs   max=177.23µs p(90)=1.89µs   p(95)=2.08µs  
     http_req_connecting............: avg=1ns      min=0s       med=0s       max=124.99µs p(90)=0s       p(95)=0s      
     http_req_duration..............: avg=215.36µs min=162.28µs med=202.5µs  max=58.6ms   p(90)=228.96µs p(95)=238.71µs
       { expected_response:true }...: avg=215.36µs min=162.28µs med=202.5µs  max=58.6ms   p(90)=228.96µs p(95)=238.71µs
     http_req_failed................: 0.00%   ✓ 0           ✗ 107356
     http_req_receiving.............: avg=25.64µs  min=14.25µs  med=23.78µs  max=2.47ms   p(90)=31.17µs  p(95)=33.87µs 
     http_req_sending...............: avg=6.51µs   min=4.15µs   med=5.75µs   max=305.64µs p(90)=8.31µs   p(95)=9.11µs  
     http_req_tls_handshaking.......: avg=0s       min=0s       med=0s       max=0s       p(90)=0s       p(95)=0s      
     http_req_waiting...............: avg=183.2µs  min=134.89µs med=170.28µs max=58.54ms  p(90)=193.73µs p(95)=202.54µs
     http_reqs......................: 107356  3578.404859/s
     iteration_duration.............: avg=274.86µs min=209.4µs  med=260.96µs max=58.72ms  p(90)=291.1µs  p(95)=302.73µs
     iterations.....................: 107356  3578.404859/s
     vus............................: 1       min=1         max=1   
     vus_max........................: 1       min=1         max=1   

Copy link
Contributor

github-actions bot commented Feb 25, 2025

@benchmarks/server results (native)

     ✓ no-errors
     ✓ expected-result

   ✓ checks.........................: 100.00% ✓ 226766      ✗ 0     
     data_received..................: 23 MB   760 kB/s
     data_sent......................: 9.1 MB  302 kB/s
     http_req_blocked...............: avg=1.46µs   min=902ns    med=1.24µs   max=296.01µs p(90)=1.91µs   p(95)=2.09µs  
     http_req_connecting............: avg=1ns      min=0s       med=0s       max=130.02µs p(90)=0s       p(95)=0s      
     http_req_duration..............: avg=200.37µs min=148.46µs med=189.54µs max=17.55ms  p(90)=216.04µs p(95)=226.89µs
       { expected_response:true }...: avg=200.37µs min=148.46µs med=189.54µs max=17.55ms  p(90)=216.04µs p(95)=226.89µs
     http_req_failed................: 0.00%   ✓ 0           ✗ 113383
     http_req_receiving.............: avg=25.89µs  min=14.05µs  med=24.3µs   max=2.71ms   p(90)=31.56µs  p(95)=34.14µs 
     http_req_sending...............: avg=6.66µs   min=4.16µs   med=5.91µs   max=1.91ms   p(90)=8.36µs   p(95)=9.24µs  
     http_req_tls_handshaking.......: avg=0s       min=0s       med=0s       max=0s       p(90)=0s       p(95)=0s      
     http_req_waiting...............: avg=167.81µs min=118.7µs  med=156.98µs max=17.47ms  p(90)=180.38µs p(95)=190.06µs
     http_reqs......................: 113383  3779.286831/s
     iteration_duration.............: avg=259.99µs min=196.82µs med=248.09µs max=17.7ms   p(90)=278.3µs  p(95)=292.61µs
     iterations.....................: 113383  3779.286831/s
     vus............................: 1       min=1         max=1   
     vus_max........................: 1       min=1         max=1   

Copy link
Contributor

github-actions bot commented Feb 25, 2025

@benchmarks/server results (ponyfill)

     ✓ no-errors
     ✓ expected-result

   ✓ checks.........................: 100.00% ✓ 294314      ✗ 0     
     data_received..................: 29 MB   966 kB/s
     data_sent......................: 12 MB   392 kB/s
     http_req_blocked...............: avg=1.37µs   min=852ns    med=1.17µs   max=297.34µs p(90)=1.85µs   p(95)=2.02µs  
     http_req_connecting............: avg=0ns      min=0s       med=0s       max=117.01µs p(90)=0s       p(95)=0s      
     http_req_duration..............: avg=141.31µs min=94.65µs  med=136.48µs max=5.93ms   p(90)=158.93µs p(95)=166.14µs
       { expected_response:true }...: avg=141.31µs min=94.65µs  med=136.48µs max=5.93ms   p(90)=158.93µs p(95)=166.14µs
     http_req_failed................: 0.00%   ✓ 0           ✗ 147157
     http_req_receiving.............: avg=24.4µs   min=11.23µs  med=22.83µs  max=1.96ms   p(90)=30.3µs   p(95)=33.02µs 
     http_req_sending...............: avg=6.31µs   min=3.95µs   med=5.44µs   max=3.58ms   p(90)=8.06µs   p(95)=8.79µs  
     http_req_tls_handshaking.......: avg=0s       min=0s       med=0s       max=0s       p(90)=0s       p(95)=0s      
     http_req_waiting...............: avg=110.59µs min=68.34µs  med=105.52µs max=5.86ms   p(90)=124.68µs p(95)=130.54µs
     http_reqs......................: 147157  4905.056761/s
     iteration_duration.............: avg=199.33µs min=140.38µs med=193.82µs max=6.42ms   p(90)=219.74µs p(95)=228.93µs
     iterations.....................: 147157  4905.056761/s
     vus............................: 1       min=1         max=1   
     vus_max........................: 1       min=1         max=1   

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/promise-helpers/src/index.ts (1)

46-78: Avoid using property names that conflict with Promise methods.

The implementation of fakePromise creates an object with a 'then' property, which could cause issues with linters and potentially lead to unexpected behavior.

-    then(resolve: (value: T) => any) {
+    // Use Symbol.species or another approach to create a Promise-compatible interface
+    [Symbol.species](resolve: (value: T) => any) {

Alternatively, consider using a proper Promise subclass or extending Promise directly if your target environments support it.

🧰 Tools
🪛 Biome (1.9.4)

[error] 53-53: Do not add then to an object.

(lint/suspicious/noThenProperty)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6497ae6 and 6ffce09.

📒 Files selected for processing (20)
  • .changeset/@whatwg-node_cookie-store-2102-dependencies.md (1 hunks)
  • .changeset/@whatwg-node_disposablestack-2102-dependencies.md (1 hunks)
  • .changeset/@whatwg-node_node-fetch-2102-dependencies.md (1 hunks)
  • .changeset/@whatwg-node_server-2102-dependencies.md (1 hunks)
  • .changeset/green-rocks-bow.md (1 hunks)
  • packages/cookie-store/package.json (1 hunks)
  • packages/cookie-store/src/CookieStore.ts (4 hunks)
  • packages/disposablestack/package.json (1 hunks)
  • packages/disposablestack/src/AsyncDisposableStack.ts (3 hunks)
  • packages/disposablestack/src/utils.ts (0 hunks)
  • packages/node-fetch/package.json (1 hunks)
  • packages/node-fetch/src/utils.ts (1 hunks)
  • packages/promise-helpers/package.json (1 hunks)
  • packages/promise-helpers/src/index.ts (1 hunks)
  • packages/server/package.json (1 hunks)
  • packages/server/src/createServerAdapter.ts (4 hunks)
  • packages/server/src/plugins/useErrorHandling.ts (2 hunks)
  • packages/server/src/utils.ts (2 hunks)
  • packages/server/src/uwebsockets.ts (2 hunks)
  • tsconfig.json (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/disposablestack/src/utils.ts
✅ Files skipped from review due to trivial changes (6)
  • .changeset/@whatwg-node_server-2102-dependencies.md
  • .changeset/green-rocks-bow.md
  • .changeset/@whatwg-node_node-fetch-2102-dependencies.md
  • .changeset/@whatwg-node_disposablestack-2102-dependencies.md
  • .changeset/@whatwg-node_cookie-store-2102-dependencies.md
  • packages/promise-helpers/package.json
🧰 Additional context used
🪛 Biome (1.9.4)
packages/promise-helpers/src/index.ts

[error] 53-53: Do not add then to an object.

(lint/suspicious/noThenProperty)

🔇 Additional comments (35)
packages/disposablestack/package.json (1)

37-39: Dependency Addition: Approved Inclusion
The new dependency "@whatwg-node/promise-helpers": "^0.0.0" is correctly introduced here. This aligns with the broader initiative to centralize promise utilities across multiple packages, ensuring a uniform approach.

packages/server/package.json (1)

37-39: New Dependency for Promise Helpers
The addition of "@whatwg-node/promise-helpers": "^0.0.0" in the dependencies is consistent with the PR's objectives. It ensures that promise-related utilities (such as handleMaybePromise) are standardized across packages.

packages/node-fetch/package.json (1)

37-39: Standardizing Promise Utilities
The inclusion of "@whatwg-node/promise-helpers": "^0.0.0" in the dependencies is correctly applied. This change contributes to unifying how promise handling is implemented across the project.

packages/cookie-store/package.json (1)

37-39: Unified Dependency Addition for Promise Helpers
Adding "@whatwg-node/promise-helpers": "^0.0.0" to the dependencies ensures that the promise utility functions (e.g., fakePromise) are resolved uniformly. This is consistent with changes made in related packages and supports maintainability.

tsconfig.json (1)

33-34: Path Mapping Addition for Promise Helpers
The new path mapping entry

"@whatwg-node/promise-helpers": ["packages/promise-helpers/src/index.ts"]

enables TypeScript to correctly resolve the new package. This addition integrates seamlessly with the project’s module resolution strategy.

packages/node-fetch/src/utils.ts (1)

28-28: Good refactoring to use the dedicated promise helpers package.

Using the standardized fakePromise implementation from @whatwg-node/promise-helpers improves code maintainability by centralizing the Promise utility implementation in a dedicated package.

packages/server/src/plugins/useErrorHandling.ts (2)

2-2: Good dependency adoption.

Appropriate import of the new promise utility from the dedicated package.


58-64: Excellent refactoring of error handling logic.

The refactoring to use handleMaybePromise simplifies the code by eliminating explicit promise checking and try/catch boilerplate. This approach provides a cleaner way to handle both synchronous and asynchronous responses with unified error handling.

packages/server/src/createServerAdapter.ts (6)

3-3: Good dependency adoption.

Appropriate import of the new promise utility from the dedicated package.


188-202: Clean refactoring of response hook execution.

The refactoring to use handleMaybePromise simplifies promise handling for response hooks, making the code more maintainable.


206-209: Streamlined early response handling.

Good use of handleMaybePromise to simplify the early response logic, eliminating complex conditional promise handling.


213-237: Improved request hook execution flow.

The refactored code uses handleMaybePromise to simplify the request hook execution process, making the code more readable and maintainable while preserving functionality.


273-292: Streamlined Node request and response handling.

Good refactoring to use nested handleMaybePromise calls, which clearly separates the request handling, response handling, and error handling logic.


327-345: Improved UWS response handling.

The refactored code for μWebSockets (UWS) response handling uses handleMaybePromise consistently with other parts of the codebase, improving maintainability and error handling.

packages/server/src/uwebsockets.ts (2)

1-1: Good dependency adoption.

Appropriate import of the fakePromise utility from the dedicated package.


273-273: Maintained export API compatibility.

Good practice to maintain API compatibility by re-exporting the fakePromise function, allowing existing code to continue working without changes.

packages/server/src/utils.ts (3)

5-5: Good use of external module to consolidate promise utilities.

Replacing in-house promise utility functions with a dedicated module helps improve codebase maintainability.


8-9: LGTM! Maintaining backward compatibility.

Re-exporting the imported functions maintains the public API while benefiting from the consolidated implementation.


450-450: LGTM! Added export of iterateAsyncVoid.

Properly exports the utility function from the new promise-helpers package.

packages/cookie-store/src/CookieStore.ts (5)

1-1: LGTM! Importing fakePromise utility.

Importing the utility from a dedicated package improves maintainability.


26-34: LGTM! Improved promise chaining.

Changed from using async/await to promise chaining with .then(). This maintains the same functionality while aligning with the new codebase promise handling approach.


99-103: LGTM! Simplified promise handling.

Using fakePromise to consistently return a promise object without the overhead of async/await syntax.


110-111: LGTM! Consistent promise wrapping for filtered results.

Properly wraps the filtered cookie array with fakePromise for consistent behavior.


113-133: LGTM! Simplified promise chain in delete method.

Removed the async keyword and directly returns the promise from set() method, which is cleaner and more efficient.

packages/disposablestack/src/AsyncDisposableStack.ts (5)

1-1: LGTM! Using handleMaybePromiseLike for better promise handling.

Importing the specialized utility for handling promise-like objects.


9-9: Enhanced type flexibility with MaybePromiseLike.

Updated type from MaybePromise to MaybePromiseLike, which provides better compatibility with various promise-like objects beyond standard Promises.


23-23: Consistent type update in adopt method parameter.

Changed from MaybePromise to MaybePromiseLike to align with the callbacks array type.


30-30: Consistent type update in defer method parameter.

Changed from MaybePromise to MaybePromiseLike to align with the callbacks array type.


49-60: Simplified error handling with handleMaybePromiseLike.

Refactored the _iterateCallbacks method to use handleMaybePromiseLike, which significantly improves readability and maintainability by delegating complex promise handling logic to a specialized utility.

packages/promise-helpers/src/index.ts (6)

1-2: LGTM! Well-defined type aliases for promise handling.

Clear definition of MaybePromise and MaybePromiseLike types that will enable consistent promise type handling across the codebase.


4-10: LGTM! Simple and effective promise type checking utilities.

The isPromise and isPromiseLike functions provide a standardized way to check for promise-like behavior, with isPromise delegating to isPromiseLike for consistency.


12-32: LGTM! Robust promise-like handling utility.

The handleMaybePromiseLike function elegantly handles both promise-like and non-promise values, with proper error handling and factory functions for success and error cases.


34-44: LGTM! Type-safe wrapper for handleMaybePromiseLike.

handleMaybePromise ensures the return type is specifically MaybePromise rather than the more general MaybePromiseLike.


80-105: LGTM! Modern approach to deferred promises.

Excellent implementation that uses Promise.withResolvers when available (modern browsers) and falls back to a manual implementation for older environments.


107-132: LGTM! Effective async iteration utility.

The iterateAsyncVoid function provides a clean way to iterate over collections with async callbacks, including the ability to stop iteration early.

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 (1)
packages/promise-helpers/src/index.ts (1)

46-77: Address linting issue with the 'then' property

The fakePromise implementation has a linting error about adding 'then' to an object. While functionally correct, consider addressing this to maintain code quality standards.

Since the object is specifically designed to mimic a Promise, you could use a more explicit approach to satisfy the linter:

-  return {
+  // Define a fake promise without triggering linting issues
+  const fakePromiseObj: Promise<T> = {
     then(resolve: (value: T) => any) {
       // ...existing implementation...
     },
     // ...other methods...
     [Symbol.toStringTag]: 'Promise',
   };
+  return fakePromiseObj;
🧰 Tools
🪛 Biome (1.9.4)

[error] 53-53: Do not add then to an object.

(lint/suspicious/noThenProperty)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ffce09 and d59e1ff.

📒 Files selected for processing (7)
  • packages/disposablestack/tests/disposablestack.spec.ts (2 hunks)
  • packages/promise-helpers/src/index.ts (1 hunks)
  • packages/server/src/createServerAdapter.ts (5 hunks)
  • packages/server/src/plugins/useCors.ts (4 hunks)
  • packages/server/src/plugins/useErrorHandling.ts (2 hunks)
  • packages/server/src/types.ts (6 hunks)
  • packages/server/src/utils.ts (3 hunks)
🧰 Additional context used
🪛 GitHub Check: e2e / cloudflare-modules
packages/server/src/utils.ts

[failure] 480-480:
Cannot find name 'MaybePromise'.

packages/server/src/createServerAdapter.ts

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: type check
packages/server/src/utils.ts

[failure] 480-480:
Cannot find name 'MaybePromise'.

packages/server/src/createServerAdapter.ts

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: e2e / cloudflare-workers
packages/server/src/utils.ts

[failure] 480-480:
Cannot find name 'MaybePromise'.

packages/server/src/createServerAdapter.ts

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: e2e / azure-function
packages/server/src/utils.ts

[failure] 480-480:
Cannot find name 'MaybePromise'.

packages/server/src/createServerAdapter.ts

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: e2e / aws-lambda
packages/server/src/utils.ts

[failure] 480-480:
Cannot find name 'MaybePromise'.

packages/server/src/createServerAdapter.ts

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 Biome (1.9.4)
packages/server/src/plugins/useErrorHandling.ts

[error] 47-47: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

packages/promise-helpers/src/index.ts

[error] 53-53: Do not add then to an object.

(lint/suspicious/noThenProperty)

🪛 GitHub Actions: test
packages/server/src/createServerAdapter.ts

[error] 405-405: TypeScript error TS2304: Cannot find name 'MaybePromise'.

⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: unit / node 23
  • GitHub Check: unit / node 22
  • GitHub Check: unit / deno
  • GitHub Check: unit / node 20
  • GitHub Check: unit / bun
  • GitHub Check: alpha / snapshot
  • GitHub Check: node-fetch (consumeBody)
  • GitHub Check: unit / node 18
  • GitHub Check: node-fetch (noConsumeBody)
  • GitHub Check: lint
  • GitHub Check: server (undici)
  • GitHub Check: esm
  • GitHub Check: server (ponyfill)
  • GitHub Check: prettier
  • GitHub Check: server (native)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (27)
packages/disposablestack/tests/disposablestack.spec.ts (2)

1-2: Enhanced type system with promise-helpers import.

The new import of MaybePromise from @whatwg-node/promise-helpers brings a more standardized approach to handling types that could be either a direct value or a Promise.


15-15: Improved type signature using MaybePromise.

Replacing void | Promise<void> with MaybePromise<void> improves readability and consistency with the rest of the codebase while maintaining the same behavior.

packages/server/src/utils.ts (3)

5-5: Standardizing promise utilities with shared dependency.

Importing createDeferredPromise and isPromise from @whatwg-node/promise-helpers centralizes these utilities in a dedicated package, promoting code reuse and consistency.


8-8: Re-exporting promise utilities.

Re-exporting functions maintains backward compatibility for existing consumers while utilizing the standardized implementation.


450-450: Simplified export by using imported implementation.

Replacing a local implementation with an imported utility from a dedicated package reduces code duplication and maintenance burden.

packages/server/src/plugins/useErrorHandling.ts (2)

2-2: Importing promise utilities from central package.

Importing from a dedicated package enhances consistency in promise handling across the codebase.


47-47:

❓ Verification inconclusive

Simplified type signature with MaybePromise.

Using MaybePromise<Response> improves the type definition by concisely capturing both synchronous and asynchronous return paths.


🌐 Web query:

Is void confusing inside a union type in TypeScript?

💡 Result:

Yes, using void inside union types in TypeScript can lead to confusion and unintended behavior. Here's why:

Key Issues with void in Unions

  1. Type Compatibility Problems
    void represents the absence of a meaningful value from functions, but when used in unions:

    type ConfusingUnion = number | void;
    • void cannot be assigned to other types like undefined or null[1][7]
    • Variables of this type cannot safely interact with values expecting concrete types
  2. Misleading Developer Expectations

    • void in parameter positions suggests "no value needed," but TypeScript allows passing undefined for void parameters[5][7]
    • Union members become effectively unrepresentable at runtime since void only exists in type space
  3. Linter Enforcement
    Biome's noConfusingVoidType rule specifically flags these cases:

    type PossibleValues = number | void; // ✖ lint error [1]

    The suggested fix replaces void with undefined, though this is marked "unsafe" due to compatibility differences[1]

Practical Example of Confusion

function handleValue(value: string | void) {
  // ❌ Can't safely use string methods without type guards
  if (typeof value === 'string') {
    console.log(value.toUpperCase());
  }
}

Here, the void case forces excessive type checking for a parameter that should either be a string or explicitly optional[5][7].

Recommended Alternatives

Use Case Instead of void Better Choice
Optional values `T void`
Function returns (): void Keep as-is
Generic contexts <T extends void> Use judiciously

The TypeScript documentation notes that unions appear to have intersection-like behavior for property access, which compounds confusion when void is involved[5]. Best practice is to reserve void strictly for function return types and use undefined for optional value positions[1][4][7].

Citations:


Potential clarity issue: Consider replacing void with undefined for improved type clarity

The simplified signature using MaybePromise<Response> concisely supports both synchronous and asynchronous returns. However, as confirmed by our research, including void in the union (MaybePromise<Response> | void) can be confusing. It might be clearer to represent the absence of a return value explicitly—e.g., by using MaybePromise<Response | undefined>—unless the current approach is a deliberate design choice. If you choose to keep it as is, please ensure the behavior is well-documented to avoid future misunderstandings.

  • File: packages/server/src/plugins/useErrorHandling.ts (Line 47)
🧰 Tools
🪛 Biome (1.9.4)

[error] 47-47: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

packages/server/src/plugins/useCors.ts (3)

1-1: Adopting centralized promise helpers.

Importing handleMaybePromise and MaybePromise from the dedicated package aligns with the broader refactoring effort.


25-25: Type enhancement with MaybePromise.

Updating the return type to MaybePromise<CORSOptions> improves readability while capturing the same semantics as the previous type.


148-159: Consistent promise handling in onResponse method.

Using handleMaybePromise here creates a uniform approach to handling promises throughout the codebase.

The code is cleaner and follows the same pattern established in other parts of the codebase.

packages/server/src/createServerAdapter.ts (6)

188-202: Good refactoring of promise handling with handleMaybePromise

This is a good refactoring that simplifies the code by using the handleMaybePromise utility function from the new promise-helpers package. The previous implementation likely had more verbose promise handling with explicit checks for promises.


206-209: Simplified promise handling with handleMaybePromise

Good use of the handleMaybePromise function to simplify the control flow. This makes the code more readable and easier to maintain.


213-237: Improved request hooks implementation

The refactoring from direct promise handling to using handleMaybePromise makes the code more maintainable and consistent in how it deals with asynchronous operations.


273-292: Enhanced error handling with handleMaybePromise

The nested handleMaybePromise calls provide a cleaner approach to handling errors at different stages of the request processing pipeline. This is more maintainable than separate try-catch blocks.


327-345: Consistent promise handling for UWS requests

This change ensures that UWS request handling follows the same pattern as other request types in the application, improving consistency across the codebase.


404-405: Fix the MaybePromise type import

The return type now uses MaybePromise, but the type is not imported, causing TypeScript errors.

🧰 Tools
🪛 GitHub Check: e2e / cloudflare-modules

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: type check

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: e2e / cloudflare-workers

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: e2e / azure-function

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Check: e2e / aws-lambda

[failure] 405-405:
Cannot find name 'MaybePromise'.

🪛 GitHub Actions: test

[error] 405-405: TypeScript error TS2304: Cannot find name 'MaybePromise'.

packages/promise-helpers/src/index.ts (6)

1-2: Good type definitions for flexible promise handling

These type definitions provide a clean way to represent values that can be either promises or direct values, enhancing type safety while maintaining flexibility.


4-10: Clean implementation of promise type guards

These utility functions provide a concise way to check if a value is a promise or promise-like, which is useful for conditional handling of synchronous and asynchronous values.


12-32: Flexible promise handling with appropriate error recovery

The handleMaybePromiseLike function provides a robust way to handle both synchronous and asynchronous values with proper error handling. The internal structure with _handleMaybePromiseLike helps avoid code duplication while maintaining clear error boundaries.


34-44: Type-safe wrapper for promise handling

This function provides a more specific type signature based on handleMaybePromiseLike, ensuring that the return type is consistently typed as MaybePromise<TOutput>.


80-105: Modern and fallback implementation for deferred promises

Good approach to utilize Promise.withResolvers when available, with a clean fallback implementation. This provides optimal performance on modern JS engines while maintaining compatibility.


107-132: Efficient asynchronous iteration with early termination support

The iterateAsyncVoid function provides a well-designed approach to asynchronous iteration with support for early termination. It effectively leverages handleMaybePromise for consistent promise handling.

packages/server/src/types.ts (5)

2-2: Good type imports for promise handling

Importing both MaybePromise and MaybePromiseLike types provides the flexibility needed across the type system.


7-9: Enhanced FetchEvent interface with flexible promise types

The updated method signatures in the FetchEvent interface provide better flexibility by allowing both synchronous and asynchronous values using the MaybePromise and MaybePromiseLike types.


31-48: More flexible method signatures in ServerAdapterObject

These changes to the return types of the methods in the ServerAdapterObject interface provide better flexibility by allowing both synchronous and asynchronous returns with MaybePromise<Response>.


57-98: Consistent use of MaybePromise across handler methods

The consistent use of MaybePromise<Response> as the return type for all handler methods ensures a uniform interface throughout the server adapter.


128-128: Updated ServerAdapterRequestHandler for consistent promise handling

This change ensures that the ServerAdapterRequestHandler type aligns with the method signatures in the interfaces, maintaining consistency throughout the type system.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/server/src/createServerAdapter.ts (2)

188-202: Simplified promise handling in handleResponse function.

The refactoring uses handleMaybePromise to replace the previous manual promise detection and handling logic. This makes the code more readable and consistent by abstracting away the promise-checking boilerplate.


213-237: Streamlined request hooks iteration with handleMaybePromise.

Refactored the request hooks iteration to use handleMaybePromise, which simplifies the code by removing manual promise handling and provides a more consistent approach to promise flow control.

packages/promise-helpers/src/index.ts (1)

53-88: Lint Warning for then Property
The custom fakePromise provides a neat fallback for non-promise values by imitating the full API surface of a Promise. However, the static analysis tool flags adding a then property on an object. While this pattern is intentional for creating a “thenable,” some linters label it suspicious. If you need to silence the lint warning, consider either disabling that rule locally or returning a genuine new Promise to avoid confusion:

-export function fakePromise<T>(value: T): Promise<T> {
-  if (isPromise(value)) {
-    return value;
-  }
-  return {
-    then(resolve) { ... },
-    ...
-  }
+export function fakePromise<T>(value: T): Promise<T> {
+  return new Promise((resolve) => resolve(value));
 }

Whether you keep the existing approach or switch to a new Promise is a design choice. Just be aware of potential confusion in some environments.

🧰 Tools
🪛 Biome (1.9.4)

[error] 60-60: Do not add then to an object.

(lint/suspicious/noThenProperty)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d59e1ff and d63274a.

📒 Files selected for processing (6)
  • deno.json (1 hunks)
  • packages/node-fetch/src/fetchCurl.ts (1 hunks)
  • packages/node-fetch/src/utils.ts (1 hunks)
  • packages/promise-helpers/src/index.ts (1 hunks)
  • packages/server/src/createServerAdapter.ts (5 hunks)
  • packages/server/src/utils.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/node-fetch/src/fetchCurl.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/promise-helpers/src/index.ts

[error] 60-60: Do not add then to an object.

(lint/suspicious/noThenProperty)

⏰ Context from checks skipped due to timeout of 90000ms (21)
  • GitHub Check: esm
  • GitHub Check: unit / node 23
  • GitHub Check: unit / node 22
  • GitHub Check: alpha / snapshot
  • GitHub Check: unit / deno
  • GitHub Check: unit / node 20
  • GitHub Check: unit / bun
  • GitHub Check: server (undici)
  • GitHub Check: e2e / cloudflare-modules
  • GitHub Check: server (ponyfill)
  • GitHub Check: unit / node 18
  • GitHub Check: e2e / cloudflare-workers
  • GitHub Check: type check
  • GitHub Check: server (native)
  • GitHub Check: prettier
  • GitHub Check: e2e / azure-function
  • GitHub Check: node-fetch (consumeBody)
  • GitHub Check: e2e / aws-lambda
  • GitHub Check: node-fetch (noConsumeBody)
  • GitHub Check: lint
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (19)
deno.json (1)

11-12: Added the promise helpers package to imports.

The import mapping for @whatwg-node/promise-helpers has been correctly added, pointing to the package's entry point. This change enables the use of promise utilities throughout the project.

packages/node-fetch/src/utils.ts (1)

28-28: Centralized promise utilities by importing from dedicated package.

The local implementation of fakePromise has been replaced with an import from the dedicated @whatwg-node/promise-helpers package. This change follows the DRY principle by centralizing utility functions in a specialized package rather than duplicating implementations across the codebase.

packages/server/src/utils.ts (4)

5-5: Imported promise utilities from dedicated package.

You've added the necessary imports from @whatwg-node/promise-helpers including MaybePromise, which was previously identified as missing and causing build failures. Good job addressing this issue.


8-8: Re-exported promise utilities for backward compatibility.

Re-exporting these functions maintains backward compatibility for other modules that may be importing these utilities from this file rather than directly from the new package.


450-450: Imported iterateAsyncVoid from dedicated package.

Replacing the local implementation with an import from the dedicated package helps with maintaining a single source of truth for promise-related utilities.


480-480: Updated parameter type to use MaybePromise.

Updating the parameter type from Promise<Response> | Response to MaybePromise<Response> provides better type safety and more clearly expresses the intent that this function can handle both promises and direct values.

packages/server/src/createServerAdapter.ts (5)

3-3: Imported promise helper utilities.

Added imports for both handleMaybePromise and MaybePromise from the dedicated promise helpers package, which will help simplify promise handling throughout this file.


205-210: Improved error handling in handleEarlyResponse.

Using handleMaybePromise for handling both promise and non-promise values eliminates potential edge cases in promise handling and ensures consistent error propagation.


273-293: Enhanced error handling in requestListener.

The nested handleMaybePromise calls create a clean chain of promise handling with proper error handling at each step. This ensures errors are appropriately caught and logged without interrupting the request flow.


327-346: Improved promise handling in handleUWS.

Similar to the requestListener function, this refactoring ensures consistent promise handling and error management when dealing with UWS responses, making the code more robust.


405-405: Updated return type to use MaybePromise.

The return type now accurately reflects that this function can return either a direct value or a promise, using the more expressive MaybePromise type from the new package.

packages/promise-helpers/src/index.ts (8)

1-2: Well-structured Generic Types
The definitions of MaybePromise and MaybePromiseLike are straightforward and neatly capture values that may or may not be wrapped in a promise. This pattern will help ensure flexible handling of both synchronous and asynchronous flows.


4-6: Utility Specialization
isPromise is a suitable convenience function building on isPromiseLike. This maintains readability in call sites that only need to confirm a full Promise.


8-12: Checks for then Presence
Using (value as TPromiseLike)?.then != null is a succinct way to detect promise-like objects. The approach seems consistent and minimal.


14-39: Flexible Promise-Like Handling
handleMaybePromiseLike correctly addresses both promise-like objects and immediate values, applying success or error transformations as needed. The layering of _handleMaybePromiseLike within a try-catch ensures synchronous exceptions are properly caught. This function appears robust for a variety of asynchronous patterns.


41-51: Convenient Wrapper
handleMaybePromise is a more specialized variant of handleMaybePromiseLike, defaulting to native Promise. This keeps the code DRY and simplifies usage in typical promise-based workflows.


90-94: Clear Deferred Interface
DeferredPromise neatly exposes the internal resolve and reject methods. This is a familiar pattern for capturing references to a promise’s resolution functions without special wrappers.


96-115: Conditionally Using Promise.withResolvers
createDeferredPromise checks for Promise.withResolvers, an experimental feature. Ensure your environment or build setup supports this. Otherwise, the fallback logic with a regular new Promise is correctly implemented.

Would you like to confirm compatibility in older Node versions or browsers? A simple approach is searching for usage references to see if it’s guarded or polyfilled.


117-142: Asynchronous Iteration
iterateAsyncVoid effectively processes iterable items in sequence, short-circuiting when stopEarly is invoked. This approach is straightforward and easy to follow, relying on handleMaybePromise for controlling asynchronous flow.

Copy link
Collaborator

@enisdenjo enisdenjo left a comment

Choose a reason for hiding this comment

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

Fine by me!

@ardatan ardatan merged commit 5cf6b2d into master Feb 25, 2025
1 check passed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/promise-helpers/src/index.ts (3)

8-12: Suggest verifying that then is indeed callable.

Currently, isPromiseLike checks whether value.then != null. For stricter type checking, consider verifying that then is a function:

-return (value as TPromiseLike)?.then != null;
+return typeof (value as TPromiseLike)?.then === 'function';

This helps ensure the object truly behaves like a promise.


53-88: Heed lint warning: Avoid assigning .then to plain objects.

The static analysis tool (lint/suspicious/noThenProperty) flags this as suspicious. While this custom “fake” promise may be intentional, it’s an uncommon pattern that can cause confusion or break third-party libraries expecting standard promise constructors. If possible, refactor to use real Promises or a minimal polyfill:

🧰 Tools
🪛 Biome (1.9.4)

[error] 60-60: Do not add then to an object.

(lint/suspicious/noThenProperty)


144-166: Again, address lint warning about .then property.

Similar to fakePromise, fakeRejectPromise attaches .then and others to a plain object. If this is strictly necessary, consider an explanatory comment or refactor to avoid potential pitfalls and confusion with native Promise semantics.

🧰 Tools
🪛 Biome (1.9.4)

[error] 149-149: Do not add then to an object.

(lint/suspicious/noThenProperty)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d63274a and 4b50396.

📒 Files selected for processing (1)
  • packages/promise-helpers/src/index.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/promise-helpers/src/index.ts

[error] 60-60: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 149-149: Do not add then to an object.

(lint/suspicious/noThenProperty)

⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: unit / node 23
  • GitHub Check: unit / deno
  • GitHub Check: unit / node 22
  • GitHub Check: esm
  • GitHub Check: unit / bun
  • GitHub Check: alpha / snapshot
  • GitHub Check: unit / node 20
  • GitHub Check: node-fetch (consumeBody)
  • GitHub Check: unit / node 18
  • GitHub Check: node-fetch (noConsumeBody)
  • GitHub Check: server (undici)
  • GitHub Check: lint
  • GitHub Check: e2e / azure-function
  • GitHub Check: server (ponyfill)
  • GitHub Check: prettier
  • GitHub Check: e2e / aws-lambda
  • GitHub Check: server (native)
  • GitHub Check: type check
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
packages/promise-helpers/src/index.ts (2)

14-39: Clarify synchronous vs. asynchronous error flow.

The synchronous try/catch in handleMaybePromiseLike won't handle errors thrown asynchronously within a Promise chain. If an asynchronous error occurs without an error callback, it may remain unhandled. Consider clearly documenting or testing this behavior to avoid confusion in callers.


96-115: Check availability of Promise.withResolvers.

Promise.withResolvers is not yet a standard API in all JavaScript runtimes. If this code runs in environments that do not support it, fallback or polyfill logic will be essential. Verify that build and runtime targets are compatible, and consider documenting this implementation detail.

@coderabbitai coderabbitai bot mentioned this pull request Mar 5, 2025
@ardatan ardatan deleted the introduce-promise-helpers branch May 12, 2025 16:19
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