Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

ShenQingchuan
Copy link
Member

@ShenQingchuan ShenQingchuan commented Aug 20, 2025

Summary by CodeRabbit

  • New Features

    • Top-level and exported TypeScript enums are now recognized as constant bindings, making them usable in templates and setup returns.
    • Improved handling of exported declarations to ensure their inner bindings are correctly detected at the top level.
    • Clearer binding behavior: const declarations treated as literal constants; let/var treated as mutable bindings.
  • Tests

    • Added comprehensive tests validating top-level declaration bindings (functions, classes, enums, instances, and lets) across inline and separated template modes.
    • Introduced utilities to format and snapshot transformed output for reliability.

Copy link

netlify bot commented Aug 20, 2025

Deploy Preview for vue-vine ready!

Name Link
🔨 Latest commit 87d4515
🔍 Latest deploy log https://app.netlify.com/projects/vue-vine/deploys/68a53374fd7294000872a5fd
😎 Deploy Preview https://deploy-preview-307--vue-vine.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

Warning

Rate limit exceeded

@ShenQingchuan has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 57 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 85b20b5 and 87d4515.

⛔ Files ignored due to path filters (2)
  • packages/compiler/tests/__snapshots__/transform.spec.ts.snap is excluded by !**/*.snap
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • packages/compiler/src/analyze.ts (5 hunks)
  • packages/compiler/tests/analyze.spec.ts (2 hunks)
  • packages/compiler/tests/transform.spec.ts (3 hunks)
  • packages/docs/package.json (1 hunks)
  • packages/vite-plugin/src/index.ts (2 hunks)
  • pnpm-workspace.yaml (4 hunks)

Walkthrough

Adds export-unwrapping and TypeScript enum handling to top-level binding analysis in the compiler. Adjusts binding kinds for const/let/var. Ensures Vine component function declarations are skipped after identification. Expands tests to verify bindings and that separated/inline modes include top-level declarations in setup returns.

Changes

Cohort / File(s) Summary
Compiler analysis logic
packages/compiler/src/analyze.ts
Unwrap ExportDefault/ExportNamed to analyze inner declarations; treat TSEnumDeclaration as literal-const; set const→literal-const and let/var→setup-let; switch loop var to let; continue after detecting Vine component function; import isExportNamedDeclaration/isTSEnumDeclaration.
Binding analysis tests
packages/compiler/tests/analyze.spec.ts
Add tests covering top-level declarations (functions, class, enum, instance, let) and ensure enums are literal-const; include exported enum usage in templates.
Transform tests and helpers
packages/compiler/tests/transform.spec.ts
Add helper to format codegen results; add tests asserting top-level declarations appear in setup returns for inline and separated modes via snapshots.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant TS as TypeScript AST
  participant Analyzer as Analyzer (analyze.ts)
  participant Binder as Binding Table
  participant Transformer as Transform (setup returns)

  TS->>Analyzer: Provide top-level statements
  loop For each top-level stmt
    Analyzer->>Analyzer: Unwrap export declarations
    alt TSEnumDeclaration
      Analyzer->>Binder: Record name → literal-const
    else VariableDeclaration
      alt const
        Analyzer->>Binder: name → literal-const
      else let/var
        Analyzer->>Binder: name → setup-let
      end
    else Function/Class/Other
      Analyzer->>Binder: Record binding kind as per rules
      note right of Analyzer: If Vine component fn detected, continue
    end
  end

  Analyzer-->>Transformer: Binding table
  Transformer->>Transformer: Generate setup returns (inline & separated)
  Transformer-->>Caller: Code with top-level bindings exposed
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Assessment against linked issues

Objective Addressed Explanation
Separated mode’s setup returns should contain top-level declarations under export (whatever with or without export) [#306]

Poem

A hop, a skip, through exports I go,
Unwrapping tops where bindings now show.
Enums stand still, like stones they stay,
Setup packs all for both render ways.
Thump-thump! I ship with tidy delight—
Carrots for tests that pass tonight. 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch next-patch

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

pkg-pr-new bot commented Aug 20, 2025

Open in StackBlitz

@vue-vine/compiler

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/compiler@307

create-vue-vine

npm i https://pkg.pr.new/vue-vine/vue-vine/create-vue-vine@307

@vue-vine/eslint-config

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/eslint-config@307

@vue-vine/eslint-parser

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/eslint-parser@307

@vue-vine/eslint-plugin

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/eslint-plugin@307

@vue-vine/language-server

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/language-server@307

@vue-vine/language-service

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/language-service@307

@vue-vine/nuxt

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/nuxt@307

vue-vine-tsc

npm i https://pkg.pr.new/vue-vine/vue-vine/vue-vine-tsc@307

@vue-vine/vite-plugin

npm i https://pkg.pr.new/vue-vine/vue-vine/@vue-vine/vite-plugin@307

vue-vine

npm i https://pkg.pr.new/vue-vine/vue-vine@307

commit: 87d4515

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 40a0b9e and 85b20b5.

⛔ Files ignored due to path filters (1)
  • packages/compiler/tests/__snapshots__/transform.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • packages/compiler/src/analyze.ts (5 hunks)
  • packages/compiler/tests/analyze.spec.ts (2 hunks)
  • packages/compiler/tests/transform.spec.ts (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-07-20T18:38:22.094Z
Learnt from: CR
PR: vue-vine/vue-vine#0
File: .cursor/rules/vue-vine-repo-rules.mdc:0-0
Timestamp: 2025-07-20T18:38:22.094Z
Learning: Applies to **/*.vine.ts : 在 `.vine.ts` 文件中,所有函数只要满足条件:“返回值是一个 tagged template string 且标签名必须是 `vine` 的字符串”,都将被视为一个组件函数

Applied to files:

  • packages/compiler/src/analyze.ts
  • packages/compiler/tests/transform.spec.ts
📚 Learning: 2025-07-20T18:38:22.094Z
Learnt from: CR
PR: vue-vine/vue-vine#0
File: .cursor/rules/vue-vine-repo-rules.mdc:0-0
Timestamp: 2025-07-20T18:38:22.094Z
Learning: Applies to **/*.vine.ts : Vine 仅会处理文件名后缀为 `.vine.ts` 的文件

Applied to files:

  • packages/compiler/tests/transform.spec.ts
🧬 Code Graph Analysis (3)
packages/compiler/src/analyze.ts (2)
packages/compiler/src/constants.ts (1)
  • VineBindingTypes (97-138)
packages/compiler/src/babel-helpers/ast.ts (2)
  • isVineCompFnDecl (50-97)
  • getFunctionPickedInfos (264-309)
packages/compiler/tests/analyze.spec.ts (2)
packages/compiler/tests/test-utils.ts (1)
  • createMockTransformCtx (4-26)
packages/compiler/src/index.ts (1)
  • compileVineTypeScriptFile (143-173)
packages/compiler/tests/transform.spec.ts (3)
packages/compiler/src/index.ts (2)
  • VineCompilerOptions (42-42)
  • compileVineTypeScriptFile (143-173)
packages/compiler/src/types.ts (1)
  • VineCompilerOptions (81-102)
packages/compiler/tests/test-utils.ts (1)
  • createMockTransformCtx (4-26)
🔇 Additional comments (11)
packages/compiler/src/analyze.ts (6)

49-49: LGTM!

The addition of isExportNamedDeclaration and isTSEnumDeclaration imports aligns well with the PR's objective to handle top-level exports and TypeScript enums properly.

Also applies to: 63-63


334-337: Good simplification of enum handling.

The change to treat TypeScript enums as LITERAL_CONST directly removes the complex per-member initialization logic. This makes the code cleaner and aligns with the deterministic handling goal.


783-791: Excellent implementation for handling Vine component function declarations.

The logic correctly:

  1. Identifies Vine component function declarations
  2. Adds them to bindings as SETUP_CONST
  3. Uses continue to skip further processing for these declarations

This ensures proper separation between component functions and regular top-level declarations.


793-799: Proper unwrapping of export declarations.

The code correctly unwraps ExportDefaultDeclaration and ExportNamedDeclaration to access the underlying declaration, allowing proper analysis of exported entities.


801-809: Accurate binding type assignment for variable declarations.

The logic correctly distinguishes between const declarations (yielding LITERAL_CONST) and other kinds (yielding SETUP_LET), which aligns with the PR objectives to handle top-level declarations properly.


818-820: Correct handling of TypeScript enums.

The addition of explicit handling for TSEnumDeclaration at the top level as LITERAL_CONST is consistent with the enum handling in analyzeVineFnBodyStmtForBindings.

packages/compiler/tests/analyze.spec.ts (2)

399-399: LGTM! Test correctly validates enum binding.

The test expectation properly validates that MyOutsideEnum is treated as literal-const, which aligns with the enum handling changes in the analyzer.


619-669: Comprehensive test coverage for top-level declarations.

The new test suite thoroughly validates the binding analysis for various top-level declarations including:

  • Exported arrow and plain functions
  • Classes and enums
  • Const and let variables

The assertions correctly verify that each entity receives the appropriate binding type.

packages/compiler/tests/transform.spec.ts (3)

1-1: LGTM! Necessary import for test helper.

The addition of the VineCompilerOptions type import is required for the new test helper function's type annotations.


120-136: Well-structured test helper function.

The getFormatedCodegenResult helper effectively encapsulates the common test setup and formatting logic, improving code reusability across tests.


475-516: Excellent test coverage for top-level declaration bindings.

The test comprehensively validates that top-level declarations are correctly included in the setup returns for both inline and separated template modes. This ensures the fix for issue #306 works correctly across different compilation modes.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/compiler/src/analyze.ts (1)

810-817: Guard function/class bindings to respect local shadowing.

Same precedence concern as variables: use ??= to avoid overriding component-local identifiers.

Apply this diff:

-      vineCompFnCtx.bindings[declStmt.id.name] = VineBindingTypes.LITERAL_CONST
+      vineCompFnCtx.bindings[declStmt.id.name] ??= VineBindingTypes.LITERAL_CONST
🧹 Nitpick comments (3)
packages/compiler/tests/analyze.spec.ts (1)

618-669: Solid coverage for top-level declarations in bindings.

This test exercises exported and non-exported top-level decls and checks the expected binding kinds, including enums and let. One nit: the template references MyClass.getFoo() and myInstance.num() but the class here doesn’t define them. It doesn’t affect analysis, but adding stubs would reduce confusion for future readers.

Would you like me to send a patch to add those methods here (as you did in transform tests) for consistency?

packages/compiler/tests/transform.spec.ts (2)

120-137: Avoid spreading possibly-undefined options; consider typo fix.

  • If options is ever omitted, { ...options } will throw at runtime. Prefer options ?? {}.
  • Optional nit: rename getFormatedCodegenResult to getFormattedCodegenResult.

Apply this diff to harden the helper:

-async function getFormatedCodegenResult(
+async function getFormattedCodegenResult(
   specContent: string,
   options?: VineCompilerOptions,
 ) {
-  const { mockCompilerCtx, mockCompilerHooks } = createMockTransformCtx({
-    ...options,
-  })
+  const { mockCompilerCtx, mockCompilerHooks } = createMockTransformCtx(options ?? {})
   compileVineTypeScriptFile(specContent, 'testTransformSeparatedResult', { compilerHooks: mockCompilerHooks })
   expect(mockCompilerCtx.vineCompileErrors.length).toBe(0)
   const fileCtx = mockCompilerCtx.fileCtxMap.get('testTransformSeparatedResult')
   const transformed = fileCtx?.fileMagicCode.toString() ?? ''
   const formated = await format(
     transformed,
     { parser: 'babel-ts' },
   )
   return formated
 }

And update the two call sites below accordingly.


475-516: Great end-to-end validation for inline vs separated modes.

This test ensures top-level decls flow into setup returns consistently across both modes and that the generated outputs remain stable. After renaming the helper (if applied), update the invocations.

Apply this diff if you accept the helper rename:

-    const inlineModeResult = await getFormatedCodegenResult(specContent, {
+    const inlineModeResult = await getFormattedCodegenResult(specContent, {
       inlineTemplate: true,
     })
-    const separatedModeResult = await getFormatedCodegenResult(specContent, {
+    const separatedModeResult = await getFormattedCodegenResult(specContent, {
       inlineTemplate: false,
     })
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 40a0b9e and 85b20b5.

⛔ Files ignored due to path filters (1)
  • packages/compiler/tests/__snapshots__/transform.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • packages/compiler/src/analyze.ts (5 hunks)
  • packages/compiler/tests/analyze.spec.ts (2 hunks)
  • packages/compiler/tests/transform.spec.ts (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-07-20T18:38:22.094Z
Learnt from: CR
PR: vue-vine/vue-vine#0
File: .cursor/rules/vue-vine-repo-rules.mdc:0-0
Timestamp: 2025-07-20T18:38:22.094Z
Learning: Applies to **/*.vine.ts : Vine 仅会处理文件名后缀为 `.vine.ts` 的文件

Applied to files:

  • packages/compiler/tests/transform.spec.ts
📚 Learning: 2025-07-20T18:38:22.094Z
Learnt from: CR
PR: vue-vine/vue-vine#0
File: .cursor/rules/vue-vine-repo-rules.mdc:0-0
Timestamp: 2025-07-20T18:38:22.094Z
Learning: Applies to **/*.vine.ts : 在 `.vine.ts` 文件中,所有函数只要满足条件:“返回值是一个 tagged template string 且标签名必须是 `vine` 的字符串”,都将被视为一个组件函数

Applied to files:

  • packages/compiler/tests/transform.spec.ts
  • packages/compiler/src/analyze.ts
🧬 Code Graph Analysis (3)
packages/compiler/tests/transform.spec.ts (3)
packages/compiler/src/index.ts (2)
  • VineCompilerOptions (42-42)
  • compileVineTypeScriptFile (143-173)
packages/compiler/src/types.ts (1)
  • VineCompilerOptions (81-102)
packages/compiler/tests/test-utils.ts (1)
  • createMockTransformCtx (4-26)
packages/compiler/src/analyze.ts (2)
packages/compiler/src/constants.ts (1)
  • VineBindingTypes (97-138)
packages/compiler/src/babel-helpers/ast.ts (2)
  • isVineCompFnDecl (50-97)
  • getFunctionPickedInfos (264-309)
packages/compiler/tests/analyze.spec.ts (2)
packages/compiler/tests/test-utils.ts (1)
  • createMockTransformCtx (4-26)
packages/compiler/src/index.ts (1)
  • compileVineTypeScriptFile (143-173)
🔇 Additional comments (7)
packages/compiler/src/analyze.ts (5)

49-49: Good addition: import isExportNamedDeclaration.

Needed for the new export-unwrapping logic below.


63-63: Good addition: import isTSEnumDeclaration.

Enables explicit handling of TS enums in binding analysis.


334-337: Enum inside function body treated as literal-const is reasonable.

Marking TSEnumDeclaration as LITERAL_CONST aligns with non-reactive, non-ref semantics used in templates.


784-791: Using let + continue avoids reprocessing Vine component decls.

This is an effective way to short-circuit after component identification and prevents double classification.


793-800: Export unwrapping is correct and necessary.

Unwrapping export default and export named declarations ensures the inner declarations are analyzed uniformly. This fixes the exported-top-level omission described in the issue.

packages/compiler/tests/analyze.spec.ts (1)

399-400: Snapshot update to include MyOutsideEnum looks correct.

Enum classification as literal-const matches new analysis behavior.

packages/compiler/tests/transform.spec.ts (1)

1-1: Type-only import is fine.

It keeps runtime bundle clean while documenting the helper’s options shape.

ShenQingchuan and others added 2 commits August 20, 2025 10:25
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@ShenQingchuan ShenQingchuan merged commit 344cf40 into main Aug 20, 2025
17 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.

Separated mode's setup returns should contain top level declarations (whatever with or without export)
1 participant