before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
'npm create -- tsrouter-app@latest TARGET_DIR --framework Solid --interactive',
},
{
name: 'custom-vike-solid',
display: 'Vike ↗',
color: cyan,
customCommand: 'npm create -- vike@latest --solid TARGET_DIR',
},
],
},
{
name: 'ember',
display: 'E... | ```suggestion
customCommand: 'npm exec -- ember-cli@latest new TARGET_DIR --typescript',
},
{
name: 'ember-app',
display: 'JavaScript ↗',
color: redBright,
customCommand: 'npm exec -- ember-cli@latest new TARGET_DIR',
```
Just noticed that we should use `npm ... | 'npm create -- tsrouter-app@latest TARGET_DIR --framework Solid --interactive',
},
{
name: 'custom-vike-solid',
display: 'Vike ↗',
color: cyan,
customCommand: 'npm create -- vike@latest --solid TARGET_DIR',
},
],
},
{
name: 'ember',
display: 'E... | @@ -286,6 +286,25 @@ const FRAMEWORKS: Framework[] = [
},
],
},
+ {
+ name: 'ember',
+ display: 'Ember',
+ color: redBright,
+ variants: [
+ {
+ name: 'ember-app-ts',
+ display: 'TypeScript ↗',
+ color: blueBright,
+ customCommand: 'npx ember-cli@latest new T... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 476 | 51 | 51 | false | feat(create-vite): add ember | 20,069 | vitejs/vite | 78,557 | TypeScript | sapphi-red | NullVoxPopuli |
},
{
name: 'custom-tanstack-router-solid',
display: 'TanStack Router ↗',
color: cyan,
customCommand:
'npm create -- tsrouter-app@latest TARGET_DIR --framework Solid --interactive',
},
{
name: 'custom-vike-solid',
display: 'Vike ↗',
... | ```suggestion
customCommand:
'npm exec -- ember-cli@latest new TARGET_DIR --typescript',
``` | },
{
name: 'custom-tanstack-router-solid',
display: 'TanStack Router ↗',
color: cyan,
customCommand:
'npm create -- tsrouter-app@latest TARGET_DIR --framework Solid --interactive',
},
{
name: 'custom-vike-solid',
display: 'Vike ↗',
... | @@ -286,6 +286,25 @@ const FRAMEWORKS: Framework[] = [
},
],
},
+ {
+ name: 'ember',
+ display: 'Ember',
+ color: redBright,
+ variants: [
+ {
+ name: 'ember-app-ts',
+ display: 'TypeScript ↗',
+ color: blueBright,
+ customCommand: 'npm exec -- ember-cli@late... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 113 | 51 | 51 | false | feat(create-vite): add ember | 20,069 | vitejs/vite | 78,557 | TypeScript | sapphi-red | NullVoxPopuli |
esbuildContext = prepareEsbuildScanner(
environment,
entries,
deps,
missing,
)
context = await esbuildContext
if (scanContext.cancelled) return
try {
await context!.rebuild()
return {
// Ensure a fixed order so hashes are stable an... | This is the place the `TypeError: Cannot read properties of undefined (reading 'join')` error was happening.
When `computeEntries` throws an error, `entries = computedEntries` in the `then` after `computeEntries` is not executed and `entries` will be kept as `undefined`.
The old code was not clear which variable li... | esbuildContext = prepareEsbuildScanner(
environment,
entries,
deps,
missing,
)
context = await esbuildContext
if (scanContext.cancelled) return
try {
await context!.rebuild()
return {
// Ensure a fixed order so hashes are stable an... | @@ -153,82 +153,73 @@ export function scanImports(environment: ScanEnvironment): {
.map((entry) => `\n ${colors.dim(entry)}`)
.join('')}`,
)
- return prepareEsbuildScanner(
- environment,
- entries,
- deps,
- missing,
- scanContext,
- )
- })
+ const deps: Recor... | packages/vite/src/node/optimizer/scan.ts | 26 | TypeScript | 1 | refactor | 602 | 51 | 51 | false | fix(optimizer): show error when `computeEntries` failed | 20,079 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
const deps: Record<string, string> = {}
const missing: Record<string, string> = {}
let context: BuildContext | undefined
try {
esbuildContext = prepareEsbuildScanner(
environment,
entries,
deps,
missing,
)
context = await esbuildContext
if (scanCo... | Should this return `undefined` like in line 168? Now that there is a fallback at 222, maybe it is good to normalize it. Or if not, return `{ deps: {}, missing: {} }` everywhere instead of the fallback | const deps: Record<string, string> = {}
const missing: Record<string, string> = {}
let context: BuildContext | undefined
try {
esbuildContext = prepareEsbuildScanner(
environment,
entries,
deps,
missing,
)
context = await esbuildContext
if (scanCo... | @@ -153,82 +153,73 @@ export function scanImports(environment: ScanEnvironment): {
.map((entry) => `\n ${colors.dim(entry)}`)
.join('')}`,
)
- return prepareEsbuildScanner(
- environment,
- entries,
- deps,
- missing,
- scanContext,
- )
- })
+ const deps: Recor... | packages/vite/src/node/optimizer/scan.ts | 26 | TypeScript | 1 | suggestion | 201 | 51 | 51 | false | fix(optimizer): show error when `computeEntries` failed | 20,079 | vitejs/vite | 78,557 | TypeScript | patak-cat | sapphi-red |
import colors from 'picocolors'
import type { Logger } from './logger'
import type { ResolvedConfig, ResolvedEnvironmentOptions } from './config'
import type { Plugin } from './plugin'
const environmentColors = [
colors.blue,
colors.magenta,
colors.green,
colors.gray,
]
export function getDefaultResolvedEnvir... | For environments that aren't in the config, we are using here the config plugins without expanding `applyToEnvironment`. Maybe we should directly disallow the creation of an environment that isn't in the resolved config. | import colors from 'picocolors'
import type { Logger } from './logger'
import type { ResolvedConfig, ResolvedEnvironmentOptions } from './config'
import type { Plugin } from './plugin'
const environmentColors = [
colors.blue,
colors.magenta,
colors.green,
colors.gray,
]
export class PartialEnvironment {
nam... | @@ -20,6 +20,7 @@ export function getDefaultResolvedEnvironmentOptions(
optimizeDeps: config.optimizeDeps,
dev: config.dev,
build: config.build,
+ plugins: config.plugins, | packages/vite/src/node/baseEnvironment.ts | 23 | TypeScript | 0.786 | suggestion | 220 | 48 | 48 | false | feat: resolve environments plugins at config time | 20,120 | vitejs/vite | 78,557 | TypeScript | patak-cat | patak-cat |
workerConfig,
workerUserPlugins,
configEnv,
)
const workerResolved: ResolvedConfig = {
...workerConfig,
...resolved,
isWorker: true,
mainConfig: resolved,
bundleChain,
}
const resolvedWorkerPlugins = (await resolvePlugins(
workerResolved,
work... | Could we have a comment that explains why this need to mutate `workerResolved.plugins`? Also do we also need to mutate `workerResolved.environments`, or is that fine? | workerConfig,
workerUserPlugins,
configEnv,
)
const workerResolved: ResolvedConfig = {
...workerConfig,
...resolved,
isWorker: true,
mainConfig: resolved,
bundleChain,
}
// Plugins resolution needs the resolved config (minus plugins) so we need to mutate... | @@ -1450,10 +1453,20 @@ export async function resolveConfig(
.getSortedPluginHooks('configResolved')
.map((hook) => hook.call(resolvedConfigContext, workerResolved)),
)
+ ;(workerResolved.plugins as Plugin[]) = resolvedWorkerPlugins | packages/vite/src/node/config.ts | 26 | TypeScript | 0.714 | question | 166 | 51 | 51 | false | feat: resolve environments plugins at config time | 20,120 | vitejs/vite | 78,557 | TypeScript | sapphi-red | patak-cat |
return {
define: options.define,
resolve,
keepProcessEnv:
options.keepProcessEnv ??
(isSsrTargetWebworkerEnvironment ? false : consumer === 'server'),
consumer,
optimizeDeps: resolveDepOptimizationOptions(
options.optimizeDeps,
resolve.preserveSymlinks,
forceOptimizeD... | ```suggestion
plugins: undefined!, // to be resolved later
``` | return {
define: options.define,
resolve,
keepProcessEnv:
options.keepProcessEnv ??
(isSsrTargetWebworkerEnvironment ? false : consumer === 'server'),
consumer,
optimizeDeps: resolveDepOptimizationOptions(
options.optimizeDeps,
resolve.preserveSymlinks,
forceOptimizeD... | @@ -850,6 +852,7 @@ function resolveEnvironmentOptions(
logger,
consumer,
),
+ plugins: undefined as any, // to be resolved later | packages/vite/src/node/config.ts | 26 | TypeScript | 1 | suggestion | 68 | 51 | 51 | false | feat: resolve environments plugins at config time | 20,120 | vitejs/vite | 78,557 | TypeScript | sapphi-red | patak-cat |
...workerNormalPlugins,
...workerPostPlugins,
]
workerConfig = await runConfigHook(
workerConfig,
workerUserPlugins,
configEnv,
)
const workerResolved: ResolvedConfig = {
...workerConfig,
...resolved,
isWorker: true,
mainConfig: resolved,
bund... | ```suggestion
// During Build the client environment is used to bundle the worker
``` | ...workerNormalPlugins,
...workerPostPlugins,
]
workerConfig = await runConfigHook(
workerConfig,
workerUserPlugins,
configEnv,
)
const workerResolved: ResolvedConfig = {
...workerConfig,
...resolved,
isWorker: true,
mainConfig: resolved,
bund... | @@ -1437,24 +1440,38 @@ export async function resolveConfig(
mainConfig: resolved,
bundleChain,
}
- const resolvedWorkerPlugins = (await resolvePlugins(
+
+ // Plugins resolution needs the resolved config (minus plugins) so we need to mutate here
+ ;(workerResolved.plugins as Plugin[]) = awa... | packages/vite/src/node/config.ts | 26 | TypeScript | 0.857 | suggestion | 91 | 51 | 51 | false | feat: resolve environments plugins at config time | 20,120 | vitejs/vite | 78,557 | TypeScript | sapphi-red | patak-cat |
}
// check if we can return 304 early for CSS requests. These aren't handled
// by the cachedTransformMiddleware due to the browser possibly mixing the
// etags of direct and imported CSS
const ifNoneMatch = req.headers['if-none-match']
if (
ifNon... | The test will pass without this added check because of the fallback logic added to `deniedServingAccessForTransform`, but if we know the id is a virtual module, then we can skip the check directly. | url = injectQuery(url, 'direct')
}
// check if we can return 304 early for CSS requests. These aren't handled
// by the cachedTransformMiddleware due to the browser possibly mixing the
// etags of direct and imported CSS
const ifNoneMatch = req.headers['if-... | @@ -264,7 +265,10 @@ export function transformMiddleware(
const result = await transformRequest(environment, url, {
html: req.headers.accept?.includes('text/html'),
allowId(id) {
- return !deniedServingAccessForTransform(id, server, res, next)
+ return (
+ ... | packages/vite/src/node/server/middlewares/transform.ts | 26 | TypeScript | 0.714 | suggestion | 197 | 51 | 51 | false | fix: virtual svg module | 20,144 | vitejs/vite | 78,557 | TypeScript | patak-cat | patak-cat |
}
} else {
const originalUrl = url.replace(/\.map($|\?)/, '$1')
const map = (
await environment.moduleGraph.getModuleByUrl(originalUrl)
)?.transformResult?.map
if (map) {
return send(req, res, JSON.stringify(map), 'json', {
... | At this point, we have replaced the `NULL_BYTE_PLACEHOLDER` but didn't yet unwrapped the id. We could actually remove the whole check now that we are doing it before load but leaving that to be done in a separate PR. | }
} else {
const originalUrl = url.replace(/\.map($|\?)/, '$1')
const map = (
await environment.moduleGraph.getModuleByUrl(originalUrl)
)?.transformResult?.map
if (map) {
return send(req, res, JSON.stringify(map), 'json', {
... | @@ -213,6 +213,7 @@ export function transformMiddleware(
'',
)
if (
+ !url.startsWith('/@id/\0') && | packages/vite/src/node/server/middlewares/transform.ts | 26 | TypeScript | 1 | suggestion | 216 | 51 | 51 | false | fix: virtual svg module | 20,144 | vitejs/vite | 78,557 | TypeScript | patak-cat | patak-cat |
export const parent = import.meta.glob('../../playground/src/*.ts', {
query: '?url',
import: 'default',
})
export const rootMixedRelative = import.meta.glob(
['/*.ts', '../fixture-b/*.ts'],
{ query: '?url', import: 'default' },
)
export const cleverCwd1 = import.meta.glob(
'./node_modules/framework/**/*.pa... | ```suggestion
})
export const customBaseParent = import.meta.glob('/fixture-b/**/*.ts', {
base: '/fixture-a',
})
```
I think it'd be nice to have a test case that generates an output that includes `../`.
|
export const parent = import.meta.glob('../../playground/src/*.ts', {
query: '?url',
import: 'default',
})
export const rootMixedRelative = import.meta.glob(
['/*.ts', '../fixture-b/*.ts'],
{ query: '?url', import: 'default' },
)
export const cleverCwd1 = import.meta.glob(
'./node_modules/framework/**/*.pa... | @@ -110,3 +110,9 @@ export const cleverCwd2 = import.meta.glob([
'../fixture-b/*.ts',
'!**/index.ts',
])
+
+export const customBase = import.meta.glob('./**/*.ts', { base: './' })
+
+export const customRootBase = import.meta.glob('./**/*.ts', {
+ base: '/fixture-b',
+}) | packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts | 26 | TypeScript | 1 | suggestion | 215 | 27 | 31 | false | feat: add base option to import.meta.glob | 20,163 | vitejs/vite | 78,557 | TypeScript | sapphi-red | patak-cat |
export type ImportMetaResolver = (specifier: string, importer: string) => string
const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/'
const customizationHooksModule = /* js */ `
export async function resolve(specifier, context, nextResolve) {
if (specifier.startsWith(${JSON.stringify(cust... | I'm a bit confused about `shorCircuit`. What does it mean to inject `shortCircuit: true` when `nextResolve` is already called?
If `shortCircuit: true` is redundant, then we could eliminate async/await entirely by returning `nextResolve` directly and that seems recommended based on the doc https://nodejs.org/docs/v22... | export type ImportMetaResolver = (specifier: string, importer: string) => string
const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/'
const customizationHooksModule = /* js */ `
export async function resolve(specifier, context, nextResolve) {
if (specifier.startsWith(${JSON.stringify(cust... | @@ -0,0 +1,51 @@
+export type ImportMetaResolver = (specifier: string, importer: string) => string
+
+const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/'
+const customizationHooksModule = /* js */ `
+
+export async function resolve(specifier, context, nextResolve) {
+ if (specifier.startsWi... | packages/vite/src/module-runner/importMetaResolver.ts | 19 | TypeScript | 1 | performance | 641 | 44 | 44 | false | feat(ssr): support `import.meta.resolve` in module runner | 20,260 | vitejs/vite | 78,557 | TypeScript | hi-ogawa | sapphi-red |
export async function resolve(specifier, context, nextResolve) {
if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
const [parsedSpecifier, parsedImporter] = JSON.parse(data)
specifier = parsedSpeci... | It looks like this code fails to throw when running `vite/module-runner` on Vite dev browser like https://github.com/hi-ogawa/vite-environment-examples/blob/c54e8e3b1ba0195677bb838d6f12be6510dc361d/examples/web-worker/src/lib/runner.ts#L1, so it fails at `module.register` where `module === undefined`
```
module-run... |
export async function resolve(specifier, context, nextResolve) {
if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
const [parsedSpecifier, parsedImporter] = JSON.parse(data)
specifier = parsedSpeci... | @@ -0,0 +1,47 @@
+export type ImportMetaResolver = (specifier: string, importer: string) => string
+
+const customizationHookNamespace = 'vite-module-runner:import-meta-resolve/v1/'
+const customizationHooksModule = /* js */ `
+
+export async function resolve(specifier, context, nextResolve) {
+ if (specifier.startsWi... | packages/vite/src/module-runner/importMetaResolver.ts | 26 | TypeScript | 1 | bug | 1,477 | 44 | 45 | false | feat(ssr): support `import.meta.resolve` in module runner | 20,260 | vitejs/vite | 78,557 | TypeScript | hi-ogawa | sapphi-red |
],
},
{
text: 'Past',
items: [],
},
],
},
outline: {
level: [2, 3],
},
},
transformPageData(pageData) {
const canonicalUrl = `${ogUrl}/${pageData.relativePath}`
.replace(/\/index\.md$/, '/')
.replace(/\.md$/, '')
page... | @antfu @brc-dd Is this change expected to be required?
| ],
},
{
text: 'Past',
items: [],
},
],
},
outline: {
level: [2, 3],
},
},
transformPageData(pageData) {
const canonicalUrl = `${ogUrl}/${pageData.relativePath}`
.replace(/\/index\.md$/, '/')
.replace(/\.md$/, '')
page... | @@ -459,6 +459,7 @@ export default defineConfig({
return pageData
},
markdown: {
+ languages: ['ts', 'json'], | docs/.vitepress/config.ts | 26 | TypeScript | 0.357 | question | 58 | 51 | 51 | false | docs(deps): update to vitepress v2 alpha | 20,275 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
const thisModule = moduleGraph.getModuleById(id)
// Handle CSS @import dependency HMR and other added modules via this.addWatchFile.
// JS-related HMR is handled in the import-analysis plugin.
if (thisModule) {
// CSS modules cannot self-accept since it exports values
... | Since this line is removed, #19563 and #19786 will be fixed. | // CSS modules cannot self-accept since it exports values
const isSelfAccepting =
!cssModulesCache.get(config)?.get(id) &&
!inlineRE.test(id) &&
!htmlProxyRE.test(id)
// attached by pluginContainer.addWatchFile
const pluginImports = (this as un... | @@ -1101,20 +1100,7 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
// main import to hot update
const depModules = new Set<string | EnvironmentModuleNode>()
for (const file of pluginImports) {
- if (isCSSRequest(file)) {
- depMod... | packages/vite/src/node/plugins/css.ts | 26 | TypeScript | 0.357 | suggestion | 60 | 51 | 51 | false | fix(hmr): register css deps as `type: asset` | 20,391 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
continue
}
updates.push(
...boundaries.map(
({ boundary, acceptedVia, isWithinCircularImport }) => ({
type: `${boundary.type}-update` as const,
timestamp,
path: normalizeHmrUrl(boundary.url),
acceptedPath: normalizeHmrUrl(acceptedVia.url),
e... | This part is added for cases that was covered by
https://github.com/vitejs/vite/pull/20391/files#diff-863416a9b0769ffb1d7e36b6840ce6d0d84170a80a5c4ce4539464b0ebcbd137L801-L813
| continue
}
updates.push(
...boundaries.map(
({ boundary, acceptedVia, isWithinCircularImport }) => ({
type: `${boundary.type}-update` as const,
timestamp,
path: normalizeHmrUrl(boundary.url),
acceptedPath: normalizeHmrUrl(acceptedVia.url),
e... | @@ -693,7 +688,11 @@ export function updateModules(
)
}
- if (needFullReload) {
+ // html file cannot be hot updated
+ const isClientHtmlChange =
+ file.endsWith('.html') && environment.name === 'client'
+
+ if (needFullReload || isClientHtmlChange) { | packages/vite/src/node/server/hmr.ts | 26 | TypeScript | 0.286 | suggestion | 176 | 51 | 51 | false | fix(hmr): register css deps as `type: asset` | 20,391 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
// been loaded in the browser and we should stop propagation.
if (node.id && node.isSelfAccepting === undefined) {
debugHmr?.(
`[propagate update] stop propagation because not analyzed: ${colors.dim(
node.id,
)}`,
)
return false
}
if (node.isSelfAccepting) {
// isSelfAccepti... | This part is no longer needed. `type=asset` module is a separate module from `type=js`, so `updateModules` is called separately for CSS files. | if (traversedModules.has(node)) {
return false
}
traversedModules.add(node)
// #7561
// if the imports of `node` have not been analyzed, then `node` has not
// been loaded in the browser and we should stop propagation.
if (node.id && node.isSelfAccepting === undefined) {
debugHmr?.(
`[propa... | @@ -761,25 +764,13 @@ function propagateUpdate(
}
if (node.isSelfAccepting) {
+ // isSelfAccepting is only true for js and css
+ const boundary = node as EnvironmentModuleNode & { type: 'js' | 'css' }
boundaries.push({
- boundary: node,
- acceptedVia: node,
+ boundary,
+ acceptedV... | packages/vite/src/node/server/hmr.ts | 26 | TypeScript | 0.786 | suggestion | 142 | 51 | 51 | false | fix(hmr): register css deps as `type: asset` | 20,391 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
import { expect, test } from 'vitest'
import { editFile, getColor, isServe, page, untilBrowserLogAfter } from '~utils'
test('should render', async () => {
expect(await page.textContent('#pagetitle')).toBe('Page title')
})
test.runIf(isServe)('HMR works with HTML', async () => {
await expect.poll(() => getColor('.... | This is still a full reload and that's expected, right? Is it just a wrong test name or is there any changed compared to the previous behavior? | import { expect, test } from 'vitest'
import { editFile, getColor, isServe, page, untilBrowserLogAfter } from '~utils'
test('should render', async () => {
expect(await page.textContent('#pagetitle')).toBe('Page title')
})
test.runIf(isServe)(
'full reload happens when the HTML is changed',
async () => {
awa... | @@ -5,6 +5,15 @@ test('should render', async () => {
expect(await page.textContent('#pagetitle')).toBe('Page title')
})
+test.runIf(isServe)('HMR works with HTML', async () => {
+ await expect.poll(() => getColor('.html')).toBe('oklch(0.623 0.214 259.815)')
+
+ editFile('index.html', (code) =>
+ code.replace... | playground/tailwind/__test__/tailwind.spec.ts | 15 | TypeScript | 0.5 | bug | 143 | 40 | 40 | false | fix(hmr): register css deps as `type: asset` | 20,391 | vitejs/vite | 78,557 | TypeScript | hi-ogawa | sapphi-red |
transform: {
async handler(_, id) {
if (
!isCSSRequest(id) ||
commonjsProxyRE.test(id) ||
SPECIAL_QUERY_RE.test(id)
) {
return
}
const { moduleGraph } = this.environment as DevEnvironment
const thisModule = moduleGraph.getModule... | This is great! I just explored the case in https://github.com/vitejs/vite-plugin-react/pull/616, so let me share what I found. Client hot update looks like this when changing server component:
_before_
```
🔷 [hotUpdate] client [
{
environment: 'client',
url: '/src/routes/root.tsx',
id: '/home/... | id: {
include: CSS_LANGS_RE,
exclude: [commonjsProxyRE, SPECIAL_QUERY_RE],
},
},
async handler(_, id) {
const { moduleGraph } = this.environment as DevEnvironment
const thisModule = moduleGraph.getModuleById(id)
// Handle CSS @import dependency HM... | @@ -1101,20 +1100,7 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
// main import to hot update
const depModules = new Set<string | EnvironmentModuleNode>()
for (const file of pluginImports) {
- if (isCSSRequest(file)) {
- depMod... | packages/vite/src/node/plugins/css.ts | 26 | TypeScript | 1 | style | 1,431 | 51 | 51 | false | fix(hmr): register css deps as `type: asset` | 20,391 | vitejs/vite | 78,557 | TypeScript | hi-ogawa | sapphi-red |
normalizeHmrUrl(acceptedVia.url) === firstInvalidatedBy,
)
) {
needFullReload = 'circular import invalidate'
continue
}
updates.push(
...boundaries.map(
({ boundary, acceptedVia, isWithinCircularImport }) => ({
type: `${boundary.type}-update` as const,
... | This comment explains what the code does rather than why. According to the coding guidelines, comments should explain why the code does what it does, not what it does. Consider explaining why HTML files cannot be hot updated (e.g., 'HTML files require full page reload because they affect the entire document structure')... | normalizeHmrUrl(acceptedVia.url) === firstInvalidatedBy,
)
) {
needFullReload = 'circular import invalidate'
continue
}
updates.push(
...boundaries.map(
({ boundary, acceptedVia, isWithinCircularImport }) => ({
type: `${boundary.type}-update` as const,
... | @@ -693,7 +688,16 @@ export function updateModules(
)
}
- if (needFullReload) {
+ // html file cannot be hot updated | packages/vite/src/node/server/hmr.ts | 26 | TypeScript | 0.643 | suggestion | 321 | 51 | 51 | false | fix(hmr): register css deps as `type: asset` | 20,391 | vitejs/vite | 78,557 | TypeScript | Copilot | sapphi-red |
target?: SSRTarget
/**
* Control over which dependencies are optimized during SSR and esbuild options
* During build:
* no external CJS dependencies are optimized by default
* During dev:
* explicit no external CJS dependencies are optimized by default
* @experimental
*/
optimizeDeps?: S... | I think `module-sync` should be added here? | target?: SSRTarget
/**
* Control over which dependencies are optimized during SSR and esbuild options
* During build:
* no external CJS dependencies are optimized by default
* During dev:
* explicit no external CJS dependencies are optimized by default
* @experimental
*/
optimizeDeps?: S... | @@ -40,7 +40,7 @@ export interface SSROptions {
/**
* Conditions that are used during ssr import (including `ssrLoadModule`) of externalized dependencies.
*
- * @default []
+ * @default ['node'] | packages/vite/src/node/ssr/index.ts | 26 | TypeScript | 0.5 | question | 43 | 51 | 51 | false | feat(ssr): resolve externalized packages with `resolve.externalConditions` and add `module-sync` to default external condition | 20,409 | vitejs/vite | 78,557 | TypeScript | benmccann | sapphi-red |
'~utils': resolve(__dirname, './playground/test-utils'),
},
},
test: {
include: ['./playground/**/*.spec.[tj]s'],
setupFiles: ['./playground/vitestSetup.ts'],
globalSetup: ['./playground/vitestGlobalSetup.ts'],
testTimeout: timeout,
hookTimeout: timeout,
reporters: 'dot',
deps:... | @hi-ogawa It seems Vitest uses `resolve.conditions` for both externalized files and no-externalized files. Is it possible to configure Vitest to only use `module-sync` for externalized files? (since `module-sync` should not be used for no-externalized files) | '~utils': resolve(__dirname, './playground/test-utils'),
},
},
test: {
include: ['./playground/**/*.spec.[tj]s'],
setupFiles: ['./playground/vitestSetup.ts'],
globalSetup: ['./playground/vitestGlobalSetup.ts'],
testTimeout: timeout,
hookTimeout: timeout,
reporters: 'dot',
deps:... | @@ -26,6 +26,12 @@ export default defineConfig({
},
},
},
+ ssr: {
+ resolve: {
+ // FIXME: this is a bug in Vitest, resolving externalized modules should use externalConditions
+ conditions: ['node', 'module-sync'],
+ },
+ }, | vitest.config.e2e.ts | 26 | TypeScript | 0.786 | suggestion | 258 | 32 | 26 | false | feat(ssr): resolve externalized packages with `resolve.externalConditions` and add `module-sync` to default external condition | 20,409 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
// no `exports` key, should resolve to entries/dir/index.js
import dirEntry from '@vitejs/test-entries/dir'
// no `exports` key, should resolve to entries/file.js
import fileEntry from '@vitejs/test-entries/file'
// has `exports` key, should resolve to pkg-exports/entry
import pkgExportsEntry from '@vitejs/test-resolve... | I commented out this test case as it wasn't working.
The output contains `@vitejs/test-deep-import/bar` as-is, but to make that work in Node, it needs to be rewritten to `@vitejs/test-deep-import/utils/bar.js` as Node does not read `package.json` for directory specifiers in ESM.
| // no `exports` key, should resolve to entries/dir/index.js
import dirEntry from '@vitejs/test-entries/dir'
// no `exports` key, should resolve to entries/file.js
import fileEntry from '@vitejs/test-entries/file'
// has `exports` key, should resolve to pkg-exports/entry
import pkgExportsEntry from '@vitejs/test-resolve... | @@ -5,14 +5,16 @@ import fileEntry from '@vitejs/test-entries/file'
// has `exports` key, should resolve to pkg-exports/entry
import pkgExportsEntry from '@vitejs/test-resolve-pkg-exports/entry'
import deepFoo from '@vitejs/test-deep-import/foo'
-import deepBar from '@vitejs/test-deep-import/bar'
+// import deepBar ... | playground/ssr-resolve/main.js | 8 | JavaScript | 0.571 | suggestion | 280 | 19 | 21 | false | feat(ssr): resolve externalized packages with `resolve.externalConditions` and add `module-sync` to default external condition | 20,409 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
import path from 'node:path'
import fs from 'node:fs'
import { defineConfig } from 'tsdown'
import { parseTarGzip } from 'nanotar'
// for rolldown-vite v7.0.9, check https://pkg.pr.new/~/vitejs/rolldown-vite
const PLUGIN_LEGACY_FOR_ROLLDOWN_VITE =
'https://pkg.pr.new/vitejs/rolldown-vite/@vitejs/plugin-legacy@5c52bb... | How about adding this to devDependencies and copy it from `node_modules`? That seems more robust than fetching from pkg.pr.new on every build. | import path from 'node:path'
import fs from 'node:fs'
import { defineConfig } from 'tsdown'
import { fdir } from 'fdir'
const pluginLegacyForRolldownVitePackagePath = path.resolve(
import.meta.dirname,
'./node_modules/@vitejs/plugin-legacy-for-rolldown-vite',
)
export default defineConfig({
entry: ['src/index.t... | @@ -1,8 +1,71 @@
+import path from 'node:path'
+import fs from 'node:fs'
import { defineConfig } from 'tsdown'
+import { parseTarGzip } from 'nanotar'
+
+// for rolldown-vite v7.0.9, check https://pkg.pr.new/~/vitejs/rolldown-vite
+const PLUGIN_LEGACY_FOR_ROLLDOWN_VITE =
+ 'https://pkg.pr.new/vitejs/rolldown-vite/@vi... | packages/plugin-legacy/tsdown.config.ts | 8 | TypeScript | 0.5 | question | 142 | 33 | 33 | false | feat(legacy): add rolldown-vite support | 20,417 | vitejs/vite | 78,557 | TypeScript | hi-ogawa | sapphi-red |
inMap: SourceMap | { mappings: '' } | null,
url: string,
originalCode = code,
) {
return ssrTransform(code, inMap, url, originalCode, {
json: {
stringify:
config.json.stringify === true && config.json.namedExports !== true,
},
})
},
transfo... | Similar to https://github.com/vitejs/vite/pull/20436#discussion_r2224250645, I think we need a new deprecation name like `'removeServerWarmupRequest'` | inMap: SourceMap | { mappings: '' } | null,
url: string,
originalCode = code,
) {
return ssrTransform(code, inMap, url, originalCode, {
json: {
stringify:
config.json.stringify === true && config.json.namedExports !== true,
},
})
},
transfo... | @@ -601,6 +601,11 @@ export async function _createServer(
return environment.transformRequest(url)
},
warmupRequest(url, options) {
+ warnFutureDeprecation(
+ config,
+ 'removeServerTransformRequest',
+ 'server.warmupRequest() is deprecated. Use environment.warmupRequest() ins... | packages/vite/src/node/server/index.ts | 26 | TypeScript | 0.714 | suggestion | 150 | 51 | 51 | false | feat: add `server.warmupRequest` to future deprecation | 20,431 | vitejs/vite | 78,557 | TypeScript | bluwy | sapphi-red |
export function optimizedDepsPlugin(): Plugin {
return {
name: 'vite:optimized-deps',
applyToEnvironment(environment) {
return !isDepOptimizationDisabled(environment.config.optimizeDeps)
},
resolveId(id) {
const environment = this.environment as DevEnvironment
if (environment.depsO... | `versionMatch` always returned `undefined` because `cleanUrl` strips the query.
This was a bug introduced in https://github.com/vitejs/vite/pull/17789/files#diff-0648e3b1da8ac697354cfca37ada638d3a353be4b3312211c6b131597f6ca101.
| export function optimizedDepsPlugin(): Plugin {
return {
name: 'vite:optimized-deps',
applyToEnvironment(environment) {
return !isDepOptimizationDisabled(environment.config.optimizeDeps)
},
resolveId(id) {
const environment = this.environment as DevEnvironment
if (environment.depsO... | @@ -42,7 +42,7 @@ export function optimizedDepsPlugin(): Plugin {
if (depsOptimizer?.isOptimizedDepFile(id)) {
const metadata = depsOptimizer.metadata
const file = cleanUrl(id)
- const versionMatch = DEP_VERSION_RE.exec(file)
+ const versionMatch = DEP_VERSION_RE.exec(id) | packages/vite/src/node/plugins/optimizedDeps.ts | 26 | TypeScript | 1 | bug | 228 | 51 | 51 | false | fix(optimizer): incorrect incompatible error | 20,439 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
try {
// This is an entry point, it may still not be bundled
await info.processing
} catch {
// If the refresh has not happened after timeout, Vite considers
// something unexpected has happened. In this case, Vite
// returns an empty respo... | This old condition did not match requests for stale optimized files.
The requests that was sent between "the optimizer starts the bundle" and "the optimizer finishes the bundle" is handled above after `await info.processing`, but the requests that was sent after "the optimizer finishes the bundle" doesn't match the con... | try {
// This is an entry point, it may still not be bundled
await info.processing
} catch {
// If the refresh has not happened after timeout, Vite considers
// something unexpected has happened. In this case, Vite
// returns an empty respo... | @@ -77,9 +77,8 @@ export function optimizedDepsPlugin(): Plugin {
try {
return await fsp.readFile(file, 'utf-8')
} catch {
- const newMetadata = depsOptimizer.metadata
- if (optimizedDepInfoFromFile(newMetadata, file)) {
- // Outdated non-entry points (CHUNK), l... | packages/vite/src/node/plugins/optimizedDeps.ts | 26 | TypeScript | 1 | performance | 470 | 51 | 51 | false | fix(optimizer): incorrect incompatible error | 20,439 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
if (isExternalUrl(resolved.id)) {
return [resolved.id, resolved.id]
}
const isRelative = url[0] === '.'
const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer)
url = normalizeResolvedIdToUrl(environment, url, resolved)
// make the URL browser... | This was causing `moduleGraph._ensureEntryFromUrl` below to be called with
```js
await moduleGraph._ensureEntryFromUrl(
unwrapId(url), // url with `?v=` query
canSkipImportAnalysis(url) || forceSkipImportAnalysis,
resolved, // resolved result without `?v=` query
)
```
and caused the `moduleGraph.urlToModu... | if (isExternalUrl(resolved.id)) {
return [resolved.id, resolved.id]
}
url = normalizeResolvedIdToUrl(environment, url, resolved)
try {
// delay setting `isSelfAccepting` until the file is actually used (#7870)
// We use an internal function to avoid resolv... | @@ -373,32 +373,8 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
return [resolved.id, resolved.id]
}
- const isRelative = url[0] === '.'
- const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer)
-
url = normalizeResolvedIdToUrl(env... | packages/vite/src/node/plugins/importAnalysis.ts | 26 | TypeScript | 1 | bug | 1,168 | 51 | 51 | false | fix(optimizer): incorrect incompatible error | 20,439 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
export function optimizedDepsPlugin(): Plugin {
return {
name: 'vite:optimized-deps',
applyToEnvironment(environment) {
return !isDepOptimizationDisabled(environment.config.optimizeDeps)
},
resolveId(id) {
const environment = this.environment as DevEnvironment
if (environment.depsO... | The change from `file` to `id` for version matching is correct. Using `cleanUrl(id)` in `file` removes query parameters including the version hash, which would cause `versionMatch` to always be `undefined` and lead to incorrect error handling. | export function optimizedDepsPlugin(): Plugin {
return {
name: 'vite:optimized-deps',
applyToEnvironment(environment) {
return !isDepOptimizationDisabled(environment.config.optimizeDeps)
},
resolveId(id) {
const environment = this.environment as DevEnvironment
if (environment.depsO... | @@ -42,7 +42,7 @@ export function optimizedDepsPlugin(): Plugin {
if (depsOptimizer?.isOptimizedDepFile(id)) {
const metadata = depsOptimizer.metadata
const file = cleanUrl(id)
- const versionMatch = DEP_VERSION_RE.exec(file)
+ const versionMatch = DEP_VERSION_RE.exec(id) | packages/vite/src/node/plugins/optimizedDeps.ts | 26 | TypeScript | 1 | bug | 243 | 51 | 51 | false | fix(optimizer): incorrect incompatible error | 20,439 | vitejs/vite | 78,557 | TypeScript | Copilot | sapphi-red |
// This is an entry point, it may still not be bundled
await info.processing
} catch {
// If the refresh has not happened after timeout, Vite considers
// something unexpected has happened. In this case, Vite
// returns an empty response that will er... | The simplified logic using `browserHash` is cleaner than the previous approach that checked metadata. This directly correlates the presence of a browser hash with outdated files, making the code more readable and maintainable.
```suggestion
// Check current metadata for browserHash mismatch before throwing ... | // This is an entry point, it may still not be bundled
await info.processing
} catch {
// If the refresh has not happened after timeout, Vite considers
// something unexpected has happened. In this case, Vite
// returns an empty response that will er... | @@ -77,9 +77,8 @@ export function optimizedDepsPlugin(): Plugin {
try {
return await fsp.readFile(file, 'utf-8')
} catch {
- const newMetadata = depsOptimizer.metadata
- if (optimizedDepInfoFromFile(newMetadata, file)) {
- // Outdated non-entry points (CHUNK), l... | packages/vite/src/node/plugins/optimizedDeps.ts | 26 | TypeScript | 1 | performance | 635 | 51 | 51 | false | fix(optimizer): incorrect incompatible error | 20,439 | vitejs/vite | 78,557 | TypeScript | Copilot | sapphi-red |
server.environments.ssr.moduleGraph.invalidateAll()
server.environments.ssr.hot.send({ type: 'full-reload' })
await vi.waitFor(() => {
const mod = runner.evaluatedModules.getModuleById('\0virtual:test')
expect(mod?.exports.default).toBe('reloaded')
})
})
it("the external module's ID and... | ```suggestion
expect(meta.externalize).toMatch(/^file:\/\/\/\w:\//) // file:///C:/
expect(moduleNode.id).toMatch(/^\w:\//) // C:/
expect(moduleNode.file).toMatch(/^\w:\//) // C:/
} else {
expect(meta.externalize).toMatch(/^file:\/\/\//) // file:///
expect(moduleNode.id).toMatch(/^\//) ... | server.environments.ssr.moduleGraph.invalidateAll()
server.environments.ssr.hot.send({ type: 'full-reload' })
await vi.waitFor(() => {
const mod = runner.evaluatedModules.getModuleById('\0virtual:test')
expect(mod?.exports.default).toBe('reloaded')
})
})
it("the external module's ID and... | @@ -489,4 +494,25 @@ describe('virtual module hmr', async () => {
expect(mod?.exports.default).toBe('reloaded')
})
})
+
+ it("the external module's ID and file are resolved correctly", async ({
+ server,
+ runner,
+ }) => {
+ await runner.import(
+ posix.join(server.config.root, 'fixtures... | packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts | 26 | TypeScript | 1 | suggestion | 424 | 30 | 29 | false | fix(module-runner): normalize file:// on windows | 20,449 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sheremet-va |
const maybeJSX = !isVue && isJSRequest(importer)
const probablyBinary = source.includes(
'\ufffd' /* unicode replacement character */,
)
const msg = isVue
? `Install @vitejs/plugin-vue to handle .vue files.`
: maybeJSX
? isJsx
? `If you use tsconfig.json, make sure to not set jsx to p... | This ignore comment is not needed as Rolldown does not keep this function in a single line anyway. | const maybeJSX = !isVue && isJSRequest(importer)
const probablyBinary = source.includes(
'\ufffd' /* unicode replacement character */,
)
const msg = isVue
? `Install @vitejs/plugin-vue to handle .vue files.`
: maybeJSX
? isJsx
? `If you use tsconfig.json, make sure to not set jsx to p... | @@ -897,8 +897,18 @@ export function createParseErrorInfo(
showCodeFrame: !probablyBinary,
}
}
-// prettier-ignore | packages/vite/src/node/plugins/importAnalysis.ts | 26 | TypeScript | 0.143 | suggestion | 98 | 51 | 51 | false | fix(dev): incorrect sourcemap when optimized CJS is imported | 20,458 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { transformCjsImport } from '../../plugins/importAnalysis'
describe('transformCjsImport', () => {
const url = './node_modules/.vite/deps/react.js'
const rawUrl = 'react'
const config: any = {
command: 'serve',
logger: {
warn: vi... | The main change in this file is this part. | import { beforeEach, describe, expect, test, vi } from 'vitest'
import { transformCjsImport } from '../../plugins/importAnalysis'
describe('runTransform', () => {
const config: any = {
command: 'serve',
logger: {
warn: vi.fn(),
},
}
function runTransformCjsImport(importExp: string) {
const... | @@ -1,29 +1,39 @@
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { transformCjsImport } from '../../plugins/importAnalysis'
-describe('transformCjsImport', () => {
- const url = './node_modules/.vite/deps/react.js'
- const rawUrl = 'react'
+describe('runTransform', () => {
const config:... | packages/vite/src/node/__tests__/plugins/import.spec.ts | 25 | TypeScript | 0.286 | suggestion | 42 | 50 | 50 | false | fix(dev): incorrect sourcemap when optimized CJS is imported | 20,458 | vitejs/vite | 78,557 | TypeScript | sapphi-red | sapphi-red |
const workerType = isBuild
? format === 'es'
? 'module'
: 'classic'
: 'module'
const workerTypeOption = `{
${workerType === 'module' ? `type: "module",` : ''}
name: options?.name
}`
let urlCode: string
if (isBuild) ... | add a comment that we shouldn't call `revokeObjectURL` just after `new Worker` | const workerType = isBuild
? format === 'es'
? 'module'
: 'classic'
: 'module'
const workerTypeOption = `{
${workerType === 'module' ? `type: "module",` : ''}
name: options?.name
}`
let urlCode: string
if (isBuild) ... | @@ -293,7 +293,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
? `${jsContent}
const blob = typeof self !== "undefined" && self.Blob && new Blob([${
workerType === 'classic'
- ? ''
+ ? `'(self.URL || self.webkitURL).revoke... | packages/vite/src/node/plugins/worker.ts | 26 | TypeScript | 0.571 | suggestion | 78 | 51 | 51 | false | fix(worker): resolve WebKit compat with inline workers by deferring blob URL revocation | 20,460 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const { format } = config.worker
const workerConstructor =
workerMatch[1] === 'sharedworker' ? 'SharedWorker' : 'Worker'
const workerType = isBuild
? format === 'es'
? 'module'
: 'classic'
: 'module'
const workerTypeOption = `{
... | ```suggestion
const blob = typeof self !== "undefined" && self.Blob && new Blob([${
// NOTE: Revoke the objURL after creating the worker, otherwise it breaks WebKit-based browsers
``` | const { format } = config.worker
const workerConstructor =
workerMatch[1] === 'sharedworker' ? 'SharedWorker' : 'Worker'
const workerType = isBuild
? format === 'es'
? 'module'
: 'classic'
: 'module'
const workerTypeOption = `{
... | @@ -293,7 +293,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
? `${jsContent}
const blob = typeof self !== "undefined" && self.Blob && new Blob([${ | packages/vite/src/node/plugins/worker.ts | 26 | TypeScript | 1 | suggestion | 209 | 51 | 51 | false | fix(worker): resolve WebKit compat with inline workers by deferring blob URL revocation | 20,460 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
`"unknown" isn't a valid template. Please choose from below:`,
)
})
test('asks to overwrite non-empty target directory', () => {
createNonEmptyDir()
const { stdout } = run([projectName], { cwd: __dirname })
expect(stdout).toContain(`Target directory "${projectName}" is not empty.`)
})
test('asks to overwr... | Don't add `-i false` to existing tests. | '--interactive',
'--template',
'unknown',
])
expect(stdout).toContain(
`"unknown" isn't a valid template. Please choose from below:`,
)
})
test('asks to overwrite non-empty target directory', () => {
createNonEmptyDir()
const { stdout } = run([projectName, '--interactive'], { cwd: __dirname }... | @@ -103,7 +103,7 @@ test('asks to overwrite non-empty current directory', () => {
})
test('successfully scaffolds a project based on vue starter template', () => {
- const { stdout } = run([projectName, '--template', 'vue'], {
+ const { stdout } = run([projectName, '--template', 'vue', '-i', 'false'], { | packages/create-vite/__tests__/cli.spec.ts | 26 | TypeScript | 0.286 | suggestion | 39 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
createNonEmptyDir()
const { stdout } = run(['.', '--overwrite', 'ignore'], { cwd: genPath })
expect(stdout).not.toContain(`Current directory is not empty.`)
})
test('return help usage how to use create-vite', () => {
const { stdout } = run(['--help'], { cwd: __dirname })
const message = 'Usage: create-vite [... | ```suggestion
test('shows help', () => {
const { stdout } = run(['--help'], { cwd: __dirname })
expect(stdout).toMatchInlineSnapshot()
})
``` | ],
{
cwd: __dirname,
},
)
const generatedFiles = fs.readdirSync(genPathWithSubfolder).sort()
// Assertions
expect(stdout).toContain(`Scaffolding project in ${genPathWithSubfolder}`)
expect(templateFilesReact).toEqual(generatedFiles)
})
test('successfully scaffolds a project with subfolder ... | @@ -152,3 +155,34 @@ test('return help usage how to use create-vite with -h alias', () => {
const message = 'Usage: create-vite [OPTION]... [DIRECTORY]'
expect(stdout).toContain(message)
})
+
+test('shows immediate and agent options in help', () => {
+ const { stdout } = run(['--help'], { cwd: __dirname })
+ e... | packages/create-vite/__tests__/cli.spec.ts | 26 | TypeScript | 1 | suggestion | 145 | 48 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
template = variant
}
// 5. Ask about immediate install and package manager
let immediate = argImmediate
let agent = argAgent
if (immediate === undefined) {
const immediateResult = await prompts.confirm({
message: 'Install and start now?',
initialValue: false,
})
if (prompts.isCa... | Select the package manager got from `pkgManager` variable by default. | const framework = await prompts.select({
message: hasInvalidArgTemplate
? `"${argTemplate}" isn't a valid template. Please choose from below: `
: 'Select a framework:',
options: FRAMEWORKS.map((framework) => {
const frameworkColor = framework.color
return {
... | @@ -470,6 +506,32 @@ async function init() {
template = variant
}
+ // 5. Ask about immediate install and package manager
+ let immediate = argImmediate
+ let agent = argAgent
+
+ if (immediate === undefined) {
+ const immediateResult = await prompts.confirm({
+ message: 'Install and start now?',
... | packages/create-vite/src/index.ts | 26 | TypeScript | 0.357 | suggestion | 69 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const targetPath = path.join(root, renameFiles[file] ?? file)
if (content) {
fs.writeFileSync(targetPath, content)
} else {
copy(path.join(templateDir, file), targetPath)
}
}
const files = fs.readdirSync(templateDir)
for (const file of files.filter((f) => f !== 'package.json')) {
... | ```suggestion
if (immediate) {
if (!agent) throw new Error()
```
`agent` should always exist here
| if (customCommand) {
const fullCustomCommand = getFullCustomCommand(customCommand, pkgInfo)
const [command, ...args] = fullCustomCommand.split(' ')
// we replace TARGET_DIR here because targetDir may include a space
const replacedArgs = args.map((arg) =>
arg.replace('TARGET_DIR', () => targetDi... | @@ -533,25 +595,30 @@ async function init() {
setupReactSwc(root, template.endsWith('-ts'))
}
- let doneMessage = ''
- const cdProjectName = path.relative(cwd, root)
- doneMessage += `Done. Now run:\n`
- if (root !== cwd) {
- doneMessage += `\n cd ${
- cdProjectName.includes(' ') ? `"${cdProjectN... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 104 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const variant = await prompts.select({
message: 'Select a variant:',
options: framework.variants.map((variant) => {
const variantColor = variant.color
const command = variant.customCommand
? getFullCustomCommand(variant.customCommand, pkgInfo).replace(
/ TARGET_DI... | ```suggestion
```
Move `agent` variable declaration to just above `if (immediate && !agent) {`. | },
})
if (prompts.isCancel(packageNameResult)) return cancel()
packageName = packageNameResult
} else {
packageName = toValidPackageName(packageName)
}
}
// 4. Choose a framework and variant
let template = argTemplate
let hasInvalidArgTemplate = false
if (argTemplate &... | @@ -470,6 +506,19 @@ async function init() {
template = variant
}
+ // 5. Ask about immediate install and package manager
+ let immediate = argImmediate
+ let agent = argAgent
+ | packages/create-vite/src/index.ts | 26 | TypeScript | 0.857 | suggestion | 95 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const command = variant.customCommand
? getFullCustomCommand(variant.customCommand, pkgInfo).replace(
/ TARGET_DIR$/,
'',
)
: undefined
return {
label: variantColor(variant.display || variant.name),
value: variant.name,
... | ```suggestion
```
This should be the default. | } else {
packageName = toValidPackageName(packageName)
}
}
// 4. Choose a framework and variant
let template = argTemplate
let hasInvalidArgTemplate = false
if (argTemplate && !TEMPLATES.includes(argTemplate)) {
template = undefined
hasInvalidArgTemplate = true
}
if (!template) {
... | @@ -470,6 +506,19 @@ async function init() {
template = variant
}
+ // 5. Ask about immediate install and package manager
+ let immediate = argImmediate
+ let agent = argAgent
+
+ if (immediate === undefined) {
+ const immediateResult = await prompts.confirm({
+ message: 'Install and start now?',
... | packages/create-vite/src/index.ts | 26 | TypeScript | 0.786 | suggestion | 45 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
// Assertions
expect(stdout).toContain(`Scaffolding project in ${genPath}`)
expect(templateFiles).toEqual(generatedFiles)
})
test('accepts command line override for --overwrite', () => {
createNonEmptyDir()
const { stdout } = run(['.', '--overwrite', 'ignore'], { cwd: genPath })
expect(stdout).not.toContai... | wrap `stdout` with `stripVTCharacters` from `node:util`. | test('successfully scaffolds a project with subfolder based on react starter template', () => {
const { stdout } = run(
[
`subfolder/${projectName}`,
'--interactive',
'--no-immediate',
'--template',
'react',
'--no-rolldown',
],
{
cwd: __dirname,
},
)
const... | @@ -155,7 +155,28 @@ test('return help usage how to use create-vite with -h alias', () => {
test('shows immediate and agent options in help', () => {
const { stdout } = run(['--help'], { cwd: __dirname })
- expect(stdout).toMatchInlineSnapshot()
+ expect(stdout).toMatchInlineSnapshot(` | packages/create-vite/__tests__/cli.spec.ts | 26 | TypeScript | 0.357 | suggestion | 56 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
const defaultTargetDir = 'vite-project'
function run(...params: Parameters<typeof spawn.sync>) {
const { status, error } = spawn.sync(...params)
if (status != null && status > 0) {
process.exit(status)
}
if (error) {... | Don't skip these even in tests. | )
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
const defaultTargetDir = 'vite-project'
function run(...params: Parameters<typeof spawn.sync>) {
const { status, error } = spawn.sync(...params)
if (status != null && status > 0) {
process.exit(status)
}
if (error)... | @@ -359,6 +359,11 @@ function run(...params: Parameters<typeof spawn.sync>) {
}
function install(root: string, agent: string) {
+ // Skip actual installation in test environment
+ if (process.env.NODE_ENV === 'test' || process.env.VITEST) {
+ console.log(`\nInstalling dependencies via ${agent}... (skipped in t... | packages/create-vite/src/index.ts | 26 | TypeScript | 0.071 | suggestion | 31 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
}
// Only prompt for immediate if not already determined
if (immediate === undefined) {
const immediateResult = await prompts.confirm({
message: 'Install and start now?',
})
if (prompts.isCancel(immediateResult)) return cancel()
immediate = immediateResult
// If user wants immediate in... | ```suggestion
// 5. Ask about immediate install and package manager
let immediate = argImmediate
// If agent is specified but immediate is not explicitly set, default immediate to true
if (argAgent && immediate === undefined) {
immediate = true
}
if (immediate === undefined) {
const immediateResult ... | hint: command,
}
}),
})
if (prompts.isCancel(variant)) return cancel()
template = variant
} else {
template = 'vanilla-ts'
}
}
const pkgManager = pkgInfo ? pkgInfo.name : 'npm'
// 5. Ask about immediate install and package manager
let immediate = ... | @@ -507,14 +517,43 @@ async function init() {
}
// 5. Ask about immediate install and package manager
+ const pkgManager = pkgInfo ? pkgInfo.name : 'npm'
+ let agent = argAgent
let immediate = argImmediate
+ // If agent is specified but immediate is not explicitly set, default immediate to true
+ if (a... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 1,000 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
(a, b) => a.concat(b),
[],
)
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
const defaultTargetDir = 'vite-project'
function run(...params: Parameters<typeof spawn.sync>) {
const { status, error } = spawn.sync(...params)
if (status != null && status > 0) {
proces... | ```suggestion
```
this comment is not needed here |
const TEMPLATES = FRAMEWORKS.map((f) => f.variants.map((v) => v.name)).reduce(
(a, b) => a.concat(b),
[],
)
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
const defaultTargetDir = 'vite-project'
function run(...params: Parameters<typeof spawn.sync>) {
const { status, e... | @@ -340,12 +344,54 @@ const renameFiles: Record<string, string | undefined> = {
const defaultTargetDir = 'vite-project'
+function run(...params: Parameters<typeof spawn.sync>) {
+ const { status, error } = spawn.sync(...params)
+
+ if (status != null && status > 0) {
+ process.exit(status)
+ }
+
+ if (error... | packages/create-vite/src/index.ts | 26 | TypeScript | 0.786 | suggestion | 49 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
if (status != null && status > 0) {
process.exit(status)
}
if (error) {
console.error(`\n${params.slice(0, -1).join(' ')} error!`)
console.error(error)
process.exit(1)
}
}
function install(root: string, agent: string) {
// Skip actual installation in test environment
if (process.env._VITE_... | ```suggestion
```
this comment is not needed here | const { status, error } = spawn.sync(...params)
if (status != null && status > 0) {
process.exit(status)
}
if (error) {
console.error(`\n${params.slice(0, -1).join(' ')} error!`)
console.error(error)
process.exit(1)
}
}
function install(root: string, agent: string) {
if (process.env._VITE_... | @@ -340,12 +344,54 @@ const renameFiles: Record<string, string | undefined> = {
const defaultTargetDir = 'vite-project'
+function run(...params: Parameters<typeof spawn.sync>) {
+ const { status, error } = spawn.sync(...params)
+
+ if (status != null && status > 0) {
+ process.exit(status)
+ }
+
+ if (error... | packages/create-vite/src/index.ts | 26 | TypeScript | 0.786 | suggestion | 49 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
})
const generatedFiles = fs.readdirSync(genPath).sort()
// Assertions
expect(stdout).toContain(`Scaffolding project in ${genPath}`)
expect(templateFiles).toEqual(generatedFiles)
})
test('accepts command line override for --overwrite', () => {
createNonEmptyDir()
const { stdout } = run(['.', '--overwrit... | set `_VITE_TEST_CLI` env var in `run` function | })
test('successfully scaffolds a project with subfolder based on react starter template', () => {
const { stdout } = run(
[
`subfolder/${projectName}`,
'--interactive',
'--no-immediate',
'--template',
'react',
'--no-rolldown',
],
{
cwd: __dirname,
},
)
c... | @@ -152,3 +153,57 @@ test('return help usage how to use create-vite with -h alias', () => {
const message = 'Usage: create-vite [OPTION]... [DIRECTORY]'
expect(stdout).toContain(message)
})
+ | packages/create-vite/__tests__/cli.spec.ts | 26 | TypeScript | 0.286 | suggestion | 46 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
const defaultTargetDir = 'vite-project'
function run(...params: Parameters<typeof spawn.sync>) {
const { status, error } = spawn.sync(...params)
if (status != null && status > 0) {
process.exit(status)
}
if (error) {... | ```suggestion
if (process.env._VITE_TEST_CLI) {
console.log(`\nInstalling dependencies with ${agent}... (skipped in test)`)
return
}
console.log(`\nInstalling dependencies with ${agent}...`)
```
I think using `with` is a bit more natural here. | )
const renameFiles: Record<string, string | undefined> = {
_gitignore: '.gitignore',
}
const defaultTargetDir = 'vite-project'
function run(...params: Parameters<typeof spawn.sync>) {
const { status, error } = spawn.sync(...params)
if (status != null && status > 0) {
process.exit(status)
}
if (error)... | @@ -340,12 +344,52 @@ const renameFiles: Record<string, string | undefined> = {
const defaultTargetDir = 'vite-project'
+function run(...params: Parameters<typeof spawn.sync>) {
+ const { status, error } = spawn.sync(...params)
+
+ if (status != null && status > 0) {
+ process.exit(status)
+ }
+
+ if (error... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 258 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
if (error) {
console.error(`\n${params.slice(0, -1).join(' ')} error!`)
console.error(error)
process.exit(1)
}
}
function install(root: string, agent: string) {
if (process.env._VITE_TEST_CLI) {
console.log(`\nInstalling dependencies via ${agent}... (skipped in test)`)
return
}
console.l... | ```suggestion
if (process.env._VITE_TEST_CLI) {
console.log('\nStarting dev server... (skipped in test)')
return
}
console.log('\nStarting dev server...')
``` | }
if (error) {
console.error(`\n${params.slice(0, -1).join(' ')} error!`)
console.error(error)
process.exit(1)
}
}
function install(root: string, agent: string) {
if (process.env._VITE_TEST_CLI) {
prompts.log.step(
`Installing dependencies with ${agent}... (skipped in test)`,
)
r... | @@ -340,12 +344,52 @@ const renameFiles: Record<string, string | undefined> = {
const defaultTargetDir = 'vite-project'
+function run(...params: Parameters<typeof spawn.sync>) {
+ const { status, error } = spawn.sync(...params)
+
+ if (status != null && status > 0) {
+ process.exit(status)
+ }
+
+ if (error... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 172 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
if (immediate === undefined) {
// In test mode, default to false to avoid prompts
if (process.env._VITE_TEST_CLI) {
immediate = false
} else {
const immediateResult = await prompts.confirm({
message: 'Install and start now?',
})
if (prompts.isCancel(immediateResult)) return... | Perhaps here there's an opportunity to combine as a single prompt for most cases. Could we ask in the first prompt something like this?
```
> Install with <detected-pm> and start now?
- Yes
- Select a different package manager
- No
```
Alternatively I'm also thinking we could skip the package manager prompt altogethe... | const command = variant.customCommand
? getFullCustomCommand(variant.customCommand, pkgInfo).replace(
/ TARGET_DIR$/,
'',
)
: undefined
return {
label: variantColor(variant.display || variant.name),
value: ... | @@ -470,6 +514,42 @@ async function init() {
template = variant
}
+ // 5. Ask about immediate install and package manager
+ let immediate = argImmediate
+ // If agent is specified but immediate is not explicitly set, default immediate to true
+ if (argAgent && immediate === undefined) {
+ immediate = t... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 599 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
} else {
copy(path.join(templateDir, file), targetPath)
}
}
const files = fs.readdirSync(templateDir)
for (const file of files.filter((f) => f !== 'package.json')) {
write(file)
}
const pkg = JSON.parse(
fs.readFileSync(path.join(templateDir, `package.json`), 'utf-8'),
)
pkg.name ... | Something I'm just wondering, maybe we should `cd` into the project so that when the dev server is stopped the directory is on the project, which also makes it feel like we're just auto-executing the commands we printed in non-immediate mode. | options: [
{
label: 'Yes',
value: true,
hint: 'The future default Vite, which is powered by Rolldown',
},
{ label: 'No', value: false },
],
initialValue: false,
})
if (prompts.isCancel(rolldownViteValue)) return cancel... | @@ -533,25 +611,31 @@ async function init() {
setupReactSwc(root, template.endsWith('-ts'))
}
- let doneMessage = ''
- const cdProjectName = path.relative(cwd, root)
- doneMessage += `Done. Now run:\n`
- if (root !== cwd) {
- doneMessage += `\n cd ${
- cdProjectName.includes(' ') ? `"${cdProjectN... | packages/create-vite/src/index.ts | 26 | TypeScript | 0.786 | suggestion | 243 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
}
}
function install(root: string, agent: string) {
if (process.env._VITE_TEST_CLI) {
console.log(`\nInstalling dependencies with ${agent}... (skipped in test)`)
return
}
console.log(`\nInstalling dependencies with ${agent}...`)
run(agent, agent === 'yarn' ? [] : ['install'], {
stdio: 'inherit',
... | Maybe we should use clack prompts logging functions so the install steps are consistent with the other messages (e.g. the "scaffolding project ..." message)
```suggestion
function install(root: string, agent: string) {
if (process.env._VITE_TEST_CLI) {
prompts.log.step(`Installing dependencies with ${agent}..... | console.error(error)
process.exit(1)
}
}
function install(root: string, agent: string) {
if (process.env._VITE_TEST_CLI) {
prompts.log.step(
`Installing dependencies with ${agent}... (skipped in test)`,
)
return
}
prompts.log.step(`Installing dependencies with ${agent}...`)
run(agen... | @@ -340,12 +343,51 @@ const renameFiles: Record<string, string | undefined> = {
const defaultTargetDir = 'vite-project'
+function run(...params: Parameters<typeof spawn.sync>) {
+ const { status, error } = spawn.sync(...params)
+
+ if (status != null && status > 0) {
+ process.exit(status)
+ }
+
+ if (error... | packages/create-vite/src/index.ts | 26 | TypeScript | 1 | suggestion | 851 | 51 | 51 | false | feat(create-vite): support auto install dependencies and start dev | 20,468 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
function handleParseError(
parserError: ParserError,
html: string,
filePath: string,
) {
switch (parserError.code) {
case 'missing-doctype':
// ignore missing DOCTYPE
return
case 'abandoned-head-element-child':
// Accept elements without closing tag in <head>
return
case 'dup... | Instead of suppressing this, I think we can change all the errors that are not suppressed to be a warning. The ones that are not suppressed are likely to be an user error (if it's intended, they can suppress it). | frame: generateCodeFrame(
html,
parserError.startOffset,
parserError.endOffset,
),
loc: {
file: id,
line: parserError.startLine,
column: parserError.startCol,
},
} satisfies RollupError
return formattedError
}
function handleParseError(
parserError: ParserError... | @@ -316,6 +316,9 @@ function handleParseError(
// Allow <?xml> declaration and <?> empty elements
// lit generates <?>: https://github.com/lit/lit/issues/2470
return
+ case 'control-character-in-input-stream':
+ // Allow control characters in HTML #20482
+ return | packages/vite/src/node/plugins/html.ts | 26 | TypeScript | 0.857 | suggestion | 212 | 51 | 51 | false | fix(html): allow control character in input stream | 20,483 | vitejs/vite | 78,557 | TypeScript | sapphi-red | btea |
): node is DefaultTreeAdapterMap['element'] {
return node.nodeName[0] !== '#'
}
function traverseNodes(
node: DefaultTreeAdapterMap['node'],
visitor: (node: DefaultTreeAdapterMap['node']) => void,
) {
if (node.nodeName === 'template') {
node = (node as DefaultTreeAdapterMap['template']).content
}
visit... | ```suggestion
warn: ResolvedConfig['logger']['warn'],
visitor: (node: DefaultTreeAdapterMap['node']) => void,
```
I think this is better. `visitor` is normally long and that makes it easier to overlook the parameters after it.
| ResolvedConfig,
Map<string, boolean>
>()
export function nodeIsElement(
node: DefaultTreeAdapterMap['node'],
): node is DefaultTreeAdapterMap['element'] {
return node.nodeName[0] !== '#'
}
function traverseNodes(
node: DefaultTreeAdapterMap['node'],
visitor: (node: DefaultTreeAdapterMap['node']) => void,
... | @@ -188,14 +188,15 @@ export async function traverseHtml(
html: string,
filePath: string,
visitor: (node: DefaultTreeAdapterMap['node']) => void,
+ warn: ResolvedConfig['logger']['warn'], | packages/vite/src/node/plugins/html.ts | 26 | TypeScript | 1 | suggestion | 231 | 51 | 51 | false | fix(html): allow control character in input stream | 20,483 | vitejs/vite | 78,557 | TypeScript | sapphi-red | btea |
return
case 'duplicate-attribute':
// Accept duplicate attributes #5966
// The first attribute is used, browsers silently ignore duplicates
return
case 'non-void-html-element-start-tag-with-trailing-solidus':
// Allow self closing on non-void elements #10439
return
case '... | Since we are omitting the whole code frame instead of a specific line.
```suggestion
`${parseError.frame.length > 300 ? '[this code frame is omitted as the content was too long] ' : parseError.frame}`,
``` | function handleParseError(
parserError: ParserError,
html: string,
filePath: string,
warnings: ParseWarnings,
) {
switch (parserError.code) {
case 'missing-doctype':
// ignore missing DOCTYPE
return
case 'abandoned-head-element-child':
// Accept elements without closing tag in <head>... | @@ -317,11 +320,20 @@ function handleParseError(
// lit generates <?>: https://github.com/lit/lit/issues/2470
return
}
+ fileErrorInfo[filePath] ??= {}
+ if (fileErrorInfo[filePath][parserError.code]) {
+ // already warned about this error
+ return
+ }
+ fileErrorInfo[filePath][parserError.co... | packages/vite/src/node/plugins/html.ts | 26 | TypeScript | 1 | refactor | 213 | 51 | 51 | false | fix(html): allow control character in input stream | 20,483 | vitejs/vite | 78,557 | TypeScript | sapphi-red | btea |
}
return s
}
/**
* Format parse5 @type {ParserError} to @type {RollupError}
*/
function formatParseError(parserError: ParserError, id: string, html: string) {
const formattedError = {
code: parserError.code,
message: `parse5 error code ${parserError.code}`,
frame: generateCodeFrame(
html,
... | I think we should only dedupe if the content is same. So probably something like:
```ts
const shownWarnings: Record<string, { contentHash: string, codes: Set<string> }> = {}
const addShownWarning = (content: string, filename: string, code: string) => {
const contentHash = hash(code)
shownWarnings[filename] ??= { co... | return s
}
export function removeViteIgnoreAttr(
s: MagicString,
sourceCodeLocation: Token.Location,
): MagicString {
const loc = (sourceCodeLocation as Token.LocationWithAttributes).attrs?.[
'vite-ignore'
]
if (loc) {
s.remove(loc.startOffset, loc.endOffset)
}
return s
}
/**
* Format parse5 ... | @@ -293,10 +295,12 @@ function formatParseError(parserError: ParserError, id: string, html: string) {
return formattedError
}
+const fileErrorInfo: Record<string, Record<string, boolean>> = {} | packages/vite/src/node/plugins/html.ts | 26 | TypeScript | 1 | suggestion | 391 | 51 | 51 | false | fix(html): allow control character in input stream | 20,483 | vitejs/vite | 78,557 | TypeScript | sapphi-red | btea |
}
}
watcher.on('event', callback)
await new Promise<void>((resolve) => {
resolveFn = resolve
})
return watcher.off('event', callback)
}
export function createInMemoryLogger(logs: string[]): Logger {
const loggedErrors = new WeakSet<Error | RollupError>()
const warnedMessages = new Set<string>()
... | Could we use a custom plugin that throws an error instead of this change? It would be difficult to notice this code when writing the tests in `playground/html`. | previewServer.config.base,
)
await page.goto(viteTestUrl)
}
}
/**
* Send the rebuild complete message in build watch
*/
export async function notifyRebuildComplete(
watcher: RollupWatcher,
): Promise<RollupWatcher> {
let resolveFn: undefined | (() => void)
const callback = (event: RollupWatcher... | @@ -320,6 +320,11 @@ export function createInMemoryLogger(logs: string[]): Logger {
logs.push(msg)
},
warn(msg) {
+ // for invalid HTML, we throw an error
+ // to avoid false positives in tests
+ if (msg.includes('Unable to parse HTML;')) {
+ throw new Error(msg)
+ } | playground/vitestSetup.ts | 26 | TypeScript | 1 | suggestion | 160 | 51 | 51 | false | fix(html): allow control character in input stream | 20,483 | vitejs/vite | 78,557 | TypeScript | sapphi-red | btea |
return entries
}
async function prepareEsbuildScanner(
environment: ScanEnvironment,
entries: string[],
deps: Record<string, string>,
missing: Record<string, string>,
): Promise<BuildContext> {
const plugin = esbuildScanPlugin(environment, deps, missing, entries)
const { plugins = [], ...esbuildOptions ... | I'd imagine there was a reason to only pick up `experimentalDecorators` instead of entire `tsconfig`, but I didn't understand the comment above and didn't have tests failing with expanding jsx here too. | return entries
}
async function prepareEsbuildScanner(
environment: ScanEnvironment,
entries: string[],
deps: Record<string, string>,
missing: Record<string, string>,
): Promise<BuildContext> {
const plugin = esbuildScanPlugin(environment, deps, missing, entries)
const { plugins = [], ...esbuildOptions ... | @@ -294,8 +294,23 @@ async function prepareEsbuildScanner(
const { tsconfig } = await loadTsconfigJsonForFile(
path.join(environment.config.root, '_dummy.js'),
)
- if (tsconfig.compilerOptions?.experimentalDecorators) {
- tsconfigRaw = { compilerOptions: { experimentalDecorators: true } }
+ ... | packages/vite/src/node/optimizer/scan.ts | 26 | TypeScript | 0.786 | bug | 202 | 51 | 51 | false | fix(optimizer): discover correct jsx runtime during scan | 20,495 | vitejs/vite | 78,557 | TypeScript | hi-ogawa | hi-ogawa |
jsxImportSource: tsconfig.compilerOptions?.jsxImportSource,
},
}
}
}
return await esbuild.context({
absWorkingDir: process.cwd(),
write: false,
stdin: {
contents: entries.map((e) => `import ${JSON.stringify(e)}`).join('\n'),
loader: 'js',
},
bundle: true,... | This is to align with esbuild transform
https://github.com/vitejs/vite/blob/f0880df0eab077e61abb533c4edde6538bd729f9/packages/vite/src/node/config.ts#L1508-L1512 | jsxFactory: esbuildOptions.jsxFactory
? undefined
: tsconfig.compilerOptions?.jsxFactory,
jsxFragmentFactory: esbuildOptions.jsxFragment
? undefined
: tsconfig.compilerOptions?.jsxFragmentFactory,
jsxImportSource: esbuildOptions.jsxImportSour... | @@ -310,6 +325,7 @@ async function prepareEsbuildScanner(
format: 'esm',
logLevel: 'silent',
plugins: [...plugins, plugin],
+ jsxDev: !environment.config.isProduction, | packages/vite/src/node/optimizer/scan.ts | 26 | TypeScript | 0.286 | suggestion | 164 | 51 | 51 | false | fix(optimizer): discover correct jsx runtime during scan | 20,495 | vitejs/vite | 78,557 | TypeScript | hi-ogawa | hi-ogawa |
;(globalThis as any).__test_scan_jsx_runtime ??= 0
;(globalThis as any).__test_scan_jsx_runtime++
// @ts-ignore
export default <div>test</div>
| [nit] Maybe using `preact` can remove this `@ts-ignore`? | ;(globalThis as any).__test_scan_jsx_runtime ??= 0
;(globalThis as any).__test_scan_jsx_runtime++
export default <div />
| @@ -0,0 +1,5 @@
+;(globalThis as any).__test_scan_jsx_runtime ??= 0
+;(globalThis as any).__test_scan_jsx_runtime++
+
+// @ts-ignore
+export default <div>test</div> | packages/vite/src/node/__tests__/fixtures/scan-jsx-runtime/entry-jsx.tsx | 5 | TypeScript | 0.571 | refactor | 56 | 6 | 5 | false | fix(optimizer): discover correct jsx runtime during scan | 20,495 | vitejs/vite | 78,557 | TypeScript | sapphi-red | hi-ogawa |
test('scan jsx-runtime', async (ctx) => {
const server = await createServer({
configFile: false,
logLevel: 'error',
root: path.join(import.meta.dirname, 'fixtures', 'scan-jsx-runtime'),
environments: {
client: {
// silence client optimizer
optimizeDeps: {
noDiscovery: t... | I think `server.listen` itself is not needed. The reason why it requires it now is probably:
- it is safer to start the optimizer after `buildStart` is called (https://github.com/vitejs/vite/pull/12832)
- it is safer to start the optimizer after the previous server is stopped (https://github.com/vitejs/vite/blob/557f79... | test('scan jsx-runtime', async (ctx) => {
const server = await createServer({
configFile: false,
logLevel: 'error',
root: path.join(import.meta.dirname, 'fixtures', 'scan-jsx-runtime'),
environments: {
client: {
// silence client optimizer
optimizeDeps: {
noDiscovery: t... | @@ -123,3 +125,44 @@ describe('optimizer-scan:script-test', () => {
expect(ret).not.toContain('export default')
})
})
+
+test('scan jsx-runtime', async (ctx) => {
+ const server = await createServer({
+ configFile: false,
+ logLevel: 'error',
+ root: path.join(import.meta.dirname, 'fixtures', 'scan-j... | packages/vite/src/node/__tests__/scan.spec.ts | 26 | TypeScript | 0.643 | performance | 411 | 41 | 43 | false | fix(optimizer): discover correct jsx runtime during scan | 20,495 | vitejs/vite | 78,557 | TypeScript | sapphi-red | hi-ogawa |
tsconfig.compilerOptions?.experimentalDecorators ||
tsconfig.compilerOptions?.jsx ||
tsconfig.compilerOptions?.jsxFactory ||
tsconfig.compilerOptions?.jsxFragmentFactory ||
tsconfig.compilerOptions?.jsxImportSource
) {
tsconfigRaw = {
compilerOptions: {
experime... | I think we need
https://github.com/vitejs/vite/blob/f0880df0eab077e61abb533c4edde6538bd729f9/packages/vite/src/node/plugins/esbuild.ts#L167-L174
here ([esbuild try](https://esbuild.github.io/try/#YgAwLjI1LjgALS1qc3g9YXV0b21hdGljIC0tdHNjb25maWctcmF3PSd7ImNvbXBpbGVyT3B0aW9ucyI6eyJqc3giOiAicmVhY3QifX0nAGUAZW50cnkuanN4AGNv... | tsconfig.compilerOptions?.experimentalDecorators ||
tsconfig.compilerOptions?.jsx ||
tsconfig.compilerOptions?.jsxFactory ||
tsconfig.compilerOptions?.jsxFragmentFactory ||
tsconfig.compilerOptions?.jsxImportSource
) {
tsconfigRaw = {
compilerOptions: {
experime... | @@ -294,8 +294,23 @@ async function prepareEsbuildScanner(
const { tsconfig } = await loadTsconfigJsonForFile(
path.join(environment.config.root, '_dummy.js'),
)
- if (tsconfig.compilerOptions?.experimentalDecorators) {
- tsconfigRaw = { compilerOptions: { experimentalDecorators: true } }
+ ... | packages/vite/src/node/optimizer/scan.ts | 26 | TypeScript | 0.643 | suggestion | 347 | 51 | 51 | false | fix(optimizer): discover correct jsx runtime during scan | 20,495 | vitejs/vite | 78,557 | TypeScript | sapphi-red | hi-ogawa |
`offset is longer than source length! offset ${offset} > length ${source.length}`,
)
}
const lines = source.slice(0, offset).split(splitRE)
return {
line: lines.length,
column: lines[lines.length - 1].length,
}
}
export function generateCodeFrame(
source: string,
start: number | Pos = 0,... | It took me a while to understand why its doing a log10 here. I think the previous `String().length` was easier to understand. Is there a reason you switched to this? | `offset is longer than source length! offset ${offset} > length ${source.length}`,
)
}
const lines = source.slice(0, offset).split(splitRE)
return {
line: lines.length,
column: lines[lines.length - 1].length,
}
}
export function generateCodeFrame(
source: string,
start: number | Pos = 0,... | @@ -511,6 +511,11 @@ export function generateCodeFrame(
end !== undefined ? posToNumber(source, end) : start,
source.length,
)
+ const lastPosLine =
+ end !== undefined
+ ? numberToPos(source, end).line
+ : numberToPos(source, start).line + range
+ const lineNumberWidth = Math.max(3, Math.fl... | packages/vite/src/node/utils.ts | 26 | TypeScript | 0.5 | question | 165 | 51 | 51 | false | feat: support files with more than 1000 lines by `generateCodeFrame` | 20,508 | vitejs/vite | 78,557 | TypeScript | bluwy | sapphi-red |
import { dependencyIsMain } from './dependency'
export default {
isMain: import.meta.main,
dependencyIsMain,
url: import.meta.url,
dirname: import.meta.dirname,
filename: import.meta.filename,
}
| This variable and the `dependency.ts` file can be removed | export default {
isMain: import.meta.main,
url: import.meta.url,
dirname: import.meta.dirname,
filename: import.meta.filename,
}
| @@ -0,0 +1,9 @@
+import { dependencyIsMain } from './dependency'
+
+export default {
+ isMain: import.meta.main,
+ dependencyIsMain, | packages/vite/src/node/__tests__/fixtures/config/import-meta/vite.config.ts | 5 | TypeScript | 0.571 | suggestion | 57 | 10 | 7 | false | feat: add `import.meta.main` support in config (bundle config loader) | 20,516 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
path.resolve(fixtures, './entry/vite.config.import-attributes.ts'),
path.resolve(fixtures, './entry'),
))!
expect(config).toMatchInlineSnapshot(`
{
"jsonValue": "vite",
}
`)
})
test('import.meta.main is correctly set', async () => {
const { config } = (await ... | ```suggestion
expect(config.isMain).toBe(false)
expect(config.url).toContain('file://')
expect(config.dirname).toContain('import-meta')
expect(config.filename).toContain('vite.config.ts')
``` | path.resolve(fixtures, './entry/vite.config.import-attributes.ts'),
path.resolve(fixtures, './entry'),
))!
expect(config).toMatchInlineSnapshot(`
{
"jsonValue": "vite",
}
`)
})
test('import.meta.main is correctly set', async () => {
const { config } = (await ... | @@ -803,6 +803,24 @@ describe('loadConfigFromFile', () => {
`)
})
+ test('import.meta.main is correctly set', async () => {
+ const { config } = (await loadConfigFromFile(
+ {} as any,
+ path.resolve(fixtures, './import-meta/vite.config.ts'),
+ path.resolve(fixtures, './import-meta'),
+ ... | packages/vite/src/node/__tests__/config.spec.ts | 26 | TypeScript | 1 | suggestion | 207 | 50 | 46 | false | feat: add `import.meta.main` support in config (bundle config loader) | 20,516 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
`)
})
test('loadConfigFromFile with import attributes', async () => {
const { config } = (await loadConfigFromFile(
{} as any,
path.resolve(fixtures, './entry/vite.config.import-attributes.ts'),
path.resolve(fixtures, './entry'),
))!
expect(config).toMatchInlineSnapshot(`
... | use `expect(config).toMatchInlineSnapshot` instead | `)
})
test('loadConfigFromFile with import attributes', async () => {
const { config } = (await loadConfigFromFile(
{} as any,
path.resolve(fixtures, './entry/vite.config.import-attributes.ts'),
path.resolve(fixtures, './entry'),
))!
expect(config).toMatchInlineSnapshot(`
... | @@ -803,6 +803,18 @@ describe('loadConfigFromFile', () => {
`)
})
+ test('import.meta.main is correctly set', async () => {
+ const { config } = (await loadConfigFromFile(
+ {} as any,
+ path.resolve(fixtures, './import-meta/vite.config.ts'),
+ path.resolve(fixtures, './import-meta'),
+ ... | packages/vite/src/node/__tests__/config.spec.ts | 26 | TypeScript | 0.571 | suggestion | 50 | 50 | 51 | false | feat: add `import.meta.main` support in config (bundle config loader) | 20,516 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
createImportMetaResolver,
} from './importMetaResolver'
import type { ModuleRunnerImportMeta } from './types'
import { posixDirname, posixPathToFileHref, toWindowsPath } from './utils'
const envProxy = new Proxy({} as any, {
get(_, p) {
throw new Error(
`[module runner] Dynamic access of "import.meta.env... | only add `import.meta.main` to `createNodeImportMeta` and the value should be always `false`. | createImportMetaResolver,
} from './importMetaResolver'
import type { ModuleRunnerImportMeta } from './types'
import { posixDirname, posixPathToFileHref, toWindowsPath } from './utils'
const envProxy = new Proxy({} as any, {
get(_, p) {
throw new Error(
`[module runner] Dynamic access of "import.meta.env... | @@ -25,6 +26,7 @@ export function createDefaultImportMeta(
dirname: isWindows ? toWindowsPath(dirname) : dirname,
url: href,
env: envProxy,
+ main: isMainModule, | packages/vite/src/module-runner/createImportMeta.ts | 26 | TypeScript | 0.571 | suggestion | 93 | 51 | 51 | false | feat(ssr): add `import.meta.main` support for Node.js module runner | 20,517 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
)
})
test(`deadlock doesn't happen for dynamic imports`, async () => {
await page.goto(`${url}/forked-deadlock-dynamic-imports`)
expect(await page.textContent('.forked-deadlock-dynamic-imports')).toMatch(
'rendered... | Wrap this and the test above with `describe('import.meta is supported')` and dedupe the ``await page.goto(`${url}/import-meta`)`` call. |
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
)
})
test(`deadlock doesn't happen for dynamic imports`, async () => {
await page.goto(`${url}/forked-deadlock-dynamic-imports`)
expect(await page.textContent('.forked-deadlock-dynamic-imports')).toMatch(
'rendered... | @@ -52,6 +52,12 @@ test(`import.meta.resolve is supported`, async () => {
expect(await page.textContent('.import-meta-resolve')).toBe(metaUrl)
})
+test(`import.meta.main is false in Node.js environment`, async () => {
+ await page.goto(`${url}/import-meta`)
+
+ expect(await page.textContent('.import-meta-main')... | playground/ssr/__tests__/ssr.spec.ts | 26 | TypeScript | 0.5 | suggestion | 135 | 51 | 51 | false | feat(ssr): add `import.meta.main` support for Node.js module runner | 20,517 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
expect(await page.textContent('.circ-import')).toMatchInlineSnapshot(
'"A is: __A__"',
)
})
test(`deadlock doesn't happen for static imports`, async () => {
await page.goto(`${url}/forked-deadlock-static-imports`)
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
... | ```suggestion
describe('import.meta is supported', async () => {
await page.goto(`${url}/import-meta`)
``` |
expect(await page.textContent('.circ-import')).toMatchInlineSnapshot(
'"A is: __A__"',
)
})
test(`deadlock doesn't happen for static imports`, async () => {
await page.goto(`${url}/forked-deadlock-static-imports`)
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
... | @@ -44,12 +44,20 @@ test(`deadlock doesn't happen for dynamic imports`, async () => {
)
})
-test(`import.meta.resolve is supported`, async () => {
- await page.goto(`${url}/import-meta`)
+describe('import.meta is supported', () => {
+ beforeEach(async () => {
+ await page.goto(`${url}/import-meta`)
+ }) | playground/ssr/__tests__/ssr.spec.ts | 26 | TypeScript | 1 | suggestion | 108 | 51 | 51 | false | feat(ssr): add `import.meta.main` support for Node.js module runner | 20,517 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
)
})
test(`deadlock doesn't happen for dynamic imports`, async () => {
await page.goto(`${url}/forked-deadlock-dynamic-imports`)
expect(await page.textContent('.forked-deadlock-dynamic-imports')).toMatch(
'rendered... | ```suggestion
test(`import.meta.main is supported`, async () => {
``` |
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
)
})
test(`deadlock doesn't happen for dynamic imports`, async () => {
await page.goto(`${url}/forked-deadlock-dynamic-imports`)
expect(await page.textContent('.forked-deadlock-dynamic-imports')).toMatch(
'rendered... | @@ -44,12 +44,20 @@ test(`deadlock doesn't happen for dynamic imports`, async () => {
)
})
-test(`import.meta.resolve is supported`, async () => {
- await page.goto(`${url}/import-meta`)
+describe('import.meta is supported', () => {
+ beforeEach(async () => {
+ await page.goto(`${url}/import-meta`)
+ })
-... | playground/ssr/__tests__/ssr.spec.ts | 26 | TypeScript | 0.857 | suggestion | 71 | 51 | 51 | false | feat(ssr): add `import.meta.main` support for Node.js module runner | 20,517 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
test(`deadlock doesn't happen for static imports`, async () => {
await page.goto(`${url}/forked-deadlock-static-imports`)
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
)
})
test(`deadlock doesn't happen for dynamic imports`, async () => {
await page.goto(`${url}/f... | ```suggestion
test(`import.meta.main is supported`, async () => {
``` |
test(`deadlock doesn't happen for static imports`, async () => {
await page.goto(`${url}/forked-deadlock-static-imports`)
expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(
'rendered',
)
})
test(`deadlock doesn't happen for dynamic imports`, async () => {
await page.goto(`${url}/f... | @@ -52,6 +52,12 @@ test(`import.meta.resolve is supported`, async () => {
expect(await page.textContent('.import-meta-resolve')).toBe(metaUrl)
})
+test(`import.meta.main is false in Node.js environment`, async () => { | playground/ssr/__tests__/ssr.spec.ts | 26 | TypeScript | 0.857 | suggestion | 69 | 51 | 51 | false | feat(ssr): add `import.meta.main` support for Node.js module runner | 20,517 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const referenceId = this.emitFile({
type: 'asset',
name: cssAssetName,
originalFileName,
source: content,
})
const filename = this.getFileName(referenceId)
chunk.viteMetadata!.importedAssets.add(cleanUrl(filename))
const ... | instead of changing this condition. make the default value of `chunkCSS` be `undefined` and check whether it's `undefined` here. | const referenceId = this.emitFile({
type: 'asset',
name: cssAssetName,
originalFileName,
source: content,
})
const filename = this.getFileName(referenceId)
chunk.viteMetadata!.importedAssets.add(cleanUrl(filename))
const ... | @@ -824,7 +824,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
}
}
- if (chunkCSS) {
+ if (chunkCSS || (isPureCssChunk && chunk.isEntry)) { | packages/vite/src/node/plugins/css.ts | 26 | TypeScript | 1 | suggestion | 128 | 51 | 51 | false | fix(css): empty CSS entry points should generate CSS files, not JS files | 20,518 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
test.runIf(isBuild)('CSS modules should be treeshaken if not used', () => {
const css = findAssetFile(/\.css$/, undefined, undefined, true)
expect(css).not.toContain('treeshake-module-b')
})
test.runIf(isBuild)('Scoped CSS via cssScopeTo should be treeshaken', () => {
const css = findAssetFile(/\.cs... | Do we need to use the manifest to validate the file extension? Could we check the output assets directly like this?
https://github.com/vitejs/vite/blob/e49f50599d852eec644e79b074b4648e2dff1e5d/playground/css/__tests__/tests.ts#L519-L524 | ),
).not.toBeUndefined()
})
test.runIf(isBuild)('CSS modules should be treeshaken if not used', () => {
const css = findAssetFile(/\.css$/, undefined, undefined, true)
expect(css).not.toContain('treeshake-module-b')
})
test.runIf(isBuild)('Scoped CSS via cssScopeTo should be treeshaken', () ... | @@ -539,4 +540,13 @@ export const tests = (isLightningCSS: boolean) => {
expect(await getColor('.treeshake-scoped-order')).toBe('red')
expect(await getBgColor('.treeshake-scoped-order')).toBe('blue')
})
+
+ test.runIf(isBuild)(
+ 'empty CSS files should generate .css assets, not .js assets',
+ () =>... | playground/css/__tests__/tests.ts | 26 | TypeScript | 0.571 | question | 237 | 28 | 31 | false | fix(css): empty CSS entry points should generate CSS files, not JS files | 20,518 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
test('return help usage how to use create-vite', () => {
const { stdout } = run(['--help'], { cwd: __dirname })
const message = 'Usage: create-vite [OPTION]... [DIRECTORY]'
expect(stdout).toContain(message)
})
test('return help usage how to use create-vite with -h alias', () => {
const { stdout } = run(['--h'... | ```suggestion
const indexHtmlPath = path.join(genPath, 'index.html')
const indexHtmlContent = fs.readFileSync(indexHtmlPath, 'utf-8')
expect(stdout).toContain(`Scaffolding project in ${genPath}`)
expect(indexHtmlContent).toContain(`<title>${projectName}</title>`)
``` | import fs from 'node:fs'
import path from 'node:path'
import type { SyncOptions, SyncResult } from 'execa'
import { execaCommandSync } from 'execa'
import { afterEach, beforeAll, expect, test } from 'vitest'
const CLI_PATH = path.join(__dirname, '..')
const projectName = 'test-app'
const genPath = path.join(__dirname... | @@ -152,3 +152,18 @@ test('return help usage how to use create-vite with -h alias', () => {
const message = 'Usage: create-vite [OPTION]... [DIRECTORY]'
expect(stdout).toContain(message)
})
+
+test('sets index.html title to project name', () => {
+ const { stdout } = run([projectName, '--template', 'react'], {
... | packages/create-vite/__tests__/cli.spec.ts | 26 | TypeScript | 1 | suggestion | 276 | 28 | 167 | false | feat(create-vite): set default title in index.html to project name | 20,519 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
const [command, ...args] = fullCustomCommand.split(' ')
// we replace TARGET_DIR here because targetDir may include a space
const replacedArgs = args.map((arg) =>
arg.replace('TARGET_DIR', () => targetDir),
)
const { status } = spawn.sync(command, replacedArgs, {
stdio: 'inherit',
}... | no need to handle lit differently |
const [command, ...args] = fullCustomCommand.split(' ')
// we replace TARGET_DIR here because targetDir may include a space
const replacedArgs = args.map((arg) =>
arg.replace('TARGET_DIR', () => targetDir),
)
const { status } = spawn.sync(command, replacedArgs, {
stdio: 'inherit',
}... | @@ -511,6 +511,21 @@ async function init() {
const targetPath = path.join(root, renameFiles[file] ?? file)
if (content) {
fs.writeFileSync(targetPath, content)
+ } else if (file === 'index.html') {
+ // Handle index.html files specially to replace title with project name | packages/create-vite/src/index.ts | 26 | TypeScript | 0.357 | suggestion | 33 | 51 | 51 | false | feat(create-vite): set default title in index.html to project name | 20,519 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, test } from 'vitest'
import { build } from 'vite'
import type { RollupOutput } from 'rollup'
import type { TerserOptions } from '../../plugins/terser'
const __dirname = resolve(fileURLToPath(import.meta.url), '..')
... | This change seems unnecessary. | import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, test } from 'vitest'
import { build } from 'vite'
import type { RollupOutput } from 'rollup'
import type { TerserOptions } from '../../plugins/terser'
const __dirname = resolve(fileURLToPath(import.meta.url), '..')
... | @@ -8,14 +8,15 @@ import type { TerserOptions } from '../../plugins/terser'
const __dirname = resolve(fileURLToPath(import.meta.url), '..')
describe('terser', () => {
- const run = async (terserOptions: TerserOptions) => {
+ const run = async (terserOptions: TerserOptions, buildOptions = {}) => {
const resul... | packages/vite/src/node/__tests__/plugins/terser.spec.ts | 19 | TypeScript | 0.286 | suggestion | 30 | 44 | 44 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
// We also need the plugin even if minify isn't 'terser' as we force
// terser in plugin-legacy
return !!environment.config.build.minify
},
async renderChunk(code, _chunk, outputOptions) {
// This plugin is included for any non-false value of config.build.minify,
// so that normal... | Remove this condition completely | let worker: ReturnType<typeof makeWorker>
return {
name: 'vite:terser',
applyToEnvironment(environment) {
// We also need the plugin even if minify isn't 'terser' as we force
// terser in plugin-legacy
return !!environment.config.build.minify
},
async renderChunk(code, chunk, ou... | @@ -91,18 +91,33 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
}
// Do not minify ES lib output since that would remove pure annotations
- // and break tree-shaking.
- if (config.build.lib && outputOptions.format === 'es') {
+ // and break tree-shaking, unless the user... | packages/vite/src/node/plugins/terser.ts | 26 | TypeScript | 0.286 | refactor | 32 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
// so that normal chunks can use the preferred minifier, and legacy chunks
// can use terser.
if (
config.build.minify !== 'terser' &&
// @ts-expect-error injected by @vitejs/plugin-legacy
!outputOptions.__vite_force_terser__
) {
return null
}
// Do n... | ```suggestion
// For ES lib mode, preserve comments to maintain pure annotations for tree-shaking
``` | // terser in plugin-legacy
return !!environment.config.build.minify
},
async renderChunk(code, chunk, outputOptions) {
// This plugin is included for any non-false value of config.build.minify,
// so that normal chunks can use the preferred minifier, and legacy chunks
// can use t... | @@ -91,18 +91,33 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
}
// Do not minify ES lib output since that would remove pure annotations
- // and break tree-shaking.
- if (config.build.lib && outputOptions.format === 'es') {
+ // and break tree-shaking, unless the user... | packages/vite/src/node/plugins/terser.ts | 26 | TypeScript | 1 | suggestion | 107 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
config.build.minify !== 'terser' &&
// @ts-expect-error injected by @vitejs/plugin-legacy
!outputOptions.__vite_force_terser__
) {
return null
}
// Do not minify ES lib output since that would remove pure annotations
// and break tree-shaking, unless the user exp... | ```suggestion
? terserOptions.output?.comments === 'all' ? 'all' : /^#__/ // pure annotation comments
``` |
async renderChunk(code, chunk, outputOptions) {
// This plugin is included for any non-false value of config.build.minify,
// so that normal chunks can use the preferred minifier, and legacy chunks
// can use terser.
if (
config.build.minify !== 'terser' &&
// @ts-expect-err... | @@ -91,18 +91,33 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
}
// Do not minify ES lib output since that would remove pure annotations
- // and break tree-shaking.
- if (config.build.lib && outputOptions.format === 'es') {
+ // and break tree-shaking, unless the user... | packages/vite/src/node/plugins/terser.ts | 26 | TypeScript | 1 | suggestion | 113 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
expect(log).not.toMatch('All "@import" rules must come first')
})
})
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readFile('dist/my-lib-custom-filename.iife.js')
const umd = readFile('dist/my-lib-custom-filename.umd.cjs')
expect(e... | ```suggestion
expect(terserEs).toMatch(/function/)
``` | expect(log).not.toMatch('All "@import" rules must come first')
})
})
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readFile('dist/my-lib-custom-filename.iife.js')
const umd = readFile('dist/my-lib-custom-filename.umd.cjs')
expect(e... | @@ -82,6 +82,21 @@ describe.runIf(isBuild)('build', () => {
expect(umd).toMatch('process.env.NODE_ENV')
})
+ test('terser minification for es lib mode', () => {
+ const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
+ const normalEs = readFile('dist/my-lib-custom-filename.js')
+
+ // T... | playground/lib/__tests__/lib.spec.ts | 26 | TypeScript | 0.857 | suggestion | 58 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
return !!environment.config.build.minify
},
async renderChunk(code, _chunk, outputOptions) {
// This plugin is included for any non-false value of config.build.minify,
// so that normal chunks can use the preferred minifier, and legacy chunks
// can use terser.
if (
config... | ```suggestion
: /^[@#]__/ // pure annotation comments
``` | return {
name: 'vite:terser',
applyToEnvironment(environment) {
// We also need the plugin even if minify isn't 'terser' as we force
// terser in plugin-legacy
return !!environment.config.build.minify
},
async renderChunk(code, chunk, outputOptions) {
// This plugin is includ... | @@ -90,19 +90,26 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
return null
}
- // Do not minify ES lib output since that would remove pure annotations
- // and break tree-shaking.
- if (config.build.lib && outputOptions.format === 'es') {
- return null
- ... | packages/vite/src/node/plugins/terser.ts | 26 | TypeScript | 0.857 | suggestion | 67 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
serverLogs.forEach((log) => {
// no warning from esbuild css minifier
expect(log).not.toMatch('All "@import" rules must come first')
})
})
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readFile('dist/my-lib-custom-filename.iife.j... | ```suggestion
const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
expect(terserEs).not.toMatch('console.log')
``` | serverLogs.forEach((log) => {
// no warning from esbuild css minifier
expect(log).not.toMatch('All "@import" rules must come first')
})
})
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readFile('dist/my-lib-custom-filename.iife.j... | @@ -82,6 +82,30 @@ describe.runIf(isBuild)('build', () => {
expect(umd).toMatch('process.env.NODE_ENV')
})
+ test('terser minification for es lib mode', () => {
+ const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
+
+ // Should not contain console.log since drop_console is true
+ exp... | playground/lib/__tests__/lib.spec.ts | 26 | TypeScript | 1 | suggestion | 136 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
expect(iife).toMatch('process.env.NODE_ENV')
expect(umd).toMatch('process.env.NODE_ENV')
})
test('terser minification for es lib mode', () => {
const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
// Should not contain console.log since drop_console is true
expect(terserEs).not.t... | ```suggestion
const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
expect(terserEs).toMatch(/[#@]__PURE__/)
``` | expect(iife).toMatch('process.env.NODE_ENV')
expect(umd).toMatch('process.env.NODE_ENV')
})
test('debugger statements are removed by terser for es', () => {
const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
expect(terserEs).not.toMatch('debugger')
})
test('pure annotations are... | @@ -82,6 +82,30 @@ describe.runIf(isBuild)('build', () => {
expect(umd).toMatch('process.env.NODE_ENV')
})
+ test('terser minification for es lib mode', () => {
+ const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
+
+ // Should not contain console.log since drop_console is true
+ exp... | playground/lib/__tests__/lib.spec.ts | 26 | TypeScript | 1 | suggestion | 133 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
function createObject() {
return { created: Date.now() }
}
export default function myLib(sel) {
// Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951)
console.log({ ...'foo' })
document.querySelector(sel).textContent = 'It works'
// Env vars should not be replaced
console.log(proce... | ```suggestion
// Pure annotation comment should be kept for ESM format
``` | export default /* @__PURE__ */ Object.assign(function myLib(sel) {
// Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951)
console.log({ ...'foo' })
document.querySelector(sel).textContent = 'It works'
// Env vars should not be replaced
console.log(process.env.NODE_ENV)
// make sure... | @@ -9,6 +13,12 @@ export default function myLib(sel) {
// make sure umd helper has been moved to the right position
console.log(`amd function(){ "use strict"; }`)
+
+ // Test pure annotation preservation for tree-shaking
+ // This should preserve the pure annotation comment | playground/lib/src/main.js | 18 | JavaScript | 0.857 | suggestion | 76 | 26 | 19 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
test('@import hoist', async () => {
serverLogs.forEach((log) => {
// no warning from esbuild css minifier
expect(log).not.toMatch('All "@import" rules must come first')
})
})
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readF... | ```suggestion
test('pure annotations are not removed by terser for es', () => {
const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
// Verify that the createObject function is present (not tree-shaken) since it's used
expect(terserEs).toMatch(/Date\.now/)
``` |
test('@import hoist', async () => {
serverLogs.forEach((log) => {
// no warning from esbuild css minifier
expect(log).not.toMatch('All "@import" rules must come first')
})
})
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readF... | @@ -82,6 +82,17 @@ describe.runIf(isBuild)('build', () => {
expect(umd).toMatch('process.env.NODE_ENV')
})
+ test('terser minification for es lib mode', () => {
+ const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
+ expect(terserEs).not.toMatch('console.log')
+ })
+
+ test('pure annot... | playground/lib/__tests__/lib.spec.ts | 26 | TypeScript | 1 | suggestion | 288 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
import { defineConfig } from 'vite'
import baseConfig from './vite.config'
export default defineConfig({
...baseConfig,
build: {
...baseConfig.build,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
outDir: 'dist/terser',
... | @copilot add a test case for `debugger` | import path from 'node:path'
import { defineConfig } from 'vite'
import baseConfig from './vite.config'
export default defineConfig({
...baseConfig,
build: {
...baseConfig.build,
minify: 'terser',
terserOptions: {
compress: {
drop_debugger: true,
},
},
outDir: 'dist/terser',... | @@ -0,0 +1,23 @@
+import { defineConfig } from 'vite'
+import baseConfig from './vite.config'
+
+export default defineConfig({
+ ...baseConfig,
+ build: {
+ ...baseConfig.build,
+ minify: 'terser',
+ terserOptions: {
+ compress: {
+ drop_console: true,
+ drop_debugger: true, | playground/lib/vite.terser.config.js | 12 | JavaScript | 0.571 | bug | 39 | 24 | 25 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
function createObject() {
return { created: Date.now() }
}
export default /* @__PURE__ */ Object.assign(
function myLib(sel) {
// Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951)
console.log({ ...'foo' })
document.querySelector(sel).textContent = 'It works'
// Env vars s... | @copilot This part can now be removed | export default /* @__PURE__ */ Object.assign(function myLib(sel) {
// Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951)
console.log({ ...'foo' })
document.querySelector(sel).textContent = 'It works'
// Env vars should not be replaced
console.log(process.env.NODE_ENV)
// make sure... | @@ -1,15 +1,27 @@
-export default function myLib(sel) {
- // Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951)
- console.log({ ...'foo' })
+function createObject() {
+ return { created: Date.now() }
+}
- document.querySelector(sel).textContent = 'It works'
+export default /* @__PURE__ */ ... | playground/lib/src/main.js | 21 | JavaScript | 0.286 | suggestion | 37 | 28 | 19 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
})
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readFile('dist/my-lib-custom-filename.iife.js')
const umd = readFile('dist/my-lib-custom-filename.umd.cjs')
expect(es).toMatch('process.env.NODE_ENV')
expect(iife).toMatch('process.env.NOD... | ```suggestion
expect(terserEs).toMatch(/[@#]__PURE__/)
``` | })
test('preserve process.env', () => {
const es = readFile('dist/my-lib-custom-filename.js')
const iife = readFile('dist/my-lib-custom-filename.iife.js')
const umd = readFile('dist/my-lib-custom-filename.umd.cjs')
expect(es).toMatch('process.env.NODE_ENV')
expect(iife).toMatch('process.env.NOD... | @@ -82,6 +82,23 @@ describe.runIf(isBuild)('build', () => {
expect(umd).toMatch('process.env.NODE_ENV')
})
+ test('terser minification for es lib mode', () => {
+ const terserEs = readFile('dist/terser/my-lib-custom-filename.js')
+ // Console.log should remain since drop_console was removed
+ expect... | playground/lib/__tests__/lib.spec.ts | 26 | TypeScript | 0.857 | suggestion | 64 | 51 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
import { defineConfig } from 'vite'
import baseConfig from './vite.config'
export default defineConfig({
...baseConfig,
build: {
...baseConfig.build,
minify: 'terser',
terserOptions: {
compress: {
drop_debugger: true,
},
},
outDir: 'dist/terser',
lib: {
...baseConf... | ```suggestion
...baseConfig.build.lib,
entry: baseConfig.build.lib.entry!,
``` | import path from 'node:path'
import { defineConfig } from 'vite'
import baseConfig from './vite.config'
export default defineConfig({
...baseConfig,
build: {
...baseConfig.build,
minify: 'terser',
terserOptions: {
compress: {
drop_debugger: true,
},
},
outDir: 'dist/terser',... | @@ -0,0 +1,22 @@
+import { defineConfig } from 'vite'
+import baseConfig from './vite.config'
+
+export default defineConfig({
+ ...baseConfig,
+ build: {
+ ...baseConfig.build,
+ minify: 'terser',
+ terserOptions: {
+ compress: {
+ drop_debugger: true,
+ },
+ },
+ outDir: 'dist/terser... | playground/lib/vite.terser.config.js | 17 | JavaScript | 0.857 | suggestion | 93 | 23 | 25 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
async renderChunk(code, _chunk, outputOptions) {
// This plugin is included for any non-false value of config.build.minify,
// so that normal chunks can use the preferred minifier, and legacy chunks
// can use terser.
if (
config.build.minify !== 'terser' &&
// @ts-expect-er... | I think we should also respect the user's `preserve_annotations` config if they're not building a library in ES output. E.g. if they enable `preserve_annotations` explicitly for other things, this would've always force it to `false`. |
applyToEnvironment(environment) {
// We also need the plugin even if minify isn't 'terser' as we force
// terser in plugin-legacy
return !!environment.config.build.minify
},
async renderChunk(code, chunk, outputOptions) {
// This plugin is included for any non-false value of config... | @@ -90,19 +90,19 @@ export function terserPlugin(config: ResolvedConfig): Plugin {
return null
}
- // Do not minify ES lib output since that would remove pure annotations
- // and break tree-shaking.
- if (config.build.lib && outputOptions.format === 'es') {
- return null
- ... | packages/vite/src/node/plugins/terser.ts | 26 | TypeScript | 0.786 | suggestion | 233 | 42 | 51 | false | feat(lib): enable minification but keep pure annotations for es output with terser | 20,522 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
)
}
}
}
}
}
debug?.(
`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`,
)
return successfulResult
})
.catch((e) => {
if (e.errors && e.message.includes('The build wa... | Use this code
https://github.com/vitejs/vite/blob/c12a4a76a299237a0a13b885c72fdda6e4a3c9b7/packages/vite/src/node/optimizer/scan.ts#L182-L196 | )
}
}
}
}
}
debug?.(
`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`,
)
return successfulResult
})
.catch(async (e) => {
if (e.errors && e.message.includes('The bu... | @@ -730,7 +730,12 @@ export function runOptimizeDeps(
// return an empty result instead
return cancelledResult
}
- throw e
+ // Add context about dependency optimization to make errors clearer
+ const depOptError = new Error(
+ `Error during dependency optimi... | packages/vite/src/node/optimizer/index.ts | 26 | TypeScript | 0.5 | performance | 141 | 51 | 51 | false | feat(optimizer): improve dependency optimization error messages with esbuild formatMessages | 20,525 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
jsPath,
js.slice(0, js.lastIndexOf('//# sourceMappingURL=')),
)
}
}
}
}
}
debug?.(
`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`,
)
return suc... | ```suggestion
const prependMessage = colors.red('Error during dependency optimization:\n\n')
```
I think this can be a bit shorter so it doesn't take up multiple lines, and as there's no interpolation. | jsPath,
js.slice(0, js.lastIndexOf('//# sourceMappingURL=')),
)
}
}
}
}
}
debug?.(
`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`,
)
return suc... | @@ -724,12 +724,25 @@ export function runOptimizeDeps(
return successfulResult
})
- .catch((e) => {
+ .catch(async (e) => {
if (e.errors && e.message.includes('The build was canceled')) {
// esbuild logs an error when cancelling, but this is expected so
// retu... | packages/vite/src/node/optimizer/index.ts | 26 | TypeScript | 1 | suggestion | 210 | 51 | 51 | false | feat(optimizer): improve dependency optimization error messages with esbuild formatMessages | 20,525 | vitejs/vite | 78,557 | TypeScript | bluwy | Copilot |
node.meta = undefined
node.map = undefined
node.promise = undefined
node.exports = undefined
// remove imports in case they are changed,
// don't remove the importers because otherwise it will be empty after evaluation
// this can create a bug when file was removed but it still triggers full... | @copilot revert the regex pattern change | }
public invalidateModule(node: EvaluatedModuleNode): void {
node.evaluated = false
node.meta = undefined
node.map = undefined
node.promise = undefined
node.exports = undefined
// remove imports in case they are changed,
// don't remove the importers because otherwise it will be empty a... | @@ -108,12 +104,30 @@ export class EvaluatedModules {
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
- const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
- mod.meta.code,
- )?.[1]
+
+ // Find the last occurrence of sourceMapping... | packages/vite/src/module-runner/evaluatedModules.ts | 26 | TypeScript | 0.286 | suggestion | 40 | 51 | 51 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
node.evaluated = false
node.meta = undefined
node.map = undefined
node.promise = undefined
node.exports = undefined
// remove imports in case they are changed,
// don't remove the importers because otherwise it will be empty after evaluation
// this can create a bug when file was removed... | @copilot keep this regex hoisted | return moduleNode
}
public invalidateModule(node: EvaluatedModuleNode): void {
node.evaluated = false
node.meta = undefined
node.map = undefined
node.promise = undefined
node.exports = undefined
// remove imports in case they are changed,
// don't remove the importers because otherw... | @@ -108,12 +104,30 @@ export class EvaluatedModules {
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
- const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
- mod.meta.code,
- )?.[1]
+
+ // Find the last occurrence of sourceMapping... | packages/vite/src/module-runner/evaluatedModules.ts | 26 | TypeScript | 0.071 | suggestion | 32 | 51 | 51 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
// we are fine with the bug for now because it's not a common case
node.imports.clear()
}
/**
* Extracts the inlined source map from the module code and returns the decoded
* source map. If the source map is not inlined, it will return null.
* @param id Resolved module ID
*/
getModuleSourceMa... | @copilot find the line by `.lastIndexOf` and try matching each lines | node.exports = undefined
// remove imports in case they are changed,
// don't remove the importers because otherwise it will be empty after evaluation
// this can create a bug when file was removed but it still triggers full-reload
// we are fine with the bug for now because it's not a common case
... | @@ -108,12 +104,30 @@ export class EvaluatedModules {
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
- const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
- mod.meta.code,
- )?.[1]
+
+ // Find the last occurrence of sourceMapping... | packages/vite/src/module-runner/evaluatedModules.ts | 26 | TypeScript | 0.571 | suggestion | 68 | 51 | 51 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
/**
* Extracts the inlined source map from the module code and returns the decoded
* source map. If the source map is not inlined, it will return null.
* @param id Resolved module ID
*/
getModuleSourceMapById(id: string): DecodedMap | null {
const mod = this.getModuleById(id)
if (!mod) return nu... | ```suggestion
const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(mod.meta.code.slice(lastIndex))?.[1]
```
@copilot actually this should be fine
| /**
* Extracts the inlined source map from the module code and returns the decoded
* source map. If the source map is not inlined, it will return null.
* @param id Resolved module ID
*/
getModuleSourceMapById(id: string): DecodedMap | null {
const mod = this.getModuleById(id)
if (!mod) return nu... | @@ -108,12 +108,31 @@ export class EvaluatedModules {
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
- const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
- mod.meta.code,
- )?.[1]
+
+ // Find the last occurrence of sourceMapping... | packages/vite/src/module-runner/evaluatedModules.ts | 26 | TypeScript | 1 | suggestion | 159 | 51 | 51 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
if (!mod.meta || !('code' in mod.meta)) return null
// Find the last occurrence of sourceMappingURL by finding the last line that contains it
const pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`
const lastIndex = mod.meta.code.lastIndexOf(pattern)
if (lastIndex === -1) return nu... | @copilot actually let's keep this part as-is | if (!mod.meta || !('code' in mod.meta)) return null
const pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`
const lastIndex = mod.meta.code.lastIndexOf(pattern)
if (lastIndex === -1) return null
const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
mod.meta.code.slice(l... | @@ -108,12 +108,31 @@ export class EvaluatedModules {
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
- const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
- mod.meta.code,
- )?.[1]
+
+ // Find the last occurrence of sourceMapping... | packages/vite/src/module-runner/evaluatedModules.ts | 26 | TypeScript | 0.071 | suggestion | 44 | 51 | 49 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
*/
getModuleSourceMapById(id: string): DecodedMap | null {
const mod = this.getModuleById(id)
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
// Find the last occurrence of sourceMappingURL by finding the last line that contains it
cons... | ```suggestion
mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file)
return mod.map
``` | */
getModuleSourceMapById(id: string): DecodedMap | null {
const mod = this.getModuleById(id)
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
const pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`
const lastIndex = mod... | @@ -108,12 +108,26 @@ export class EvaluatedModules {
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
+
+ // Find the last occurrence of sourceMappingURL by finding the last line that contains it
+ const pattern = `//# ${SOURCEMAPPING_URL}=data:... | packages/vite/src/module-runner/evaluatedModules.ts | 26 | TypeScript | 1 | suggestion | 115 | 51 | 51 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
it('deep stacktrace', async ({ runner, server }) => {
const methodError = await getError(async () => {
const mod = await runner.import('/fixtures/has-error-deep.ts')
mod.main()
})
expect(serializeStackDeep(server, methodError).slice(0, 3)).toEqual([
'Error: crash',
' at crash (... | @copilot Add a fixture and use `await getError` like above. |
it('deep stacktrace', async ({ runner, server }) => {
const methodError = await getError(async () => {
const mod = await runner.import('/fixtures/has-error-deep.ts')
mod.main()
})
expect(serializeStackDeep(server, methodError).slice(0, 3)).toEqual([
'Error: crash',
' at crash (... | @@ -93,4 +93,24 @@ describe('module runner initialization', async () => {
' at Module.main (<root>/fixtures/has-error-deep.ts:6:3)',
])
})
+
+ it('should not crash when sourceMappingURL pattern appears in string literals', async ({
+ runner,
+ }) => {
+ const modules = runner.evaluatedModules
... | packages/vite/src/node/ssr/runtime/__tests__/server-source-maps.spec.ts | 26 | TypeScript | 0.857 | suggestion | 59 | 34 | 30 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
// This file contains sourceMappingURL pattern in string literals
// which should not crash the module runner
const text = '//# sourceMappingURL=data:application/json;base64,invalidbase64'
console.log(text)
export function getMessage() {
return text
}
| @copilot also add a function that throws an error to test the stacktrace | // This file contains sourceMappingURL pattern in string literals
// which should not crash the module runner
const text = '//# sourceMappingURL=data:application/json;base64,invalidbase64'
export function getMessage() {
return text
}
export function throwError() {
throw new Error('Test error for stacktrace')
}
| @@ -0,0 +1,9 @@
+// This file contains sourceMappingURL pattern in string literals
+// which should not crash the module runner
+
+const text = '//# sourceMappingURL=data:application/json;base64,invalidbase64'
+console.log(text)
+
+export function getMessage() {
+ return text
+} | packages/vite/src/node/ssr/runtime/__tests__/fixtures/string-literal-sourcemap.ts | 8 | TypeScript | 0.429 | suggestion | 72 | 10 | 13 | false | fix(module-runner): prevent crash when sourceMappingURL pattern appears in string literals | 20,554 | vitejs/vite | 78,557 | TypeScript | sapphi-red | Copilot |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.