Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Nov 21, 2025

fixes #2294

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 21, 2025

📝 Walkthrough

Walkthrough

Adds TypeDef-aware handling to the enhancer: auth type generation now detects TypeDef vs DataModel, tracks per-type isTypeDef and required relations, renders type references conditionally as $TypeDefs. or _P. based on Prisma generator, injects json-types import when needed, and adds tests including a regression for #2294.

Changes

Cohort / File(s) Summary
Auth type generator
packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts
Add isTypeDef tracking in per-type metadata; introduce findType(name) to locate DataModel or TypeDef; replace field helpers with addTypeField storing requiredRelations by type name; index/render types by name; get Prisma generator via getPrismaClientGenerator(model) and render references as $TypeDefs.<Type> when new generator + TypeDef, otherwise _P.<Type>.
Enhancer import generation
packages/schema/src/plugins/enhancer/enhance/index.ts
Detect presence of TypeDef declarations (hasTypeDef) at runtime; when hasTypeDef and using the new Prisma client generator, append import type * as $TypeDefs from './json-types' to generated imports; otherwise keep legacy import path.
Tests — integration & regression
tests/integration/tests/enhancements/with-policy/auth.test.ts, tests/regression/tests/issue-2294.test.ts
Rename existing auth test for the legacy generator; add a parallel compile-time test exercising the new Prisma generator flow; add regression test for issue #2294 to ensure TypeDef (@@auth) types are preserved and runtime enhance works with generated JSON types.

Sequence Diagram(s)

sequenceDiagram
    participant Schema
    participant Enhancer
    participant AuthGen
    participant Output

    Schema->>Enhancer: load schema (models + TypeDefs)
    Enhancer->>Enhancer: detect hasTypeDef flag
    Enhancer->>Enhancer: getPrismaClientGenerator(model) -> isNewGenerator

    alt hasTypeDef && isNewGenerator
        Enhancer->>Output: include "import type * as $TypeDefs from './json-types'"
    else
        Enhancer->>Output: include legacy `_P` imports
    end

    Enhancer->>AuthGen: request auth namespace generation
    AuthGen->>AuthGen: findType(name) -> DataModel | TypeDef
    AuthGen->>AuthGen: record typeInfo { isTypeDef, requiredRelations }
    AuthGen->>Output: render auth types
    alt isNewGenerator && typeInfo.isTypeDef
        Output->>Schema: reference $TypeDefs.<Type>
    else
        Output->>Schema: reference _P.<Type>
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review focus:
    • auth-type-generator.ts: correctness of findType, isTypeDef derivation, and requiredRelations aggregation.
    • Conditional rendering choosing $TypeDefs.<Type> vs _P.<Type> and interaction with getPrismaClientGenerator.
    • enhance/index.ts import injection and hasTypeDef detection.
    • New/updated tests for both generator flows and regression coverage.

Possibly related PRs

  • #2151 — Adds/uses getPrismaClientGenerator and branches generation for the new prisma-client generator (isNewGenerator handling).
  • #2270 — Adjusts enhancer generation to detect the new Prisma client generator and modify type import/usage for TypeDefs/json-types.
  • #2182 — Modifies enhancer import generation and runtime branching between new and legacy Prisma client imports (relevant to conditional $TypeDefs import).

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main issue: fixing compilation for types with @@auth when using the new Prisma-client generator.
Description check ✅ Passed The description references issue #2294, which matches the PR objectives and the changes made throughout the codebase.
Linked Issues check ✅ Passed The PR changes directly address issue #2294 by detecting TypeDef declarations, importing JSON types, and using dynamic type references ($TypeDefs vs _P) based on generator type.
Out of Scope Changes check ✅ Passed All changes are scoped to supporting Prisma type declarations with @@auth: auth-type-generator.ts updates logic, index.ts adds TypeDefs import, and tests verify both legacy and new generator paths.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ 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/issue-2294

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 58204be and 01d4dba.

📒 Files selected for processing (1)
  • packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (1)
packages/sdk/src/utils.ts (2)
  • getPrismaClientGenerator (709-732)
  • getIdFields (521-541)
⏰ 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: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
🔇 Additional comments (4)
packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (4)

1-11: Auth declaration widened to DataModel | TypeDef looks consistent

Importing getPrismaClientGenerator/isTypeDef and typing authDecl as DataModel | TypeDef align with the goal of supporting @@auth on type. Call sites should now get proper compile‑time coverage for both variants; I don’t see any runtime risk introduced here.

Also applies to: 19-20


20-57: Per‑type metadata and helpers are sound and guard against missing declarations

Storing isTypeDef alongside requiredRelations and using findType from model.declarations in both ensureType and addTypeField, with an early return when decl is missing, keeps the map consistent and prevents crashes when a relation target can’t be resolved. The duplication between ensureType and the first half of addTypeField is minor and acceptable given the current scope.


63-89: The original review comment is based on incorrect assumptions and should be disregarded

The code correctly restricts relation handling to DataModel targets. TypeDef fields in the schema are not relations in the Prisma sense—they are JSON-typed custom structures that require the @json attribute, not @relation. The codebase consistently shows this distinction (e.g., datamodel-validator.ts line 111–112 enforces @json on TypeDef fields), so there is no future scenario where TypeDef-to-TypeDef or DataModel-to-TypeDef "relations" would need to be included in the auth context. The isDataModel filters are correct and require no extension.

Likely an incorrect or invalid review comment.


91-93: Verification confirms the implementation is sound

The conditional logic correctly selects between $TypeDefs.<Type> and _P.<Type>: json-types.ts is only generated when TypeDefs exist and the import is properly guarded by hasTypeDef && this.isNewPrismaClientGenerator. The runtime selection at line 107 uses both isNewGenerator && typeInfo.isTypeDef to switch references, ensuring TypeDefs use the new path while models and the old generator continue as before. The composed types remain structurally unchanged, confirming low regression risk.


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.

Copy link
Contributor

@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/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (1)

44-54: Consider defensive check for undefined declaration.

At line 48, isTypeDef(decl) is called where decl might be undefined if findType returns no match. While type guards typically handle undefined gracefully, adding an explicit check would make the code more robust and prevent adding non-existent types to the map.

 const addTypeField = (typeName: string, fieldName: string, fieldType: string, array: boolean) => {
     let typeInfo = types.get(typeName);
     if (!typeInfo) {
         const decl = findType(typeName);
+        if (!decl) {
+            return;
+        }
         typeInfo = { isTypeDef: isTypeDef(decl), requiredRelations: [] };
         types.set(typeName, typeInfo);
     }
     if (!typeInfo.requiredRelations.find((f) => f.name === fieldName)) {
         typeInfo.requiredRelations.push({ name: fieldName, type: array ? `${fieldType}[]` : fieldType });
     }
 };
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c23ff10 and 3c6a135.

📒 Files selected for processing (4)
  • packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (5 hunks)
  • packages/schema/src/plugins/enhancer/enhance/index.ts (1 hunks)
  • tests/integration/tests/enhancements/with-policy/auth.test.ts (2 hunks)
  • tests/regression/tests/issue-2294.test.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
tests/integration/tests/enhancements/with-policy/auth.test.ts (1)
packages/testtools/src/schema.ts (1)
  • loadSchema (173-249)
tests/regression/tests/issue-2294.test.ts (1)
packages/testtools/src/schema.ts (1)
  • loadSchema (173-249)
packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (1)
packages/sdk/src/utils.ts (2)
  • getPrismaClientGenerator (709-732)
  • getIdFields (521-541)
⏰ 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: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
🔇 Additional comments (6)
packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (2)

1-8: LGTM! Imports correctly added.

The new imports getPrismaClientGenerator and isTypeDef are properly added to support TypeDef tracking and conditional type reference generation.


88-125: Excellent solution for TypeDef type references!

The conditional type reference logic correctly addresses the core issue from #2294. By detecting the new Prisma client generator and using $TypeDefs for TypeDefs (which are generated in json-types.ts) versus _P for the legacy path, this ensures auth types work correctly across both generator versions.

tests/regression/tests/issue-2294.test.ts (1)

1-48: LGTM! Effective regression test for issue #2294.

This test correctly validates the fix by:

  • Using the new "prisma-client" generator
  • Declaring AuthUser as a type (not model) with @@auth
  • Verifying the generated code compiles and can be imported

This directly addresses the reported issue where TypeDef auth types were undefined in generated enhancement files.

packages/schema/src/plugins/enhancer/enhance/index.ts (1)

325-331: LGTM! Conditional import enables TypeDef references.

The hasTypeDef check correctly detects TypeDef declarations and conditionally imports $TypeDefs from json-types when using the new generator. This import is essential for the $TypeDefs.${type} references generated by auth-type-generator.ts to resolve correctly.

tests/integration/tests/enhancements/with-policy/auth.test.ts (2)

868-922: LGTM! Backwards compatibility preserved.

Renaming the existing test to clarify it targets the legacy generator path ensures clear test coverage and maintains validation of the existing functionality.


924-993: LGTM! Comprehensive test coverage for new generator.

The new test effectively validates TypeDef auth types with the new "prisma-client" generator by:

  • Explicitly configuring the new generator in the schema
  • Using custom output paths to test the new code generation paths
  • Testing the same policy scenarios as the legacy test to ensure functional parity
  • Verifying compilation succeeds with generated types

This provides strong confidence that the fix works correctly for the new generator.

Copy link
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c6a135 and 58204be.

📒 Files selected for processing (1)
  • packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (1)
packages/sdk/src/utils.ts (2)
  • getPrismaClientGenerator (709-732)
  • getIdFields (521-541)
⏰ 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: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
🔇 Additional comments (2)
packages/schema/src/plugins/enhancer/enhance/auth-type-generator.ts (2)

60-86: Traversal correctly reuses addTypeField and preserves relation semantics

The updated traversal now calls addTypeField with the container type (exprType.name / fieldDecl.$container.name) and the related type name, while ensuring the related type itself is present via ensureType. This keeps requiredRelations keyed by the owning auth/user type and still ensures the relation target gets its own entry in types.

Given the guards (isDataModel(exprType) and isDataModel(fieldType)), this remains constrained to real model relations, and the new isTypeDef flag will be set correctly for TypeDef containers when they appear here.

Looks good to me.


88-106: Dynamic $TypeDefs vs _P selection for TypeDefs vs models looks sound

The isNewGenerator check combined with typeInfo.isTypeDef:

const typeRef = isNewGenerator && typeInfo.isTypeDef ? `$TypeDefs.${type}` : `_P.${type}`;

cleanly addresses the reported issue: for the new prisma-client generator, auth types backed by type/TypeDef now resolve to JSON types ($TypeDefs.X), while DataModels and all legacy generators continue to use _P.X. Reusing getIdFields(authDecl) for both DataModel and TypeDef keeps the “id fields are required” behavior consistent.

Assuming the enhancer’s import logic brings in $TypeDefs only when needed (as described in the PR), this rendering strategy looks correct and backward‑compatible.

Also applies to: 115-118, 122-122

@ymc9 ymc9 merged commit dfa6402 into dev Nov 22, 2025
8 checks passed
@ymc9 ymc9 deleted the fix/issue-2294 branch November 22, 2025 00:21
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