Skip to content

Commit

Permalink
chore: rename to BaseEnvironment (#16797)
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudBarre authored May 23, 2024
1 parent 4d03124 commit d86553a
Show file tree
Hide file tree
Showing 19 changed files with 204 additions and 193 deletions.
4 changes: 2 additions & 2 deletions packages/vite/src/node/__tests__/external.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url'
import { describe, expect, test } from 'vitest'
import { resolveConfig } from '../config'
import { createIsConfiguredAsExternal } from '../external'
import { Environment } from '../environment'
import { PartialEnvironment } from '../baseEnvironment'

describe('createIsConfiguredAsExternal', () => {
test('default', async () => {
Expand All @@ -25,6 +25,6 @@ async function createIsExternal(external?: true) {
},
'serve',
)
const environment = new Environment('ssr', resolvedConfig)
const environment = new PartialEnvironment('ssr', resolvedConfig)
return createIsConfiguredAsExternal(environment)
}
5 changes: 2 additions & 3 deletions packages/vite/src/node/__tests__/plugins/css.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, test, vi } from 'vitest'
import { resolveConfig } from '../../config'
import { Environment } from '../../environment'
import type { PluginEnvironment } from '../../plugin'
import type { InlineConfig } from '../../config'
import {
convertTargets,
Expand All @@ -12,6 +10,7 @@ import {
getEmptyChunkReplacer,
hoistAtRules,
} from '../../plugins/css'
import { PartialEnvironment } from '../../baseEnvironment'

describe('search css url function', () => {
test('some spaces before it', () => {
Expand Down Expand Up @@ -215,7 +214,7 @@ async function createCssPluginTransform(
inlineConfig: InlineConfig = {},
) {
const config = await resolveConfig(inlineConfig, 'serve')
const environment = new Environment('client', config) as PluginEnvironment
const environment = new PartialEnvironment('client', config)

const { transform, buildStart } = cssPlugin(config)

Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/__tests__/plugins/define.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'vitest'
import { definePlugin } from '../../plugins/define'
import { resolveConfig } from '../../config'
import { Environment } from '../../environment'
import { PartialEnvironment } from '../../baseEnvironment'

async function createDefinePluginTransform(
define: Record<string, any> = {},
Expand All @@ -13,7 +13,7 @@ async function createDefinePluginTransform(
build ? 'build' : 'serve',
)
const instance = definePlugin(config)
const environment = new Environment(ssr ? 'ssr' : 'client', config)
const environment = new PartialEnvironment(ssr ? 'ssr' : 'client', config)

return async (code: string) => {
// @ts-expect-error transform should exist
Expand Down
103 changes: 103 additions & 0 deletions packages/vite/src/node/baseEnvironment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import colors from 'picocolors'
import type { Logger } from './logger'
import type { ResolvedConfig, ResolvedEnvironmentOptions } from './config'
import type { EnvironmentPlugin } from './plugin'

export class PartialEnvironment {
name: string
config: ResolvedConfig
options: ResolvedEnvironmentOptions
logger: Logger

constructor(
name: string,
config: ResolvedConfig,
options: ResolvedEnvironmentOptions = config.environments[name],
) {
this.name = name
this.config = config
this.options = options
const environment = colors.dim(`(${this.name})`)
const colorIndex =
[...environment].reduce((acc, c) => acc + c.charCodeAt(0), 0) %
environmentColors.length
const infoColor = environmentColors[colorIndex || 0]
this.logger = {
get hasWarned() {
return config.logger.hasWarned
},
info(msg, opts) {
return config.logger.info(msg, {
...opts,
environment: infoColor(environment),
})
},
warn(msg, opts) {
return config.logger.warn(msg, {
...opts,
environment: colors.yellow(environment),
})
},
warnOnce(msg, opts) {
return config.logger.warnOnce(msg, {
...opts,
environment: colors.yellow(environment),
})
},
error(msg, opts) {
return config.logger.error(msg, {
...opts,
environment: colors.red(environment),
})
},
clearScreen(type) {
return config.logger.clearScreen(type)
},
hasErrorLogged(error) {
return config.logger.hasErrorLogged(error)
},
}
}
}

export class BaseEnvironment extends PartialEnvironment {
get plugins(): EnvironmentPlugin[] {
if (!this._plugins)
throw new Error(
`${this.name} environment.plugins called before initialized`,
)
return this._plugins
}

/**
* @internal
*/
_plugins: EnvironmentPlugin[] | undefined
/**
* @internal
*/
_initiated: boolean = false

constructor(
name: string,
config: ResolvedConfig,
options: ResolvedEnvironmentOptions = config.environments[name],
) {
super(name, config, options)
}
}

/**
* This is used both to avoid users to hardcode conditions like
* !scan && !build => dev
*/
export class FutureCompatEnvironment extends BaseEnvironment {
mode = 'futureCompat' as const
}

const environmentColors = [
colors.blue,
colors.magenta,
colors.green,
colors.gray,
]
8 changes: 4 additions & 4 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ import { completeSystemWrapPlugin } from './plugins/completeSystemWrap'
import { mergeConfig } from './publicUtils'
import { webWorkerPostPlugin } from './plugins/worker'
import { getHookHandler } from './plugins'
import { Environment } from './environment'
import { BaseEnvironment } from './baseEnvironment'
import type { Plugin, PluginContext } from './plugin'
import type { RollupPluginHooks } from './typeUtils'

Expand Down Expand Up @@ -1458,7 +1458,7 @@ function areSeparateFolders(a: string, b: string) {
)
}

export class BuildEnvironment extends Environment {
export class BuildEnvironment extends BaseEnvironment {
mode = 'build' as const

constructor(
Expand All @@ -1481,10 +1481,10 @@ export class BuildEnvironment extends Environment {
}

async init(): Promise<void> {
if (this._inited) {
if (this._initiated) {
return
}
this._inited = true
this._initiated = true
this._plugins = await resolveEnvironmentPlugins(this)
}
}
Expand Down
7 changes: 2 additions & 5 deletions packages/vite/src/node/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { ServerOptions } from './server'
import type { CLIShortcut } from './shortcuts'
import type { LogLevel } from './logger'
import { createLogger } from './logger'
import { resolveConfig } from './config'

const cli = cac('vite')

Expand Down Expand Up @@ -339,8 +340,6 @@ cli
)
.action(
async (root: string, options: { force?: boolean } & GlobalCLIOptions) => {
/* TODO: do we need this command?
filterDuplicateOptions(options)
const { optimizeDeps } = await import('./optimizer')
try {
Expand All @@ -354,16 +353,14 @@ cli
},
'serve',
)
const environment = new Environment('client', config)
await optimizeDeps(environment, options.force, true)
await optimizeDeps(config, options.force, true)
} catch (e) {
createLogger(options.logLevel).error(
colors.red(`error when optimizing deps:\n${e.stack}`),
{ error: e },
)
process.exit(1)
}
*/
},
)

Expand Down
10 changes: 4 additions & 6 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import {
import type {
HookHandler,
Plugin,
PluginEnvironment,
PluginOption,
PluginWithRequiredHook,
} from './plugin'
Expand All @@ -43,7 +42,6 @@ import {
} from './build'
import type { ResolvedServerOptions, ServerOptions } from './server'
import { resolveServerOptions } from './server'
import { Environment } from './environment'
import type { DevEnvironment } from './server/environment'
import type { PreviewOptions, ResolvedPreviewOptions } from './preview'
import { resolvePreviewOptions } from './preview'
Expand Down Expand Up @@ -89,6 +87,7 @@ import { findNearestPackageData } from './packages'
import { loadEnv, resolveEnvPrefix } from './env'
import type { ResolvedSSROptions, SSROptions } from './ssr'
import { resolveSSROptions } from './ssr'
import { FutureCompatEnvironment } from './baseEnvironment'

const debug = createDebugger('vite:config')
const promisifiedRealpath = promisify(fs.realpath)
Expand Down Expand Up @@ -1223,11 +1222,10 @@ export async function resolveConfig(
plugins: Plugin[],
) => {
// The used alias and resolve plugins only use configuration options from the
// environment so we can safely cast to a base Environment instance to a
// PluginEnvironment here
const environment = new Environment(environmentName, this)
// environment so we can safely just use the FutureCompatEnvironment here
const environment = new FutureCompatEnvironment(environmentName, this)
const pluginContainer = await createEnvironmentPluginContainer(
environment as PluginEnvironment,
environment,
plugins,
)
await pluginContainer.buildStart({})
Expand Down
101 changes: 9 additions & 92 deletions packages/vite/src/node/environment.ts
Original file line number Diff line number Diff line change
@@ -1,96 +1,13 @@
import colors from 'picocolors'
import type { Logger } from './logger'
import type { ResolvedConfig, ResolvedEnvironmentOptions } from './config'
import type { EnvironmentPlugin } from './plugin'
import type { DevEnvironment } from './server/environment'
import type { BuildEnvironment } from './build'
import type { ScanEnvironment } from './optimizer/scan'
import { type FutureCompatEnvironment } from './baseEnvironment'

export class Environment {
name: string

config: ResolvedConfig
options: ResolvedEnvironmentOptions

get plugins(): EnvironmentPlugin[] {
if (!this._plugins)
throw new Error(
`${this.name} environment.plugins called before initialized`,
)
return this._plugins
}
/**
* @internal
*/
_plugins: EnvironmentPlugin[] | undefined
/**
* @internal
*/
_inited: boolean = false

#logger: Logger | undefined
get logger(): Logger {
if (this.#logger) {
return this.#logger
}
const environment = colors.dim(`(${this.name})`)
const colorIndex =
Number([...environment].map((c) => c.charCodeAt(0))) %
environmentColors.length
const infoColor = environmentColors[colorIndex || 0]
const logger = this.config.logger
this.#logger = {
get hasWarned() {
return logger.hasWarned
},
info(msg, opts) {
return logger.info(msg, {
...opts,
environment: infoColor(environment),
})
},
warn(msg, opts) {
return logger.warn(msg, {
...opts,
environment: colors.yellow(environment),
})
},
warnOnce(msg, opts) {
return logger.warnOnce(msg, {
...opts,
environment: colors.yellow(environment),
})
},
error(msg, opts) {
return logger.error(msg, {
...opts,
environment: colors.red(environment),
})
},
clearScreen(type) {
return logger.clearScreen(type)
},
hasErrorLogged(error) {
return logger.hasErrorLogged(error)
},
}
return this.#logger
}

constructor(
name: string,
config: ResolvedConfig,
options: ResolvedEnvironmentOptions = config.environments[name],
) {
this.name = name
this.config = config
this.options = options
}
}

const environmentColors = [
colors.blue,
colors.magenta,
colors.green,
colors.gray,
]
export type Environment =
| DevEnvironment
| BuildEnvironment
| ScanEnvironment
| FutureCompatEnvironment

export function cachedByEnvironment<Data>(
create: (environment: Environment) => Data,
Expand Down
3 changes: 2 additions & 1 deletion packages/vite/src/node/external.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
isBuiltin,
} from './utils'
import type { Environment } from './environment'
import type { PartialEnvironment } from './baseEnvironment'

const debug = createDebugger('vite:external')

Expand Down Expand Up @@ -49,7 +50,7 @@ export function isConfiguredAsExternal(
}

export function createIsConfiguredAsExternal(
environment: Environment,
environment: PartialEnvironment,
): (id: string, importer?: string) => boolean {
const { config, options } = environment
const { root } = config
Expand Down
Loading

0 comments on commit d86553a

Please sign in to comment.