Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Nov 27, 2025

Summary by CodeRabbit

  • New Features

    • Authentication typing extended to accept both model-based and type-definition-based auth schemas, improving flexibility and type safety.
    • Conditional typing enhancements to allow partial and array-aware type definitions for custom auth types.
  • Tests

    • Added end-to-end tests and sample schema to validate custom authentication typing integration and behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings November 27, 2025 04:04
@coderabbitai
Copy link

coderabbitai bot commented Nov 27, 2025

Walkthrough

This PR expands the ORM's TypeScript typings to support type-definition (TypeDef) based auth types, adds conditional utility types (PartialIf, ArrayIf), refines TypeDefResult with a Partial flag, introduces TypeDefFieldIsArray, and adds E2E tests and generated test schema for auth-type validation. (49 words)

Changes

Cohort / File(s) Summary
Auth type conditional
packages/orm/src/client/contract.ts
Extended AuthType<Schema> conditional to accept GetTypeDefs in addition to GetModels, resolving to TypeDefResult<...> for TypeDef-based auth; added type imports GetTypeDefs and TypeDefResult.
TypeDef result & field mapping
packages/orm/src/client/crud-types.ts
Added Partial extends boolean = false to TypeDefResult; renamed/generalized MapTypeDefFieldTypeMapFieldDefType and threaded Partial through field mapping; switched optionality handling to PartialIf and updated nested TypeDef resolution to include Record<string, unknown>.
Type utilities
packages/orm/src/utils/type-utils.ts
Added PartialIf<T, Condition extends boolean> and ArrayIf<T, Condition extends boolean> exports.
Schema types
packages/schema/src/schema.ts
Broadened SchemaDef.authType to allow `GetModels
E2E test files — schema
tests/e2e/orm/schemas/auth-type/schema.zmodel, .../schema.ts, .../models.ts, .../input.ts
Added test schema (SQLite) with Permission and Auth type (Auth marked as @@auth) and Foo model; generated schema/types/models and operation type aliases for the auth-type scenario.
E2E test
tests/e2e/orm/client-api/auth-typing.test.ts
New end-to-end test verifying custom auth typing via db.$setAuth using the TypeDef-based Auth (id, role, permissions array) shape.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Areas needing attention:
    • TypeDefResult changes and PartialIf interaction for optional/partial behavior.
    • Nested TypeDef resolution (MapFieldDefType) and its interplay with ArrayIf.
    • AuthType conditional ordering and compatibility with existing model-based auth flows.
    • Generated test schema and test correctness vs. the new typings.

Possibly related PRs

Poem

🐰
I nibble through types, keen and spry,
TypeDefs bloom where auth used to lie.
Partial flags wiggle, arrays hop in line,
Nested shapes resolve—oh what design!
Hoppy typings, small and fine.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately describes the main change: fixing a typing issue when authentication type is defined as a typedef, which aligns with the core modifications extending AuthType to support TypeDef-based auth.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/auth-type

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 and usage tips.

@claude
Copy link

claude bot commented Nov 27, 2025

Claude finished @ymc9's task —— View job


PR Review: Auth Type Typedef Fix

I've thoroughly analyzed this PR that fixes typing issues when auth type is a typedef. Here's my comprehensive review:

Todo List

  • Read and analyze all changed files
  • Review core typing changes in orm package
  • Examine test coverage and new test files
  • Provide feedback on code quality and best practices
  • Check for potential bugs or issues
  • Assess performance and security considerations

📋 Summary

This PR addresses a typing issue in ZenStack's ORM package where auth types defined as typedefs weren't properly supported. The fix adds support for typedef-based auth types alongside the existing model-based auth types.

Excellent Work - Code Quality & Implementation

Strong Points:

  1. Clean Type System Enhancement (packages/orm/src/client/contract.ts:858-863)

    • The AuthType type properly handles both model-based and typedef-based auth types using conditional types
    • Excellent use of TypeScript's discriminated unions to distinguish between models and typedefs
  2. Comprehensive Type Infrastructure (packages/orm/src/client/crud-types.ts:252-280)

    • Added TypeDefResult type that correctly handles typedef field mapping
    • Proper support for nested typedefs and array fields
    • Well-structured optionality handling with PartialIf conditional type
  3. Schema Definition Enhancement (packages/schema/src/schema.ts:18)

    • Clean addition of authType field to support both models and typedefs
    • Maintains backward compatibility
  4. Excellent Test Coverage

    • Complete test setup with schema, models, and client API tests
    • Real-world scenario testing with nested typedef structures (Auth type with Permission array)
    • Type-safe auth context usage in tests

Code Quality Highlights:

  • Type Safety: Proper TypeScript conditional types ensure compile-time safety
  • Maintainability: Changes are well-organized and follow existing patterns
  • Extensibility: The solution supports future typedef enhancements
  • Documentation: Auto-generated files are properly marked as such

🔧 Technical Implementation Review

Core Changes Analysis:

  1. AuthModelType Enhancement: Correctly handles recursive typedef types for nested auth data structures
  2. TypeDefResult Implementation: Robust field mapping that handles optionality and arrays correctly
  3. Schema Integration: Clean integration of typedef auth types into the existing schema definition

Type System Correctness:

  • Proper use of GetTypeDefs and GetModels for type extraction
  • Correct conditional type logic for distinguishing between models and typedefs
  • Well-structured recursive types for nested typedef handling

🚫 No Issues Found

Security: No security concerns - purely type-level changes
Performance: No runtime performance impact - compile-time only changes
Bug Risk: Very low - well-isolated changes with comprehensive tests
Breaking Changes: None - maintains full backward compatibility

📊 Test Coverage Assessment

Excellent test coverage:

  • ✅ Schema generation test (typedef to TypeScript compilation)
  • ✅ Type validation test (auth context assignment)
  • ✅ Integration test (client creation and auth setting)
  • ✅ Real-world scenario (complex nested typedef structure)

🎯 Recommendations

This PR is ready for merge. The implementation is:

  • Well-architected and follows TypeScript best practices
  • Thoroughly tested with realistic use cases
  • Maintains backward compatibility
  • Addresses the typedef auth typing issue completely

Minor suggestion for future enhancement:
Consider adding JSDoc comments to the new TypeDefResult type for better developer experience, though this is not blocking for this PR.


Overall Assessment: ⭐⭐⭐⭐⭐ Excellent

This is a high-quality fix that properly addresses the auth typedef typing issue with clean implementation and comprehensive test coverage. The solution is well-architected and ready for production use.


Copy link

@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 (1)
tests/e2e/orm/client-api/auth-typing.test.ts (1)

6-17: Missing required name field in auth object.

The Auth TypeDef in schema.zmodel has a required name: String field, but this test omits it. Since AuthType uses TypeDefResult<Schema, 'Auth', true> with Partial=true, all fields become optional for the auth context.

This is likely intentional design (auth context can be partial), but consider adding a comment explaining that auth objects are intentionally partial, or add a second test case that includes all fields to validate the complete type works as well.

 describe('Custom auth typing tests', () => {
     it('works with custom auth typing', async () => {
         const db = await createTestClient(schema);
+        // Auth context accepts partial data - not all fields required
         db.$setAuth({
             id: 1,
             role: 'ADMIN',
             permissions: [
                 {
                     actionCode: 'MANAGE',
                 },
             ],
         });
     });
+
+    it('works with complete auth object', async () => {
+        const db = await createTestClient(schema);
+        db.$setAuth({
+            id: 1,
+            name: 'Admin User',
+            role: 'ADMIN',
+            permissions: [{ actionCode: 'MANAGE' }],
+        });
+    });
 });
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fbcc6e4 and 094dcfb.

📒 Files selected for processing (9)
  • packages/orm/src/client/contract.ts (3 hunks)
  • packages/orm/src/client/crud-types.ts (2 hunks)
  • packages/orm/src/utils/type-utils.ts (1 hunks)
  • packages/schema/src/schema.ts (1 hunks)
  • tests/e2e/orm/client-api/auth-typing.test.ts (1 hunks)
  • tests/e2e/orm/schemas/auth-type/input.ts (1 hunks)
  • tests/e2e/orm/schemas/auth-type/models.ts (1 hunks)
  • tests/e2e/orm/schemas/auth-type/schema.ts (1 hunks)
  • tests/e2e/orm/schemas/auth-type/schema.zmodel (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
tests/e2e/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

E2E tests should validate real-world schema compatibility with established projects

Files:

  • tests/e2e/orm/client-api/auth-typing.test.ts
  • tests/e2e/orm/schemas/auth-type/models.ts
  • tests/e2e/orm/schemas/auth-type/schema.ts
  • tests/e2e/orm/schemas/auth-type/input.ts
**/*.zmodel

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.zmodel: Always run zenstack generate after modifying ZModel schemas
ZModel schema files should define database structure and policies that compile to TypeScript via zenstack generate

Files:

  • tests/e2e/orm/schemas/auth-type/schema.zmodel
🧠 Learnings (8)
📓 Common learnings
Learnt from: ymc9
Repo: zenstackhq/zenstack-v3 PR: 319
File: packages/runtime/src/client/executor/zenstack-query-executor.ts:63-72
Timestamp: 2025-10-21T16:09:31.218Z
Learning: In ZenStack, TypeDefs can be inherited by models. When a TypeDef contains fields with `map` attributes, those mapped field names need to be processed by the QueryNameMapper since they become part of the inheriting model's schema. Therefore, when checking if a schema has mapped names (e.g., in `schemaHasMappedNames`), both `schema.models` and `schema.typeDefs` must be inspected for `@map` and `map` attributes.
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.{ts,tsx} : Implement plugin hooks at ORM, Kysely, and entity mutation levels for query interception and customization
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/**/type*.{ts,tsx} : Ensure TypeScript inference and type coverage are validated through type coverage tests
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/e2e/**/*.{ts,tsx} : E2E tests should validate real-world schema compatibility with established projects

Applied to files:

  • tests/e2e/orm/client-api/auth-typing.test.ts
  • tests/e2e/orm/schemas/auth-type/models.ts
  • tests/e2e/orm/schemas/auth-type/schema.ts
  • tests/e2e/orm/schemas/auth-type/input.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.test.{ts,tsx} : ORM package tests should include comprehensive client API tests and policy tests

Applied to files:

  • tests/e2e/orm/client-api/auth-typing.test.ts
  • tests/e2e/orm/schemas/auth-type/models.ts
  • packages/orm/src/client/contract.ts
  • tests/e2e/orm/schemas/auth-type/schema.ts
  • tests/e2e/orm/schemas/auth-type/input.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/**/type*.{ts,tsx} : Ensure TypeScript inference and type coverage are validated through type coverage tests

Applied to files:

  • tests/e2e/orm/client-api/auth-typing.test.ts
  • tests/e2e/orm/schemas/auth-type/models.ts
  • tests/e2e/orm/schemas/auth-type/schema.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to **/*.zmodel : ZModel schema files should define database structure and policies that compile to TypeScript via `zenstack generate`

Applied to files:

  • tests/e2e/orm/schemas/auth-type/models.ts
  • tests/e2e/orm/schemas/auth-type/schema.zmodel
  • tests/e2e/orm/schemas/auth-type/schema.ts
  • tests/e2e/orm/schemas/auth-type/input.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.{ts,tsx} : Implement plugin hooks at ORM, Kysely, and entity mutation levels for query interception and customization

Applied to files:

  • tests/e2e/orm/schemas/auth-type/models.ts
  • tests/e2e/orm/schemas/auth-type/schema.ts
  • tests/e2e/orm/schemas/auth-type/input.ts
📚 Learning: 2025-10-21T16:09:31.218Z
Learnt from: ymc9
Repo: zenstackhq/zenstack-v3 PR: 319
File: packages/runtime/src/client/executor/zenstack-query-executor.ts:63-72
Timestamp: 2025-10-21T16:09:31.218Z
Learning: In ZenStack, TypeDefs can be inherited by models. When a TypeDef contains fields with `map` attributes, those mapped field names need to be processed by the QueryNameMapper since they become part of the inheriting model's schema. Therefore, when checking if a schema has mapped names (e.g., in `schemaHasMappedNames`), both `schema.models` and `schema.typeDefs` must be inspected for `@map` and `map` attributes.

Applied to files:

  • tests/e2e/orm/schemas/auth-type/models.ts
  • packages/schema/src/schema.ts
  • packages/orm/src/client/contract.ts
  • tests/e2e/orm/schemas/auth-type/schema.ts
  • packages/orm/src/client/crud-types.ts
📚 Learning: 2025-11-26T01:55:04.540Z
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.{ts,tsx} : Use Kysely as the query builder interface for low-level database queries, avoiding raw SQL when possible

Applied to files:

  • tests/e2e/orm/schemas/auth-type/models.ts
  • tests/e2e/orm/schemas/auth-type/schema.ts
  • tests/e2e/orm/schemas/auth-type/input.ts
🧬 Code graph analysis (2)
tests/e2e/orm/client-api/auth-typing.test.ts (2)
packages/testtools/src/client.ts (1)
  • createTestClient (99-248)
tests/e2e/orm/schemas/auth-type/schema.ts (1)
  • schema (73-73)
tests/e2e/orm/schemas/auth-type/schema.ts (1)
packages/schema/src/schema.ts (1)
  • SchemaDef (11-19)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Agent
  • GitHub Check: claude-review
  • GitHub Check: build-test (20.x, sqlite)
  • GitHub Check: build-test (20.x, postgresql)
🔇 Additional comments (8)
packages/orm/src/utils/type-utils.ts (1)

5-9: LGTM!

The new conditional type utilities PartialIf and ArrayIf follow the established patterns in this file (similar to NullableIf on line 7) and provide clean, reusable type transformations for the TypeDef handling.

tests/e2e/orm/schemas/auth-type/models.ts (1)

1-12: LGTM!

Auto-generated file correctly exports the model and TypeDef result types. The TypeDefResult usage for Permission and Auth aligns with the PR's objective of supporting TypeDef-based auth types.

packages/schema/src/schema.ts (1)

244-249: LGTM!

The TypeDefFieldIsArray type follows the established pattern of TypeDefFieldIsOptional and correctly extracts the array status from TypeDef field definitions.

tests/e2e/orm/schemas/auth-type/schema.ts (1)

1-74: LGTM!

Auto-generated schema correctly represents the ZModel definitions. Key elements:

  • authType: "Auth" enables TypeDef-based auth typing
  • permissions field properly marked with array: true
  • Schema satisfies SchemaDef constraint
packages/orm/src/client/crud-types.ts (2)

252-280: LGTM! Well-structured recursive TypeDef handling.

The updated TypeDefResult correctly:

  1. Adds a Partial generic that propagates through nested TypeDefs
  2. Uses ArrayIf to wrap nested TypeDef results when the field is an array
  3. When Partial=true, all fields become optional via PartialIf, and the optional keys become never (avoiding double-optionality)
  4. When Partial=false, maintains existing optionality behavior

The recursive call on line 265 properly passes the Partial flag to nested TypeDefs.


32-48: Imports correctly added.

New imports for TypeDefFieldIsArray, ArrayIf, and PartialIf are properly added to support the enhanced TypeDefResult type.

tests/e2e/orm/schemas/auth-type/schema.zmodel (1)

10-17: @id on TypeDef fields is valid and intentional in ZenStack.

After verification, the Auth TypeDef with @id is correct. This is an established pattern in ZenStack schemas—the CommonFields type used throughout the codebase also defines @id @default(cuid()) on a TypeDef. The @@auth attribute marks Auth as the authentication context type, and the @id field is valid metadata for the auth schema structure.

Likely an incorrect or invalid review comment.

tests/e2e/orm/schemas/auth-type/input.ts (1)

8-30: Generated Foo model aliases correctly mirror ORM CRUD generics

The Foo-specific argument and payload aliases are wired cleanly to the generic @zenstackhq/orm types ($Find*Args, $Create*Args, $Update*Args, $Delete*Args, $WhereInput, $SelectInput, $IncludeInput, $OmitInput, SelectIncludeOmit, SimplifiedModelResult). FooGetPayload’s generic constraints and default Options match the expected pattern and should give solid type inference for the e2e auth-type tests.

Copilot finished reviewing on behalf of ymc9 November 27, 2025 04:08
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a TypeScript typing issue that occurred when using a typedef (custom type) as the authentication type with nested typedef fields that are arrays. The fix enhances the type system to properly handle recursive typedef resolution and array typing in auth contexts.

Key changes:

  • Added support for recursive typedef field resolution with proper array and partial handling
  • Extended auth type support from models-only to both models and typedefs
  • Added utility types (PartialIf, ArrayIf, TypeDefFieldIsArray) following existing patterns

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated no comments.

Show a summary per file
File Description
tests/e2e/orm/schemas/auth-type/schema.zmodel New test schema defining Auth typedef with nested Permission[] typedef field
tests/e2e/orm/schemas/auth-type/schema.ts Auto-generated schema file with typedef metadata including array flags
tests/e2e/orm/schemas/auth-type/models.ts Auto-generated type exports for typedefs using TypeDefResult
tests/e2e/orm/schemas/auth-type/input.ts Auto-generated input types for the test model
tests/e2e/orm/client-api/auth-typing.test.ts Typing test validating $setAuth works with typedef auth containing arrays
packages/schema/src/schema.ts Added TypeDefFieldIsArray helper to check if typedef fields are arrays
packages/orm/src/utils/type-utils.ts Added PartialIf and ArrayIf utility types for conditional type transformations
packages/orm/src/client/crud-types.ts Enhanced TypeDefResult to handle recursive typedefs, arrays, and partial mode
packages/orm/src/client/contract.ts Updated AuthType to support typedef-based auth with proper partial typing

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review for a chance to win a $100 gift card. Take the survey.

@claude
Copy link

claude bot commented Nov 27, 2025

Claude finished @ymc9's task —— View job


PR Review: Auth Type Typedef Fix

I've thoroughly analyzed this PR that fixes typing issues when auth type is a typedef. Here's my comprehensive review:

Todo List

  • Read and analyze all changed files
  • Review core typing changes in orm package
  • Examine test coverage and new test files
  • Provide feedback on code quality and best practices
  • Check for potential bugs or issues
  • Assess performance and security considerations

📋 Summary

This PR addresses a typing issue in ZenStack's ORM package where auth types defined as typedefs weren't properly supported. The fix adds support for typedef-based auth types alongside the existing model-based auth types.

Excellent Work - Code Quality & Implementation

Strong Points:

  1. Clean Type System Enhancement (packages/orm/src/client/contract.ts:858-863)

    • The AuthType type properly handles both model-based and typedef-based auth types using conditional types
    • Excellent use of TypeScript's discriminated unions to distinguish between models and typedefs
  2. Comprehensive Type Infrastructure (packages/orm/src/client/crud-types.ts:252-280)

    • Added TypeDefResult type that correctly handles typedef field mapping
    • Proper support for nested typedefs and array fields
    • Well-structured optionality handling with PartialIf conditional type
  3. Schema Definition Enhancement (packages/schema/src/schema.ts:18)

    • Clean addition of authType field to support both models and typedefs
    • Maintains backward compatibility
  4. Excellent Test Coverage

    • Complete test setup with schema, models, and client API tests
    • Real-world scenario testing with nested typedef structures (Auth type with Permission array)
    • Type-safe auth context usage in tests

Code Quality Highlights:

  • Type Safety: Proper TypeScript conditional types ensure compile-time safety
  • Maintainability: Changes are well-organized and follow existing patterns
  • Extensibility: The solution supports future typedef enhancements
  • Documentation: Auto-generated files are properly marked as such

🔧 Technical Implementation Review

Core Changes Analysis:

  1. AuthModelType Enhancement: Correctly handles recursive typedef types for nested auth data structures
  2. TypeDefResult Implementation: Robust field mapping that handles optionality and arrays correctly
  3. Schema Integration: Clean integration of typedef auth types into the existing schema definition

Type System Correctness:

  • Proper use of GetTypeDefs and GetModels for type extraction
  • Correct conditional type logic for distinguishing between models and typedefs
  • Well-structured recursive types for nested typedef handling

🚫 No Issues Found

Security: No security concerns - purely type-level changes
Performance: No runtime performance impact - compile-time only changes
Bug Risk: Very low - well-isolated changes with comprehensive tests
Breaking Changes: None - maintains full backward compatibility

📊 Test Coverage Assessment

Excellent test coverage:

  • ✅ Schema generation test (typedef to TypeScript compilation)
  • ✅ Type validation test (auth context assignment)
  • ✅ Integration test (client creation and auth setting)
  • ✅ Real-world scenario (complex nested typedef structure)

🎯 Recommendations

This PR is ready for merge. The implementation is:

  • Well-architected and follows TypeScript best practices
  • Thoroughly tested with realistic use cases
  • Maintains backward compatibility
  • Addresses the typedef auth typing issue completely

Minor suggestion for future enhancement:
Consider adding JSDoc comments to the new TypeDefResult type for better developer experience, though this is not blocking for this PR.


Overall Assessment: ⭐⭐⭐⭐⭐ Excellent

This is a high-quality fix that properly addresses the auth typedef typing issue with clean implementation and comprehensive test coverage. The solution is well-architected and ready for production use.


Copy link

@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 (1)
packages/orm/src/client/crud-types.ts (1)

635-647: MapFieldDefType generalization looks correct; minor redundancy possible

The generalized MapFieldDefType correctly:

  • Handles enums via GetEnums<Schema>.
  • Expands typedef-typed fields through TypeDefResult<Schema, T['type'], Partial>.
  • Propagates Partial for nested typedefs and still defers nullability/array wrapping to WrapType.

One tiny cleanup: since TypeDefResult already ends with & Record<string, unknown>, the extra & Record<string, unknown> in the typedef branch is redundant and could be dropped to simplify printed types, if you care about readability.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 094dcfb and b226eaf.

📒 Files selected for processing (2)
  • packages/orm/src/client/crud-types.ts (3 hunks)
  • packages/schema/src/schema.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.test.{ts,tsx} : ORM package tests should include comprehensive client API tests and policy tests
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to packages/zenstackhq/orm/**/*.{ts,tsx} : Implement plugin hooks at ORM, Kysely, and entity mutation levels for query interception and customization
Learnt from: CR
Repo: zenstackhq/zenstack-v3 PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-26T01:55:04.540Z
Learning: Applies to tests/e2e/**/*.{ts,tsx} : E2E tests should validate real-world schema compatibility with established projects
📚 Learning: 2025-10-21T16:09:31.218Z
Learnt from: ymc9
Repo: zenstackhq/zenstack-v3 PR: 319
File: packages/runtime/src/client/executor/zenstack-query-executor.ts:63-72
Timestamp: 2025-10-21T16:09:31.218Z
Learning: In ZenStack, TypeDefs can be inherited by models. When a TypeDef contains fields with `map` attributes, those mapped field names need to be processed by the QueryNameMapper since they become part of the inheriting model's schema. Therefore, when checking if a schema has mapped names (e.g., in `schemaHasMappedNames`), both `schema.models` and `schema.typeDefs` must be inspected for `@map` and `map` attributes.

Applied to files:

  • packages/schema/src/schema.ts
  • packages/orm/src/client/crud-types.ts
🧬 Code graph analysis (1)
packages/orm/src/client/crud-types.ts (2)
packages/schema/src/schema.ts (5)
  • SchemaDef (11-19)
  • GetTypeDefs (142-142)
  • GetTypeDefFields (172-175)
  • GetTypeDefField (177-181)
  • TypeDefFieldIsOptional (238-242)
packages/orm/src/utils/type-utils.ts (3)
  • PartialIf (5-5)
  • Optional (3-3)
  • WrapType (25-31)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build-test (20.x, postgresql)
  • GitHub Check: build-test (20.x, sqlite)
  • GitHub Check: claude-review
🔇 Additional comments (3)
packages/schema/src/schema.ts (2)

18-18: Auth type now correctly accepts both model and typedef names

Extending authType to GetModels<SchemaDef> | GetTypeDefs<SchemaDef> aligns the schema contract with typedef‑based auth without changing runtime behavior; looks good.


244-248: TypeDefFieldIsArray helper is consistent and reusable

This mirrors TypeDefFieldIsOptional and cleanly exposes the array flag for typedef fields; good addition for downstream conditional typing.

packages/orm/src/client/crud-types.ts (1)

250-274: Partial-aware TypeDefResult preserves existing semantics

The new TypeDefResult<..., Partial> keeps the old behavior when Partial is false and cleanly switches to “all fields optional” (including nested typedefs, via MapFieldDefType) when Partial is true. The use of Optional for schema‑declared optional fields plus PartialIf for the mode flag is sound and backwards‑compatible.

@ymc9 ymc9 merged commit d73c49e into dev Nov 27, 2025
6 checks passed
@ymc9 ymc9 deleted the fix/auth-type branch November 27, 2025 04:41
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.

2 participants