Skip to content

merge dev to main (v3.7.1)#2679

Merged
ymc9 merged 3 commits into
mainfrom
dev
May 23, 2026
Merged

merge dev to main (v3.7.1)#2679
ymc9 merged 3 commits into
mainfrom
dev

Conversation

@ymc9
Copy link
Copy Markdown
Member

@ymc9 ymc9 commented May 22, 2026

Summary by CodeRabbit

Release Notes

  • New Features

    • Added @@delegateMap attribute to map delegate sub-models to custom discriminator values
    • Introduced support for enum-based discriminators in delegate model inheritance
  • Improvements

    • Enhanced Prisma schema generation handling for ID functions

Review Change Stack

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented May 22, 2026

Claude finished @ymc9's task —— View job


PR Review: merge dev to main (v3.7.1)

This is a well-structured release PR merging dev to main for version 3.7.1. Based on my comprehensive analysis, here are my findings:

Code Quality & Best Practices

  • Version Management: All 30+ packages properly bumped to v3.7.1 - excellent monorepo consistency
  • Feature Implementation: The new @@delegateMap attribute is well-architected with proper validation and type safety
  • Testing: Strong test coverage with new focused tests and comprehensive validation scenarios
  • Documentation: Feature properly documented in stdlib.zmodel with clear usage patterns

Technical Implementation Review

New delegateMap Feature (Primary Change)

  • Purpose: Enables explicit discriminator value mapping for delegate sub-models
  • Implementation Quality:
    • Robust validation in datamodel-validator.ts:500-617
    • Type-safe integration with CRUD types via GetModelDelegateMapValue
    • Proper fallback to model name when not specified
    • Schema generation correctly handles both string literals and enum values

Format Args Fix

  • Issue: Prisma schema generation was including format arguments for ID functions
  • Solution: Clean implementation strips format args (cuid, uuid, ulid, nanoid)
  • Testing: Comprehensive test coverage validates the fix

Performance Considerations

  • No performance regressions identified
  • Efficient validation logic with early returns
  • Type-level computations don't impact runtime performance

Security Assessment

  • No security vulnerabilities introduced
  • Input validation properly implemented for delegateMap values
  • Type safety prevents injection of invalid discriminator values
  • Proper error handling without information leakage

Potential Issues Assessment

Minor Observations:

  1. Schema Generation: The format args stripping logic is sound but could potentially affect custom format patterns in edge cases
  2. Validation Complexity: The delegateMap validation logic is comprehensive but adds some complexity to the validator

No Breaking Changes Detected:

  • All changes are additive features or bug fixes
  • Existing delegate functionality remains unchanged
  • Type definitions properly extend existing interfaces

Overall Assessment: APPROVE

This PR represents a high-quality release with:

  • Well-tested new functionality (delegateMap attribute)
  • Important bug fix (format args stripping)
  • Consistent version management across the monorepo
  • No security or performance concerns
  • Clean, maintainable code following established patterns

The implementation follows ZenStack's architecture patterns and maintains backward compatibility while adding valuable new functionality for polymorphic model management.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 22, 2026

📝 Walkthrough

Walkthrough

This release introduces the @@delegateMap attribute to enable explicit discriminator value mapping for delegate models, updates schema generation and ORM runtime to respect those mappings, fixes Prisma ID function schema generation, and migrates E2E tests to typed enum discriminators.

Changes

Delegate Discriminator Mapping and 3.7.1 Release

Layer / File(s) Summary
Package version bump to 3.7.1
package.json, packages/*/package.json, samples/orm/package.json, tests/*/package.json
All packages across the monorepo are bumped from 3.7.0 to 3.7.1 for the release.
Delegate map attribute definition and validation
packages/language/res/stdlib.zmodel, packages/language/src/validators/datamodel-validator.ts, packages/language/test/delegate.test.ts
@@delegateMap attribute is added to the language. Validators enforce single per-model usage, restrict to delegate sub-models, check uniqueness of mapped values across sub-models, and verify value types match discriminator types (string literal for String fields, enum values for enum fields from the correct enum). Tests cover valid patterns and error cases.
Schema definition for delegate map values
packages/schema/src/schema.ts
ModelDef gains optional delegateMap?: string property. Utility type GetModelDelegateMapValue<Schema, Model> resolves the model's discriminator value: returns Model when delegateMap is absent, otherwise the non-undefined mapped value.
Schema generation for delegate map
packages/sdk/src/ts-schema-generator.ts
Schema generator reads @@delegateMap attributes from delegate models and emits the resolved value into the generated schema's delegateMap field. Helper getDelegateMapValue parses @@delegateMap and resolves string literals and enum-field references.
ORM runtime support for delegate discriminator mapping
packages/orm/src/client/query-utils.ts, packages/orm/src/client/crud-types.ts, packages/orm/src/client/crud/operations/base.ts
ORM runtime adds getDelegateDiscriminatorValue to resolve delegate discriminator values from the schema. CRUD types update DelegateUnionResult to use GetModelDelegateMapValue for discriminator field typing. Base operations use the resolved mapped value instead of model name when assigning discriminator fields on create.
Prisma schema generation test and ID function handling
packages/cli/test/prisma-schema-gen.test.ts, packages/sdk/src/prisma/prisma-schema-generator.ts
Test suite verifies PrismaSchemaGenerator correctly strips format arguments from ID functions (ulid, uuid, cuid, nanoid). Generator updated with ID_FUNCTIONS constant and makeFunctionCall filters format-specific arguments before emitting Prisma function calls.
E2E delegate test schema migration to typed enums
tests/e2e/orm/schemas/delegate/schema.zmodel, tests/e2e/orm/schemas/delegate/schema.ts
Delegate E2E schema source adds AssetKind and VideoKind enums, replaces string discriminators with typed enum fields, and includes @@delegateMap directives mapping enum values to delegate targets. Generated schema includes enum definitions and updated discriminator field types.
E2E test assertions updated for delegate enum discriminators
tests/e2e/orm/client-api/delegate.test.ts, tests/e2e/orm/schemas/delegate/typecheck.ts
Client API and type-check tests updated to expect constant-style discriminator values (e.g., ASSET_KIND_VIDEO, VIDEO_KIND_RATED) from the new enum discriminators. Discriminator narrowing and error assertions reflect the new typed enum values throughout create, find, and update operations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • zenstackhq/zenstack#2677: Addresses the same Prisma ID function schema generation issue tested in this PR's new prisma-schema-gen.test.ts suite.
  • zenstackhq/zenstack#2676: Implements the core delegateMap feature with overlapping changes to language validation, schema contracts, and schema generation.
  • zenstackhq/zenstack#2546: Modifies the same delegate CRUD type generation in crud-types.ts for discriminator union typing.

Poem

🐰 A map for delegates, so they know their way,
Enum-typed paths to guide them today,
Schema and runtime in perfect accord,
Discriminators mapped—the feature restored!
Three point seven point one hops into view,
Prisma schemas clean, and the types ring true! 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the pull request as a merge of the dev branch to main with version bump to 3.7.1, which aligns with the changes across all package.json files and the meaningful feature additions.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dev

Warning

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

🔧 ESLint

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

packages/cli/test/prisma-schema-gen.test.ts

ESLint skipped: missing config or dependency (missing-dependency). The ESLint configuration references a package that is not available in the sandbox.

packages/language/src/validators/datamodel-validator.ts

ESLint skipped: missing config or dependency (missing-dependency). The ESLint configuration references a package that is not available in the sandbox.

packages/language/test/delegate.test.ts

ESLint skipped: the ESLint configuration for this file references a package that is not available in the sandbox.

  • 6 others

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
Copy Markdown
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

🧹 Nitpick comments (1)
packages/sdk/src/prisma/prisma-schema-generator.ts (1)

387-391: ⚡ Quick win

Simplify the filter logic for better readability.

The boolean expression on lines 389-390 is correct but difficult to parse due to implicit operator precedence, outer negation, and mixed conditions. The intent appears to be: for ulid, remove the first argument (format string); for other ID functions, remove the second argument (format string).

Consider refactoring for clarity:

♻️ Proposed refactor for clearer logic
         return new PrismaFunctionCall(
             node.function.ref!.name,
 
-            // strip format args from id functions
-            node.args.filter((_, i) => (
-                !(ID_FUNCTIONS.includes(node.function.ref!.name) && (node.function.ref!.name === 'ulid' && i === 0 || i === 1))
-            )).map((arg) => {
+            // Strip format args from ID functions:
+            // - ulid: remove arg at index 0 (format string)
+            // - cuid/uuid/nanoid: remove arg at index 1 (format string, keeping version/size at index 0)
+            node.args.filter((_, i) => {
+                if (!ID_FUNCTIONS.includes(node.function.ref!.name)) {
+                    return true; // keep all args for non-ID functions
+                }
+                const funcName = node.function.ref!.name;
+                return funcName === 'ulid' ? i !== 0 : i !== 1;
+            }).map((arg) => {
                 const val = match(arg.value)
🤖 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 `@packages/sdk/src/prisma/prisma-schema-generator.ts` around lines 387 - 391,
The current filter on node.args is correct but hard to read due to negation and
mixed conditions; change it to an explicit, positive check: compute const name =
node.function.ref!.name and then filter args to exclude the format-argument by
removing index 0 when name === 'ulid' and index 1 when
ID_FUNCTIONS.includes(name) for all other ID functions (i.e., keep args when not
(ID_FUNCTIONS.includes(name) && ((name === 'ulid' && i === 0) || (name !==
'ulid' && i === 1)))), or better yet flip to a clear conditional that returns
true to keep and false to drop using those explicit cases so
node.args.filter(...) is easy to read; reference node.args, ID_FUNCTIONS and
node.function.ref!.name when applying the change.
🤖 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 `@packages/language/src/validators/datamodel-validator.ts`:
- Around line 529-542: The current loop in subModels.forEach uses
getDelegateMapRawValue(model) ?? model.name to derive a value but skips enum
membership validation when falling back to model.name, allowing invalid
discriminator values; update the logic in the loop (the block using seen,
getDelegateMapRawValue, and accept) to always validate the computed value
against the delegate enum members for the parent DataModel (reuse the existing
enum membership check or helper used elsewhere in datamodel-validator.ts), and
if the value is not a valid enum member emit an accept('error', ...) referencing
the model and the invalid value before checking/recording duplicates in seen.

---

Nitpick comments:
In `@packages/sdk/src/prisma/prisma-schema-generator.ts`:
- Around line 387-391: The current filter on node.args is correct but hard to
read due to negation and mixed conditions; change it to an explicit, positive
check: compute const name = node.function.ref!.name and then filter args to
exclude the format-argument by removing index 0 when name === 'ulid' and index 1
when ID_FUNCTIONS.includes(name) for all other ID functions (i.e., keep args
when not (ID_FUNCTIONS.includes(name) && ((name === 'ulid' && i === 0) || (name
!== 'ulid' && i === 1)))), or better yet flip to a clear conditional that
returns true to keep and false to drop using those explicit cases so
node.args.filter(...) is easy to read; reference node.args, ID_FUNCTIONS and
node.function.ref!.name when applying the change.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 276401ba-f48e-43f9-a5e9-a6d23833923b

📥 Commits

Reviewing files that changed from the base of the PR and between cc24964 and 76febc9.

📒 Files selected for processing (40)
  • package.json
  • packages/auth-adapters/better-auth/package.json
  • packages/cli/package.json
  • packages/cli/test/prisma-schema-gen.test.ts
  • packages/clients/client-helpers/package.json
  • packages/clients/fetch-client/package.json
  • packages/clients/tanstack-query/package.json
  • packages/common-helpers/package.json
  • packages/config/eslint-config/package.json
  • packages/config/tsdown-config/package.json
  • packages/config/typescript-config/package.json
  • packages/config/vitest-config/package.json
  • packages/create-zenstack/package.json
  • packages/ide/vscode/package.json
  • packages/language/package.json
  • packages/language/res/stdlib.zmodel
  • packages/language/src/validators/datamodel-validator.ts
  • packages/language/test/delegate.test.ts
  • packages/orm/package.json
  • packages/orm/src/client/crud-types.ts
  • packages/orm/src/client/crud/operations/base.ts
  • packages/orm/src/client/query-utils.ts
  • packages/plugins/policy/package.json
  • packages/schema/package.json
  • packages/schema/src/schema.ts
  • packages/sdk/package.json
  • packages/sdk/src/prisma/prisma-schema-generator.ts
  • packages/sdk/src/ts-schema-generator.ts
  • packages/server/package.json
  • packages/testtools/package.json
  • packages/zod/package.json
  • samples/orm/package.json
  • tests/e2e/orm/client-api/delegate.test.ts
  • tests/e2e/orm/schemas/delegate/schema.ts
  • tests/e2e/orm/schemas/delegate/schema.zmodel
  • tests/e2e/orm/schemas/delegate/typecheck.ts
  • tests/e2e/package.json
  • tests/regression/package.json
  • tests/runtimes/bun/package.json
  • tests/runtimes/edge-runtime/package.json

Comment thread packages/language/src/validators/datamodel-validator.ts
@ymc9 ymc9 merged commit b15bdfd into main May 23, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants