Skip to content

fix(compile-sfc): handle inline template source map in prod build #12701

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

edison1105
Copy link
Member

@edison1105 edison1105 commented Jan 13, 2025

close #12682
close vitejs/vite-plugin-vue#500

Summary by CodeRabbit

  • New Features

    • Improved source map accuracy for single-file components with inline templates, ensuring correct mapping between original source and compiled output.
  • Tests

    • Added new test case to validate source map generation and mapping accuracy for script setup and template code.
  • Refactor

    • Centralized utility function for code position calculation to a shared module for reuse across tests.
  • Documentation

    • Updated type definitions and utility exports to reflect new and refactored functionality.

Copy link

github-actions bot commented Jan 13, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB 38.3 kB 34.5 kB
vue.global.prod.js 159 kB 58.5 kB 52 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.6 kB 18.2 kB 16.7 kB
createApp 54.5 kB 21.2 kB 19.4 kB
createSSRApp 58.8 kB 23 kB 20.9 kB
defineCustomElement 59.5 kB 22.8 kB 20.8 kB
overall 68.6 kB 26.4 kB 24.1 kB

Copy link

pkg-pr-new bot commented Jan 13, 2025

Open in StackBlitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@12701

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@12701

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@12701

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@12701

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@12701

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@12701

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@12701

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@12701

@vue/shared

npm i https://pkg.pr.new/@vue/shared@12701

@vue/compat

npm i https://pkg.pr.new/@vue/compat@12701

vue

npm i https://pkg.pr.new/vue@12701

commit: 5132463

@edison1105 edison1105 added ready to merge The PR is ready to be merged. scope: sfc labels Jan 13, 2025
@edison1105 edison1105 added the 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. label Feb 18, 2025
Copy link

coderabbitai bot commented May 16, 2025

Walkthrough

The changes introduce enhanced source map merging in the Vue SFC compiler to accurately map both <script setup> and <template> sections. A new utility for code position calculation is centralized, and a new test verifies correct source map mappings for identifiers in compiled SFCs. No existing logic is modified outside these enhancements.

Changes

File(s) Change Summary
packages/compiler-sfc/src/compileScript.ts Added mergeSourceMaps function to combine script and template source maps. Updated compileScript to merge maps when using inline templates, ensuring the returned map reflects both script and template code.
packages/compiler-sfc/__tests__/compileScript.spec.ts Added a test case to verify that the generated source map correctly maps identifiers from both <script setup> and <template> sections. Utilizes SourceMapConsumer and the new getPositionInCode utility.
packages/compiler-sfc/__tests__/compileTemplate.spec.ts Refactored to remove the local getPositionInCode utility and Pos interface. Now imports getPositionInCode from the new shared utility module.
packages/compiler-sfc/__tests__/utils.ts New file introducing the getPositionInCode function and Pos interface to calculate line/column positions of tokens in code. Exported for use in multiple test files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant compileScript
    participant compileTemplate
    participant mergeSourceMaps

    User->>compileScript: Compile SFC with inline template
    compileScript->>compileTemplate: Compile template, get code and source map
    compileScript->>compileScript: Generate script setup source map
    compileScript->>mergeSourceMaps: Merge script and template maps with offset
    mergeSourceMaps-->>compileScript: Return merged source map
    compileScript-->>User: Return compiled content and merged source map
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure that the source map includes mappings for both <script setup> and <template> sections (#12682, #500)
Source map should correctly map errors thrown in <template> to the correct line in the original SFC (#500)
Provide utilities/tests to validate source map accuracy for SFCs (#12682, #500)

Poem

In code we hop, with maps so neat,
Now scripts and templates finally meet!
No more lost lines or mapping dread,
Errors point true, just as we said.
With merged maps clear, we leap with glee—
A happy rabbit in SFC!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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

🧹 Nitpick comments (2)
packages/compiler-sfc/__tests__/compileScript.spec.ts (1)

701-719: Import ref to keep the fixture realistic and future-proof

The new test relies on ref() but omits

import { ref } from 'vue'

While the compiler currently tolerates the missing import, adding it prevents false positives if future binding-analysis becomes stricter and makes the snippet closer to real-world usage.

       <script setup>
-        const count = ref(0)
+        import { ref } from 'vue'
+        const count = ref(0)
       </script>
packages/compiler-sfc/src/compileScript.ts (1)

1303-1340: Avoid touching private fields of source-map-js & release consumers

_sources, _sourceRoot, _file are private internals; relying on them risks breakage on minor upgrades.
The public API already covers these needs:

-  const generator = new SourceMapGenerator()
+  const generator = new SourceMapGenerator({
+    file: scriptMap.file,
+    sourceRoot: scriptMap.sourceRoot,
+  })-  ;(generator as any)._sourceRoot = scriptMap.sourceRoot
-  ;(generator as any)._file = scriptMap.file
+  // no direct property mutation necessary

Also, each SourceMapConsumer should be .destroy()-ed (async) or .close() (sync) when done to free WASM/worker resources:

const consumer = await new SourceMapConsumer(map)
try {
  
} finally {
  consumer.destroy?.()
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 163b365 and 5132463.

📒 Files selected for processing (4)
  • packages/compiler-sfc/__tests__/compileScript.spec.ts (2 hunks)
  • packages/compiler-sfc/__tests__/compileTemplate.spec.ts (1 hunks)
  • packages/compiler-sfc/__tests__/utils.ts (1 hunks)
  • packages/compiler-sfc/src/compileScript.ts (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test / unit-test-windows
  • GitHub Check: test / e2e-test
🔇 Additional comments (1)
packages/compiler-sfc/__tests__/compileTemplate.spec.ts (1)

9-9: Centralize position utility via shared import
Great refactor—removing the local getPositionInCode definition and importing it from ./utils DRYs up the code and ensures consistency across tests. The relative path is accurate given the __tests__ directory structure.

Comment on lines +50 to +75
export function getPositionInCode(
code: string,
token: string,
expectName: string | boolean = false,
): Pos {
const generatedOffset = code.indexOf(token)
let line = 1
let lastNewLinePos = -1
for (let i = 0; i < generatedOffset; i++) {
if (code.charCodeAt(i) === 10 /* newline char code */) {
line++
lastNewLinePos = i
}
}
const res: Pos = {
line,
column:
lastNewLinePos === -1
? generatedOffset
: generatedOffset - lastNewLinePos - 1,
}
if (expectName) {
res.name = typeof expectName === 'string' ? expectName : token
}
return res
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against “token not found” and CRLF line endings

indexOf() can return -1 ‑ leading to line=1 and column=-1, which later feeds SourceMapConsumer.originalPositionFor() with negative values.
In addition, the loop only treats \n (LF) as a newline; on Windows a CRLF sequence will mis-count lines.

+  if (generatedOffset === -1) {
+    throw new Error(`Token "${token}" not found in supplied code snippet`)
+  }
   for (let i = 0; i < generatedOffset; i++) {
-    if (code.charCodeAt(i) === 10 /* newline char code */) {
+    const ch = code.charCodeAt(i)
+    // 10 → \n  |  13 → \r
+    if (ch === 10 || ch === 13) {
       line++
       lastNewLinePos = i
     }
   }

This eliminates silent mis-mappings and makes the helper reliable across OSes.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/compiler-sfc/__tests__/utils.ts between lines 50 and 75, the
function getPositionInCode does not handle the case when the token is not found,
causing indexOf to return -1 and resulting in invalid line and column values.
Additionally, it only counts '\n' as a newline, which fails on Windows CRLF line
endings. Fix this by adding a guard to return a default or error position if
token is not found, and update the loop to correctly count both '\r\n' and '\n'
as newlines to ensure accurate line and column calculation across OSes.

Comment on lines +1030 to +1038
}) as unknown as RawSourceMap)
: undefined
// merge source maps of the script setup and template in inline mode
if (templateMap && map) {
const offset = content.indexOf(returned)
const templateLineOffset =
content.slice(0, offset).split(/\r?\n/).length - 1
map = mergeSourceMaps(map, templateMap, templateLineOffset)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential mismatch when returned appears earlier in content

content.indexOf(returned) assumes the first occurrence marks the template insertion point.
A comment, string literal or earlier return block containing the same substring would shift templateLineOffset, producing wrong mappings.

Safer approach: remember the exact start line when you append returned, e.g., obtain ctx.s.lineToOffset() before appendRight, or return the offset from compileTemplate and pass it through.

🤖 Prompt for AI Agents
In packages/compiler-sfc/src/compileScript.ts around lines 1030 to 1038, the
code uses content.indexOf(returned) to find the template insertion point, which
can be incorrect if the returned string appears earlier in content. To fix this,
track the exact start line or offset at the moment you append the returned
template string, for example by calling ctx.s.lineToOffset() before appendRight
or by modifying compileTemplate to return the offset, then use this precise
offset to calculate templateLineOffset for merging source maps accurately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. ready to merge The PR is ready to be merged. scope: sfc
Projects
None yet
1 participant