Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: cancellable scan during optimization #12225

Merged
merged 3 commits into from
Feb 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
44 changes: 26 additions & 18 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export async function optimizeDeps(
return cachedMetadata
}

const deps = await discoverProjectDependencies(config)
const deps = await (await discoverProjectDependencies(config)).result

const depsString = depsLogString(Object.keys(deps))
log(colors.green(`Optimizing dependencies:\n ${depsString}`))
Expand Down Expand Up @@ -382,24 +382,32 @@ export function loadCachedDepOptimizationMetadata(
*/
export async function discoverProjectDependencies(
config: ResolvedConfig,
): Promise<Record<string, string>> {
const { deps, missing } = await scanImports(config)

const missingIds = Object.keys(missing)
if (missingIds.length) {
throw new Error(
`The following dependencies are imported but could not be resolved:\n\n ${missingIds
.map(
(id) =>
`${colors.cyan(id)} ${colors.white(
colors.dim(`(imported by ${missing[id]})`),
)}`,
): Promise<{
cancel: () => Promise<void>
result: Promise<Record<string, string>>
}> {
const { cancel, result } = await scanImports(config)

return {
cancel,
result: result.then(({ deps, missing }) => {
const missingIds = Object.keys(missing)
if (missingIds.length) {
throw new Error(
`The following dependencies are imported but could not be resolved:\n\n ${missingIds
.map(
(id) =>
`${colors.cyan(id)} ${colors.white(
colors.dim(`(imported by ${missing[id]})`),
)}`,
)
.join(`\n `)}\n\nAre they installed?`,
)
.join(`\n `)}\n\nAre they installed?`,
)
}
}

return deps
return deps
}),
}
}

export function toDiscoveredDependencies(
Expand Down Expand Up @@ -679,7 +687,7 @@ export async function findKnownImports(
config: ResolvedConfig,
ssr: boolean,
): Promise<string[]> {
const deps = (await scanImports(config)).deps
const deps = (await (await scanImports(config)).result).deps
await addManuallyIncludedOptimizeDeps(deps, config, ssr)
return Object.keys(deps)
}
Expand Down
11 changes: 10 additions & 1 deletion packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,18 @@ async function createDepsOptimizer(
let firstRunCalled = !!cachedMetadata

let postScanOptimizationResult: Promise<DepOptimizationResult> | undefined
let discover:
| {
cancel: () => Promise<void>
result: Promise<Record<string, string>>
}
| undefined

let optimizingNewDeps: Promise<DepOptimizationResult> | undefined
async function close() {
closed = true
await Promise.allSettled([
discover?.cancel(),
depsOptimizer.scanProcessing,
postScanOptimizationResult,
optimizingNewDeps,
Expand Down Expand Up @@ -204,7 +211,9 @@ async function createDepsOptimizer(
try {
debug(colors.green(`scanning for dependencies...`))

const deps = await discoverProjectDependencies(config)
discover = await discoverProjectDependencies(config)
const deps = await discover.result
discover = undefined

debug(
colors.green(
Expand Down
89 changes: 54 additions & 35 deletions packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from 'node:path'
import { performance } from 'node:perf_hooks'
import glob from 'fast-glob'
import type { Loader, OnLoadResult, Plugin } from 'esbuild'
import { build, formatMessages, transform } from 'esbuild'
import esbuild, { formatMessages, transform } from 'esbuild'
import colors from 'picocolors'
import type { ResolvedConfig } from '..'
import {
Expand Down Expand Up @@ -48,8 +48,11 @@ export const importsRE =
/(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm

export async function scanImports(config: ResolvedConfig): Promise<{
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is the return type right here? It looks like its returning { cancel, result } and not Promise<{ cancel, result }>

Copy link
Member Author

Choose a reason for hiding this comment

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

I was following @dominikg's PR here. The esbuildContext is only available after waiting for other async operations. But I agree that from a consumer POV, it is better to avoid the double promise, vitejs/vite@5ff8d8b (#12225) avoids this at the expense of a bit more complexity inside scanImports

deps: Record<string, string>
missing: Record<string, string>
cancel: () => Promise<void>
result: Promise<{
deps: Record<string, string>
missing: Record<string, string>
}>
}> {
// Only used to scan non-ssr code

Expand Down Expand Up @@ -93,7 +96,10 @@ export async function scanImports(config: ResolvedConfig): Promise<{
),
)
}
return { deps: {}, missing: {} }
return {
cancel: () => Promise.resolve(),
result: Promise.resolve({ deps: {}, missing: {} }),
}
} else {
debug(`Crawling dependencies using entries:\n ${entries.join('\n ')}`)
}
Expand All @@ -106,44 +112,57 @@ export async function scanImports(config: ResolvedConfig): Promise<{
const { plugins = [], ...esbuildOptions } =
config.optimizeDeps?.esbuildOptions ?? {}

try {
await build({
absWorkingDir: process.cwd(),
write: false,
stdin: {
contents: entries.map((e) => `import ${JSON.stringify(e)}`).join('\n'),
loader: 'js',
},
bundle: true,
format: 'esm',
logLevel: 'silent',
plugins: [...plugins, plugin],
...esbuildOptions,
const esbuildContext = await esbuild.context({
absWorkingDir: process.cwd(),
write: false,
stdin: {
contents: entries.map((e) => `import ${JSON.stringify(e)}`).join('\n'),
loader: 'js',
},
bundle: true,
format: 'esm',
logLevel: 'silent',
plugins: [...plugins, plugin],
...esbuildOptions,
})

const result = esbuildContext
.rebuild()
.then(() => {
return {
// Ensure a fixed order so hashes are stable and improve logs
deps: orderedDependencies(deps),
missing,
}
})
} catch (e) {
const prependMessage = colors.red(`\
.catch(async (e) => {
const prependMessage = colors.red(`\
Failed to scan for dependencies from entries:
${entries.join('\n')}

`)
if (e.errors) {
const msgs = await formatMessages(e.errors, {
kind: 'error',
color: true,
})
e.message = prependMessage + msgs.join('\n')
} else {
e.message = prependMessage + e.message
}
throw e
}

debug(`Scan completed in ${(performance.now() - start).toFixed(2)}ms:`, deps)
if (e.errors) {
const msgs = await formatMessages(e.errors, {
kind: 'error',
color: true,
})
e.message = prependMessage + msgs.join('\n')
} else {
e.message = prependMessage + e.message
}
throw e
})
.finally(() => {
esbuildContext.dispose()
debug(
`Scan completed in ${(performance.now() - start).toFixed(2)}ms:`,
deps,
)
})

return {
// Ensure a fixed order so hashes are stable and improve logs
deps: orderedDependencies(deps),
missing,
cancel: () => esbuildContext.cancel(),
result,
}
}

Expand Down