Skip to content

feat: add unit tests for RelayClient#8

Open
Atharva0506 wants to merge 5 commits into
AOSSIE-Org:mainfrom
Atharva0506:feat/add-tests
Open

feat: add unit tests for RelayClient#8
Atharva0506 wants to merge 5 commits into
AOSSIE-Org:mainfrom
Atharva0506:feat/add-tests

Conversation

@Atharva0506

@Atharva0506 Atharva0506 commented Jul 14, 2026

Copy link
Copy Markdown
Member

All tests mock the global fetch function — no network required.

Addressed Issues:

Fixes #(issue number)
Adds a comprehensive Vitest test suite to ensure the SDK correctly interacts with the server endpoints and handles errors robustly.

Screenshots/Recordings:

Additional Notes:

  • Tests success and error paths for all SDK methods (send, receive, delete, poll, health).
  • Mocks the global fetch function natively (no network required to run the tests).
  • Verifies edge cases (e.g., 404 on delete, 413 Payload Too Large, 429 Rate Limited).
  • Tests the AbortController timeout and exponential backoff retry mechanisms.

Checklist

  • My code follows the project's code style and conventions
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings or errors
  • I have joined the Discord server and I will share a link to this PR with the project maintainers there
  • I have read the Contributing Guidelines

⚠️ AI Notice - Important!

We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact.

Summary by CodeRabbit

  • New Features
    • Introduced a TypeScript SDK with a RelayClient to send, receive, delete messages, and check server health.
    • Added polling support with configurable intervals and a stop mechanism.
    • Implemented request timeouts, automatic retries, and base URL normalization.
  • New Error Handling
    • Added dedicated SDK error types for network issues, rate limits (including retry-after), unauthorized access, not found, and oversized payloads.
  • Tests
    • Added a comprehensive Vitest suite covering request/response flows, polling behavior, authentication, URL handling, retries, and error mapping.

Set up the TypeScript SDK build infrastructure, aligned with AOSSIE
npm package standards (IndexedDB-Import-Export reference):

- package.json: dual ESM/CJS, type:module, publishConfig for npm,
  bugs/homepage URLs, GPL-3.0 license, eslint + prettier deps
- tsconfig.json: strict mode with noUncheckedIndexedAccess,
  noUnusedLocals, noUnusedParameters
- tsup.config.ts: ESM + CJS output, sourcemaps, ES2020 target
- eslint.config.js: flat config with typescript-eslint
- .prettierrc: AOSSIE standard formatting rules
- vitest.config.ts: test runner configuration
Add the core SDK implementation — a zero-dependency TypeScript client
for the ThruBox Server relay:

- src/client.ts:  RelayClient class with send, receive, delete, poll,
                  health. Automatic retry with exponential backoff on
                  5xx/network errors. Configurable timeout via
                  AbortController.
- src/types.ts:   Message, CreateMessageParams, ClientOptions,
                  HealthResponse type definitions.
- src/errors.ts:  Typed error hierarchy (RelayError, NetworkError,
                  HttpError, RateLimitError, PayloadTooLargeError,
                  NotFoundError).
- src/index.ts:   Public API barrel export.
- client.ts: Validated and normalized baseUrl using URL parser
- client.ts: Rejected invalid timeout, retry, and polling values
- client.ts: Added onError callback to PollOptions to prevent swallowing errors
- client.ts: Used recursive setTimeout for polling to prevent overlapping requests
- client.ts: Fixed headers to only send application/json for POST/PUT/PATCH
- client.ts: Disabled automatic retries for non-idempotent POST requests
- client.ts: Wrapped fetch in try/finally to ensure timeout is cleared during body consumption
- client.ts: Added proper HTTP-date parsing for Retry-After headers
- vitest.config.ts / package.json: Added @vitest/coverage-v8 provider and coverage script
@github-actions github-actions Bot added no-issue-linked PR is not linked to any issue javascript JavaScript/TypeScript code changes tests Test file changes size/L Large PR (201-500 lines changed) repeat-contributor PR from an external contributor who already had PRs merged needs-review labels Jul 14, 2026
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Atharva0506, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 30 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9e7b59bb-3ec3-40b6-b1e5-e628f2be6b8e

📥 Commits

Reviewing files that changed from the base of the PR and between e7481bd and f7174e2.

📒 Files selected for processing (2)
  • src/client.ts
  • tests/client.test.ts

Walkthrough

Adds the RelayClient TypeScript SDK, typed request and error contracts, package/build tooling, and Vitest coverage for requests, retries, authentication, polling, and validation.

Changes

RelayClient SDK

Layer / File(s) Summary
Public contracts and error types
src/types.ts, src/errors.ts, src/index.ts
Defines exported message, client, polling, health, and typed relay error contracts, then exposes them through the package entrypoint.
Client operations and request handling
src/client.ts
Implements URL and option validation, message and health operations, polling, API-key headers, timeouts, HTTP error mapping, and retries.
Package and build configuration
package.json, tsconfig.json, tsup.config.ts, eslint.config.js, .prettierrc, vitest.config.ts
Configures package exports, TypeScript compilation, ESM/CJS builds, linting, formatting, test discovery, and coverage reporting.
RelayClient behavior tests
tests/client.test.ts
Validates endpoint requests, response handling, error mappings, retry behavior, API-key configuration, polling, and input validation.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant RelayClient
  participant RelayServer
  Caller->>RelayClient: Invoke client operation
  RelayClient->>RelayServer: Send HTTP request
  RelayServer-->>RelayClient: Return response or error status
  RelayClient-->>Caller: Return result or typed error
Loading

Suggested labels: Typescript Lang

Poem

A rabbit builds a relay road,
Where typed messages hop their load.
Retries bounce and timers chime,
Errors wear names, neat every time.
“Ship it!” cheers the bunny bright.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding unit tests for RelayClient.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor
Messages
📖

⚠️ PR Template Check

These are non-blocking, but please fix:

  • Please replace the placeholder Fixes #(issue number) with the actual issue number (e.g. Fixes #42).

  • Some required checklist items are not completed:

  • My PR addresses a single issue

Generated by 🚫 dangerJS against f7174e2

@coderabbitai coderabbitai 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.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/client.test.ts`:
- Around line 155-156: Extend the error-handling tests around the existing 401
case to cover 404 responses, invalid input validation, and request timeout
cancellation using AbortController. Assert the expected errors and cancellation
behavior, reusing the existing client and fetch-mocking setup.
- Around line 193-194: Extend the “should retry on 5xx errors” test in the
“retry logic” suite to verify exponential backoff durations, not only retry
count. Use vi.useFakeTimers() to control time, advance the timer by each
expected delay between retries, and assert that retries do not occur before
those delays; restore real timers after the test.
- Around line 254-288: Wrap the test body in a try/finally block and move
vi.useRealTimers() into the finally clause, preserving the existing polling
assertions and cleanup behavior while ensuring real timers are restored even
when an assertion fails.
- Around line 169-175: Refactor the receive error test around client.receive so
it no longer calls expect.fail inside the try block, which can be caught as if
it were the expected error. Use expect.assertions to require the two catch-block
assertions, while preserving validation that the error is a RelayRateLimitError
with retryAfter equal to 30.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e869778f-031c-4e7b-b1e1-db58c3bb1a0a

📥 Commits

Reviewing files that changed from the base of the PR and between b88e93d and 7a75b73.

📒 Files selected for processing (1)
  • tests/client.test.ts
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • AOSSIE-Org/ThruBox-Server (manual)

Comment thread tests/client.test.ts
Comment thread tests/client.test.ts
Comment thread tests/client.test.ts Outdated
Comment thread tests/client.test.ts
Adds a comprehensive Vitest test suite to ensure the SDK correctly
interacts with the server endpoints and handles errors robustly.

- Tests success and error paths for all SDK methods
- Verifies input validation and URL parsing
- Mocks the global fetch natively without network
- Verifies edge cases (404, 413, 429, AbortError cancellation)
- Tests the AbortController timeout and exponential backoff timings using vi.useFakeTimers()
@github-actions github-actions Bot added configuration Configuration file changes dependencies Dependency file changes size/XL Extra large PR (>500 lines changed) and removed size/L Large PR (201-500 lines changed) labels Jul 14, 2026
@socket-security

socket-security Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addednpm/​@​vitest/​coverage-v8@​3.2.7991007299100
Addednpm/​typescript-eslint@​8.64.01001007498100
Addednpm/​vitest@​3.2.7981007999100
Addednpm/​tsup@​8.5.1981009583100
Addednpm/​typescript@​5.9.31001009010090
Addednpm/​@​eslint/​js@​10.0.110010010093100
Addednpm/​prettier@​3.9.5961009498100
Addednpm/​eslint@​10.7.09810010097100

View full report

@coderabbitai coderabbitai 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.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@package.json`:
- Around line 1-65: Verify the package configuration preserves the
zero-runtime-dependency requirement: keep all listed tooling under
devDependencies and do not add a dependencies block. No changes are needed to
the current package.json dependency setup.

In `@src/client.ts`:
- Around line 161-165: Update the polling catch block around the onError
callback so errors are logged when options.onError is absent, while preserving
the existing callback behavior when provided. Normalize non-Error values
consistently before invoking the callback or fallback logger, and ensure polling
errors are never silently swallowed.
- Around line 293-296: Update the retry delay in the exponential backoff block
within the retry flow to add randomized jitter before the setTimeout call.
Preserve the existing exponential backoff base and maxRetries condition, while
ensuring concurrent clients do not retry at identical intervals.
- Around line 246-249: In the Retry-After handling block, replace parseInt-based
conversion with Number() so the entire header value must be numeric; retain the
existing NaN check and retryAfter assignment, allowing malformed values such as
“10abc” to proceed to the Date fallback logic.

In `@tests/client.test.ts`:
- Around line 321-326: Update the “should strip trailing slashes from base URL”
test to verify the normalized URL through the outgoing network request rather
than accessing RelayClient.baseUrl via an any assertion. Mock or capture the
request and assert its URL uses the trailing-slash-free base URL, preserving the
test’s behavioral coverage without breaking encapsulation.
- Around line 32-35: Update the beforeEach setup for the RelayClient tests to
call vi.resetAllMocks() instead of vi.clearAllMocks(), ensuring mock
implementations and call history are reset between tests, including the
persistent mockFetch configuration used by poll().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: aa00c784-b876-40ee-81b9-e6c7793fb8ef

📥 Commits

Reviewing files that changed from the base of the PR and between 7a75b73 and e7481bd.

📒 Files selected for processing (11)
  • .prettierrc
  • eslint.config.js
  • package.json
  • src/client.ts
  • src/errors.ts
  • src/index.ts
  • src/types.ts
  • tests/client.test.ts
  • tsconfig.json
  • tsup.config.ts
  • vitest.config.ts
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • AOSSIE-Org/ThruBox-Server (manual)

Comment thread package.json
Comment thread src/client.ts
Comment thread src/client.ts Outdated
Comment thread src/client.ts
Comment thread tests/client.test.ts
Comment thread tests/client.test.ts Outdated
- client: prevent swallowed polling exceptions by logging to console
- client: use Number() instead of parseInt() for Retry-After parsing
- client: add random jitter to exponential backoff delay
- tests: use vi.resetAllMocks() to fully reset implementations
- tests: test URL trailing slash handling via observable network calls
- tests: mock Math.random to stabilize exponential backoff assertions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

configuration Configuration file changes dependencies Dependency file changes javascript JavaScript/TypeScript code changes needs-review no-issue-linked PR is not linked to any issue repeat-contributor PR from an external contributor who already had PRs merged size/XL Extra large PR (>500 lines changed) tests Test file changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant