Skip to content

fix: frontend environment variable type error#164

Merged
kagol merged 3 commits into
opentiny:devfrom
GaoNeng-wWw:fix/front-end-env-type-error
Dec 30, 2025
Merged

fix: frontend environment variable type error#164
kagol merged 3 commits into
opentiny:devfrom
GaoNeng-wWw:fix/front-end-env-type-error

Conversation

@GaoNeng-wWw
Copy link
Copy Markdown
Collaborator

@GaoNeng-wWw GaoNeng-wWw commented Dec 29, 2025

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • Bug Fixes

    • Improved mock proxy normalization so mock routes are matched more reliably, reducing incorrect proxying.
  • Chores

    • Expanded development environment configuration with additional VITE_* variables and global declarations to support more tooling and flexibility.
    • Improved mock server handling and developer experience for local setups.

✏️ Tip: You can customize this high-level summary in your review settings.

@github-actions github-actions Bot added the bug Something isn't working label Dec 29, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 29, 2025

Walkthrough

Vite proxy rewrite now replaces occurrences of the dynamic mock-host string (from VITE_MOCK_SERVER_HOST) with "/mock" instead of matching a fixed prefix. env.d.ts was restructured: ImportMetaEnv moved into a global augmentation and expanded with additional VITE_* keys; BUILD_TOOLS and NodeRequire declared globally and Vue i18n ComponentCustomProperties augmentation removed.

Changes

Cohort / File(s) Change Summary
Proxy Configuration
template/tinyvue/config/vite.config.dev.ts
Proxy rewrite for the mock server now replaces occurrences of the host string derived from VITE_MOCK_SERVER_HOST with '/mock' (previously replaced a leading '/mock' prefix), altering which request paths are normalized/proxied.
Type Definitions
template/tinyvue/src/env.d.ts
ImportMetaEnv moved into a declare global augmentation and expanded with multiple VITE_* fields (VITE_API_BASE_URL, VITE_MOCK_SERVER_HOST, VITE_LOWCODE_DESIGNER_ENABLED, VITE_CONTEXT, VITE_BASE_API, VITE_SERVER_HOST, VITE_MOCK_HOST, VITE_USE_MOCK, VITE_MOCK_IGNORE). Added global BUILD_TOOLS and NodeRequire.context declarations; removed the @vue/runtime-core augmentation that defined $t and $tm.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I hop through rewrites, quick and neat,
Swapping hosts for paths in a tidy beat.
Types grew wider, globals stand tall,
i18n echoes softened — a gentler call.
Tiny rabbit cheers this little change with a happy squeak.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: frontend environment variable type error' directly addresses the main changes in the PR, which involve fixing type definitions in env.d.ts by restructuring the ImportMetaEnv interface and adding VITE environment variables.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • 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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (2)
template/tinyvue/src/env.d.ts (2)

3-3: Remove unused import.

The I18n import from 'vue-i18n' is not used anywhere in this file.

🔎 Proposed fix
-import { I18n } from 'vue-i18n'
-

26-28: Remove redundant declare keywords inside declare global block.

The declare keyword is redundant when declarations are already inside a declare global block.

🔎 Proposed fix
-  declare const BUILD_TOOLS: string;
-  declare interface NodeRequire {
+  const BUILD_TOOLS: string;
+  interface NodeRequire {
     context: any;
   }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 182fce2 and aca87ea.

📒 Files selected for processing (2)
  • template/tinyvue/config/vite.config.dev.ts
  • template/tinyvue/src/env.d.ts
🧰 Additional context used
🪛 ast-grep (0.40.3)
template/tinyvue/config/vite.config.dev.ts

[warning] 20-20: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${loadEnv('', process.cwd()).VITE_MOCK_SERVER_HOST})
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

⏰ 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). (1)
  • GitHub Check: e2e-test

Comment on lines +19 to +22
rewrite: (path: string) => {

return path.replace(new RegExp(`${loadEnv('', process.cwd()).VITE_MOCK_SERVER_HOST}`), '/mock')
},
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, locate the file
find . -name "vite.config.dev.ts" -type f

Repository: opentiny/tiny-pro

Length of output: 105


🏁 Script executed:

# Read the file to see the actual code at the mentioned lines
cat -n template/tinyvue/config/vite.config.dev.ts | head -30

Repository: opentiny/tiny-pro

Length of output: 1109


🏁 Script executed:

# Check if there are other similar patterns with loadEnv and RegExp
rg "loadEnv.*RegExp|new RegExp.*loadEnv" -A 2 -B 2

Repository: opentiny/tiny-pro

Length of output: 780


🏁 Script executed:

# Check environment files to see typical values of these env vars
find . -name ".env*" -o -name "*.env" | head -10

Repository: opentiny/tiny-pro

Length of output: 392


🏁 Script executed:

# Check if there are any documentation or comments about these env vars
rg "VITE_BASE_API|VITE_MOCK_SERVER_HOST" --type-list | head -20

Repository: opentiny/tiny-pro

Length of output: 450


🏁 Script executed:

# Let me search for documentation or config examples
rg "VITE_BASE_API|VITE_MOCK_SERVER_HOST" -B 2 -A 2

Repository: opentiny/tiny-pro

Length of output: 25975


🏁 Script executed:

# Check the actual .env file to see what values are being used
cat template/tinyvue/dev.env

Repository: opentiny/tiny-pro

Length of output: 364


🏁 Script executed:

# Check if there are any other .env files that might be used
find . -path "*/tinyvue/.env*" -type f -exec cat {} \;

Repository: opentiny/tiny-pro

Length of output: 390


🏁 Script executed:

# Verify that these environment variables could potentially contain special regex characters
# by checking all places where they're configured
rg "VITE_BASE_API|VITE_MOCK_SERVER_HOST" --type-list 2>/dev/null || rg "VITE_BASE_API|VITE_MOCK_SERVER_HOST" -B 1 -A 1 | grep -E "^[^:]+:[^:]*=" | head -20

Repository: opentiny/tiny-pro

Length of output: 1227


🏁 Script executed:

# Let me verify the escaping pattern is correct for regex special characters
python3 << 'EOF'
import re

# Current regex metacharacters that need escaping in RegExp
special_chars = r'.*+?^${}()|[\]'

# Test what needs escaping
test_values = ['/api', '/mock', '/api.*', '/api[test]', '/api+test']

for val in test_values:
    try:
        # Without escaping
        pattern_unescaped = val
        regex_unescaped = re.compile(pattern_unescaped)
        print(f"✓ '{val}' compiles as regex (unescaped)")
    except re.error as e:
        print(f"✗ '{val}' FAILS to compile as regex (unescaped): {e}")
    
    # With escaping (proposed fix)
    escaped = re.sub(r'[.*+?^${}()|[\]\\]', r'\\\g<0>', val)
    try:
        regex_escaped = re.compile(escaped)
        print(f"✓ '{val}' -> '{escaped}' compiles as regex (escaped)")
    except re.error as e:
        print(f"✗ Escaping failed: {e}")
    print()
EOF

Repository: opentiny/tiny-pro

Length of output: 147


🏁 Script executed:

# Check if there are any other places in the project using similar patterns
rg "new RegExp.*loadEnv|new RegExp.*process.env" -A 2 -B 2

Repository: opentiny/tiny-pro

Length of output: 780


🏁 Script executed:

# Verify the proposed fix approach is sound for JavaScript/TypeScript
cat > /tmp/test_regex_escape.js << 'EOF'
// Test the escaping approach from the review
const testValues = ['/api', '/mock', '/api.*test', '/api[123]', '/api+test'];

testValues.forEach(val => {
  console.log(`\nTesting: ${val}`);
  
  // Without escaping (current code pattern)
  try {
    const regex1 = new RegExp(val);
    console.log(`  Unescaped: OK - matches '/api' as string`);
    console.log(`  Test: '/api/users' matches? ${regex1.test('/api/users')}`);
  } catch (e) {
    console.log(`  Unescaped: ERROR - ${e.message}`);
  }
  
  // With proposed escaping
  const escaped = val.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  try {
    const regex2 = new RegExp(escaped);
    console.log(`  Escaped ('${escaped}'): OK`);
    console.log(`  Test: '/api/users' matches? ${regex2.test('/api/users')}`);
  } catch (e) {
    console.log(`  Escaped: ERROR - ${e.message}`);
  }
});
EOF
node /tmp/test_regex_escape.js

Repository: opentiny/tiny-pro

Length of output: 862


Escape special characters in RegExp patterns constructed from environment variables.

Lines 12 and 21 create RegExp patterns from unescaped environment variables. While current values (/api, /mock) are safe, if these variables ever contain regex metacharacters, they will be interpreted as patterns rather than literal strings, causing unexpected behavior.

     rewrite: (path: string) =>
       path.replace(
-        new RegExp(`${loadEnv('', process.cwd()).VITE_BASE_API}`),
+        new RegExp(loadEnv('', process.cwd()).VITE_BASE_API.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),
         '',
       ),
     rewrite: (path: string) => {
-      return path.replace(new RegExp(`${loadEnv('', process.cwd()).VITE_MOCK_SERVER_HOST}`), '/mock')
+      const host = loadEnv('', process.cwd()).VITE_MOCK_SERVER_HOST;
+      return path.replace(new RegExp(host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), '/mock')
     },

Apply the same escaping to both locations to prevent ReDoS vulnerabilities.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
rewrite: (path: string) => {
return path.replace(new RegExp(`${loadEnv('', process.cwd()).VITE_MOCK_SERVER_HOST}`), '/mock')
},
rewrite: (path: string) => {
const host = loadEnv('', process.cwd()).VITE_MOCK_SERVER_HOST;
return path.replace(new RegExp(host.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), '/mock')
},
🧰 Tools
🪛 ast-grep (0.40.3)

[warning] 20-20: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(${loadEnv('', process.cwd()).VITE_MOCK_SERVER_HOST})
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

🤖 Prompt for AI Agents
In template/tinyvue/config/vite.config.dev.ts around lines 12 and 21, the code
builds RegExp objects directly from environment variable strings which may
contain regex metacharacters; update both sites to escape regex-special
characters from the env values before passing them to new RegExp (e.g.,
implement a small escape function that replaces [.*+?^${}()|[\]\\] with escaped
versions) and use the escaped string to construct the RegExp so the env value is
treated as a literal and avoids unexpected behavior or ReDoS risks.

Comment thread template/tinyvue/src/env.d.ts Outdated
Copy link
Copy Markdown

@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)
template/tinyvue/src/env.d.ts (1)

26-29: Remove redundant declare keywords inside declare global block.

Within a declare global block, the declare keyword is redundant for constants and interfaces. TypeScript already treats everything inside declare global as ambient declarations.

🔎 Proposed fix
   }
-  declare const BUILD_TOOLS: string;
-  declare interface NodeRequire {
+  const BUILD_TOOLS: string;
+  interface NodeRequire {
     context: any;
   }
 }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aca87ea and 3004dc5.

📒 Files selected for processing (1)
  • template/tinyvue/src/env.d.ts
⏰ 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). (1)
  • GitHub Check: e2e-test
🔇 Additional comments (1)
template/tinyvue/src/env.d.ts (1)

14-25: LGTM! Environment variables now correctly typed.

The ImportMetaEnv interface correctly declares all Vite environment variables as string type, which properly addresses the critical type error flagged in the previous review. Line 18 specifically fixes VITE_LOWCODE_DESIGNER_ENABLED by changing it from boolean to string, matching Vite's runtime behavior where all environment variables are strings.

Comment thread template/tinyvue/src/env.d.ts Outdated
Copy link
Copy Markdown

@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)
template/tinyvue/src/env.d.ts (1)

24-27: Remove redundant declare keywords inside declare global block.

Inside a declare global block, declarations are implicitly ambient, so the declare keyword is redundant. While TypeScript accepts this syntax, removing it aligns with idiomatic TypeScript declaration patterns.

🔎 Proposed refactor
-  declare const BUILD_TOOLS: string;
-  declare interface NodeRequire {
+  const BUILD_TOOLS: string;
+  interface NodeRequire {
     context: any;
   }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3004dc5 and 82f8aab.

📒 Files selected for processing (1)
  • template/tinyvue/src/env.d.ts
⏰ 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). (1)
  • GitHub Check: e2e-test
🔇 Additional comments (1)
template/tinyvue/src/env.d.ts (1)

12-23: LGTM! Environment variable types are now correct.

The VITE_LOWCODE_DESIGNER_ENABLED variable is now correctly typed as string (line 16), which resolves the type error mentioned in previous reviews. All Vite environment variables are properly typed as string, which matches Vite's runtime behavior.

@kagol kagol merged commit 12f464b into opentiny:dev Dec 30, 2025
2 of 3 checks passed
discreted66 pushed a commit to discreted66/tiny-pro that referenced this pull request Jan 7, 2026
* fix: frontend environment variable type error

* fix: lowcode designer enable type

* refactor: remove unused import
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants