Skip to content

Commit

Permalink
refactor: enable no-unnecessary-condition
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Nov 27, 2024
1 parent 26cc678 commit 16ecfc9
Show file tree
Hide file tree
Showing 50 changed files with 238 additions and 245 deletions.
13 changes: 13 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,16 @@ export default tseslint.config(
'@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/prefer-for-of': 'off',
'@typescript-eslint/prefer-function-type': 'off',
...(shouldTypeCheck
? {
'@typescript-eslint/no-unnecessary-condition': [
'error',
{
allowConstantLoopConditions: true,
},
],
}
: {}),

'import-x/no-nodejs-modules': [
'error',
Expand Down Expand Up @@ -346,5 +356,8 @@ export default tseslint.config(
project: false,
},
},
rules: {
'@typescript-eslint/no-unnecessary-condition': 'off',
},
},
)
10 changes: 5 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,7 @@ async function init() {
}),
},
{
type: (framework: Framework) =>
framework && framework.variants ? 'select' : null,
type: 'select',
name: 'variant',
message: reset('Select a variant:'),
choices: (framework: Framework) =>
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-legacy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,7 @@ function wrapIIFEBabelPlugin(): BabelPlugin {
}

const hash =
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
// eslint-disable-next-line n/no-unsupported-features/node-builtins, @typescript-eslint/no-unnecessary-condition -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
crypto.hash ??
((
algorithm: string,
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ const hasDocument = 'document' in globalThis
function createErrorOverlay(err: ErrorPayload['err']) {
clearErrorOverlay()
const { customElements } = globalThis
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (customElements) {
const ErrorOverlayConstructor = customElements.get(overlayId)!
document.body.appendChild(new ErrorOverlayConstructor(err))
Expand Down
31 changes: 15 additions & 16 deletions packages/vite/src/client/overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,23 +267,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 All @@ -295,6 +293,7 @@ export class ErrorOverlay extends HTMLElement {

export const overlayId = 'vite-error-overlay'
const { customElements } = globalThis // Ensure `customElements` is defined before the next line.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (customElements && !customElements.get(overlayId)) {
customElements.define(overlayId, ErrorOverlay)
}
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
1 change: 1 addition & 0 deletions packages/vite/src/module-runner/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ export class ModuleRunner {

const { code, file } = fetchResult

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- is this needed?
if (code == null) {
const importer = callstack[callstack.length - 2]
throw new Error(
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/module-runner/sourcemap/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export function enableSourceMapSupport(runner: ModuleRunner): () => void {
`Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`,
)
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- process.sourceMapsEnabled is not available in Node < 20.7.0
const isEnabledAlready = process.sourceMapsEnabled ?? false
process.setSourceMapsEnabled(true)
return () => !isEnabledAlready && process.setSourceMapsEnabled(false)
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/module-runner/sourcemap/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,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 Expand Up @@ -351,7 +351,7 @@ function cloneCallSite(frame: CallSite) {
}

function wrapCallSite(frame: CallSite, state: State) {
// provides interface backward compatibility
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- provides interface backward compatibility
if (state === undefined) state = { nextPosition: null, curPosition: null }

if (frame.isNative()) {
Expand Down
18 changes: 9 additions & 9 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ export function resolveBuildEnvironmentOptions(
// Backward compatibility
isSsrTargetWebworkerEnvironment?: boolean,
): ResolvedBuildEnvironmentOptions {
const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload
const deprecatedPolyfillModulePreload = raw.polyfillModulePreload
const { polyfillModulePreload, ...rest } = raw
raw = rest
if (deprecatedPolyfillModulePreload !== undefined) {
Expand Down Expand Up @@ -454,7 +454,6 @@ export function resolveBuildEnvironmentOptions(
}

if (isSsrTargetWebworkerEnvironment) {
resolved.rollupOptions ??= {}
resolved.rollupOptions.output ??= {}
const output = resolved.rollupOptions.output
for (const out of arraify(output)) {
Expand Down Expand Up @@ -558,7 +557,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 @@ -571,7 +570,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 @@ -611,7 +610,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 @@ -751,7 +750,7 @@ async function buildEnvironment(

// resolve lib mode outputs
const outputs = resolveBuildOutputs(
options.rollupOptions?.output,
options.rollupOptions.output,
libOptions,
logger,
)
Expand All @@ -768,7 +767,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 @@ -1066,7 +1065,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 @@ -1234,6 +1233,7 @@ function injectEnvironmentInContext<Context extends MinimalPluginContext>(
context: Context,
environment: BuildEnvironment,
) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- context.environment is undefined here
context.environment ??= environment
return context
}
Expand Down Expand Up @@ -1449,7 +1449,7 @@ export class BuildEnvironment extends BaseEnvironment {
if (setup?.options) {
options = mergeConfig(
options,
setup?.options,
setup.options,
) as ResolvedEnvironmentOptions
}
super(name, config, options)
Expand Down
52 changes: 21 additions & 31 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 @@ -1006,7 +1007,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 @@ -1020,7 +1021,7 @@ export async function resolveConfig(

// resolve plugins
const rawPlugins = (
(await asyncFlatten(config.plugins || [])) as Plugin[]
(await asyncFlatten(config.plugins || [])) as Array<Plugin | FalsyPlugin>
).filter(filterPlugin)

const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawPlugins)
Expand Down Expand Up @@ -1072,12 +1073,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 All @@ -1103,11 +1104,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 @@ -1240,7 +1237,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 @@ -1573,7 +1570,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 @@ -1840,7 +1837,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 @@ -1913,11 +1910,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 @@ -1934,15 +1929,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 @@ -1956,7 +1949,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 All @@ -1976,10 +1969,7 @@ function optimizeDepsDisabledBackwardCompatibility(
}
`),
)
} else if (
optimizeDepsDisabled === false ||
optimizeDepsDisabled === 'build'
) {
} else {
resolved.logger.warn(
colors.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
Setting it to ${optimizeDepsDisabled} now has no effect.
Expand Down
Loading

0 comments on commit 16ecfc9

Please sign in to comment.