feat: add unit tests for RelayClient#8
Conversation
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
|
Warning Review limit reached
Next review available in: 30 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughAdds the RelayClient TypeScript SDK, typed request and error contracts, package/build tooling, and Vitest coverage for requests, retries, authentication, polling, and validation. ChangesRelayClient SDK
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
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 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)
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()
7a75b73 to
e7481bd
Compare
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
There was a problem hiding this comment.
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
📒 Files selected for processing (11)
.prettierrceslint.config.jspackage.jsonsrc/client.tssrc/errors.tssrc/index.tssrc/types.tstests/client.test.tstsconfig.jsontsup.config.tsvitest.config.ts
🔗 Linked repositories identified
CodeRabbit considers these linked repositories for cross-repo context during reviews:
AOSSIE-Org/ThruBox-Server(manual)
- 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
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:
send,receive,delete,poll,health).fetchfunction natively (no network required to run the tests).Checklist
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
RelayClientto send, receive, delete messages, and check server health.