Repository navigation
Keep procedure contracts aligned with runtime - #7
tunnckoCore merged 16 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR refines async detection for schemas, handlers, and cache adapters. It updates procedure execution, validation, error and result shapes, context handling, and ChangesAsync detection, procedure wiring, validation, and tests
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Caller
participant Zagora
participant Validator
participant Cache
Caller->>Zagora: invoke callable(input)
Zagora->>Validator: validate input schema
Validator-->>Zagora: result.ok or validation error
alt validation succeeds
Zagora->>Cache: has, get, or set
Cache-->>Zagora: value or Promise<value>
Zagora-->>Caller: result or Promise<result>
else validation fails
Zagora-->>Caller: validation result
end
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 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: 2
🧹 Nitpick comments (6)
src/is-promise.ts (1)
70-74: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocument that
ResolvePromisemust keep a naked type parameter.The union result depends on distributive conditional types.
TAsyncis a naked type parameter, soIsPromise<T> = booleandistributes toResult | Promise<Result>. If a future refactor inlines this check asIsPromise<T> extends true ? ... : ..., distribution stops and mixed unions collapse toResult. Add a short comment to protect the behavior.♻️ Proposed comment
+// NOTE: `TAsync` must stay a naked type parameter. Distribution over +// `boolean` is what yields `Result | Promise<Result>` for mixed unions. type ResolvePromise<TAsync extends boolean, Result> = TAsync extends true ? Promise<Result> : Result;🤖 Prompt for 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. In `@src/is-promise.ts` around lines 70 - 74, Add a brief comment immediately above ResolvePromise explaining that TAsync must remain a naked type parameter so conditional-type distribution preserves Result | Promise<Result> when IsPromise<T> resolves to boolean; do not inline the IsPromise check into the conditional type.test/types-testing.test.ts (1)
184-206: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a negative assertion for the fully synchronous case.
The tests cover definite async and mixed async states. They do not lock the
falseresult. Add assertions for all-sync schemas and for absent schemas. This prevents a regression whereHasAsyncSchemawidens every procedure to a promise.♻️ Proposed additions
expectTypeOf< HasAsyncSchema<typeof asyncSchema, undefined, undefined> >().toEqualTypeOf<true>(); + expectTypeOf< + HasAsyncSchema<undefined, undefined, undefined> + >().toEqualTypeOf<false>(); + expectTypeOf< + HasAsyncSchema< + typeof syncSchema, + typeof syncSchema, + { SYNC: typeof syncSchema } + > + >().toEqualTypeOf<false>();🤖 Prompt for 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. In `@test/types-testing.test.ts` around lines 184 - 206, Add negative type assertions alongside the existing HasAsyncSchema tests: verify fully synchronous schemas return false and absent schemas return false, covering both the direct schema parameters and the procedure-map form where applicable. Use the existing syncSchema and HasAsyncSchema symbols, while preserving the current true and boolean assertions.src/types.ts (2)
150-152: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify the redundant
TErrorsMapconstraint.
Record<string, AnySchema> | anyreduces toany, so the constraint carries no information and reads as if it restricts the parameter. Useany(orunknown) directly. TheIsTypedErrordefault keeps the same behavior because it re-checksTErrorsMap extends Record<string, any>.♻️ Proposed change
export type ZagoraResult< TOutput, - TErrorsMap extends Record<string, AnySchema> | any, + TErrorsMap, TResolvedResult, IsTypedError = TErrorsMap extends Record<string, any> ? boolean : false,🤖 Prompt for 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. In `@src/types.ts` around lines 150 - 152, In the generic declaration containing TErrorsMap and TResolvedResult, replace the redundant `TErrorsMap extends Record<string, AnySchema> | any` constraint with a direct unconstrained `any` or `unknown` type parameter. Preserve the existing IsTypedError default condition and its behavior.
153-181: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConfirm that the
IsTypedErrordefault distributes as intended.The typed and untyped branches only both appear because
IsTypedErroris a naked type parameter, so the defaultbooleandistributes overtrue | false. Any future change that inlines the check, for example(TErrorsMap extends Record<string, any> ? boolean : false) extends true ? ... : ..., would silently drop the typed-error branch. Add a comment that records this constraint, similar toResolvePromiseinsrc/is-promise.ts.🤖 Prompt for 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. In `@src/types.ts` around lines 153 - 181, Add a concise comment immediately above the IsTypedError conditional type explaining that its naked type-parameter check must remain distributive over boolean (true | false), preserving both typed and untyped error branches; document that inlining or wrapping the check would drop the typed-error branch, similar to the ResolvePromise note.src/index.ts (1)
267-278: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winKeep the autoCallable third
ZagoraResultparameter concrete when possible.
ZagoraResultusesTResolvedResultto distinguishok: trueresults from errors. Thehandler()autoCallable branch passesany, while.handler().callable()infersTResolvedResult = Awaited<ReturnType<typeof forwardProcedure>>. Use a non-anyinferred result type forautoCallable: true, or add a nearby note if this is intentionally collapsed.🤖 Prompt for 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. In `@src/index.ts` around lines 267 - 278, Update the autoCallable branch in handler’s conditional type so the third ZagoraResult generic uses the inferred resolved result type from the handler return value, rather than any. Preserve the existing conditional behavior and align it with the Awaited<ReturnType<typeof forwardProcedure>> inference used by handler().callable().test/contracts.test.ts (1)
271-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a companion test for an all-synchronous cache adapter.
This test confirms that a cache with an async
set()makes the success path return aPromise. Add a complementary case withhas(),get(), andset()all synchronous. Confirm the procedure returns a plain result, not aPromise, on both cache hit and cache miss. This closes the loop on the "path-dependent async" cache contract described in the PR objectives.🤖 Prompt for 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. In `@test/contracts.test.ts` around lines 271 - 297, Add a companion test alongside “async cache methods only make paths that invoke them async” using a cache whose has(), get(), and set() methods are all synchronous. Exercise both cache-hit and cache-miss procedure calls, asserting each returns a plain result rather than a Promise while preserving successful behavior.
🤖 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 `@README.md`:
- Around line 546-548: Update the cache documentation statements around the
async cache method behavior, including the section at line 609 and the comment
near lines 644-647, to match the possibly-async contract described by
“ZagoraResult | Promise<ZagoraResult>”. Clarify that async cache methods only
make the affected execution paths asynchronous rather than forcing the entire
procedure to always return a promise.
In `@src/utils.ts`:
- Around line 318-323: Update deepMerge to handle a non-plain override argument
bbb consistently with a non-plain base argument aaa: either throw the same
“Expects an object args” error or return bbb as a full replacement, rather than
silently returning a spread of aaa. Preserve recursive merging for plain-object
overrides and ensure the behavior applies to both context and env call sites.
---
Nitpick comments:
In `@src/index.ts`:
- Around line 267-278: Update the autoCallable branch in handler’s conditional
type so the third ZagoraResult generic uses the inferred resolved result type
from the handler return value, rather than any. Preserve the existing
conditional behavior and align it with the Awaited<ReturnType<typeof
forwardProcedure>> inference used by handler().callable().
In `@src/is-promise.ts`:
- Around line 70-74: Add a brief comment immediately above ResolvePromise
explaining that TAsync must remain a naked type parameter so conditional-type
distribution preserves Result | Promise<Result> when IsPromise<T> resolves to
boolean; do not inline the IsPromise check into the conditional type.
In `@src/types.ts`:
- Around line 150-152: In the generic declaration containing TErrorsMap and
TResolvedResult, replace the redundant `TErrorsMap extends Record<string,
AnySchema> | any` constraint with a direct unconstrained `any` or `unknown` type
parameter. Preserve the existing IsTypedError default condition and its
behavior.
- Around line 153-181: Add a concise comment immediately above the IsTypedError
conditional type explaining that its naked type-parameter check must remain
distributive over boolean (true | false), preserving both typed and untyped
error branches; document that inlining or wrapping the check would drop the
typed-error branch, similar to the ResolvePromise note.
In `@test/contracts.test.ts`:
- Around line 271-297: Add a companion test alongside “async cache methods only
make paths that invoke them async” using a cache whose has(), get(), and set()
methods are all synchronous. Exercise both cache-hit and cache-miss procedure
calls, asserting each returns a plain result rather than a Promise while
preserving successful behavior.
In `@test/types-testing.test.ts`:
- Around line 184-206: Add negative type assertions alongside the existing
HasAsyncSchema tests: verify fully synchronous schemas return false and absent
schemas return false, covering both the direct schema parameters and the
procedure-map form where applicable. Use the existing syncSchema and
HasAsyncSchema symbols, while preserving the current true and boolean
assertions.
🪄 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: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 68dc1c8e-9fdd-49cd-8d07-47b0fb18d83f
📒 Files selected for processing (9)
README.mdsrc/errors.tssrc/index.tssrc/is-promise.tssrc/types.tssrc/utils.tstest/contracts.test.tstest/main.test.tstest/types-testing.test.ts
|
@codex review this |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9985427357
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review this |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 64d65ac443
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review this |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
00f887f to
d1a94ff
Compare
Review — 6 findingsDiff reviewed: 1.
|
|
Implemented the aligned disposition of the Claude review in 8c9a6e0:
Verification passed: format, native typecheck, lint, and build. |
|
@codex review this |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (5)
test/utils.test.ts (1)
137-137: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid the constructor parameter property.
Declare
nameas an explicit readonly field and assign it in the constructor.Proposed fix
class Database { - constructor(readonly name: string) {} + readonly name: string; + + constructor(name: string) { + this.name = name; + } }As per coding guidelines:
**/*.{ts,tsx}files must not use parameter properties in class constructors.🤖 Prompt for 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. In `@test/utils.test.ts` at line 137, Replace the constructor parameter property in the class constructor with an explicit readonly name field, then assign the constructor argument to that field while preserving the class’s current behavior.Source: Coding guidelines
test/types-testing.test.ts (2)
336-337: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAssert the adapter shape on the source object, not on the annotated variable.
mixedAdapteris annotated asCacheAdapter, sotoExtend<CacheAdapter>()holds by construction. The assertion does not check thatasyncHasCachesatisfies the adapter contract. Assert on the object itself.♻️ Proposed change
- const mixedAdapter: CacheAdapter = asyncHasCache; - expectTypeOf(mixedAdapter).toExtend<CacheAdapter>(); + expectTypeOf(asyncHasCache).toExtend<CacheAdapter>();🤖 Prompt for 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. In `@test/types-testing.test.ts` around lines 336 - 337, Update the type assertion in the mixed adapter test to target asyncHasCache directly instead of the explicitly annotated mixedAdapter variable, ensuring the check validates the source object's compatibility with CacheAdapter rather than an already-enforced annotation.
273-276: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSelf-referential expectations weaken the mixed sync/async checks. Each site derives the expected type from the actual return type with
Awaited<T> | Promise<Awaited<T>>. The check therefore passes when the return type degrades toany, and it does not confirm the concreteZagoraResultpayload. Pin the expected type explicitly, for exampleZagoraResult<string, ...> | Promise<ZagoraResult<string, ...>>, or add a companion assertion such asexpectTypeOf<Awaited<T>>().toEqualTypeOf<ZagoraResult<...>>().
test/types-testing.test.ts#L273-L276: replace the derived expectation forMixedErrorsMapResultwith the explicit result union.test/types-testing.test.ts#L367-L370: replace the derived expectation forBuilderCachedResultwith the explicit result union.test/types-testing.test.ts#L376-L379: replace the derived expectation forCallableCachedResultwith the explicit result union.test/types-testing.test.ts#L388-L391: replace the derived expectation forAutoCachedResultwith the explicit result union.test/types-testing.test.ts#L408-L414: replace the derived expectation forOptionallyOverriddenResultwith the explicit result union.test/types-testing.test.ts#L419-L422: replace the derived expectation forUndefinedOverrideResultwith the explicit result union.test/types-testing.test.ts#L431-L434: replace the derived expectation forMaybeHandlerResultwith the explicit result union.🤖 Prompt for 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. In `@test/types-testing.test.ts` around lines 273 - 276, Replace the self-referential return-type expectations with explicit ZagoraResult payload unions for MixedErrorsMapResult (test/types-testing.test.ts:273-276), BuilderCachedResult (367-370), CallableCachedResult (376-379), AutoCachedResult (388-391), OptionallyOverriddenResult (408-414), UndefinedOverrideResult (419-422), and MaybeHandlerResult (431-434). Each assertion must verify the concrete result type or its Promise-wrapped form, rather than deriving the expected type from the actual return type.src/index.ts (1)
226-226: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove explicit
anyassertions from builder paths.These assertions bypass generic contract checking.
src/index.ts#L226-L226: constructZagorawith the declared generic arguments instead of casting the result toany.src/index.ts#L552-L552: connectoptions.envto the effective environment generic and pass it withoutas any.As per coding guidelines, “Don't use the any type.”
🤖 Prompt for 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. In `@src/index.ts` at line 226, Remove the explicit any assertions in src/index.ts at lines 226 and 552. In the Zagora construction path around line 226, instantiate Zagora using its declared generic arguments instead of casting the result; in the builder path around line 552, type options.env with the effective environment generic and pass it directly without as any.Source: Coding guidelines
test/contracts.test.ts (1)
31-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove explicit
anyfrom contract tests.Use
unknownfor the assertion-helper input. Use a deliberate invalid-input escape such asas neverfor runtime validation tests.
test/contracts.test.ts#L31-L31: changeresult: anytoresult: unknown.test/contracts.test.ts#L288-L288: replace123 as anywith a non-anyinvalid-input test value.test/contracts.test.ts#L321-L321: replace123 as anywith a non-anyinvalid-input test value.As per coding guidelines, “Don't use the any type.”
🤖 Prompt for 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. In `@test/contracts.test.ts` at line 31, Remove explicit any usage in test/contracts.test.ts: update expectInternalError’s result parameter to unknown, and replace the invalid-input values at lines 288 and 321 with a deliberate non-any escape such as as never while preserving the runtime validation assertions.Source: Coding guidelines
🤖 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`:
- Line 60: Update the package.json check:types script to invoke the tsgo
executable explicitly via Bun's --package option, using
`@typescript/native-preview` as the package source instead of treating it as the
executable name.
In `@src/index.ts`:
- Around line 43-56: Update ResolveCallableEnv so an undefined TEnvVarsMap falls
back to ZagoraEnvVars instead of resolving to never, allowing callable({ env:
... }) without an explicit environment schema while preserving schema-based
inference when provided. Add a type-level test covering callable({ env: { ... }
}) without TEnvVarsMap.
In `@test/types-testing.test.ts`:
- Line 27: Update the “Run with” instruction in the type-testing documentation
comment to use the declared check:types script via bun run check:types instead
of bun run typecheck.
---
Nitpick comments:
In `@src/index.ts`:
- Line 226: Remove the explicit any assertions in src/index.ts at lines 226 and
552. In the Zagora construction path around line 226, instantiate Zagora using
its declared generic arguments instead of casting the result; in the builder
path around line 552, type options.env with the effective environment generic
and pass it directly without as any.
In `@test/contracts.test.ts`:
- Line 31: Remove explicit any usage in test/contracts.test.ts: update
expectInternalError’s result parameter to unknown, and replace the invalid-input
values at lines 288 and 321 with a deliberate non-any escape such as as never
while preserving the runtime validation assertions.
In `@test/types-testing.test.ts`:
- Around line 336-337: Update the type assertion in the mixed adapter test to
target asyncHasCache directly instead of the explicitly annotated mixedAdapter
variable, ensuring the check validates the source object's compatibility with
CacheAdapter rather than an already-enforced annotation.
- Around line 273-276: Replace the self-referential return-type expectations
with explicit ZagoraResult payload unions for MixedErrorsMapResult
(test/types-testing.test.ts:273-276), BuilderCachedResult (367-370),
CallableCachedResult (376-379), AutoCachedResult (388-391),
OptionallyOverriddenResult (408-414), UndefinedOverrideResult (419-422), and
MaybeHandlerResult (431-434). Each assertion must verify the concrete result
type or its Promise-wrapped form, rather than deriving the expected type from
the actual return type.
In `@test/utils.test.ts`:
- Line 137: Replace the constructor parameter property in the class constructor
with an explicit readonly name field, then assign the constructor argument to
that field while preserving the class’s current behavior.
🪄 Autofix
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: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 27fc0ad1-3cd1-4684-a12e-fc3f6c428299
📒 Files selected for processing (7)
README.mdpackage.jsonsrc/index.tssrc/utils.tstest/contracts.test.tstest/types-testing.test.tstest/utils.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- README.md
- src/utils.ts
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c73f650cad
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0a145d49c0
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
All requested changes are complete. All review threads are resolved.
Zagora now keeps procedure types aligned with runtime behavior for handlers, schemas, caches, errors, environment variables, and context merging. This PR supersedes #6.
Problem
Mixed synchronous and asynchronous paths lost type information. Some validation failures escaped the never-throw boundary, result shapes differed between runtime and types, and context merging could traverse dependency instances.
Changes
UNKNOWN_ERRORresults.error: undefinedfields..env()declares a schema.Intentional constraints
deepMergeroots are unsupported..env()schema.Verification
Harness: T3 Code
Model: GPT-5.6 Sol, high reasoning