Skip to content

Commit

Permalink
refactor: fix logic errors found by no-unnecessary-condition rule (#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Dec 5, 2024
1 parent 690a36f commit ea802f8
Show file tree
Hide file tree
Showing 35 changed files with 172 additions and 205 deletions.
11 changes: 6 additions & 5 deletions packages/create-vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,9 +289,10 @@ const FRAMEWORKS: Framework[] = [
},
]

const TEMPLATES = FRAMEWORKS.map(
(f) => (f.variants && f.variants.map((v) => v.name)) || [f.name],
).reduce((a, b) => a.concat(b), [])
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',
Expand Down Expand Up @@ -394,8 +395,8 @@ async function init() {
}),
},
{
type: (framework: Framework) =>
framework && framework.variants ? 'select' : null,
type: (framework: Framework | /* package name */ string) =>
typeof framework === 'object' ? 'select' : null,
name: 'variant',
message: reset('Select a variant:'),
choices: (framework: Framework) =>
Expand Down
30 changes: 14 additions & 16 deletions packages/vite/src/client/overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,23 +264,21 @@ export class ErrorOverlay extends HTMLElement {
fileRE.lastIndex = 0
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match
if (index != null) {
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch(
new URL(
`${base}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url,
),
)
}
el.appendChild(link)
curIndex += frag.length + file.length
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch(
new URL(
`${base}__open-in-editor?file=${encodeURIComponent(file)}`,
import.meta.url,
),
)
}
el.appendChild(link)
curIndex += frag.length + file.length
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/module-runner/hmrHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,11 @@ function getModulesEntrypoints(
if (!module) {
continue
}
if (module.importers && !module.importers.size) {
if (!module.importers.size) {
entrypoints.add(module.url)
continue
}
for (const importer of module.importers || []) {
for (const importer of module.importers) {
getModulesEntrypoints(runner, [importer], visited, entrypoints)
}
}
Expand All @@ -167,7 +167,7 @@ function findAllEntrypoints(
entrypoints = new Set<string>(),
): Set<string> {
for (const mod of runner.evaluatedModules.idToModuleMap.values()) {
if (mod.importers && !mod.importers.size) {
if (!mod.importers.size) {
entrypoints.add(mod.url)
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/module-runner/sourcemap/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ function mapSourcePosition(position: OriginalMapping) {
}

// Resolve the source URL relative to the URL of the source map
if (sourceMap && sourceMap.map && sourceMap.url) {
if (sourceMap.map && sourceMap.url) {
const originalPosition = getOriginalPosition(sourceMap.map, position)

// Only return the original position if a matching line was found. If no
Expand Down
16 changes: 8 additions & 8 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ export function resolveBuildEnvironmentOptions(
logger: Logger,
consumer: 'client' | 'server' | undefined,
): ResolvedBuildEnvironmentOptions {
const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload
const deprecatedPolyfillModulePreload = raw.polyfillModulePreload
const { polyfillModulePreload, ...rest } = raw
raw = rest
if (deprecatedPolyfillModulePreload !== undefined) {
Expand Down Expand Up @@ -543,7 +543,7 @@ async function buildEnvironment(

const resolve = (p: string) => path.resolve(root, p)
const input = libOptions
? options.rollupOptions?.input ||
? options.rollupOptions.input ||
(typeof libOptions.entry === 'string'
? resolve(libOptions.entry)
: Array.isArray(libOptions.entry)
Expand All @@ -556,7 +556,7 @@ async function buildEnvironment(
))
: typeof options.ssr === 'string'
? resolve(options.ssr)
: options.rollupOptions?.input || resolve('index.html')
: options.rollupOptions.input || resolve('index.html')

if (ssr && typeof input === 'string' && input.endsWith('.html')) {
throw new Error(
Expand Down Expand Up @@ -596,7 +596,7 @@ async function buildEnvironment(
output: options.rollupOptions.output,
input,
plugins,
external: options.rollupOptions?.external,
external: options.rollupOptions.external,
onwarn(warning, warn) {
onRollupWarning(warning, warn, environment)
},
Expand Down Expand Up @@ -743,7 +743,7 @@ async function buildEnvironment(

// resolve lib mode outputs
const outputs = resolveBuildOutputs(
options.rollupOptions?.output,
options.rollupOptions.output,
libOptions,
logger,
)
Expand All @@ -760,7 +760,7 @@ async function buildEnvironment(
const resolvedOutDirs = getResolvedOutDirs(
root,
options.outDir,
options.rollupOptions?.output,
options.rollupOptions.output,
)
const emptyOutDir = resolveEmptyOutDir(
options.emptyOutDir,
Expand Down Expand Up @@ -1058,7 +1058,7 @@ export function onRollupWarning(
}

clearLine()
const userOnWarn = environment.config.build.rollupOptions?.onwarn
const userOnWarn = environment.config.build.rollupOptions.onwarn
if (userOnWarn) {
userOnWarn(warning, viteWarn)
} else {
Expand Down Expand Up @@ -1441,7 +1441,7 @@ export class BuildEnvironment extends BaseEnvironment {
if (setup?.options) {
options = mergeConfig(
options,
setup?.options,
setup.options,
) as ResolvedEnvironmentOptions
}
super(name, config, options)
Expand Down
53 changes: 23 additions & 30 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
FS_PREFIX,
} from './constants'
import type {
FalsyPlugin,
HookHandler,
Plugin,
PluginOption,
Expand Down Expand Up @@ -1002,7 +1003,7 @@ export async function resolveConfig(
mode = inlineConfig.mode || config.mode || mode
configEnv.mode = mode

const filterPlugin = (p: Plugin) => {
const filterPlugin = (p: Plugin | FalsyPlugin): p is Plugin => {
if (!p) {
return false
} else if (!p.apply) {
Expand All @@ -1015,9 +1016,9 @@ export async function resolveConfig(
}

// resolve plugins
const rawPlugins = (
(await asyncFlatten(config.plugins || [])) as Plugin[]
).filter(filterPlugin)
const rawPlugins = (await asyncFlatten(config.plugins || [])).filter(
filterPlugin,
)

const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawPlugins)

Expand Down Expand Up @@ -1068,12 +1069,12 @@ export async function resolveConfig(
// Backward compatibility: server.warmup.clientFiles/ssrFiles -> environment.dev.warmup
const warmupOptions = config.server?.warmup
if (warmupOptions?.clientFiles) {
configEnvironmentsClient.dev.warmup = warmupOptions?.clientFiles
configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles
}
if (warmupOptions?.ssrFiles) {
configEnvironmentsSsr ??= {}
configEnvironmentsSsr.dev ??= {}
configEnvironmentsSsr.dev.warmup = warmupOptions?.ssrFiles
configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles
}

// Backward compatibility: merge ssr into environments.ssr.config as defaults
Expand Down Expand Up @@ -1102,11 +1103,7 @@ export async function resolveConfig(
}

// The client and ssr environment configs can't be removed by the user in the config hook
if (
!config.environments ||
!config.environments.client ||
(!config.environments.ssr && !isBuild)
) {
if (!config.environments.client || (!config.environments.ssr && !isBuild)) {
throw new Error(
'Required environments configuration were stripped out in the config hook',
)
Expand Down Expand Up @@ -1244,7 +1241,7 @@ export async function resolveConfig(
? !isBuild || config.build?.ssr
? '/'
: './'
: (resolveBaseUrl(config.base, isBuild, logger) ?? configDefaults.base)
: resolveBaseUrl(config.base, isBuild, logger)

// resolve cache directory
const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir
Expand Down Expand Up @@ -1301,7 +1298,7 @@ export async function resolveConfig(
// And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
// So we need to separate the worker plugin from the plugin that vite needs to run.
const rawWorkerUserPlugins = (
(await asyncFlatten(createUserWorkerPlugins?.() || [])) as Plugin[]
await asyncFlatten(createUserWorkerPlugins?.() || [])
).filter(filterPlugin)

// resolve worker
Expand Down Expand Up @@ -1577,7 +1574,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter
* electron or expects to deploy
*/
export function resolveBaseUrl(
base: UserConfig['base'] = '/',
base: UserConfig['base'] = configDefaults.base,
isBuild: boolean,
logger: Logger,
): string {
Expand Down Expand Up @@ -1846,7 +1843,7 @@ async function bundleConfigFile(
const { text } = result.outputFiles[0]
return {
code: text,
dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [],
dependencies: Object.keys(result.metafile.inputs),
}
}

Expand Down Expand Up @@ -1934,11 +1931,9 @@ async function runConfigHook(
for (const p of getSortedPluginsByHook('config', plugins)) {
const hook = p.config
const handler = getHookHandler(hook)
if (handler) {
const res = await handler(conf, configEnv)
if (res && res !== conf) {
conf = mergeConfig(conf, res)
}
const res = await handler(conf, configEnv)
if (res && res !== conf) {
conf = mergeConfig(conf, res)
}
}

Expand All @@ -1955,15 +1950,13 @@ async function runConfigEnvironmentHook(
for (const p of getSortedPluginsByHook('configEnvironment', plugins)) {
const hook = p.configEnvironment
const handler = getHookHandler(hook)
if (handler) {
for (const name of environmentNames) {
const res = await handler(name, environments[name], {
...configEnv,
isSsrTargetWebworker: isSsrTargetWebworkerSet && name === 'ssr',
})
if (res) {
environments[name] = mergeConfig(environments[name], res)
}
for (const name of environmentNames) {
const res = await handler(name, environments[name], {
...configEnv,
isSsrTargetWebworker: isSsrTargetWebworkerSet && name === 'ssr',
})
if (res) {
environments[name] = mergeConfig(environments[name], res)
}
}
}
Expand All @@ -1977,7 +1970,7 @@ function optimizeDepsDisabledBackwardCompatibility(
const optimizeDepsDisabled = optimizeDeps.disabled
if (optimizeDepsDisabled !== undefined) {
if (optimizeDepsDisabled === true || optimizeDepsDisabled === 'dev') {
const commonjsOptionsInclude = resolved.build?.commonjsOptions?.include
const commonjsOptionsInclude = resolved.build.commonjsOptions.include
const commonjsPluginDisabled =
Array.isArray(commonjsOptionsInclude) &&
commonjsOptionsInclude.length === 0
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/external.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function createIsConfiguredAsExternal(
!(Array.isArray(noExternal) && noExternal.length === 0) &&
createFilter(undefined, noExternal, { resolve: false })

const targetConditions = resolve.externalConditions || []
const targetConditions = resolve.externalConditions

const resolveOptions: InternalResolveOptions = {
...resolve,
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/esbuildDepPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function esbuildDepPlugin(

// remove optimizable extensions from `externalTypes` list
const allExternalTypes = extensions
? externalTypes.filter((type) => !extensions?.includes('.' + type))
? externalTypes.filter((type) => !extensions.includes('.' + type))
: externalTypes

// use separate package cache for optimizer as it caches paths around node_modules
Expand Down
Loading

0 comments on commit ea802f8

Please # to comment.