Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Jun 13, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new CLI tool, create-zenstack, for scaffolding new ZenStack projects with starter files and automated setup.
    • Added an init command to the ZenStack CLI to initialize ZenStack in existing projects with starter schema and dependencies.
  • Improvements

    • Enhanced CLI package recognition to include both scoped and unscoped ZenStack packages.
    • Updated starter templates for schema and TypeScript entry files in project initialization.
  • Dependency Updates

    • Upgraded @types/node to v20 in several packages.
    • Added package-manager-detector dependency to the CLI package.
    • Adjusted dependencies in sample and CLI packages for improved consistency.
  • Chores

    • Downgraded package versions from 3.0.0-alpha.1 to 3.0.0-alpha.0 across multiple packages.
    • Added the new create-zenstack package to the workspace configuration.

@coderabbitai
Copy link

coderabbitai bot commented Jun 13, 2025

Warning

Rate limit exceeded

@ymc9 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 44 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 98238cd and 876976e.

📒 Files selected for processing (2)
  • packages/cli/src/actions/init.ts (1 hunks)
  • packages/create-zenstack/src/index.ts (1 hunks)

Walkthrough

This update introduces a new CLI tool, create-zenstack, for scaffolding ZenStack projects, along with a new init command in the main CLI to initialize ZenStack in existing projects. Supporting templates and utilities were added, and package metadata was updated across the monorepo, including dependency and version adjustments.

Changes

Files/Groups Change Summary
package.json, packages/*/package.json Downgraded version from "3.0.0-alpha.1" to "3.0.0-alpha.0"; updated @types/node to ^20.0.0 in some packages.
packages/cli/package.json Renamed package, updated display name, added dependency, reordered devDependencies.
samples/blog/package.json Removed zenstack dependency; added @zenstackhq/cli as devDependency.
pnpm-workspace.yaml Added packages/create-zenstack to workspace packages.
packages/cli/src/actions/action-utils.ts Added handleSubProcessError function.
packages/cli/src/actions/common.ts Removed handleSubProcessError function.
packages/cli/src/actions/db.ts Updated import of handleSubProcessError to new location.
packages/cli/src/actions/generate.ts Renamed generated client variable from db to client.
packages/cli/src/actions/info.ts Expanded ZenStack package filtering logic to include zenstack.
packages/cli/src/actions/index.ts Added init to exported actions.
packages/cli/src/actions/init.ts New run function: initializes ZenStack in a project, installs dependencies, creates schema if missing.
packages/cli/src/actions/templates.ts Added starter schema and TypeScript templates as exported constants.
packages/cli/src/index.ts Added init CLI command; reorganized command registration.
packages/create-zenstack/* New package: CLI tool for scaffolding ZenStack projects, with templates, config files, and CLI entry point.

Sequence Diagram(s)

1. create-zenstack Project Creation Flow

sequenceDiagram
    participant User
    participant CLI (create-zenstack)
    participant FileSystem
    participant Shell
    participant ZenStack CLI

    User->>CLI (create-zenstack): Run `create-zenstack <project-name>`
    CLI (create-zenstack)->>FileSystem: Check if directory exists
    alt Directory exists
        CLI (create-zenstack)->>User: Exit with error
    else
        CLI (create-zenstack)->>Shell: Initialize project (npm/pnpm/yarn/bun)
        CLI (create-zenstack)->>Shell: Install dependencies
        CLI (create-zenstack)->>FileSystem: Write starter schema and main.ts
        CLI (create-zenstack)->>ZenStack CLI: Run `zenstack generate`
        CLI (create-zenstack)->>ZenStack CLI: Run `zenstack db push`
        CLI (create-zenstack)->>User: Print success and instructions
    end
Loading

2. zenstack init Command Flow

sequenceDiagram
    participant User
    participant ZenStack CLI
    participant FileSystem
    participant Shell

    User->>ZenStack CLI: Run `zenstack init [projectPath]`
    ZenStack CLI->>Shell: Detect package manager
    ZenStack CLI->>Shell: Install @zenstackhq/cli (dev) and @zenstackhq/runtime
    ZenStack CLI->>FileSystem: Ensure `zenstack` folder exists
    ZenStack CLI->>FileSystem: Create `schema.zmodel` if missing
    ZenStack CLI->>User: Print success and next steps
Loading

Poem

🐇✨
A hop, a leap, a brand-new tool,
Now ZenStack projects start so cool!
With templates bright and CLI delight,
Just one command and you’re set right.
From alpha zero, let’s begin—
The stack is ready, let’s jump in!
🌱🚀

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 5

🔭 Outside diff range comments (1)
packages/create-zenstack/src/templates.ts (1)

1-53: ⚠️ Potential issue

Critical: Incorrect template re-export
This file currently inlines or misreferences the CLI templates instead of properly re-exporting them. It should simply re-export the constants from the CLI package.

Apply this diff to fix it:

- ../../cli/src/actions/templates.ts
- 
- /// A sample data source using local sqlite db.
- datasource db {
-     provider = 'sqlite'
-     url = 'file:./dev.db'
- }
- 
- /// User model
- model User {
-     id       String @id @default(cuid())
-     email    String @unique @email @length(6, 32)
-     posts    Post[]
- }
- 
- /// Post model
- model Post {
-     id        String   @id @default(cuid())
-     createdAt DateTime @default(now())
-     updatedAt DateTime @updatedAt
-     title     String   @length(1, 256)
-     content   String
-     published Boolean  @default(false)
-     author    User     @relation(fields: [authorId], references: [id])
-     authorId  String
- }
- `;
- 
- export const STARTER_MAIN_TS = `import { ZenStackClient } from '@zenstackhq/runtime';
- import { schema } from './zenstack/schema';
- 
- async function main() {
-     const client = new ZenStackClient(schema);
-     const user = await client.user.create({
-         data: {
-             email: 'test@zenstack.dev',
-             posts: {
-                 create: [
-                     {
-                         title: 'Hello World',
-                         content: 'This is a test post',
-                     },
-                 ],
-             },
-         },
-         include: { posts: true }
-     });
-     console.log('User created:', user);
- }
- 
- main();
- `;
+ export { STARTER_ZMODEL, STARTER_MAIN_TS } from '../../cli/src/actions/templates';

This ensures the templates stay canonical and avoids duplication.

🧹 Nitpick comments (8)
packages/create-zenstack/bin/cli (1)

1-3: Verify CLI script shebang and executable permissions
The shebang with --no-warnings suppresses Node.js warnings; confirm this is intentional and compatible across environments. Also ensure this file is marked as executable (chmod +x) and correctly listed under bin in package.json.

packages/create-zenstack/tsconfig.json (1)

1-7: Consider generating type declarations
You may want to enable "declaration": true under compilerOptions to emit .d.ts files for improved IDE support and downstream type safety:

+ "compilerOptions": {
+   "outDir": "dist",
+   "declaration": true
+ },
packages/cli/src/actions/action-utils.ts (1)

37-47: Consider broadening the exit-code extraction logic

spawnSync and many process-execution helpers (e.g. execa) signal failure via either a numeric status or a string code (e.g. 'ENOENT'). Exiting with 1 for non-numeric codes can discard useful information in CI logs.

-    if (
-        err instanceof Error &&
-        'status' in err &&
-        typeof err.status === 'number'
-    ) {
-        process.exit(err.status);
-    } else {
-        process.exit(1);
-    }
+    if (err && typeof err === 'object') {
+        const anyErr = err as Record<string, unknown>;
+        if (typeof anyErr.status === 'number') {
+            process.exit(anyErr.status);
+        }
+        if (typeof anyErr.code === 'string') {
+            // map common string codes to conventional exit codes, fall back to 1
+            process.exit(anyErr.code === 'ENOENT' ? 127 : 1);
+        }
+    }
+    process.exit(1);

Keeps the current behaviour while preserving extra diagnostics when available.

packages/cli/package.json (1)

31-41: Check Node 20 type stubs & new dependency reach

Upgrading @types/node to ^20 and adding package-manager-detector pulls in Node-20-specific types and extra transitive deps. Make sure the minimum supported runtime in docs/engines aligns (Node 20) and that the new package is bundled only where needed to keep the CLI’s install size lean.

packages/cli/src/index.ts (1)

21-28: Avoid wrapper indirection – pass the action handlers directly

infoAction / initAction are just one-liners delegating to the real action functions. Commander happily accepts async functions, so you can export actions.info / actions.init directly and drop the extra delegates.
This removes 8 lines, one level of indirection, and keeps stack-traces shorter.

-const infoAction = async (projectPath: string): Promise<void> => {
-    await actions.info(projectPath);
-};
-
-const initAction = async (projectPath: string): Promise<void> => {
-    await actions.init(projectPath);
-};
+const infoAction = actions.info;
+const initAction = actions.init;
packages/create-zenstack/package.json (1)

34-37: Re-evaluate dependency choices (security & footprint)

colors@1.4.0 was at the center of the January-2022 self-sabotage incident; the package is stable now but effectively unmaintained. chalk (actively maintained, ESM-first, typings built-in) is a drop-in replacement.

Switching reduces supply-chain risk and removes the need for @types/colors.

No action required for this PR, but consider migrating in a follow-up.

packages/cli/src/actions/init.ts (1)

73-75: Minor typo – duplicated word

'compile the the schema''compile the schema'

packages/create-zenstack/src/index.ts (1)

64-66: Guard against existing zenstack directory

If a user re-runs the tool in the same folder, fs.mkdirSync('zenstack') will throw. Either check existsSync or call mkdirSync('zenstack', { recursive: true }).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ee7f20 and 7e4344a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (25)
  • package.json (1 hunks)
  • packages/cli/package.json (4 hunks)
  • packages/cli/src/actions/action-utils.ts (1 hunks)
  • packages/cli/src/actions/common.ts (0 hunks)
  • packages/cli/src/actions/db.ts (1 hunks)
  • packages/cli/src/actions/generate.ts (1 hunks)
  • packages/cli/src/actions/index.ts (1 hunks)
  • packages/cli/src/actions/info.ts (1 hunks)
  • packages/cli/src/actions/init.ts (1 hunks)
  • packages/cli/src/actions/templates.ts (1 hunks)
  • packages/cli/src/index.ts (2 hunks)
  • packages/create-zenstack/bin/cli (1 hunks)
  • packages/create-zenstack/package.json (1 hunks)
  • packages/create-zenstack/src/index.ts (1 hunks)
  • packages/create-zenstack/src/templates.ts (1 hunks)
  • packages/create-zenstack/tsconfig.json (1 hunks)
  • packages/create-zenstack/tsup.config.ts (1 hunks)
  • packages/language/package.json (2 hunks)
  • packages/runtime/package.json (1 hunks)
  • packages/sdk/package.json (2 hunks)
  • packages/tanstack-query/package.json (1 hunks)
  • packages/testtools/package.json (2 hunks)
  • packages/zod/package.json (1 hunks)
  • pnpm-workspace.yaml (1 hunks)
  • samples/blog/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/cli/src/actions/common.ts
🧰 Additional context used
🧬 Code Graph Analysis (4)
packages/create-zenstack/src/templates.ts (1)
packages/cli/src/actions/templates.ts (1)
  • STARTER_ZMODEL (1-27)
packages/create-zenstack/src/index.ts (3)
packages/cli/src/utils/exec-utils.ts (1)
  • execSync (6-18)
packages/create-zenstack/src/templates.ts (2)
  • STARTER_ZMODEL (1-27)
  • STARTER_MAIN_TS (29-52)
packages/cli/src/actions/templates.ts (2)
  • STARTER_ZMODEL (1-27)
  • STARTER_MAIN_TS (29-52)
packages/cli/src/actions/templates.ts (1)
packages/create-zenstack/src/templates.ts (2)
  • STARTER_ZMODEL (1-27)
  • STARTER_MAIN_TS (29-52)
packages/cli/src/actions/init.ts (3)
packages/cli/src/cli-error.ts (1)
  • CliError (4-4)
packages/cli/src/utils/exec-utils.ts (1)
  • execSync (6-18)
packages/cli/src/actions/templates.ts (1)
  • STARTER_ZMODEL (1-27)
🔇 Additional comments (18)
package.json (1)

3-3: Confirm the intentional version downgrade
The root version was downgraded from 3.0.0-alpha.1 to 3.0.0-alpha.0. Ensure this aligns with your release strategy and that all monorepo packages remain synchronized.

packages/tanstack-query/package.json (1)

3-3: Approve version alignment
The package version was downgraded to 3.0.0-alpha.0 to match the rest of the monorepo. This change is consistent and requires no further action.

packages/runtime/package.json (1)

3-3: Approve version alignment
The package version was downgraded to 3.0.0-alpha.0 to match the rest of the monorepo. This change is consistent and requires no further action.

packages/zod/package.json (1)

3-3: Approve version alignment
The package version was downgraded to 3.0.0-alpha.0 to match the rest of the monorepo. This change is consistent and requires no further action.

packages/language/package.json (1)

4-4: Approve version alignment
The package version was downgraded to 3.0.0-alpha.0 in line with the monorepo-wide version sync.

packages/sdk/package.json (2)

50-50: Update Node types to v20
Upgrading @types/node to ^20.0.0 may impact CI/build images—ensure your pipelines and local environments target Node v20+.


3-3:

✅ Verification successful

Confirm SDK version rollback
The version was downgraded from 3.0.0-alpha.1 to 3.0.0-alpha.0. Please verify that this rollback is intentional and synchronized across all packages to prevent mismatches during publishing.

Run this to check consistency:


🏁 Script executed:

rg -n '"version": "3\.0\.0-alpha\.\d"' --glob 'packages/*/package.json'

Length of output: 591


All packages synchronized to version 3.0.0-alpha.0
All eight packages use "version": "3.0.0-alpha.0", confirming the rollback is applied consistently. No further action required.

  • packages/create-zenstack/package.json
  • packages/testtools/package.json
  • packages/zod/package.json
  • packages/tanstack-query/package.json
  • packages/runtime/package.json
  • packages/sdk/package.json
  • packages/cli/package.json
  • packages/language/package.json
pnpm-workspace.yaml (1)

6-6: Include new package in workspace
Adding packages/create-zenstack integrates the new CLI tool into the monorepo correctly.

packages/testtools/package.json (2)

3-3: Confirm testtools version rollback
The version was downgraded from 3.0.0-alpha.1 to 3.0.0-alpha.0. Ensure this aligns with the intended release strategy and matches other packages.


32-32: Sync Node types update
Upgrading @types/node to ^20.0.0 here too—please verify that all development environments are updated to Node 20.

packages/cli/src/actions/templates.ts (2)

1-27: Approve starter schema template
The STARTER_ZMODEL constant provides a clear, self-contained schema for new projects. The content and formatting look good.


29-52: Approve example main.ts usage snippet
The STARTER_MAIN_TS constant correctly illustrates client initialization and nested create/query usage.

packages/cli/src/actions/generate.ts (1)

43-43: Consistent client identifier rename
Renaming db to client aligns generated snippets with your starter templates and improves clarity for users.

packages/cli/src/actions/db.ts (1)

3-3:

✅ Verification successful

Confirm handleSubProcessError export path
The import moved from common to action-utils. Verify that no other files still reference ./common and that common.ts can be removed if it's now unused.


🏁 Script executed:

#!/bin/bash
# Search for residual imports from actions/common
rg "from '\.\/common'" -n packages/cli/src/actions

Length of output: 150


🏁 Script executed:

#!/bin/bash
# Correctly search for residual imports from ./common in the actions directory
rg -n "from './common'" packages/cli/src/actions
rg -n 'from "./common"' packages/cli/src/actions

# Check for any remaining references to common.ts across the repo
rg -n "common\.ts" .

Length of output: 130


🏁 Script executed:

#!/bin/bash
# Check if common.ts still exists in the actions directory
find packages/cli/src/actions -maxdepth 1 -type f -name 'common.ts'

Length of output: 67


🏁 Script executed:

#!/bin/bash
# Search for any common.ts files in the repository
find . -type f -name 'common.ts'

Length of output: 77


🏁 Script executed:

#!/bin/bash
# Verify that handleSubProcessError is exported from action-utils
rg -n "export .*handleSubProcessError" packages/cli/src/actions/action-utils.ts

Length of output: 138


Review Completed: handleSubProcessError import and common.ts removal verified

  • No residual from './common' imports in packages/cli/src/actions.
  • handleSubProcessError is exported from packages/cli/src/actions/action-utils.ts (line 37).
  • No common.ts file exists under packages/cli/src/actions; it’s been removed.
  • The only remaining common.ts is in packages/language/src/validators, which is outside the CLI scope and should remain.
samples/blog/package.json (1)

21-22:

✅ Verification successful

Update devDependencies for new CLI and Prisma
Adding prisma and moving the CLI to @zenstackhq/cli is correct. Ensure that @zenstackhq/cli still exposes the zenstack binary so that existing npm scripts (zenstack generate, zenstack migrate) work without modification.


🏁 Script executed:

#!/bin/bash
# Confirm `zenstack` CLI is available in node_modules/.bin
pnpm exec which zenstack

Length of output: 99


🏁 Script executed:

#!/bin/bash
# Locate and inspect the "bin" field in the @zenstackhq/cli package.json
rg '"name"\s*:\s*"@zenstackhq/cli"' -l \
  | while read -r PKG_JSON; do
      echo "Inspecting $PKG_JSON"
      jq '.bin' "$PKG_JSON"
    done

Length of output: 225


Confirmed: zenstack binary exposed by @zenstackhq/cli
The bin field in packages/cli/package.json maps "zenstack": "bin/cli", so the zenstack executable is available and existing npm scripts (zenstack generate, zenstack migrate) will continue to work without any changes.

packages/cli/src/actions/index.ts (1)

4-7: LGTM – new init action is correctly wired

The import/export looks consistent with the existing pattern.

packages/create-zenstack/tsup.config.ts (1)

1-13: Build config looks sane

No issues spotted – defaults match typical CLIs (single entry, dual format, DTS).

packages/cli/package.json (1)

6-6: Version bump direction is reversed – verify semantic intent

The version changes from 3.0.0-alpha.1 to 3.0.0-alpha.0, i.e. a lower pre-release tag. Package managers treat this as a downgrade, which can break publishes or installs that already consumed alpha.1.

Confirm this is intentional; otherwise bump to alpha.2 or higher.

@ymc9 ymc9 merged commit e0fac4f into dev Jun 13, 2025
5 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 19, 2025
@coderabbitai coderabbitai bot mentioned this pull request Aug 31, 2025
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