Skip to content

refactor(contract, server): improve lazy, naming, hidden, ...#214

Merged
dinwwwh merged 10 commits intomainfrom
refactor/server/lazy
Mar 10, 2025
Merged

refactor(contract, server): improve lazy, naming, hidden, ...#214
dinwwwh merged 10 commits intomainfrom
refactor/server/lazy

Conversation

@dinwwwh
Copy link
Copy Markdown
Member

@dinwwwh dinwwwh commented Mar 10, 2025

  • Improve lazy, no need FlatLazy anymore
  • Improve naming,
  • Improve hidden,

Summary by CodeRabbit

  • Documentation
    • Updated the connection status header in the event iterator docs for clearer descriptions.
  • Refactor
    • Streamlined internal routing, builder, and middleware systems to improve type safety, error mapping, and lazy-loading performance.
  • Tests
    • Expanded test coverage to validate enhanced router and procedure functionalities.
    • Introduced new tests for createAssertedLazyProcedure and createContractedProcedure.
    • Added tests for the getRouter, enhanceRouter, and other router utility functions.
  • Chores
    • Consolidated module exports and internal utilities for improved maintainability.

These improvements maintain existing functionality while enhancing stability and developer efficiency.

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 10, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
orpc ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 10, 2025 9:14am

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 10, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request refactors several TypeScript modules by renaming and replacing types and functions. Major changes include renaming “Adapted…” entities to “Enhanced…” and “adapt…” functions to “enhance…” across contract, server, and router modules. The revisions enforce immutability (using readonly arrays) and update function signatures—often by adding default empty objects for options. Several test files and helper modules were removed, and the public API of some modules was restructured with new exports.

Changes

Files (Grouped) Change Summary
apps/content/docs/client/event-iterator.md Updated section header from “Event Iterator Connection Status” to “Connection Status.”
packages/contract/src/…
(builder-variants.test-d.ts, builder-variants.ts, builder.test-d.ts, builder.ts, route.test.ts, route.ts, router.test-d.ts, index.ts, router-utils.test(.ts))
Replaced type imports and functions:
• Changed references from Adapted/AdaptContractRouter… and AdaptContractRouterOptions to Enhanced/EnhanceContractRouter… and EnhanceContractRouterOptions.
• Renamed adaptRoute to enhanceRoute.
• Added new export from index.ts for router-utils.
packages/openapi/src/adapters/… & generator.ts
(fetch/openapi-handler.ts, node/openapi-handler.ts, standard/openapi-matcher.ts, openapi-generator.ts)
Updated constructor signatures by switching type parameters (from Router<T, any> to Router<any, T>) and replaced conversion functions (convertPathToHttpPath → toHttpPath).
packages/server/src/…
(builder-variants.test-d.ts, builder-variants.ts, builder.test-d.ts, builder.ts, implementer-variants.test-d.ts, implementer.test-d.ts, implementer.ts, hidden.test.ts, hidden.ts, router-hidden., router-utils., router.test-d.ts)
Replaced adaptRouter with enhanceRouter throughout.
• Updated spy functions and type assertions to use EnhancedRouter.
• Enforced readonly string[] for path parameters.
• Removed legacy files (hidden, lazy-utils, router-accessible-lazy).
packages/standard-server-fetch/src/…
(body.ts, event-iterator.ts, request.ts, response.ts)
Modified function signatures by making the options parameter optional (defaulted to an empty object).
packages/standard-server-node/src/…
(body.ts, event-iterator.ts, response.ts)
Similar adjustments to default options for functions handling HTTP body, event streaming, and response sending.
packages/zod/src/coercer.ts Changed class implementation to use HandlerPlugin instead of Plugin.
packages/server/tests/shared.ts Updated exports: renamed router as “contract” and exported ping/pong as pingContract/pongContract.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Builder
    participant RouterUtils
    Client->>Builder: Invoke router() / lazy() methods
    Builder->>RouterUtils: Call enhanceRouter(router, options)
    RouterUtils-->>Builder: Return EnhancedRouter instance
    Builder-->>Client: Provide EnhancedRouter for further operations
Loading

Possibly related PRs

  • unnoq/orpc#212: Updates documentation and parameter restructuring for the onEventIteratorStatusChange function, aligning with the changes in terminology and usage adopted here.

Poem

I'm a little rabbit on the run,
Enhancing our code is so much fun.
We hop from Adapt to Enhanced with glee,
Making our routers strong and type-safe as can be.
With readonly paths and defaults in place,
Our refactored code wins the race.
Hop along and enjoy this swift, new pace!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

 ERR_PNPM_OPTIONAL_DEPS_REQUIRE_PROD_DEPS  Optional dependencies cannot be installed without production dependencies


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 78aad21 and 626b04d.

📒 Files selected for processing (2)
  • packages/contract/src/router.test-d.ts (2 hunks)
  • packages/server/src/implementer.test.ts (4 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

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.

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new bot commented Mar 10, 2025

Open in Stackblitz

More templates

@orpc/client

npm i https://pkg.pr.new/@orpc/client@214

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@214

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@214

@orpc/openapi-client

npm i https://pkg.pr.new/@orpc/openapi-client@214

@orpc/react-query

npm i https://pkg.pr.new/@orpc/react-query@214

@orpc/server

npm i https://pkg.pr.new/@orpc/server@214

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@214

@orpc/standard-server

npm i https://pkg.pr.new/@orpc/standard-server@214

@orpc/standard-server-node

npm i https://pkg.pr.new/@orpc/standard-server-node@214

@orpc/standard-server-fetch

npm i https://pkg.pr.new/@orpc/standard-server-fetch@214

@orpc/vue-colada

npm i https://pkg.pr.new/@orpc/vue-colada@214

@orpc/vue-query

npm i https://pkg.pr.new/@orpc/vue-query@214

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@214

commit: 626b04d

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 10, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

@dinwwwh dinwwwh marked this pull request as ready for review March 10, 2025 08:21
@dinwwwh dinwwwh changed the title refactor(contract, server): many improvements refactor(contract, server): improve lazy, naming, hidden, ... Mar 10, 2025
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (8)
packages/server/src/router-hidden.ts (1)

19-21: Consider adding type safety for the contract access

The function uses a type assertion (router as any) which bypasses TypeScript's type checking. While this may be necessary for the symbol access pattern, consider if there's a more type-safe approach.

 export function getHiddenRouterContract(router: Lazyable<AnyRouter | AnyContractRouter>): AnyContractRouter | undefined {
-  return (router as any)[HIDDEN_ROUTER_CONTRACT_SYMBOL]
+  // Use a more type-safe approach that still allows symbol access
+  return Reflect.get(router, HIDDEN_ROUTER_CONTRACT_SYMBOL) as AnyContractRouter | undefined
 }
packages/contract/src/router-utils.ts (1)

17-38: Refine enumerability and type safety.
Consider using Object.keys(...) to avoid enumerating inherited properties if that behavior is unwanted. Additionally, removing the as any cast might preserve stronger type safety if feasible.

packages/server/src/procedure-utils.ts (1)

11-27: Lazy procedure assertion is well-structured.
The error message is descriptive, though you might consider tailoring it further if end users are likely to see it. Otherwise, this provides a safe fallback if the unwrapped value is not a procedure.

packages/server/src/builder.test.ts (1)

223-226: Consider adding negative test scenarios for rejected promises.
The .resolves assertion is correct for success cases; adding a test for promise rejection would enhance coverage.

packages/openapi/src/adapters/standard/openapi-matcher.ts (1)

16-16: Consider extracting the inline type into a named interface.
Currently, the inlined type LazyTraverseContractProceduresOptions & { httpPathPrefix: HTTPPath; laziedPrefix: string | undefined } might obscure readability. Defining a named interface or type alias for this structure would improve clarity.

packages/server/src/router-utils.ts (2)

74-97: EnhancedRouter type is comprehensive.
The generics are quite extensive. Adding explanatory comments or documentation near this definition could help future contributors understand the layered types.


151-207: traverseContractProcedures iteration.
Using for (const key in currentRouter) may iterate inherited properties. Prefer Object.keys(currentRouter) if inheritance is not intended. This can reduce potential edge cases.

packages/server/src/implementer.ts (1)

107-108: Consider refactoring the repeated logic in this block.
The code within the router branch is nearly identical to the lazy branch (lines 119-120). Extracting a helper function would reduce duplication and improve maintainability.

+function enhanceAndSetHidden(
+  router: AnyRouter,
+  contract: AnyContractRouter,
+  middlewares: AnyMiddleware[],
+) {
+  const adapted = enhanceRouter(router, {
+    middlewares,
+    errorMap: {},
+    prefix: undefined,
+    tags: undefined,
+  })
+  return setHiddenRouterContract(adapted, contract)
+}

...

     else if (key === 'router') {
-      const adapted = enhanceRouter(router, {
-        middlewares,
-        errorMap: {},
-        prefix: undefined,
-        tags: undefined,
-      })
-      return setHiddenRouterContract(adapted, contract)
+      return enhanceAndSetHidden(router, contract, middlewares)
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 371be67 and c495df6.

📒 Files selected for processing (80)
  • apps/content/docs/client/event-iterator.md (1 hunks)
  • packages/contract/src/builder-variants.test-d.ts (2 hunks)
  • packages/contract/src/builder-variants.ts (3 hunks)
  • packages/contract/src/builder.test-d.ts (2 hunks)
  • packages/contract/src/builder.test.ts (2 hunks)
  • packages/contract/src/builder.ts (2 hunks)
  • packages/contract/src/index.ts (1 hunks)
  • packages/contract/src/route.test.ts (3 hunks)
  • packages/contract/src/route.ts (1 hunks)
  • packages/contract/src/router-utils.test-d.ts (1 hunks)
  • packages/contract/src/router-utils.test.ts (1 hunks)
  • packages/contract/src/router-utils.ts (1 hunks)
  • packages/contract/src/router.test-d.ts (2 hunks)
  • packages/contract/src/router.test.ts (0 hunks)
  • packages/contract/src/router.ts (2 hunks)
  • packages/openapi/src/adapters/fetch/openapi-handler.ts (1 hunks)
  • packages/openapi/src/adapters/node/openapi-handler.ts (1 hunks)
  • packages/openapi/src/adapters/standard/openapi-matcher.ts (4 hunks)
  • packages/openapi/src/openapi-generator.ts (2 hunks)
  • packages/server/src/adapters/fetch/rpc-handler.ts (1 hunks)
  • packages/server/src/adapters/node/rpc-handler.ts (1 hunks)
  • packages/server/src/adapters/standard/handler.ts (3 hunks)
  • packages/server/src/adapters/standard/rpc-matcher.ts (4 hunks)
  • packages/server/src/adapters/standard/types.ts (1 hunks)
  • packages/server/src/builder-variants.test-d.ts (17 hunks)
  • packages/server/src/builder-variants.ts (4 hunks)
  • packages/server/src/builder.test-d.ts (7 hunks)
  • packages/server/src/builder.test.ts (2 hunks)
  • packages/server/src/builder.ts (3 hunks)
  • packages/server/src/hidden.test.ts (0 hunks)
  • packages/server/src/hidden.ts (0 hunks)
  • packages/server/src/implementer-procedure.test-d.ts (5 hunks)
  • packages/server/src/implementer-variants.test-d.ts (4 hunks)
  • packages/server/src/implementer-variants.ts (2 hunks)
  • packages/server/src/implementer.test-d.ts (5 hunks)
  • packages/server/src/implementer.test.ts (3 hunks)
  • packages/server/src/implementer.ts (3 hunks)
  • packages/server/src/index.ts (1 hunks)
  • packages/server/src/lazy-utils.test-d.ts (0 hunks)
  • packages/server/src/lazy-utils.test.ts (0 hunks)
  • packages/server/src/lazy-utils.ts (0 hunks)
  • packages/server/src/lazy.test.ts (1 hunks)
  • packages/server/src/lazy.ts (1 hunks)
  • packages/server/src/middleware-utils.ts (2 hunks)
  • packages/server/src/middleware.test-d.ts (1 hunks)
  • packages/server/src/middleware.ts (1 hunks)
  • packages/server/src/plugins/base.ts (1 hunks)
  • packages/server/src/plugins/cors.ts (2 hunks)
  • packages/server/src/plugins/response-headers.ts (1 hunks)
  • packages/server/src/procedure-client.test-d.ts (1 hunks)
  • packages/server/src/procedure-client.ts (2 hunks)
  • packages/server/src/procedure-decorated.test-d.ts (2 hunks)
  • packages/server/src/procedure-utils.test.ts (1 hunks)
  • packages/server/src/procedure-utils.ts (1 hunks)
  • packages/server/src/procedure.test.ts (1 hunks)
  • packages/server/src/procedure.ts (1 hunks)
  • packages/server/src/router-accessible-lazy.test-d.ts (0 hunks)
  • packages/server/src/router-accessible-lazy.test.ts (0 hunks)
  • packages/server/src/router-accessible-lazy.ts (0 hunks)
  • packages/server/src/router-client.ts (3 hunks)
  • packages/server/src/router-hidden.test.ts (1 hunks)
  • packages/server/src/router-hidden.ts (1 hunks)
  • packages/server/src/router-utils.test-d.ts (1 hunks)
  • packages/server/src/router-utils.test.ts (1 hunks)
  • packages/server/src/router-utils.ts (1 hunks)
  • packages/server/src/router.test-d.ts (2 hunks)
  • packages/server/src/router.test.ts (0 hunks)
  • packages/server/src/router.ts (1 hunks)
  • packages/server/src/utils.test.ts (1 hunks)
  • packages/server/src/utils.ts (1 hunks)
  • packages/server/tests/shared.ts (1 hunks)
  • packages/standard-server-fetch/playground/event-source.ts (1 hunks)
  • packages/standard-server-fetch/src/body.ts (1 hunks)
  • packages/standard-server-fetch/src/event-iterator.ts (1 hunks)
  • packages/standard-server-fetch/src/request.ts (1 hunks)
  • packages/standard-server-fetch/src/response.ts (1 hunks)
  • packages/standard-server-node/src/body.ts (1 hunks)
  • packages/standard-server-node/src/event-iterator.ts (1 hunks)
  • packages/standard-server-node/src/response.ts (1 hunks)
  • packages/zod/src/coercer.ts (2 hunks)
💤 Files with no reviewable changes (10)
  • packages/server/src/router-accessible-lazy.test-d.ts
  • packages/server/src/router-accessible-lazy.test.ts
  • packages/server/src/lazy-utils.test-d.ts
  • packages/server/src/hidden.ts
  • packages/server/src/lazy-utils.ts
  • packages/server/src/router-accessible-lazy.ts
  • packages/server/src/hidden.test.ts
  • packages/contract/src/router.test.ts
  • packages/server/src/router.test.ts
  • packages/server/src/lazy-utils.test.ts
🔇 Additional comments (197)
packages/openapi/src/adapters/fetch/openapi-handler.ts (1)

14-14: Confirm the reversed type parameters for the router.

Switching from Router<T, any> to Router<any, T> in the constructor may invert how context is inferred and used. Verify that this change aligns properly with other parts of the codebase (e.g., downstream references, tests, and usage patterns).

packages/standard-server-node/src/response.ts (1)

11-11: Adding a default value for options is beneficial.

Providing a default {} for the options parameter makes the function more convenient to call and reduces boilerplate. This looks good!

packages/contract/src/route.ts (3)

104-107: Renaming the route options interface aligns with the new enhancement approach.

Replacing AdaptRouteOptions with EnhanceRouteOptions reflects the larger shift from "adapt" to "enhance" in the codebase. Make sure all references are updated accordingly.


109-109: Function renamed to enhanceRoute.

The rename from adaptRoute to enhanceRoute is consistent with the new naming convention. No immediate concerns here.


116-116: Use of options.tags?.length improves clarity.

Checking options.tags?.length ensures tags are only appended if defined and non-empty, preventing accidental handling of undefined or empty arrays.

packages/server/src/router.ts (9)

1-1: Refined imports from '@orpc/contract'.

The trimmed imports make the file more focused. Confirm that no required types/functions are inadvertently removed.


3-4: Lazyable import introduced.

You’re importing Lazyable from ./lazy. Verify all references to the old lazy imports are replaced, and confirm consistency with the simplified router structure.


6-7: Router type logic updated.

Now the router logic is split between a procedure case and an object case. Validate that any shared code or calls to Router<T> are updated accordingly throughout the project.


10-10: Index signature for sub-routers.

The new index signature infers sub-router types if T[K] extends AnyContractRouter. Check for potential edge cases if T contains non-router fields.


15-15: Inferred initial context.

This specialized type logic helps unify how contexts are derived. Ensure no existing references rely on a previous approach to context inference.


20-24: Refactored InferRouterInitialContexts.

Switched to a clearer pattern that depends on Procedure<infer UInitialContext>. Please confirm usage in deeply nested or lazy-based routers remains correct.


27-31: Refactored InferRouterCurrentContexts.

Similarly, the current context is now pulled from Procedure<any, infer UCurrentContext>. Verify multi-layer or chained contexts still resolve as intended.


34-38: Refactored InferRouterInputs.

Taking SchemaInput<UInputSchema> from a procedure is more straightforward. If older code expected a different shape (especially with lazy usage), ensure it’s been updated.


40-46: Refactored InferRouterOutputs.

Leveraging SchemaOutput<UOutputSchema, UFuncOutput> clarifies the final structure for outputs. Confirm that test coverage is updated to reflect these new inferences.

packages/contract/src/router.test-d.ts (3)

3-4: LGTM: Updated type imports

The import changes appropriately reflect the shift from "Adapted..." types to "Enhanced..." types as mentioned in the PR summary, focusing on the necessary type imports for the updated tests.


7-11: LGTM: Simplified test structure

The test suite has been streamlined by consolidating the "meta" tests into a single more focused test case, which improves readability while still effectively testing the type compatibility.


43-45: LGTM: New type inference test

This new test appropriately validates the type inference for the router meta, ensuring it matches the expected BaseMeta | Meta type.

packages/contract/src/index.ts (1)

14-14: LGTM: Added router-utils export

The addition of the router-utils export aligns with the PR objectives of refactoring and improving naming conventions. This makes the enhanced router functionality available through the main package entry point.

apps/content/docs/client/event-iterator.md (1)

74-74: LGTM: Simplified section header

The simplified section header "Connection Status" improves readability while still clearly indicating the purpose of this section, which focuses on tracking the connection status of event iterators.

packages/server/src/middleware.ts (1)

33-33: LGTM: Enhanced type safety with readonly path

Changing the path property type from string[] to readonly string[] improves type safety by enforcing immutability of the path array. This prevents accidental mutations and aligns with similar changes across the codebase.

packages/standard-server-fetch/playground/event-source.ts (1)

38-42: Simplified function call by removing unnecessary parameter

The empty object parameter has been removed from the toFetchResponse call, which aligns with updates made elsewhere in the codebase. The toFetchResponse function now has a default empty object parameter in its definition, making this change both cleaner and more consistent.

packages/server/src/lazy.test.ts (4)

2-2: LGTM: Updated imports to include new getLazyMeta function

The import statement has been correctly updated to include the new getLazyMeta function.


4-5: Good enhancement to test coverage

The test description has been updated to include the new getLazyMeta function, and the lazy function is now called with metadata ({ prefix: '/adapt' }), which allows for testing the new metadata functionality.


8-8: LGTM: Added test for new metadata functionality

This assertion validates that the new getLazyMeta function correctly retrieves the metadata object passed to the lazy function.


12-12: Expanded test coverage for unlazy function

This new assertion tests the behavior of unlazy when called with a primitive value, ensuring it gets properly wrapped in a default object.

packages/server/src/procedure-client.test-d.ts (1)

106-106: Enhanced type safety with readonly array

The type assertion has been improved to expect readonly string[] for the path parameter, enforcing immutability. This is consistent with similar changes made across other files in the codebase and helps prevent accidental mutations of the path array.

packages/server/src/router-hidden.test.ts (1)

1-9: LGTM: Good test coverage for new hidden router contract functionality

This new test file provides adequate coverage for the hidden router contract functionality. It verifies both setting and retrieving the hidden contract, ensuring that the original router is returned by setHiddenRouterContract and that the original contract can be retrieved using getHiddenRouterContract.

packages/server/src/middleware.test-d.ts (1)

20-20: Improved type safety with readonly array

The change from string[] to readonly string[] enhances type safety by ensuring the path array cannot be modified within middleware functions. This aligns with the immutability pattern being applied consistently across the codebase.

packages/server/tests/shared.ts (1)

58-58: Clean re-exports with descriptive aliases

This new export statement re-exports entities from the contract test shared module with more descriptive aliases that clarify their origin. The renaming follows the pattern mentioned in the PR summary where components are being renamed for better clarity.

packages/server/src/procedure.ts (1)

16-16: Enhanced immutability with readonly path array

Changing path: string[] to path: readonly string[] prevents procedure handlers from accidentally modifying the path array. This is a good practice for ensuring immutability of input parameters and maintaining predictable behavior.

packages/server/src/adapters/standard/types.ts (1)

10-10: Consistent immutability pattern for path arrays

The change to readonly string[] aligns with the same pattern applied to path arrays throughout the codebase. This consistency improves type safety and prevents unintended modifications to path data.

packages/standard-server-fetch/src/response.ts (1)

11-11: Good improvement to the API ergonomics

Making the options parameter optional with a default empty object is a good practice that improves the API's usability by allowing the function to be called without explicitly passing options when the defaults are sufficient.

packages/standard-server-node/src/body.ts (1)

62-62: Good improvement to the API ergonomics

Adding a default empty object for the options parameter makes the function more flexible and easier to use. This change is consistent with similar improvements in other parts of the codebase and follows good API design practices.

packages/contract/src/route.test.ts (2)

1-1: Consistent renaming from "adapt" to "enhance"

The import and test name have been updated to use enhanceRoute instead of adaptRoute, which aligns with the broader refactoring effort to improve naming conventions throughout the codebase.

Also applies to: 32-32


39-46: Improved test clarity with explicit undefined parameters

The test cases now explicitly specify undefined for optional parameters rather than omitting them. This improves test readability by making it clear which parameters are intentionally not provided versus those that might have been accidentally omitted.

Also applies to: 48-55, 57-64, 66-69

packages/server/src/adapters/fetch/rpc-handler.ts (1)

14-14:

Details

✅ Verification successful

Type parameter order change and optional options parameter

Two changes have been made to this constructor:

  1. The type parameters for Router have been swapped from Router<T, any> to Router<any, T>, reflecting a change in the underlying Router type definition
  2. The options parameter is now optional with a default empty object

This change aligns with the broader refactoring effort and improves the API's usability.


🏁 Script executed:

#!/bin/bash
# Verify that the Router type parameters have been consistently updated
echo "Checking Router type definition..."
grep -n "export type Router" packages/server/src/router.ts

Length of output: 224


Action: Approve Constructor and Router Changes

The constructor update in packages/server/src/adapters/fetch/rpc-handler.ts now accepts a Router with type parameters in the new order (Router<any, T>) and uses an optional options parameter (defaulting to an empty object). The router definition in packages/server/src/router.ts

export type Router<T extends AnyContractRouter, TInitialContext extends Context> =

—confirms that these changes are consistent with the updated type parameter order. No further adjustments are necessary.

packages/server/src/procedure.test.ts (1)

1-9: Good addition of contract procedure validation

This test suite addition nicely complements the existing test by verifying that ping not only satisfies the isProcedure predicate but also the isContractProcedure predicate from the contract package. This ensures proper type compatibility in the new enhancement-based approach.

packages/server/src/adapters/node/rpc-handler.ts (1)

14-14:

Details

✅ Verification successful

Modified router type parameter order

The router parameter type has changed from Router<T, any> to Router<any, T>, swapping the order of generic parameters. This aligns with the broader refactoring effort that changes "Adapted" entities to "Enhanced" entities throughout the codebase.


🏁 Script executed:

#!/bin/bash
# Check for consistent Router type parameter usage across the codebase
echo "Checking for consistent Router type parameter usage..."
rg "Router<any, \w+>" --type ts

Length of output: 975


Router Generic Parameters Order Verified

The change from Router<T, any> to Router<any, T> in packages/server/src/adapters/node/rpc-handler.ts aligns with the overall refactoring effort. Our repository search confirms that this new generic parameter order is consistently applied across multiple modules (such as in both the OpenAPI and RPC handlers), ensuring uniformity throughout the codebase.

packages/contract/src/router-utils.test-d.ts (1)

1-46: Well-structured type tests for EnhancedContractRouter

This new test file provides thorough type checking for the EnhancedContractRouter, validating both root and nested procedure types. The tests ensure that the enhanced router correctly preserves the expected types for input/output schemas, error maps, and metadata across different procedures.

The comprehensive type assertions verify the type safety of the refactored router enhancement functionality, which is crucial for this PR's transition from "Adapted..." to "Enhanced..." patterns.

packages/openapi/src/adapters/node/openapi-handler.ts (1)

14-14: Modified router type parameter order

The router parameter type has changed from Router<T, any> to Router<any, T>, consistent with the changes in other handler classes. This change is part of the broader refactoring to standardize the router type parameter ordering across the codebase.

packages/standard-server-fetch/src/request.ts (1)

27-27: Good improvement to function signature flexibility

Making the options parameter optional with a default empty object value improves the API by allowing callers to omit the parameter when default options are sufficient.

packages/server/src/procedure-decorated.test-d.ts (1)

103-103: Improved type safety with readonly arrays

Changing the type expectation from string[] to readonly string[] enforces immutability on the path parameter, which is a good practice to prevent accidental modifications of the array.

Also applies to: 140-140

packages/server/src/index.ts (1)

17-18: Module restructuring for better organization

Adding new exports for router-related utilities is part of the broader refactoring effort to improve code organization and naming conventions. These new exports likely replace the previous ones mentioned in the summary (such as hidden, lazy-utils, and router-accessible-lazy).

packages/server/src/implementer-procedure.test-d.ts (1)

73-73: Consistent enforcement of immutability

The type changes from string[] to readonly string[] across multiple test cases ensure that path parameters are consistently treated as immutable throughout the codebase, reinforcing type safety.

Also applies to: 110-110, 223-223, 263-263, 314-314

packages/standard-server-fetch/src/body.ts (1)

64-64: LGTM: Making options parameter optional improves API flexibility

Adding a default empty object for the options parameter is a good practice that simplifies the API usage. This change allows callers to omit the options parameter when default behavior is sufficient.

packages/contract/src/router-utils.test.ts (1)

1-25: Well-structured test for enhanceContractRouter

This test effectively validates that the enhancement process:

  1. Properly merges error maps
  2. Enhances routes with the provided options
  3. Maintains the nested structure of contract routers

The test coverage is thorough, checking both top-level and nested routes.

packages/contract/src/builder.test.ts (2)

5-5: LGTM: Updated import and spy to use new module naming convention

The change from Router to RouterUtilsModule and the corresponding spy update properly reflect the refactoring from "adapt" to "enhance" naming convention.

Also applies to: 7-7


129-131: LGTM: Updated test assertions to match new function name

These assertion changes correctly verify that the new enhanceContractRouter function is called with the expected parameters.

packages/standard-server-node/src/event-iterator.ts (1)

96-96: LGTM: Adding default value for options parameter improves API

Making the options parameter optional with a default empty object is a good change that simplifies API usage without changing functionality. The function already handles missing options properties with null coalescing operators (lines 98-100).

packages/server/src/router-hidden.ts (3)

1-4: Clean imports with good type definitions

The imports are well-organized and correctly specify the types needed for the router contract functionality.


5-5: Good use of Symbol for private implementation detail

Using a Symbol for the hidden contract property ensures it won't conflict with other router properties and won't be enumerable in standard property iterations.


7-17: Well-implemented proxy pattern for contract hiding

The setHiddenRouterContract function uses the Proxy pattern effectively to intercept property access. The implementation is clean and maintains the original object's behavior for all properties except the special symbol key.

packages/standard-server-fetch/src/event-iterator.ts (1)

95-95: Good improvement to function usability

Adding a default empty object for the options parameter is a good improvement. This makes the function more user-friendly by allowing it to be called without explicitly passing options, while maintaining the same functionality since the code already handles defaults for individual options.

packages/server/src/utils.test.ts (2)

1-1: Consistent naming with implementation

Updating the import from convertPathToHttpPath to toHttpPath maintains consistency with the implementation changes and improves the naming convention.


4-6: Test updated correctly for renamed function

The test cases have been properly updated to use the toHttpPath function instead of convertPathToHttpPath while maintaining the same test coverage and assertions.

packages/zod/src/coercer.ts (2)

2-2: Updated import for renamed interface

The import has been correctly updated to use HandlerPlugin instead of Plugin, consistent with the broader renaming in the codebase.


32-32: Interface implementation updated correctly

The class implementation has been properly updated to implement HandlerPlugin<TContext> instead of Plugin<TContext>, maintaining the same functionality while using the new interface name.

packages/server/src/router-utils.test-d.ts (2)

1-17: Well-structured test for AccessibleLazyRouter type checking

The test for AccessibleLazyRouter properly verifies that both direct and nested methods are correctly typed as lazy versions of their respective procedures. This ensures type safety when accessing methods through the AccessibleLazyRouter type.


19-76: Comprehensive type checking for EnhancedRouter

The test for EnhancedRouter thoroughly validates the complex type structure, including:

  • Proper context type inheritance (InitialContext → CurrentContext)
  • Correct schema propagation for input and output
  • Error map merging (custom TErrorMap with baseErrorMap)
  • Metadata inheritance
  • Proper handling of nested lazy procedures

This ensures type safety across all router operations, which is essential for the refactoring from "Adapted" to "Enhanced" router patterns.

packages/server/src/plugins/cors.ts (1)

4-4: Interface rename from Plugin to HandlerPlugin

This change reflects a broader refactoring in the codebase to rename the Plugin interface to HandlerPlugin, making the naming more explicit about its purpose. The functionality remains the same, only the interface name has changed.

Also applies to: 17-17

packages/contract/src/builder-variants.ts (2)

5-6: Updated imports to use EnhancedContractRouter

The imports have been updated to use the new EnhancedContractRouter and EnhanceContractRouterOptions types from the router-utils module, which aligns with the PR objective of renaming from "Adapted" to "Enhanced" patterns.


105-105: Changed router options and return types to Enhanced versions

The builder's ~orpc property and the return type of the router method have been updated to use the Enhanced versions instead of Adapted versions, completing the transition to the new naming scheme.

Also applies to: 115-115

packages/contract/src/builder.test-d.ts (1)

6-6: Updated type assertions for EnhancedContractRouter

The type expectations have been properly updated to verify against EnhancedContractRouter instead of AdaptedContractRouter, maintaining type safety during the refactoring process.

Also applies to: 137-139

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

4-4: Interface renamed from Plugin to HandlerPlugin.

The interface has been renamed from Plugin to HandlerPlugin, which better reflects its specific purpose in the handler context. This naming change improves code clarity and makes the API more self-explanatory.


8-9: CompositePlugin implementation updated to use HandlerPlugin.

The CompositePlugin class has been properly updated to implement the new HandlerPlugin interface and use it for the plugins array type. This change maintains consistency with the renaming pattern introduced in this PR.

packages/server/src/adapters/standard/handler.ts (3)

5-5: Import updated from Plugin to HandlerPlugin.

The import has been updated to use the renamed HandlerPlugin interface, maintaining consistency with the changes in the plugins base file.


25-25: StandardHandlerOptions updated to use HandlerPlugin.

The plugins property type has been updated from Plugin to HandlerPlugin, ensuring consistency with the interface renaming changes.


52-52:

Details

✅ Verification successful

Router type parameters swapped in constructor.

The order of type parameters for Router has been changed from Router<T, any> to Router<any, T>. This is a significant change that suggests the Router generic parameters have been reordered in its definition.

Please confirm that this change in type parameter order has been consistently applied throughout the codebase, particularly in other handlers that use Router. Inconsistent application could lead to type errors.


🏁 Script executed:

#!/bin/bash
# Check for other uses of Router type across the codebase
rg 'Router<' --type ts | grep -v 'Router<any, T>' | grep -v "packages/server/src/adapters/standard/handler.ts"

Length of output: 7921


Router parameter order verified and consistent throughout the codebase.
I checked other occurrences in files such as packages/server/src/implementer.ts, packages/server/src/builder.ts, and the corresponding tests. Although the type variable names differ (for example, some use T vs. any or TCurrentContext vs. InitialContext), all usages follow the same ordering—first parameter representing the contract router type and second representing the context type. No inconsistent usages were found.

packages/server/src/plugins/response-headers.ts (2)

3-3: Import updated from Plugin to HandlerPlugin.

The import has been updated to use the renamed HandlerPlugin interface, maintaining consistency with the changes in the plugins base file.


9-9: ResponseHeadersPlugin implementation updated to use HandlerPlugin.

The ResponseHeadersPlugin class has been properly updated to implement the new HandlerPlugin interface, maintaining consistency with the renaming pattern introduced in this PR.

packages/server/src/procedure-utils.test.ts (3)

1-7: New imports added for testing new functionality.

The imports have been expanded to include necessary dependencies for testing the newly added functions createAssertedLazyProcedure and createContractedProcedure. This ensures that all required components are available for the new tests.


14-19: Good test coverage for createAssertedLazyProcedure.

The test for createAssertedLazyProcedure properly verifies both the success case (with a valid procedure) and the error case (with an invalid procedure). The test ensures that the function correctly validates that a lazy-loaded value is a procedure.


21-45: Thorough test for createContractedProcedure.

The test for createContractedProcedure verifies that the function correctly creates a Procedure instance and preserves the required properties. The test uses a mismatch path object to ensure that property overriding works correctly while preserving the original procedure's properties.

packages/contract/src/router-utils.ts (2)

6-12: Robust use of recursive TypeScript transformations.
Your approach to merging error maps using advanced TS generics is well-structured, ensuring flexibility for future extensions.


13-15: Interface extension is sensible.
The EnhanceContractRouterOptions interface neatly extends EnhanceRouteOptions to unify router and route transformations.

packages/server/src/procedure-client.ts (2)

36-36: Immutability enhancement.
Using readonly string[] for path helps prevent accidental mutations in interceptor options.


58-58: Consistent immutability for path property.
Changing the optional path to readonly string[] aligns with best practices for safer type usage.

packages/server/src/procedure-utils.ts (2)

2-2: Import adjustments look consistent.
These type import changes clarify usage without bloating the bundle.

Also applies to: 5-5, 7-7, 8-8


29-40: Straightforward contract merge.
createContractedProcedure cleanly merges the ~orpc properties between procedures and contracts, promoting consistency.

packages/server/src/builder.test.ts (3)

11-11: Spy creation appears consistent.
Switching to enhanceRouter aligns well with the updated approach.


215-217: Tests validate the new router enhancement correctly.
Verifying the returned object and call arguments looks good.


8-8:

Details

❓ Verification inconclusive

Confirm all references to the old router are removed.
The new import for router-utils is aligned with the refactor. Kindly verify there are no dangling references to ./router.

Run the following script to confirm:


🏁 Script executed:

#!/bin/bash
# Searching for any leftover references to "import * as Router from './router'"
rg "import\s+\*\s+as\s+Router\s+from\s+'\.\/router'"

Length of output: 212


Attention: Manual Verification Needed for Router References

The original regex in the verification script failed due to escaping issues. Please re-run the following updated script to ensure that all references to the old router ('./router') have been removed:

#!/bin/bash
# Searching for any leftover references to "import * as Router from './router'" using corrected escapes
rg "import\\s+\\*\\s+as\\s+Router\\s+from\\s+'\\.\\/router'"

Once confirmed that this command produces no output, you'll have verified that the new router-utils import is in place with no lingering references to the old router module.

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

1-3: Immutable path signature is a welcome improvement.
Renaming and using readonly string[] preserves immutability and consistency with the refactoring effort.

packages/openapi/src/openapi-generator.ts (3)

7-8: Import statements align with the new utilities.
Switching to toHttpPath and resolveContractProcedures is consistent with the refactor.


36-36: Refactor uses resolveContractProcedures effectively.
Replaces eachAllContractProcedure with an updated approach, ensuring clarity in procedure resolution.


43-43: Path conversion function updated consistently.
The switch to toHttpPath removes potential confusion from the old convertPathToHttpPath name.

packages/contract/src/builder-variants.test-d.ts (2)

6-6: Type import renamed from AdaptedRouter to EnhancedRouter

This change reflects the broader refactoring effort to rename "Adapted..." entities to "Enhanced..." across the codebase, improving the naming conventions as mentioned in the PR objectives.


313-315: Return type updated to use EnhancedContractRouter

The return type for the .router method has been updated from AdaptedContractRouter to EnhancedContractRouter, maintaining consistency with the renamed type imports.

packages/contract/src/builder.ts (4)

3-4: Added import for ContractRouter type

The explicit import of the ContractRouter type improves code clarity and maintainability.


9-9: Updated imports to use enhance-prefixed functions and types

Replaced imports for adapt-prefixed functions and types with their enhance-prefixed equivalents, maintaining consistency with the naming convention changes throughout the codebase.


16-16: Updated interface extension from AdaptRouterOptions to EnhanceContractRouterOptions

This change ensures the BuilderDef interface uses the renamed router enhancement options, aligning with the PR's naming convention improvements.


117-119: Updated router method signature and implementation

Changed method signature to return EnhancedContractRouter instead of AdaptedRouter and implementation to use enhanceContractRouter instead of adaptRouter. This maintains functional equivalence while improving naming clarity.

packages/server/src/router-utils.test.ts (5)

1-6: Well-structured imports for the new test file

The imports are organized logically, bringing in all necessary functions and test fixtures for comprehensive testing of the router utilities.


7-20: Comprehensive tests for getRouter function

Good test coverage for the getRouter function, testing various scenarios including:

  • Getting the root router
  • Getting an existing route
  • Getting a lazy-loaded route
  • Handling non-existent routes
  • Edge cases with dot notation paths

This ensures the function behaves correctly in all expected use cases.


22-76: Thorough test suite for enhanceRouter function

The tests comprehensively verify the enhanceRouter functionality:

  • Verifying middleware application
  • Ensuring route enhancement with prefixes and tags
  • Checking preservation of validation indices
  • Testing lazy-loading behavior
  • Verifying prefix merging in nested enhancement scenarios

This level of testing is crucial for ensuring the reliability of the router enhancement mechanism.


78-159: Complete testing of traverseContractProcedures

Tests cover all important use cases:

  • Traversal with contract objects
  • Traversal with router objects
  • Traversal with hidden contracts

The verification of callback invocation with correct path arguments ensures the traversal logic works as expected.


161-190: Effective tests for resolveContractProcedures

These tests verify the asynchronous resolution of contract procedures, including:

  • Calling the callback with the correct contract and path
  • Proper handling of lazy-loaded contracts
  • Correct resolution of nested contracts

This ensures that the contract resolution mechanism works correctly with various nesting levels and lazy loading.

packages/server/src/builder-variants.test-d.ts (4)

11-11: Updated import to use EnhancedRouter

This change maintains consistency with the renaming pattern applied across the codebase, replacing "Adapted" with "Enhanced" in type names.


75-75: Enhanced type safety with readonly string arrays

Changed the type of path parameters from string[] to readonly string[], which prevents accidental mutation of path arrays. This is a good practice for improving type safety, especially for parameters that shouldn't be modified.

Also applies to: 179-179, 426-426, 542-542, 718-718, 806-806, 886-886, 926-926, 1009-1009


203-268: Added test coverage for new builder methods

New tests for the .prefix, .tag, .router, and .lazy methods on the BuilderWithMiddlewares class ensure that:

  • Methods return the correct types
  • Type checking properly validates input parameters
  • Error cases are properly caught by TypeScript
  • Integration with the enhanced router system works correctly

This significantly improves the test coverage for the builder's functionality.


1072-1073: Updated return type assertions for router and lazy methods

Changed the expected return types from AdaptedRouter to EnhancedRouter, maintaining consistency with the renamed router enhancement system throughout the codebase.

Also applies to: 1096-1097

packages/server/src/implementer.test.ts (5)

7-8: Module imports renamed to match new architecture

These imports were updated to reflect the refactored module structure - moving from hidden to router-hidden and introducing the new router-utils module, which aligns with the PR's objectives of improving naming conventions.


10-12: Spy functions updated to reflect renamed methods

The spy functions have been updated to match the renamed module exports:

  • setHiddenRouterContractSpy replaces previous setRouterContractSpy
  • enhanceRouterSpy replaces previous adaptRouterSpy

This is consistent with the PR goal of renaming "adapt..." functions to "enhance..." across the codebase.


64-69: Test expectations updated to use renamed router functions

The test assertions have been updated to use getHiddenRouterContract instead of getRouterContract and verify that setHiddenRouterContractSpy was called with the enhanced router value. This properly validates the behavior of the refactored implementation.


70-74: Router enhancement verification updated

The test now verifies the enhanceRouter function was called with the correct parameters, maintaining test coverage of the refactored implementation while using the new naming convention.


80-90: Similar updates applied to lazy router test

The same pattern of renamed function calls is consistently applied to the lazy router test, ensuring all code paths continue to be properly tested after the refactoring.

packages/server/src/router.test-d.ts (5)

1-2: Updated imports to match new type structure

The imports have been updated to:

  1. Remove deprecated types (MergedErrorMap, baseErrorMap, etc.)
  2. Add the new ContractRouter type
  3. Include additional router-related type utilities

This aligns with the PR's objective of improving the type system and naming conventions.

Also applies to: 5-5


9-21: Rewritten contract router type test

The previous test has been replaced with a more focused test that verifies router compatibility with the ContractRouter type. This better aligns with the refactored architecture where "Enhanced..." replaces "Adapted..." entities.


23-28: Enhanced initial context type tests

The tests for initial context have been improved to:

  1. Check compatibility with the base InitialContext
  2. Check compatibility with extended contexts (adding optional properties)
  3. Verify incompatibility with contexts missing required properties or having incorrect types

This provides more thorough type-checking coverage.


53-59: Simplified InferRouterInputs tests

The tests for InferRouterInputs have been simplified while maintaining full type coverage. The change improves readability by first capturing the inferred type and then testing against it, rather than repeating the inference in each expectation.


63-69: Simplified InferRouterOutputs tests

Similar to the inputs tests, the outputs tests follow the same pattern of simplification while maintaining full type coverage. This consistency in testing approach improves maintainability.

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

3-3: Symbol renamed for clarity

The constant LAZY_LOADER_SYMBOL has been renamed to LAZY_SYMBOL, which is more concise and better reflects its purpose as a key in the Lazy interface. This change is part of the PR's goal to improve naming conventions.


9-14: Enhanced Lazy interface with metadata support

The Lazy interface has been significantly improved by restructuring it to include both:

  1. A loader function that returns a promise
  2. A meta property to store metadata

This change supports the PR objective of improving the hidden functionality by providing a more structured way to associate metadata with lazy-loaded components.


18-25: Updated lazy function with metadata support

The lazy function now accepts an optional meta parameter (defaulting to an empty object) and returns an object with the enhanced structure. This change makes the lazy-loading mechanism more flexible while maintaining backward compatibility through the default parameter.


27-33: Updated isLazy check

The isLazy function has been updated to check for the presence of the renamed LAZY_SYMBOL property. The check remains efficient and maintains the same behavior for identifying lazy-loaded components.


35-37: Added metadata retrieval function

A new utility function getLazyMeta has been added to safely extract metadata from lazy-loaded components. This addition supports the enhanced metadata functionality and provides a clean API for accessing the metadata.


39-41: Updated unlazy function

The unlazy function has been updated to work with the new structure, extracting the loader function from the enhanced object structure. This maintains backward compatibility while supporting the new metadata features.

packages/server/src/adapters/standard/rpc-matcher.ts (5)

3-5: Updated imports to reflect refactored modules

The imports have been updated to:

  1. Import AnyRouter type directly
  2. Replace EachContractProcedureLaziedOptions with LazyTraverseContractProceduresOptions
  3. Import utility functions from their new locations after refactoring

These changes align with the module restructuring mentioned in the PR objectives.

Also applies to: 8-10


16-16: Enforced immutability with readonly array

The path property has been changed from a mutable array (string[]) to an immutable array (readonly string[]). This is a good practice that prevents accidental modification of the path and aligns with TypeScript best practices for immutability.


23-23: Updated type for pendingRouters

The type of pendingRouters has been updated to use LazyTraverseContractProceduresOptions, reflecting the refactored options structure used for lazy traversal. This change maintains type safety while adapting to the new API.


25-50: Refactored initialization method

The init method has been updated to:

  1. Accept a readonly path parameter
  2. Use traverseContractProcedures instead of eachContractProcedure
  3. Use the renamed toHttpPath utility function

These changes maintain the same functionality while using the refactored API and enforcing immutability.


76-87: Updated router access and contract procedure creation

This section has been refactored to:

  1. Use getRouter instead of getRouterChild for router access
  2. Update the error message path conversion using toHttpPath
  3. Reverse the parameter order in createContractedProcedure for better clarity

These changes maintain the same functionality while aligning with the refactored API.

packages/contract/src/router.ts (2)

27-32: Type rename for better semantic clarity

The renaming from ContractRouterToErrorMap to InferContractRouterErrorMap improves clarity by using a verb that better describes what the type is doing - inferring error maps from contract routers. This aligns with TypeScript naming conventions for utility types.


34-34: Consistent naming pattern applied

Renaming ContractRouterToMeta to InferContractRouterMeta maintains consistency with the error map type change above, creating a clear pattern for type inference utilities.

packages/server/src/implementer.test-d.ts (5)

13-13: Type import updated to reflect refactoring

The import change from AdaptedRouter to EnhancedRouter reflects the broader renaming pattern in this PR, maintaining consistency across the codebase.


45-45: Improved type safety with readonly arrays

Using readonly string[] instead of string[] for path parameters prevents accidental mutation of the path array, which is a good practice for parameters that shouldn't be modified.


95-95: Consistent immutability applied to path parameters

Similar to the previous change, this enforces immutability on path parameters in the .use method, ensuring consistent type safety throughout the codebase.


126-126: Router type updated to match new naming convention

The expected return type for the .router method has been updated from AdaptedRouter to EnhancedRouter, maintaining consistency with the new naming pattern.


155-155: Lazy router type updated similarly

The expected return type for the .lazy method has also been updated to use EnhancedRouter, ensuring consistent naming throughout the type system.

packages/server/src/router-client.ts (6)

4-4: Import updated for improved type flexibility

Changing from Lazy to Lazyable type import suggests a more flexible approach to handling lazy-loaded components, likely part of the FlatLazy component removal mentioned in the PR objectives.


14-19: Simplified RouterClient type definition

The type definition has been streamlined to directly check if TRouter extends Procedure and if TRouter[K] extends Lazyable, making the code more readable and maintainable.


21-34: Function signature improved for clarity

The createRouterClient function signature has been updated to use T instead of TRouter and accept a Lazyable<T | undefined> parameter, which better reflects its usage and aligns with the type system changes.


36-36: Simplified parameter handling

The function now directly passes options to createProcedureClient instead of using more complex parameter handling, improving code clarity.


42-42: Updated lazy procedure creation

Using createAssertedLazyProcedure instead of the previous implementation aligns with the refactoring of the lazy loading mechanism mentioned in the PR objectives.


51-51: Router access method updated

Changed from getRouterChild to getRouter, which likely simplifies the API and makes the code more intuitive.

packages/server/src/implementer-variants.ts (6)

1-1: Updated imports to match renamed types

Import statement updated to use the new InferContractRouterErrorMap and InferContractRouterMeta types, ensuring consistency with the changes in the contract module.


5-8: Streamlined imports for router functionality

The imports have been updated to directly reference Lazy, Router, and EnhancedRouter, reflecting the architectural changes in the codebase.


11-11: Simplified type parameter name

Renaming the type parameter from TContract to T makes the code more concise while maintaining its functionality, which is a good practice for interfaces with multiple generic parameters.


21-23: Updated error and meta type references

The middleware type now uses the renamed InferContractRouterErrorMap and InferContractRouterMeta types, maintaining consistency with the contract module changes.


27-28: Router method signature updated

The router method now accepts a Router<T, TCurrentContext> parameter and returns an EnhancedRouter type, aligning with the new naming convention and parameter ordering.


30-32: Lazy loading method signature updated

The lazy method has been updated to use Router<T, TInitialContext> and returns an EnhancedRouter<Lazy<U>> type, which reflects the changes to the lazy loading mechanism mentioned in the PR objectives.

packages/server/src/implementer-variants.test-d.ts (4)

12-12: Updated import aligned with renamed entity

The import has been updated from AdaptedRouter to EnhancedRouter, which is consistent with the PR's objective of improving naming conventions.


26-26: Enhanced type safety with readonly array

Changed string[] to readonly string[] for the path parameter, enforcing immutability which prevents accidental modifications to the path array during middleware execution.


61-62: Updated type expectation for consistency

The type expectation has been updated from AdaptedRouter to EnhancedRouter, maintaining consistency with the renamed entity.


90-91: Updated type expectation for lazy router

The type expectation for the lazy router implementation has been updated from AdaptedRouter to EnhancedRouter, maintaining consistency with the renamed entity.

packages/server/src/builder.test-d.ts (7)

13-13: Updated import aligned with renamed entity

The import has been updated from AdaptedRouter to EnhancedRouter, which is consistent with the PR's objective of improving naming conventions.


124-124: Enhanced type safety with readonly array

Changed string[] to readonly string[] for the path parameter in the middleware, enforcing immutability which prevents accidental modifications to the path array.


181-181: Enhanced type safety with readonly array

Changed string[] to readonly string[] for the path parameter in the middleware with map input, enforcing immutability.


221-221: Enhanced type safety with readonly array

Changed string[] to readonly string[] for the path parameter in the middleware with map input, enforcing immutability.


336-336: Enhanced type safety with readonly array

Changed string[] to readonly string[] for the path parameter in the handler, enforcing immutability.


377-378: Updated type expectation for router method

The type expectation for the router method has been updated from AdaptedRouter to EnhancedRouter, maintaining consistency with the renamed entity.


401-402: Updated type expectation for lazy method

The type expectation for the lazy method has been updated from AdaptedRouter to EnhancedRouter, maintaining consistency with the renamed entity.

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

3-3: Improved type safety with readonly array parameters

The dedupeMiddlewares function now accepts readonly arrays as parameters, preventing accidental mutation of the arrays within the function. This is a solid improvement for immutability and type safety.


19-19: Improved type safety with readonly array parameters

The mergeMiddlewares function now accepts readonly arrays as parameters, preventing accidental mutation of the arrays within the function while still returning a new array.


23-23: Improved type safety with readonly array parameters

The addMiddleware function now accepts a readonly array as its first parameter, preventing accidental mutation of the array within the function while still returning a new array with the addition.

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

5-5: Updated import for Lazy type

Updated import statement to use the Lazy type directly from './lazy' rather than importing from a utility file.


9-10: Updated imports for enhanced router types

Updated imports to use EnhancedRouter and EnhanceRouterOptions instead of the previous "Adapted" naming, which aligns with the PR's naming improvements objective.


17-17: Updated import for router enhancement function

Updated import to use enhanceRouter instead of adaptRouter, which is consistent with the renaming pattern in the PR.


29-29: Updated interface extension

The BuilderDef interface now extends EnhanceRouterOptions instead of AdaptRouterOptions, maintaining consistency with the renamed entities.


232-236: Updated router method implementation

The router method has been updated to:

  1. Use the EnhancedRouter return type instead of AdaptedRouter
  2. Call enhanceRouter instead of adaptRouter

These changes align with the PR's objective to improve naming conventions and maintain consistency across the codebase.


238-242: Updated lazy method implementation

The lazy method has been updated to:

  1. Use the EnhancedRouter<Lazy<U>, TInitialContext, TErrorMap> return type
  2. Simplify the implementation by using enhanceRouter(lazy(loader), this['~orpc']) directly

This removes the dependency on FlatLazy as mentioned in the PR description and maintains consistency with the renaming convention.

packages/openapi/src/adapters/standard/openapi-matcher.ts (9)

1-1: No concerns with the new import statement.


4-4: Imports updated successfully.


18-19: No issues here.


43-43: No issues.


50-50: Verify concurrency assumptions in match.
If multiple requests call match() in parallel, the loop modifying this.pendingRouters may introduce race conditions. Confirm whether the environment guarantees single-threaded execution or consider applying synchronization.


60-60: No concerns here.


78-78: No issues.


82-82: No issues.


87-87: No issues.

packages/server/src/router-utils.ts (6)

1-10: Imports appear correct and comprehensive.


11-47: getRouter implementation looks solid.
The approach to handle both lazy and non-lazy router segments is clear and maintains good readability.


49-57: AccessibleLazyRouter type definition is well-structured.
No issues found here.


58-72: createAccessibleLazyRouter proxy approach looks good.
This effectively handles dynamic property access on lazy objects.


99-149: enhanceRouter function.
The layering of middlewares, error maps, and prefix handling appears coherent. No immediate issues found.


209-227: resolveContractProcedures BFS logic is clear.
No concerns regarding the async unwrapping steps.

packages/server/src/implementer.ts (14)

1-1: No issues with the updated import.


6-6: No issues with the added Lazy type import.


8-8: No concerns about AnyRouter, Router import.


15-16: setHiddenRouterContract and EnhancedRouter imports look correct.


19-19: Declaration for RouterImplementer is updated properly.


29-30: Use of InferContractRouterErrorMap<T> is a nice improvement.


33-33: No issues with returning a decorated middleware.


40-41: Error map usage is consistent.


44-44: ImplementerInternalWithMiddlewares reference is coherent.


46-47: Returning EnhancedRouter from router aligns with overall refactor.


49-51: lazy method returning an EnhancedRouter<Lazy<U>> is consistent with the lazy loading pattern.


115-115: No issues noted here.


119-120: Duplicate logic identified earlier.
The same pattern appears here as in the router branch. Consolidating into a single helper function would maintain DRY principles.


127-127: No issues here.

packages/server/src/builder-variants.ts (7)

5-5: Switching from FlattenLazy to Lazy type

This change is part of the removal of the FlatLazy component as mentioned in the PR objectives. The simplification from FlattenLazy to just Lazy likely indicates a streamlined approach to lazy loading.


9-10: Renaming from Adapted to Enhanced naming convention

Good renaming from AdaptedRouter to EnhancedRouter and AdaptRouterOptions to EnhanceRouterOptions. This improves semantics and better describes the purpose of these types, aligning with the naming improvements mentioned in the PR.


76-78: Type parameter reordering and return type update

The type parameter ordering in the Router generic has been changed, swapping the position of ContractRouter<TMeta> and TCurrentContext. The return type has also been updated from AdaptedRouter to EnhancedRouter, consistent with the new naming convention.


80-82: Updated lazy method signature

The lazy method now returns EnhancedRouter<Lazy<U>, TInitialContext, TErrorMap> instead of using FlattenLazy<U>, which aligns with the removal of the FlatLazy component mentioned in the PR objectives.


345-345: Updated RouterBuilder options property type

The ~orpc property type has been updated to use EnhanceRouterOptions instead of AdaptRouterOptions, maintaining consistency with the renamed types throughout the codebase.


367-369: Consistent type parameter reordering in RouterBuilder.router

The same type parameter reordering applied to the BuilderWithMiddlewares interface has been consistently applied here to the RouterBuilder interface, ensuring type consistency throughout the codebase.


371-373: Consistent update to lazy method in RouterBuilder

The lazy method in RouterBuilder has been updated to match the changes in the BuilderWithMiddlewares interface, maintaining consistent typing across the codebase and supporting the removal of FlattenLazy.

Comment on lines +35 to +41
it('InferContractRouterErrorMap', () => {
expectTypeOf < InferContractRouterErrorMap<typeof router>>().toEqualTypeOf<typeof baseErrorMap | Record<never, never>>()
})

it('InferContractRouterErrorMap', () => {
expectTypeOf<InferContractRouterErrorMap<typeof router>>().toEqualTypeOf<typeof baseErrorMap | Record<never, never>>()
})
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix duplicated test case

There's a duplicate test case for InferContractRouterErrorMap - the exact same test is defined twice at lines 35-37 and again at lines 39-41. Please remove one of these duplicates to maintain clean test code.

 it('InferContractRouterErrorMap', () => {
   expectTypeOf < InferContractRouterErrorMap<typeof router>>().toEqualTypeOf<typeof baseErrorMap | Record<never, never>>()
 })

-it('InferContractRouterErrorMap', () => {
-  expectTypeOf<InferContractRouterErrorMap<typeof router>>().toEqualTypeOf<typeof baseErrorMap | Record<never, never>>()
-})
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('InferContractRouterErrorMap', () => {
expectTypeOf < InferContractRouterErrorMap<typeof router>>().toEqualTypeOf<typeof baseErrorMap | Record<never, never>>()
})
it('InferContractRouterErrorMap', () => {
expectTypeOf<InferContractRouterErrorMap<typeof router>>().toEqualTypeOf<typeof baseErrorMap | Record<never, never>>()
})
it('InferContractRouterErrorMap', () => {
expectTypeOf < InferContractRouterErrorMap<typeof router>>().toEqualTypeOf<typeof baseErrorMap | Record<never, never>>()
})

Copy link
Copy Markdown

@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 (5)
packages/server/src/implementer.test.ts (1)

149-155: New test case for symbol access protection.

This new test case ensures that the implementer doesn't allow recursive access when using symbols, which is a good security practice. However, there's a duplicate assertion on line 154 that's identical to line 153.

 expect((implementer.nested as any)[Symbol.for('test')]).toBeUndefined()
 expect((implementer.nested.ping as any)[Symbol.for('test')]).toBeUndefined()
 expect((implementer.use as any)[Symbol.for('test')]).toBeUndefined()
-expect((implementer.use as any)[Symbol.for('test')]).toBeUndefined()
packages/contract/src/router-utils.ts (4)

10-10: Consider removing the non-null assertion.

The non-null assertion (!) on segment may not be necessary if you're iterating through a valid array. TypeScript should understand that array access within bounds will yield a defined value.

- const segment = path[i]!
+ const segment = path[i]

37-58: Type assertion usage could be improved.

The enhanceContractRouter function implements a recursive enhancement pattern correctly. However, the use of as any type assertions in two places (lines 48 and 57) bypasses TypeScript's type checking, which could lead to potential runtime errors.

Consider using more specific type assertions when possible:

- return enhanced as any
+ return enhanced as EnhancedContractRouter<T, TErrorMap>

While this doesn't eliminate type assertions entirely, it provides more specific type information that TypeScript can use for validation.


54-54: Add null check for router properties.

The current implementation assumes that router[key] is always defined when calling enhanceContractRouter. Add a null check to avoid potential runtime errors.

- enhanced[key] = enhanceContractRouter(router[key]!, options)
+ if (router[key] !== undefined) {
+   enhanced[key] = enhanceContractRouter(router[key], options)
+ }

51-56: Consider using Object.entries for cleaner iteration.

The current approach with a for-in loop works but could be improved for clarity and to avoid iterating over inherited properties.

- const enhanced: Record<string, any> = {}
-
- for (const key in router) {
-   enhanced[key] = enhanceContractRouter(router[key]!, options)
- }
+ const enhanced: Record<string, any> = {}
+
+ Object.entries(router).forEach(([key, value]) => {
+   if (value !== undefined) {
+     enhanced[key] = enhanceContractRouter(value, options)
+   }
+ })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c495df6 and 78aad21.

📒 Files selected for processing (7)
  • packages/contract/src/route.test.ts (3 hunks)
  • packages/contract/src/router-utils.test.ts (1 hunks)
  • packages/contract/src/router-utils.ts (1 hunks)
  • packages/openapi/src/adapters/standard/openapi-matcher.ts (4 hunks)
  • packages/openapi/src/openapi-custom.ts (2 hunks)
  • packages/server/src/implementer.test.ts (4 hunks)
  • packages/server/src/implementer.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/contract/src/router-utils.test.ts
  • packages/contract/src/route.test.ts
  • packages/server/src/implementer.ts
🔇 Additional comments (19)
packages/openapi/src/openapi-custom.ts (2)

1-1: Import type update improves type consistency.

The import change from ErrorMapItem to ErrorMap aligns with the broader refactoring effort to improve naming and type consistency across the codebase.


30-30: Type assertion enhanced for better type safety.

The change from (ErrorMapItem<any> | undefined)[] to ErrorMap[keyof ErrorMap][] represents a more precise and type-safe approach. This new type accurately captures that we're dealing with an array of any possible values in the ErrorMap, eliminating the need for the explicit undefined union as it's likely handled within the ErrorMap type definition itself.

packages/server/src/implementer.test.ts (4)

7-8: Imports updated to reflect the new module organization.

The imports have been correctly updated to reference the new module names after the refactoring from "adapt" to "enhance" pattern.


10-12: Spy references updated to match the new function names.

The spy references have been properly updated from setRouterContractSpy to setHiddenRouterContractSpy and from adaptRouterSpy to enhanceRouterSpy, which aligns with the refactoring goal mentioned in the PR objectives.


64-75: Test expectations correctly updated to use new function names.

The test assertions have been properly updated to use the new function names (getHiddenRouterContract instead of getRouterContract) and the new spy references. The parameters passed to the spy functions in the assertions have also been updated to align with the new function signatures.


80-96: Lazy router test assertions properly updated.

Similar to the router test above, the lazy router test assertions have been correctly updated to use the new function names and spy references. The validation of the lazy router implementation remains intact.

packages/contract/src/router-utils.ts (4)

1-5: Imports look good.

All necessary imports are correctly included to support the module's functionality.


6-24: LGTM: Traversal function follows immutable pattern.

The getContractRouter function correctly handles the traversal of contract router path segments with appropriate early returns. Good use of readonly for the path parameter to enforce immutability.


26-32: Well-designed recursive type.

The EnhancedContractRouter generic type effectively uses conditional types to distinguish between contract procedures and nested routers, applying the appropriate transformation to each.


33-35: Interface extends base options appropriately.

The EnhanceContractRouterOptions interface properly extends EnhanceRouteOptions with the additional errorMap property.

packages/openapi/src/adapters/standard/openapi-matcher.ts (9)

1-1: Import naming changes align with broader refactoring effort

The imports have been updated to reflect the renamed functions and types (LazyTraverseContractProceduresOptions instead of EachContractProcedureLaziedOptions, and imports like traverseContractProcedures instead of eachContractProcedure). This is consistent with the broader refactoring described in the PR objectives.

Also applies to: 4-4


10-10: Good immutability enforcement

Making the path array readonly enforces immutability, which is a good practice for preventing unintended mutations of the path array.


16-16: Type update for pendingRouters

The type has been updated from EachContractProcedureLaziedOptions to LazyTraverseContractProceduresOptions, aligning with the renaming convention changes in the PR.


18-19: Method parameter and implementation changes

The init method now:

  1. Takes a readonly path array with a default empty array
  2. Uses traverseContractProcedures instead of eachContractProcedure

These changes enhance type safety and match the broader refactoring pattern.


21-21: Consistent naming with toHttpPath

The function convertPathToHttpPath has been replaced with toHttpPath across multiple locations, which improves naming consistency and readability.

Also applies to: 43-43, 80-80


44-44: Using getLazyMeta helper

Using getLazyMeta(option.router).prefix instead of direct access improves the code's maintainability by abstracting the internal structure of the router object.


58-58: Improved module import destructuring

The code now consistently uses destructuring to extract the default export from lazy-loaded modules, which improves readability and makes the pattern more explicit.

Also applies to: 76-76


76-76: Router access method change

Changed from using getRouterChild to getRouter, which aligns with the broader API simplification in the PR.


85-85:

Details

✅ Verification successful

Parameter order change in createContractedProcedure

The parameter order in createContractedProcedure has been reversed from (contract, procedure) to (procedure, contract). Ensure this change is consistent across all usages in the codebase.


🏁 Script executed:

#!/bin/bash
# Check for other usages of createContractedProcedure to verify consistent parameter order
rg "createContractedProcedure\(" --type ts

Length of output: 604


Verified Consistency in Parameter Order for createContractedProcedure

  • The updated parameter order (procedure, contract) is consistently used across all instances.
  • Verified usages in packages/server/src/procedure-utils.ts, packages/server/src/procedure-utils.test.ts, packages/openapi/src/adapters/standard/openapi-matcher.ts, and packages/server/src/adapters/standard/rpc-matcher.ts confirm the change.

No further modifications are required.

@dinwwwh dinwwwh merged commit 3afb521 into main Mar 10, 2025
4 of 6 checks passed
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.

1 participant