Backtestsvuerun-20261009-161443#15126

Issue #15126 Merged fix PR #15136 Run 9 Oct 2026 · run-20261009-161443 vuejs/core

compileScript drops template imports from returned when analysis re-runs on a transformed template AST

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches fix the root cause the same way. When `ast.transformed` is set, `resolveTemplateAnalysisResult` re-parses the full SFC source in `parseMode: 'sfc'` with `prefixIdentifiers: true` and errors suppressed, then walks the fresh `<template>` children. Both thread `templateOptions` (compilerOptions such as delimiters) from `compileScript` into the analysis, for both the used-import check and the v-model demotion check. Correctness is essentially equivalent.

Patch A also extracts the re-parse into a shared `resolveTemplateAST` helper that `compileTemplate` now uses. That removes duplication and honours a custom `compiler`/`ssr`. However, it rewrites `compileTemplate`'s imports and logic, which is a modest extra risk. It also exports the internal `templateAnalysisCache` just so the test can clear it.

Patch B keeps the change local to `importUsageCheck.ts`, using compiler-dom's `parse`, which is the same parser the descriptor AST comes from.

On tests, Patch B is clearly stronger and maps directly onto the issue:
- It covers imports used in a template function call, in `v-for`, and as a component, and asserts unused imports stay excluded.
- It covers custom delimiters on re-parse.
- It covers recoverable parse errors not throwing.
- It covers v-model `SETUP_LET` demotion on a transformed AST.

Patch A has a single test, covering only a simple interpolation with custom delimiters, and it relies on reaching into the exported cache. Both test suites would fail before the fix. Patch B's coverage of the issue's specific scenarios (function-call expressions and v-for), together with its smaller blast radius, outweighs Patch A's deduplication.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

7m 24s

Wall-clock time in the container

Full test suite

No new failures

620 passed · 1 skipped · 621 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

216vs 173 merged

Changed lines, ours vs merged

Vue version

3.5.40

Link to minimal reproduction

https://stackblitz.com/edit/vitejs-vite-evwepvbu?file=package.json

Steps to reproduce

Compile more than 500 unique SFCs for client + SSR (non-inline mode), share each file's descriptor between the two passes (the same way @vitejs/plugin-vue does). The client pass compileTemplate changes the shared template.ast in place, when the analysis cache (capped at 500) evicts a file entry, its SSR compileScript pass re-runs the import usage analysis on that already transformed AST

What is expected?

__returned__ contains every import the template references, same output as when fewer than 500 templates are compiled. The analysis should re-parse when the AST was already transformed, the same guard compileTemplate has with if (inAST?.transformed) in line 214.

What is actually happening?

Imports referenced only from template expressions or with v-for are dropped from __returned__. While the render function still emits $setup.foo(...) and throws TypeError: $setup.foo is not a function at runtime. Because it only happens with more than 500 unique templates it only comes up in large apps in development, in production builds the template are inlined and are unaffected.

System Info

Any additional comments?

Might be the cause for vitejs/vite-plugin-vue#764, vitest-dev/vitest#9855?

The two patches

Our patch+206 −10
packages/compiler-sfc/__tests__/compileScript/__snapshots__/importUsageCheck.spec.ts.snapindex e64858744..6318c1159 100644@@ -49,6 +49,59 @@ return { fooBar, get FooBaz() { return FooBaz }, get FooQux() { return FooQux }, })" `; +exports[`descriptor template AST already transformed by compileTemplate > imports used in template expressions and v-for 1`] = `+"import { defineComponent as _defineComponent } from 'vue'+import { transformedFoo, transformedList, TransformedComp, unused } from './x'+    +export default /*@__PURE__*/_defineComponent({+  setup(__props, { expose: __expose }) {+  __expose();++    +return { get transformedFoo() { return transformedFoo }, get transformedList() { return transformedList }, get TransformedComp() { return TransformedComp } }+}++})"+`;++exports[`descriptor template AST already transformed by compileTemplate > respects template compiler options when re-parsing 1`] = `+"import { defineComponent as _defineComponent } from 'vue'+import { transformedDelim } from './x'+    +export default /*@__PURE__*/_defineComponent({+  setup(__props, { expose: __expose }) {+  __expose();++    +return { get transformedDelim() { return transformedDelim } }+}++})"+`;++exports[`descriptor template AST already transformed by compileTemplate > v-model target demotion (inlineTemplate) 1`] = `+"import { unref as _unref, resolveComponent as _resolveComponent, isRef as _isRef, openBlock as _openBlock, createBlock as _createBlock } from "vue"++import { reactive } from 'vue'+    +export default {+  setup(__props) {++    let transformedModel = reactive({ a: 1 })+    +return (_ctx, _cache) => {+  const _component_MyComponent = _resolveComponent("MyComponent")++  return (_openBlock(), _createBlock(_component_MyComponent, {+    modelValue: _unref(transformedModel),+    "onUpdate:modelValue": _cache[0] || (_cache[0] = $event => (_isRef(transformedModel) ? (transformedModel).value = $event : transformedModel = $event))+  }, null, 8 /* PROPS */, ["modelValue"]))+}+}++}"+`;+ exports[`directive 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { vMyDir } from './x'packages/compiler-sfc/__tests__/compileScript/importUsageCheck.spec.tsindex 210fa0968..da125be13 100644@@ -1,4 +1,11 @@-import { assertCode, compileSFCScript as compile } from '../utils'+import { BindingTypes } from '@vue/compiler-core'+import {+  type SFCScriptCompileOptions,+  compileScript,+  compileTemplate,+  parse,+} from '../../src'+import { assertCode, compileSFCScript as compile, mockId } from '../utils'  // in dev mode, declared bindings are returned as an object from setup() // when using TS, users may import types which should not be returned as@@ -265,3 +272,99 @@ test('shorthand binding w/ kebab-case', () => {   )   expect(content).toMatch('return { get fooBar() { return fooBar }') })++describe('descriptor template AST already transformed by compileTemplate', () => {+  // simulate a descriptor shared between client and SSR compilation, where+  // the client compileTemplate pass transforms `descriptor.template.ast` in+  // place before the analysis of this template runs (e.g. after its analysis+  // cache entry was evicted)+  function compileAfterTemplateTransform(+    src: string,+    options?: Partial<SFCScriptCompileOptions>,+  ) {+    const { descriptor } = parse(src)+    compileTemplate({+      filename: 'test.vue',+      id: mockId,+      source: descriptor.template!.content,+      ast: descriptor.template!.ast,+      compilerOptions: options?.templateOptions?.compilerOptions,+    })+    expect(descriptor.template!.ast!.transformed).toBe(true)+    return compileScript(descriptor, { ...options, id: mockId })+  }++  test('imports used in template expressions and v-for', () => {+    const { content } = compileAfterTemplateTransform(`+    <script setup lang="ts">+    import { transformedFoo, transformedList, TransformedComp, unused } from './x'+    </script>+    <template>+      <div>{{ transformedFoo(1) }}</div>+      <TransformedComp v-for="item in transformedList" :key="item" />+    </template>+    `)+    expect(content).toMatch(`get transformedFoo() { return transformedFoo }`)+    expect(content).toMatch(`get transformedList() { return transformedList }`)+    expect(content).toMatch(`get TransformedComp() { return TransformedComp }`)+    expect(content).not.toMatch(`get unused()`)+    assertCode(content)+  })++  test('respects template compiler options when re-parsing', () => {+    const { content } = compileAfterTemplateTransform(+      `+    <script setup lang="ts">+    import { transformedDelim } from './x'+    </script>+    <template>+      <div>[[ transformedDelim ]]</div>+    </template>+    `,+      { templateOptions: { compilerOptions: { delimiters: ['[[', ']]'] } } },+    )+    expect(content).toMatch(+      `get transformedDelim() { return transformedDelim }`,+    )+    assertCode(content)+  })++  test('does not throw on recoverable template parse errors', () => {+    const { descriptor } = parse(`+    <script setup lang="ts">+    import { transformedErr } from './x'+    </script>+    <template>+      <div>{{ transformedErr }}</div>+      <span>{{ a + }}</span>+    </template>+    `)+    compileTemplate({+      filename: 'test.vue',+      id: mockId,+      source: descriptor.template!.content,+      ast: descriptor.template!.ast,+    })+    expect(descriptor.template!.ast!.transformed).toBe(true)+    const { content } = compileScript(descriptor, { id: mockId })+    expect(content).toMatch(`get transformedErr() { return transformedErr }`)+  })++  test('v-model target demotion (inlineTemplate)', () => {+    const { content, bindings } = compileAfterTemplateTransform(+      `+    <script setup>+    import { reactive } from 'vue'+    const transformedModel = reactive({ a: 1 })+    </script>+    <template>+      <MyComponent v-model="transformedModel" />+    </template>+    `,+      { inlineTemplate: true },+    )+    expect(content).toMatch(`let transformedModel = reactive({ a: 1 })`)+    expect(bindings!.transformedModel).toBe(BindingTypes.SETUP_LET)+    assertCode(content)+  })+})packages/compiler-sfc/src/compileScript.tsindex a60aba17a..428fd2848 100644@@ -266,7 +266,11 @@ export function compileScript(       !sfc.template.src &&       !sfc.template.lang     ) {-      isUsedInTemplate = isImportUsed(local, sfc)+      isUsedInTemplate = isImportUsed(+        local,+        sfc,+        options.templateOptions && options.templateOptions.compilerOptions,+      )     }      ctx.userImports[local] = {@@ -769,7 +773,10 @@ export function compileScript(   // which requires a SETUP_LET binding (getter + setter) to keep script state in sync.   // In inline mode, it generates `foo = $event`, which also requires `let`.   if (sfc.template && !sfc.template.src && sfc.template.ast) {-    const vModelIds = resolveTemplateVModelIdentifiers(sfc)+    const vModelIds = resolveTemplateVModelIdentifiers(+      sfc,+      options.templateOptions && options.templateOptions.compilerOptions,+    )     if (vModelIds.size) {       const toDemote = new Set<string>()       for (const id of vModelIds) {packages/compiler-sfc/src/script/importUsageCheck.tsindex 9c087b466..6c821889e 100644@@ -1,23 +1,30 @@ import type { SFCDescriptor } from '../parse' import {+  type ElementNode,   type ExpressionNode,   NodeTypes,+  type ParserOptions,   type SimpleExpressionNode,   type TemplateChildNode,   isSimpleIdentifier,+  parse,   parserOptions,   walkIdentifiers, } from '@vue/compiler-dom' import { createCache } from '../cache'-import { camelize, capitalize, isBuiltInDirective } from '@vue/shared'+import { NOOP, camelize, capitalize, isBuiltInDirective } from '@vue/shared'  /**  * Check if an import is used in the SFC's template. This is used to determine  * the properties that should be included in the object returned from setup()  * when not using inline mode.  */-export function isImportUsed(local: string, sfc: SFCDescriptor): boolean {-  return resolveTemplateUsedIdentifiers(sfc).has(local)+export function isImportUsed(+  local: string,+  sfc: SFCDescriptor,+  parseOptions?: ParserOptions,+): boolean {+  return resolveTemplateUsedIdentifiers(sfc, parseOptions).has(local) }  const templateAnalysisCache = createCache<{@@ -27,17 +34,22 @@ const templateAnalysisCache = createCache<{  export function resolveTemplateVModelIdentifiers(   sfc: SFCDescriptor,+  parseOptions?: ParserOptions, ): Set<string> {-  return resolveTemplateAnalysisResult(sfc, false).vModelIds+  return resolveTemplateAnalysisResult(sfc, false, parseOptions).vModelIds } -function resolveTemplateUsedIdentifiers(sfc: SFCDescriptor): Set<string> {-  return resolveTemplateAnalysisResult(sfc).usedIds!+function resolveTemplateUsedIdentifiers(+  sfc: SFCDescriptor,+  parseOptions?: ParserOptions,+): Set<string> {+  return resolveTemplateAnalysisResult(sfc, true, parseOptions).usedIds! }  function resolveTemplateAnalysisResult(   sfc: SFCDescriptor,   collectUsedIds = true,+  parseOptions?: ParserOptions, ): {   usedIds?: Set<string>   vModelIds: Set<string>@@ -53,7 +65,28 @@ function resolveTemplateAnalysisResult(   const ids = collectUsedIds ? new Set<string>() : undefined   const vModelIds = new Set<string>() -  ast!.children.forEach(walk)+  let children = ast!.children+  if (ast!.transformed) {+    // The descriptor AST may have already been transformed in place by+    // compileTemplate (e.g. when the same descriptor is shared between client+    // and SSR compilation). A transformed AST no longer reflects the original+    // template, so parse a fresh one. Same as in compileTemplate, the full SFC+    // source is parsed so that location info stays relative to the SFC.+    // Expression ASTs are required for the analysis, and parse errors have+    // already been reported by parse() / compileTemplate.+    const newAST = parse(ast!.source, {+      ...parseOptions,+      prefixIdentifiers: true,+      parseMode: 'sfc',+      onError: NOOP,+    })+    const template = newAST.children.find(+      node => node.type === NodeTypes.ELEMENT && node.tag === 'template',+    ) as ElementNode+    children = template.children+  }++  children.forEach(walk)    function walk(node: TemplateChildNode) {     switch (node.type) { 
Merged fix · PR #15136+137 −36
packages/compiler-sfc/__tests__/compileScript.spec.tsindex 5e547f6b2..d54541019 100644@@ -7,6 +7,8 @@ import {   mockId, } from './utils' import { type RawSourceMap, SourceMapConsumer } from 'source-map-js'+import { compileScript, compileTemplate, parse } from '../src'+import { templateAnalysisCache } from '../src/script/importUsageCheck'  vi.mock('../src/warn', () => ({   warn: vi.fn(),@@ -345,6 +347,43 @@ describe('SFC compile <script setup>', () => {       expect(content).toMatch(`import { useCssVars, ref } from 'vue'`)     }) +    test('should re-analyze a transformed template after cache invalidation', () => {+      const delimiters: [string, string] = ['[[', ']]']+      const { descriptor } = parse(+        `+        <script setup lang="ts">+        import { cachedMsg } from './cachedMsg'+        </script>+        <template><p>[[ cachedMsg ]]</p></template>+        `,+        { templateParseOptions: { delimiters } },+      )++      const templateOptions = { compilerOptions: { delimiters } }+      compileScript(descriptor, { id: mockId, templateOptions })+      expect(templateAnalysisCache.has(descriptor.template!.content)).toBe(true)++      compileTemplate({+        filename: 'example.vue',+        id: mockId,+        source: descriptor.template!.content,+        ast: descriptor.template!.ast,+        compilerOptions: { delimiters },+      })+      expect(descriptor.template!.ast!.transformed).toBe(true)++      templateAnalysisCache.clear()+      expect(templateAnalysisCache.has(descriptor.template!.content)).toBe(+        false,+      )++      const { content } = compileScript(descriptor, {+        id: mockId,+        templateOptions,+      })+      expect(content).toMatch(`return { get cachedMsg() { return cachedMsg } }`)+    })+     test('import dedupe between <script> and <script setup>', () => {       const { content } = compile(`         <script>packages/compiler-sfc/src/compileScript.tsindex a60aba17a..d2047c5b2 100644@@ -266,7 +266,7 @@ export function compileScript(       !sfc.template.src &&       !sfc.template.lang     ) {-      isUsedInTemplate = isImportUsed(local, sfc)+      isUsedInTemplate = isImportUsed(local, sfc, options.templateOptions)     }      ctx.userImports[local] = {@@ -769,7 +769,10 @@ export function compileScript(   // which requires a SETUP_LET binding (getter + setter) to keep script state in sync.   // In inline mode, it generates `foo = $event`, which also requires `let`.   if (sfc.template && !sfc.template.src && sfc.template.ast) {-    const vModelIds = resolveTemplateVModelIdentifiers(sfc)+    const vModelIds = resolveTemplateVModelIdentifiers(+      sfc,+      options.templateOptions,+    )     if (vModelIds.size) {       const toDemote = new Set<string>()       for (const id of vModelIds) {packages/compiler-sfc/src/compileTemplate.tsindex b043cf813..6c8ad3988 100644@@ -1,14 +1,11 @@-import {-  type CodegenResult,-  type CompilerError,-  type CompilerOptions,-  type ElementNode,-  type NodeTransform,-  NodeTypes,-  type ParserOptions,-  type RawSourceMap,-  type RootNode,-  createRoot,+import type {+  CodegenResult,+  CompilerError,+  CompilerOptions,+  NodeTransform,+  ParserOptions,+  RawSourceMap,+  RootNode, } from '@vue/compiler-core' import { SourceMapConsumer, SourceMapGenerator } from 'source-map-js' import {@@ -28,6 +25,7 @@ import * as CompilerSSR from '@vue/compiler-ssr' import consolidate from '@vue/consolidate' import { warnOnce } from './warn' import { genCssVarsFromList } from './style/cssVars'+import { resolveTemplateAST } from './template/resolveTemplateAST'  export interface TemplateCompiler {   compile(source: string | RootNode, options: CompilerOptions): CodegenResult@@ -211,21 +209,12 @@ function doCompileTemplate({     inAST = undefined   } -  if (inAST?.transformed) {-    // If input AST has already been transformed, then it cannot be reused.-    // We need to parse a fresh one. Can't just use `source` here since we need-    // the AST location info to be relative to the entire SFC.-    const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, {-      prefixIdentifiers: true,-      ...compilerOptions,-      parseMode: 'sfc',-      onError: e => errors.push(e),-    })-    const template = newAST.children.find(-      node => node.type === NodeTypes.ELEMENT && node.tag === 'template',-    ) as ElementNode-    inAST = createRoot(template.children, inAST.source)-  }+  inAST = resolveTemplateAST(inAST, {+    compiler,+    compilerOptions,+    ssr,+    onError: e => errors.push(e),+  })    let { code, ast, preamble, map } = compiler.compile(inAST || source, {     mode: 'module',packages/compiler-sfc/src/script/importUsageCheck.tsindex 9c087b466..fa16a1adc 100644@@ -1,4 +1,5 @@ import type { SFCDescriptor } from '../parse'+import type { SFCTemplateCompileOptions } from '../compileTemplate' import {   type ExpressionNode,   NodeTypes,@@ -8,36 +9,57 @@ import {   parserOptions,   walkIdentifiers, } from '@vue/compiler-dom'+import type { LRUCache } from 'lru-cache' import { createCache } from '../cache' import { camelize, capitalize, isBuiltInDirective } from '@vue/shared'+import { resolveTemplateAST } from '../template/resolveTemplateAST'++type TemplateOptions = Pick<+  SFCTemplateCompileOptions,+  'compiler' | 'compilerOptions' | 'ssr'+>  /**  * Check if an import is used in the SFC's template. This is used to determine  * the properties that should be included in the object returned from setup()  * when not using inline mode.  */-export function isImportUsed(local: string, sfc: SFCDescriptor): boolean {-  return resolveTemplateUsedIdentifiers(sfc).has(local)+export function isImportUsed(+  local: string,+  sfc: SFCDescriptor,+  options?: TemplateOptions,+): boolean {+  return resolveTemplateUsedIdentifiers(sfc, options).has(local) } -const templateAnalysisCache = createCache<{+type TemplateAnalysisResult = {   usedIds?: Set<string>   vModelIds: Set<string>-}>()+}++export const templateAnalysisCache:+  | Map<string, TemplateAnalysisResult>+  | LRUCache<string, TemplateAnalysisResult> =+  createCache<TemplateAnalysisResult>()  export function resolveTemplateVModelIdentifiers(   sfc: SFCDescriptor,+  options?: TemplateOptions, ): Set<string> {-  return resolveTemplateAnalysisResult(sfc, false).vModelIds+  return resolveTemplateAnalysisResult(sfc, false, options).vModelIds } -function resolveTemplateUsedIdentifiers(sfc: SFCDescriptor): Set<string> {-  return resolveTemplateAnalysisResult(sfc).usedIds!+function resolveTemplateUsedIdentifiers(+  sfc: SFCDescriptor,+  options?: TemplateOptions,+): Set<string> {+  return resolveTemplateAnalysisResult(sfc, true, options).usedIds! }  function resolveTemplateAnalysisResult(   sfc: SFCDescriptor,   collectUsedIds = true,+  options?: TemplateOptions, ): {   usedIds?: Set<string>   vModelIds: Set<string>@@ -53,7 +75,15 @@ function resolveTemplateAnalysisResult(   const ids = collectUsedIds ? new Set<string>() : undefined   const vModelIds = new Set<string>() -  ast!.children.forEach(walk)+  const root = resolveTemplateAST(ast, {+    compiler: options?.compiler,+    compilerOptions: options?.compilerOptions,+    ssr: options?.ssr,+    // ignore errors since they were already reported by the SFC parser+    onError: () => {},+  })++  root!.children.forEach(walk)    function walk(node: TemplateChildNode) {     switch (node.type) {packages/compiler-sfc/src/template/resolveTemplateAST.tsnew file mode 100644index 000000000..b2897e56d@@ -0,0 +1,40 @@+import {+  type CompilerError,+  type ElementNode,+  NodeTypes,+  type ParserOptions,+  type RootNode,+  createRoot,+} from '@vue/compiler-core'+import * as CompilerDOM from '@vue/compiler-dom'++interface TemplateParser {+  parse(template: string, options: ParserOptions): RootNode+}++export function resolveTemplateAST(+  inAST: RootNode | undefined,+  options: {+    compiler?: TemplateParser+    compilerOptions?: ParserOptions+    ssr?: boolean+    onError: (error: CompilerError) => void+  },+): RootNode | undefined {+  if (!inAST?.transformed) {+    return inAST+  }++  // Parse the full SFC source to preserve template locations relative to it.+  const { compiler = CompilerDOM, compilerOptions, ssr, onError } = options+  const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, {+    prefixIdentifiers: true,+    ...compilerOptions,+    parseMode: 'sfc',+    onError,+  })+  const template = newAST.children.find(+    node => node.type === NodeTypes.ELEMENT && node.tag === 'template',+  ) as ElementNode+  return createRoot(template.children, inAST.source)+}