Skip to content
This repository was archived by the owner on Oct 5, 2026. It is now read-only.

Keep procedure contracts aligned with runtime - #7

Merged
tunnckoCore merged 16 commits into
tunnckoCore:masterfrom
olstenlarck:agent/predictable-procedure-contracts
Aug 24, 2026
Merged

tunnckoCore merged 16 commits into
tunnckoCore:masterfrom
olstenlarck:agent/predictable-procedure-contracts

Conversation

@olstenlarck

@olstenlarck olstenlarck commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Preserve definite and uncertain Promise states for handlers, schemas, and cache adapters.
  • Convert validator throws and rejections into UNKNOWN_ERROR results.
  • Keep declared error kinds authoritative and discriminate typed errors.
  • Preserve falsy thrown causes and successful error: undefined fields.
  • Accept indexed environment sources only after .env() declares a schema.
  • Require record-shaped plain context roots while preserving nested class instances.
  • Add the pull request babysit skill.

Intentional constraints

  • Interface-shaped context and deepMerge roots are unsupported.
  • Runtime environment values require a prior .env() schema.
  • Zod async schemas remain synchronous at type level because Standard Schema does not expose async state. Callers must await when they know a Zod schema is async.

Verification

  • Typecheck passed.
  • Format and lint passed.
  • All 145 tests passed across 10 files.
  • Build passed.
  • CodeRabbit and Socket checks passed.
  • Vercel is non-required and fails because the account is blocked.

Harness: T3 Code
Model: GPT-5.6 Sol, high reasoning

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR refines async detection for schemas, handlers, and cache adapters. It updates procedure execution, validation, error and result shapes, context handling, and deepMerge. It also adds documentation plus runtime and type-level coverage.

Changes

Async detection, procedure wiring, validation, and tests

Layer / File(s) Summary
Promise-type detection foundation
src/is-promise.ts
IsPromise distinguishes definite, impossible, and mixed promise-like types. ConditionalAsync uses ResolvePromise for conditional result wrapping.
Schema, cache, and result contracts
src/types.ts
Adds schema and cache async detection types, supports mixed cache methods, and updates ZagoraResult error discrimination.
Procedure creation and execution wiring
src/index.ts
Detects asynchronous schemas, branches validation on result.ok, wraps asynchronous execution, updates context and environment defaults, and supports per-call cache adapters.
Validation, errors, and result normalization
src/utils.ts, src/errors.ts
Handles synchronous and asynchronous validation failures, preserves unknown causes, standardizes result shapes, restricts deepMerge recursion to plain objects, and prevents error-kind overrides.
Contract-level runtime tests
test/contracts.test.ts
Tests schema failures, handler exceptions, context merging, error helpers, result shapes, cache timing, and asynchronous error maps.
Valibot async schema runtime tests
test/main.test.ts
Tests asynchronous Valibot schemas and synchronous versus asynchronous union behavior.
Compile-time async and result tests
test/types-testing.test.ts
Tests Promise edge cases, async schemas and caches, procedure return types, cache overrides, environment constraints, and typed-error discrimination.
Deep-merge contract tests
test/utils.test.ts
Tests replacement of complex source values and merging of nested objects.
Async behavior documentation and package cleanup
README.md, package.json
Documents asynchronous cache and schema behavior and replaces tsgo-dev in type checking.

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
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: aligning procedure type contracts with runtime behavior.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (6)
src/is-promise.ts (1)

70-74: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document that ResolvePromise must keep a naked type parameter.

The union result depends on distributive conditional types. TAsync is a naked type parameter, so IsPromise<T> = boolean distributes to Result | Promise<Result>. If a future refactor inlines this check as IsPromise<T> extends true ? ... : ..., distribution stops and mixed unions collapse to Result. 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 win

Add a negative assertion for the fully synchronous case.

The tests cover definite async and mixed async states. They do not lock the false result. Add assertions for all-sync schemas and for absent schemas. This prevents a regression where HasAsyncSchema widens 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 value

Simplify the redundant TErrorsMap constraint.

Record<string, AnySchema> | any reduces to any, so the constraint carries no information and reads as if it restricts the parameter. Use any (or unknown) directly. The IsTypedError default keeps the same behavior because it re-checks TErrorsMap 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 win

Confirm that the IsTypedError default distributes as intended.

The typed and untyped branches only both appear because IsTypedError is a naked type parameter, so the default boolean distributes over true | 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 to ResolvePromise in src/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 win

Keep the autoCallable third ZagoraResult parameter concrete when possible.

ZagoraResult uses TResolvedResult to distinguish ok: true results from errors. The handler() autoCallable branch passes any, while .handler().callable() infers TResolvedResult = Awaited<ReturnType<typeof forwardProcedure>>. Use a non-any inferred result type for autoCallable: 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 win

Add a companion test for an all-synchronous cache adapter.

This test confirms that a cache with an async set() makes the success path return a Promise. Add a complementary case with has(), get(), and set() all synchronous. Confirm the procedure returns a plain result, not a Promise, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7bce098 and c18bf83.

📒 Files selected for processing (9)
  • README.md
  • src/errors.ts
  • src/index.ts
  • src/is-promise.ts
  • src/types.ts
  • src/utils.ts
  • test/contracts.test.ts
  • test/main.test.ts
  • test/types-testing.test.ts

Comment thread README.md Resolved
Comment thread src/utils.ts Resolved
Repository owner deleted a comment from chatgpt-codex-connector Bot Aug 9, 2026
@tunnckoCore

Copy link
Copy Markdown
Owner

@codex review this

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/index.ts Resolved
@tunnckoCore

Copy link
Copy Markdown
Owner

@codex review this

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/index.ts Resolved
Comment thread src/utils.ts Resolved
@tunnckoCore

Copy link
Copy Markdown
Owner

@codex review this

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 00f887f900

ℹ️ 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".

@tunnckoCore
tunnckoCore force-pushed the agent/predictable-procedure-contracts branch from 00f887f to d1a94ff Compare August 10, 2026 02:49
@tunnckoCore

Copy link
Copy Markdown
Owner

Review — 6 findings

Diff reviewed: master...pr/7. Test suite (142) and tsc --noEmit both pass; everything below is something the current tests don't cover.


1. package.json:60 — check:types still calls bunx tsgo-dev, which no longer resolves (high)

0f6a723 dropped tsgo-dev from devDependencies but left the script referencing it:

"check:types": "bunx tsgo-dev -p ./tsconfig.json",

With the dep gone, bunx falls back to the registry and there is no latest dist-tag:

$ bun run check:types
error: Package "tsgo-dev" with tag "latest" not found, but package exists
error: tsgo-dev@latest failed to resolve
error: script "check:types" exited with code 1

That breaks prebuild → so bun run build, release, and prepublishOnly all fail — publishing is currently impossible. Either point the script at the local tsc (bunx tsc -p ./tsconfig.json --noEmit, which passes cleanly on this branch) or re-add the dep pinned.


2. src/index.ts:507 — the new env excess-key guard rejects any env source with a string index signature (high)

Exclude<
  keyof NonNullable<TOptions[keyof TOptions & "env"]>,
  KeysOfUnion<InferSchemaInputSafe<TEnvVarsMap>>
>

When the supplied env object has a string index signature (process.env, import.meta.env, Record<string, string>), keyof is string, and Exclude<string, "PORT" | ...> does not narrow — it stays string. So the guard becomes Record<string, never> and bans every key.

Repro (compiles on master, fails here):

type Env = { PORT: string } & Record<string, string>;
const runtimeEnv = { PORT: "3000" } as Env;

zagora()
  .env(z.object({ PORT: z.string() }))
  .handler(({ env }) => env.PORT)
  .callable({ env: runtimeEnv });
// TS2322: Type 'Env' is not assignable to type
//   '{ PORT: string; } & Record<string, never> & { PORT: string; } & Record<string, string>'

This is the documented primary usage — README.md:669 (.callable({ env: process.env })), docs/docs/handler-options.md:78, apps/web/pages/docs/handler-options.mdx:69. The exclusion needs to bail out when the key set isn't a finite union of literals.


3. src/index.ts:507 — callable({ env }) is now impossible when no .env() schema was declared (medium)

Same expression, different edge: with no .env() call, TEnvVarsMap is undefined, so InferSchemaInputSafe<TEnvVarsMap> is unknown and KeysOfUnion<unknown> is never. The exclusion list is empty, so every provided key is mapped to never:

zagora()
  .handler(({ env }) => env)
  .callable({ env: { FOO: "bar" } });
// TS2322: Type 'string' is not assignable to type 'never'

master accepts this, and the runtime still supports it — src/index.ts:346 skips validation when envVarsMapSchema is undefined and hands mergedEnvVars straight to the handler. The guard should be inert when there is no env schema, and the error message is also unactionable.


4. src/index.ts:364 — a class-instance context is silently prototype-stripped (medium)

context<TNewContext extends object> now advertises that class instances are valid contexts, but deepMerge spreads its base into a plain object, dropping the prototype:

class Ctx { greet() { return "hi"; } }

zagora()
  .context<Ctx>()
  .handler(({ context }) => context.greet())
  .callable({ context: new Ctx() })();
// { ok: false, error: { kind: "UNKNOWN_ERROR",
//   stack: "TypeError: context.greet is not a function" } }

Typechecks fine, fails at runtime. master threw Expects an object args here, so this path went from loud to silently wrong. The new isPlainObject protects class instances nested one level down (which is what test/contracts.test.ts:141 covers) but not the context root. Suggest short-circuiting when either side isn't a plain object, e.g. isPlainObject(base) ? deepMerge(...) : override.


5. src/utils.ts:326 — deepMerge lost its argument guard and now throws (low)

deepMerge is public API (export * as utils, plus the ./utils export entry). Removing the isPlainObject checks changed two behaviours:

deepMerge({ a: 1 }, undefined)
// before: { a: 1 }
// now:    TypeError: undefined is not an object (evaluating 'Object.keys(overrideRecord)')

deepMerge("abc", { a: 1 })
// before: Error("Expects an object args")
// now:    { "0": "a", "1": "b", "2": "c", a: 1 }

Internal callers are guarded with || {}, so nothing breaks today — but an uncaught TypeError from an exported helper is off-brand for a "never throwing functions" library, and the string case now silently produces garbage. The @ts-expect-error deepMerge("invalid", {}) assertion in test/utils.test.ts:145 only covers the type level. A cheap if (!isPlainObject(override)) return { ...baseRecord } restores both.


6. README.md:545 — the async-cache claim contradicts ConditionalCacheAsync (low)

This PR rewrote the line to:

Sync/async Cache: If any cache method is async -> procedure becomes async (returns Promise<ZagoraResult>)

But src/types.ts:141 deliberately does the opposite, and says so in its own comment:

export type ConditionalCacheAsync<TCache, TResult> =
  [HasAsyncCache<TCache>] extends [false] ? TResult : TResult | Promise<Awaited<TResult>>;

An async cache yields ZagoraResult | Promise<ZagoraResult>, so callers must narrow — verified: const r: { ok: boolean } = procWithAsyncCache("x") errors on the Promise<...> member. The union is the right call (an input-validation failure short-circuits before the cache runs), but the README should describe it as possibly async rather than promising a bare Promise<ZagoraResult>.


Things I checked and think are correct

  • tryCatch no longer routing handler failures through createResult genuinely fixes throw undefined / throw null / throw "" being reported as ok: true — good catch, and test/contracts.test.ts:103 locks it in.
  • resultObj.error ? → resultObj.ok ? is safe now that createResult always emits an error key.
  • IsPromise<never> = false is the right change; it was making always-throwing handlers type as Promise<Result>.
  • { kind: key, ...data } → { ...data, kind: key } in both createErrorHelpers and validateError correctly makes the declared kind authoritative.
  • HasAsyncSchema / the Promise.resolve(...) wrapper line up: an async-only error schema is the one case where the runtime would otherwise return sync on the success path, and the wrapper covers it.
  • Object.keys over for...in in createErrorHelpers, and the new isPlainObject no longer treating arrays as mergeable, are both real fixes.

🤖 Reviewed with Claude Code (Opus 5)

Comment thread src/index.ts Resolved
Comment thread test/contracts.test.ts Resolved
Comment thread src/utils.ts Resolved
Comment thread src/utils.ts Resolved
Comment thread test/utils.test.ts Resolved
@tunnckoCore

Copy link
Copy Markdown
Owner

Implemented the aligned disposition of the Claude review in 8c9a6e0:

  1. Type tooling: the explicit tsgo dependency remains removed. The tsgo-dev registry entry currently has zero published versions, so versionless bunx tsgo-dev cannot resolve, and -p tsconfig is not a valid path in this repository. The script now uses the official dependency-free native runner: bunx @typescript/native-preview -p tsconfig.json.
  2. Indexed env sources: fixed. An env source with a string index signature is accepted after an .env() schema is declared; finite object literals still receive excess-key diagnostics.
  3. Env without .env(): intentionally remains banned. Passing runtime env requires declaring its type/schema through .env() first.
  4. Context roots: intentionally only record-shaped plain objects. Interface-shaped roots and class-instance roots are unsupported; class instances remain valid nested values such as { db }.
  5. deepMerge: restored to direct Record<string, unknown> root parameters and plain-object runtime enforcement. Nested dependency instances are preserved/replaced as values rather than recursively flattened.
  6. Async cache docs: corrected only the parenthetical return type to ZagoraResult | Promise<ZagoraResult>; the procedure is still async at runtime when the cache is async, while Standard Schema limitations keep the type-level union necessary.

Verification passed: format, native typecheck, lint, and build.

@tunnckoCore

Copy link
Copy Markdown
Owner

@codex review this

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (5)
test/utils.test.ts (1)

137-137: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid the constructor parameter property.

Declare name as 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 value

Assert the adapter shape on the source object, not on the annotated variable.

mixedAdapter is annotated as CacheAdapter, so toExtend<CacheAdapter>() holds by construction. The assertion does not check that asyncHasCache satisfies 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 win

Self-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 to any, and it does not confirm the concrete ZagoraResult payload. Pin the expected type explicitly, for example ZagoraResult<string, ...> | Promise<ZagoraResult<string, ...>>, or add a companion assertion such as expectTypeOf<Awaited<T>>().toEqualTypeOf<ZagoraResult<...>>().

  • test/types-testing.test.ts#L273-L276: replace the derived expectation for MixedErrorsMapResult with the explicit result union.
  • test/types-testing.test.ts#L367-L370: replace the derived expectation for BuilderCachedResult with the explicit result union.
  • test/types-testing.test.ts#L376-L379: replace the derived expectation for CallableCachedResult with the explicit result union.
  • test/types-testing.test.ts#L388-L391: replace the derived expectation for AutoCachedResult with the explicit result union.
  • test/types-testing.test.ts#L408-L414: replace the derived expectation for OptionallyOverriddenResult with the explicit result union.
  • test/types-testing.test.ts#L419-L422: replace the derived expectation for UndefinedOverrideResult with the explicit result union.
  • test/types-testing.test.ts#L431-L434: replace the derived expectation for MaybeHandlerResult with 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 win

Remove explicit any assertions from builder paths.

These assertions bypass generic contract checking.

  • src/index.ts#L226-L226: construct Zagora with the declared generic arguments instead of casting the result to any.
  • src/index.ts#L552-L552: connect options.env to the effective environment generic and pass it without as 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 win

Remove explicit any from contract tests.

Use unknown for the assertion-helper input. Use a deliberate invalid-input escape such as as never for runtime validation tests.

  • test/contracts.test.ts#L31-L31: change result: any to result: unknown.
  • test/contracts.test.ts#L288-L288: replace 123 as any with a non-any invalid-input test value.
  • test/contracts.test.ts#L321-L321: replace 123 as any with a non-any invalid-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

📥 Commits

Reviewing files that changed from the base of the PR and between 9985427 and 8c9a6e0.

📒 Files selected for processing (7)
  • README.md
  • package.json
  • src/index.ts
  • src/utils.ts
  • test/contracts.test.ts
  • test/types-testing.test.ts
  • test/utils.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • README.md
  • src/utils.ts

Comment thread package.json Resolved
Comment thread src/index.ts Resolved
Comment thread test/types-testing.test.ts Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 8c9a6e0beb

ℹ️ 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".

@tunnckoCore

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/types.ts Resolved
Comment thread src/utils.ts Resolved
@tunnckoCore

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/index.ts Resolved
Comment thread src/utils.ts Resolved
@tunnckoCore
tunnckoCore dismissed their stale review August 10, 2026 21:29

All requested changes are complete. All review threads are resolved.

@tunnckoCore
tunnckoCore merged commit ba4d93e into tunnckoCore:master Aug 24, 2026
2 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants