Skip to content

Conversation

@edwinhuish
Copy link
Collaborator

@edwinhuish edwinhuish commented Aug 27, 2025

Description 描述

增加更多 ts 转译的配置

Summary by CodeRabbit

  • New Features
    • Run user scripts/macros as TypeScript/JavaScript with explicit module imports.
    • Support dynamic import() inside executed scripts.
    • If a script exports a function, its return value is used automatically.
    • Enforce a 1-second execution timeout to avoid long-running scripts.
    • Provide richer error messages that include filename, error details, and generated code.
    • Debug builds now produce sourcemaps for easier troubleshooting.

@coderabbitai
Copy link

coderabbitai bot commented Aug 27, 2025

Walkthrough

Refactored script execution to accept an options object with explicit imports, enhanced TypeScript/JS transpilation, VM execution with dynamic import support and a 1s timeout, and richer error messages. Updated call sites to the new signature. Also enabled sourcemaps in the core debug build script. No public API surface changes besides execScript signature.

Changes

Cohort / File(s) Summary
Build script
packages/core/package.json
Updated debug script: unbuildunbuild --sourcemap.
Exec engine
packages/core/src/utils.ts
Reworked execScript signature to ({ imports, code, filename }); prepends imports; wraps as ES module default export; transpiles with explicit TS compiler options (ES2022/CJS, relaxed checks); supports dynamic import() in VM; enforces 1000 ms timeout; improves error messages to include filename and generated JS; returns default export or invoked function result.
Macro integration
packages/core/src/page.ts
tryPageMetaFromMacro now calls execScript({ imports, code, filename: sfc.filename }) instead of passing a concatenated script string.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller as tryPageMetaFromMacro
  participant Exec as execScript(options)
  participant TS as ts.transpileModule
  participant VM as Node VM
  participant Mod as Module

  Caller->>Exec: { imports[], code, filename }
  Exec->>TS: Transpile (ES2022 → CJS, relaxed checks)
  TS-->>Exec: generated JS
  Exec->>VM: create context (require, module, exports, import(), __filename)
  Exec->>VM: run wrapped module (1s timeout)
  VM-->>Mod: module.exports / default
  alt default is function
    Exec->>Mod: invoke default()
    Mod-->>Exec: result
  else value
    Mod-->>Exec: value
  end
  Exec-->>Caller: result
  note right of Exec: On error → throw with filename + generated JS
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I munched on imports, stitched code with care,
Gave VMs a timeout and sourcemaps to spare.
TypeScript whispers, then JS takes flight,
Default or function — I'll fetch it tonight.
Hop, hop — the rabbit ships it right. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

@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/core/src/utils.ts (1)

121-121: Consider making timeout configurable.

The 1-second timeout is hardcoded, which might be insufficient for complex scripts or slow systems. Consider making this configurable through the options parameter.

-export async function execScript(options: { imports: string[], code: string, filename: string }): Promise<any> {
-  const { imports = [], code, filename } = options
+export async function execScript(options: { imports: string[], code: string, filename: string, timeout?: number }): Promise<any> {
+  const { imports = [], code, filename, timeout = 1000 } = options

And update the VM execution:

     await script.runInNewContext(vmContext, {
-      timeout: 1000, // 设置超时避免长时间运行
+      timeout, // 设置超时避免长时间运行
     })
📜 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 by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3fb4ceb and dc69ca8.

📒 Files selected for processing (3)
  • packages/core/package.json (1 hunks)
  • packages/core/src/page.ts (1 hunks)
  • packages/core/src/utils.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/core/src/page.ts (2)
packages/core/src/utils.ts (1)
  • execScript (73-138)
packages/core/src/types.ts (1)
  • UserPageMeta (147-153)
🔇 Additional comments (8)
packages/core/package.json (1)

53-53: Good addition for debugging support.

Adding --sourcemap to the debug script is a valuable improvement that will help with debugging the transpiled TypeScript code, especially given the enhanced transpilation configuration in this PR.

packages/core/src/page.ts (1)

111-115: API signature change looks good.

The refactored call to execScript using an options object is cleaner and more maintainable than the previous concatenated string approach. This properly separates imports from the actual code being executed.

packages/core/src/utils.ts (6)

64-72: Well-documented function with clear parameter descriptions.

The JSDoc comment clearly explains the function's purpose and each parameter, which improves code maintainability.


136-136: Enhanced error reporting is helpful for debugging.

Including the filename, error message, and generated JS code in the error message will significantly help with debugging transpilation and execution issues.


82-101: Comprehensive TypeScript compiler configuration.

The detailed compiler options provide good flexibility by disabling strict checks while maintaining CommonJS compatibility. The ES2022 target is a reasonable choice for modern Node.js environments.


128-133: Consider async function handling.

The code checks if the result is a function and executes it, but doesn't handle the case where the function itself might be async and return a Promise.

     // 如果是函数,执行函数并返回其返回值
     if (typeof result === 'function') {
-      return Promise.resolve(result())
+      const fnResult = result()
+      return Promise.resolve(fnResult)
     }

This ensures that if result() returns a Promise, it will be properly awaited.

Likely an incorrect or invalid review comment.


114-114: ⚠️ Evaluate dynamic import usage in your VM sandbox

The import(id) call inside a VM context still uses Node’s native dynamic-import mechanism – it doesn’t invoke your sandbox.import function and will instead:

  • Reject with ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING unless you explicitly supply an importModuleDynamically callback to your vm.Script/runIn…Context options (nodejs.org).
  • Bypass the sandbox entirely, loading modules in the main context and reintroducing any APIs or globals you’ve attempted to omit, which may defeat your isolation guarantees (nodejs.org, codingeasypeasy.com).

Please confirm that you either:

  • Provide a proper importModuleDynamically handler (or use vm.SourceTextModule) to safely wire dynamic imports within the sandbox, or
  • Remove or replace dynamic import() calls with a sandbox-friendly loader (e.g. pre-declared whitelisted modules).

78-78: No sanitization needed for AST-derived imports

The imports array is populated by extracting and regenerating only static ImportDeclaration nodes from the SFC’s AST—not from arbitrary user input at runtime—so there is no avenue for injection beyond what valid ES import syntax allows. Moreover, execScript runs in a build‐time VM context with only the extracted imports and transpiled code, meaning this is a controlled environment operating on developer‐authored files. You can safely disregard the suggestion to sanitize these imports.

Likely an incorrect or invalid review comment.

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

♻️ Duplicate comments (1)
packages/core/src/utils.ts (1)

89-89: Fix typo in Chinese comment.

The Chinese comment contains garbled text "检查" that should be corrected for better readability.

-        strictNullChecks: false, // 关闭严格的 null 和 undefined 检查
+        strictNullChecks: false, // 关闭严格的 null 和 undefined 检查,允许隐式为 null 或 undefined
🧹 Nitpick comments (1)
packages/core/src/utils.ts (1)

78-78: Consider validating the imports array format.

The imports are joined with newlines and prepended to the code. Consider validating that each import statement is properly formatted to prevent syntax errors.

 export async function execScript(options: { imports: string[], code: string, filename: string }): Promise<any> {
   const { imports = [], code, filename } = options
+  
+  // Validate import statements format
+  for (const importStmt of imports) {
+    if (!importStmt.trim().startsWith('import') && !importStmt.trim().startsWith('const') && !importStmt.trim().startsWith('var') && !importStmt.trim().startsWith('let')) {
+      throw new Error(`Invalid import statement in ${filename}: ${importStmt}`)
+    }
+  }

   let jsCode: string = ''
📜 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 by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between dc69ca8 and addb016.

📒 Files selected for processing (1)
  • packages/core/src/utils.ts (1 hunks)
🔇 Additional comments (7)
packages/core/src/utils.ts (7)

73-74: LGTM! Clean function signature refactor.

The function signature change from separate parameters to an options object improves API ergonomics and makes the function more maintainable as it grows.


81-103: Comprehensive TypeScript transpilation configuration looks good.

The TypeScript compiler options are well-configured for VM execution:

  • Appropriate target (ES2022) and module (CommonJS) settings
  • Relaxed type checking for runtime flexibility
  • Good interoperability settings with esModuleInterop and allowJs
  • Performance optimizations with skipLibCheck and removeComments

The configuration strikes a good balance between functionality and permissiveness for script execution.


108-115: Well-designed VM context with comprehensive runtime support.

The VM context provides:

  • Standard Node.js globals (__filename, __dirname)
  • Module system support (require, module, exports)
  • Dynamic import capability through the import function

This creates a robust execution environment for the transpiled scripts.


120-122: Good timeout protection for script execution.

The 1000ms timeout prevents long-running or infinite loops from blocking the execution. This is a sensible default for configuration scripts.


125-133: Smart result handling with function execution support.

The logic correctly handles both function and non-function exports:

  • Executes functions and returns their result
  • Returns non-function values directly
  • Properly handles async execution with Promise.resolve

This provides flexibility for different script patterns.


135-137: Excellent error reporting with context information.

The error handling provides comprehensive debugging information:

  • Filename for error location
  • Original error message
  • Generated JavaScript code for debugging transpilation issues

This will significantly help with debugging script execution failures.


64-72: Well-documented function with clear parameter descriptions.

The JSDoc comments clearly explain the function's purpose, parameters, and return behavior. The bilingual documentation (Chinese and code comments) is helpful for the target audience.

@FliPPeDround FliPPeDround merged commit 058b3f7 into uni-helper:main Aug 27, 2025
4 checks passed
@edwinhuish edwinhuish deleted the more_ts_transpile_configuration branch August 27, 2025 04:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants