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: environment api #16129

Merged
merged 118 commits into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
118 commits
Select commit Hold shift + click to select a range
83068fe
feat: separate module graphs per environment
patak-dev Mar 10, 2024
5f5e0ec
feat: abstract moduleGraph into ModuleExecutionEnvironment
patak-dev Mar 10, 2024
281cf97
fix: call updateModules for each environmnet
patak-dev Mar 11, 2024
4808b27
chore: rename server environment to node environment
patak-dev Mar 11, 2024
95ae29b
refactor: move safeModulesPath set to server
patak-dev Mar 11, 2024
d8ff12a
chore: rename module and error back to ssrModule and ssrError
patak-dev Mar 11, 2024
e966ba0
feat: add `hot` property to environments
sheremet-va Mar 11, 2024
1fe63b1
chore: run prettier on environment file
sheremet-va Mar 11, 2024
5e60d8a
refactor: hooks get an environment object instead of a string
patak-dev Mar 11, 2024
30be775
fix: HotContext only gets ModuleExecutionEnvironment
patak-dev Mar 11, 2024
e30b858
refactor: options and environment are required when calling container…
patak-dev Mar 11, 2024
03d3889
refactor: rework resolveId in ModuleExecutionEnvironment constructor
patak-dev Mar 11, 2024
fcebb7d
feat: environment.transformRequest
patak-dev Mar 12, 2024
f927702
chore: lint
patak-dev Mar 12, 2024
88fea3b
feat: configureDevEnvironments + configureBuildEnvironments
patak-dev Mar 12, 2024
60f7f2b
feat: vite runtime renamed to module runner (#16137)
sheremet-va Mar 13, 2024
81abf6e
wip: environment config overrides
patak-dev Mar 13, 2024
a99475e
chore: merge main
patak-dev Mar 13, 2024
92eccf9
chore: lint
patak-dev Mar 13, 2024
f4789a3
feat: builder config, runBuildTasks option
patak-dev Mar 14, 2024
7f94c03
feat: server.runHmrTasks
patak-dev Mar 14, 2024
9a600fe
chore: update
patak-dev Mar 14, 2024
b9ad620
chore: merge main
patak-dev Mar 14, 2024
5c6b6ff
fix: type error
patak-dev Mar 14, 2024
3e6216c
refactor: hooks to config for creating environments
patak-dev Mar 16, 2024
6e71b24
refactor: ModuleExecutionEnvironment -> DevEnvironment
patak-dev Mar 16, 2024
29f1b7b
refactor: environment id,type -> name + fixes
patak-dev Mar 16, 2024
cef1091
feat: inject environment in build hooks
patak-dev Mar 16, 2024
e03bac8
refactor: node -> ssr for default environment
patak-dev Mar 17, 2024
f1d660c
refactor: environments as array instead of map (#16193)
patak-dev Mar 18, 2024
ccf3de4
refactor: clientEnvironment instead of browserEnvironment (#16194)
patak-dev Mar 20, 2024
27e6488
chore: merge main
patak-dev Mar 22, 2024
a7a06fe
refactor: environments array to plain object
patak-dev Mar 22, 2024
8000e8e
refactor: isolate back compat module graph in its own module
patak-dev Mar 22, 2024
fee54ea
refactor: configEnvironment hook + enviroment config resolving
patak-dev Mar 22, 2024
d9ed857
test: fix after merge
patak-dev Mar 22, 2024
dbcc375
feat: support transport options to communicate between the environmen…
sheremet-va Mar 22, 2024
3806fe6
fix: optimizeDeps backward compatibility layer
patak-dev Mar 22, 2024
85ada0d
fix: partial backward compat for config.ssr
patak-dev Mar 22, 2024
c4f4dfb
fix: use "register" event for remote environment transport
sheremet-va Mar 25, 2024
a5ef42e
test: add test for worker transport
sheremet-va Mar 25, 2024
f29e95a
refactor: remove default nodeModuleRunner because it's not used anywhere
sheremet-va Mar 25, 2024
c9abcfc
refactor: rename createSsrEnvironment to createNodeEnvironment
sheremet-va Mar 25, 2024
6040ab3
chore: fix lint
sheremet-va Mar 25, 2024
b4e46fe
chore: fix lint
sheremet-va Mar 25, 2024
fbe6361
feat: environment in hooks, context vs param (#16261)
patak-dev Mar 26, 2024
36463d2
chore: merge main
patak-dev Mar 27, 2024
52edfc9
refactor: pass down name to the environment factory
sheremet-va Mar 27, 2024
9005841
refactor: allow custom connections in node module runner
sheremet-va Mar 27, 2024
8785f4f
chore: lint
sheremet-va Mar 27, 2024
96e825a
feat: --environment in CLI
patak-dev Mar 28, 2024
5477972
refactor: use ssr environment module graph in ssrFixStacktrace
sheremet-va Mar 28, 2024
a160a1b
fix: add auto complete to server.environments
sheremet-va Mar 28, 2024
31e1d3a
fix: fine-grained hmr
sheremet-va Mar 28, 2024
72fe84e
refactor: rename ssrInvalidates to invalidates
sheremet-va Mar 28, 2024
c7e4da2
refactor: base environment.config + environment.options
patak-dev Mar 28, 2024
2ddf28e
chore: update environment.server.config
patak-dev Mar 28, 2024
681ccd4
fix: injectEnvironmentToHooks
patak-dev Mar 29, 2024
a1d385c
fix: injectEnvironmentInContext
patak-dev Mar 29, 2024
c1fc111
refactor: buildEnvironments + hmrEnvironments
patak-dev Mar 29, 2024
3d37ac1
feat(hmr): call `hotUpdate` hook with file create/delete (#16249)
sapphi-red Mar 29, 2024
6f9467e
chore: merge main
patak-dev Mar 29, 2024
a5c7e4f
test(environment): add environment playground (#16299)
hi-ogawa Mar 29, 2024
ca0ecf9
test: skip hmt ssr test for now
sheremet-va Mar 29, 2024
a0b7edb
refactor: rename "hmrEnvironments" to "hotUpdateEnvironments"
sheremet-va Mar 29, 2024
4986641
test: fix windows test
sheremet-va Mar 29, 2024
41dcca1
chore: merge main
patak-dev Mar 29, 2024
fb9365c
fix: resolve.externalConditions
patak-dev Mar 30, 2024
beb40ef
fix: missing externalConditions back compat
patak-dev Mar 31, 2024
ef8c9b9
feat: build.ssrEmitAssets -> build.emitAssets
patak-dev Mar 31, 2024
a183a0f
refactor: remove environment name from the hmr context
sheremet-va Apr 2, 2024
9cfa916
refactor: move transport to properties
sheremet-va Apr 2, 2024
dd6332e
feat: environment aware createResolver and resolvePlugin
patak-dev Apr 3, 2024
f1dcd2c
feat: environment aware createIdResolver
patak-dev Apr 3, 2024
0bec1b9
feat: environment id resolver for css plugin
patak-dev Apr 3, 2024
a7e52aa
feat: environment aware depsOptimizer
patak-dev Apr 4, 2024
5bd8e95
refactor: ssrConfig.optimizeDeps.include/exclude
patak-dev Apr 4, 2024
1a7d290
feat: ssr.target -> environment.webCompatible
patak-dev Apr 5, 2024
2a0b524
feat: ssr.external/noExternal -> resolve.external/noExternal
patak-dev Apr 5, 2024
f96f682
release: v6.0.0-alpha.0
patak-dev Apr 5, 2024
3a27870
docs: fix capitalization typos (#16309)
jay-es Mar 29, 2024
67a74f8
fix: csp nonce injection when no closing tag (#16281) (#16282)
gregtwallace Mar 31, 2024
b39a7ed
ci: run lint in node 20 (#16338)
sapphi-red Apr 3, 2024
833dabf
chore: merge
sapphi-red Apr 3, 2024
a88d572
chore(deps): update tj-actions/changed-files action to v44 (#16326)
renovate[bot] Apr 3, 2024
c7efec4
chore(deps): update all non-major dependencies (#16325)
renovate[bot] Apr 3, 2024
9699ba3
fix: fix sourcemap when using object as `define` value (#15805)
hi-ogawa Apr 3, 2024
6c5536b
fix: do not access document in `/@vite/client` when not defined (#16318)
keyding Apr 3, 2024
dfce45b
chore: `pnpm audit --fix` (#16346)
sapphi-red Apr 3, 2024
bcac048
chore: merge
sapphi-red Apr 3, 2024
8d08db4
ci: run publish in node 20 (#16348)
sapphi-red Apr 3, 2024
a9bf430
perf: reduce size of injected __vite__mapDeps code (#16184)
panstromek Apr 5, 2024
f61d8b1
perf(css): only replace empty chunk if imported (#16349)
bluwy Apr 5, 2024
5f3c44f
chore: merge main
patak-dev Apr 5, 2024
8621c3f
fix(environment): use `environments.client.build.outDir` for preview …
hi-ogawa Apr 6, 2024
27371dc
chore: remove ssrConfig
patak-dev Apr 6, 2024
d91714b
refactor: isFileServingAllowed load fallback for SSR
patak-dev Apr 6, 2024
ea1c7eb
refactor: environment.dev.recoverable
patak-dev Apr 6, 2024
0ea8be9
chore: remove ssr.target use
patak-dev Apr 6, 2024
3ba9214
feat: dedupe/preserveSymlinks
patak-dev Apr 8, 2024
70731ce
refactor: lib options
patak-dev Apr 8, 2024
d15a157
feat: async createEnvironment
patak-dev Apr 8, 2024
f10561b
chore: merge main
patak-dev Apr 8, 2024
bdf13bb
fix: package types
patak-dev Apr 8, 2024
7254175
release: v6.0.0-alpha.1
patak-dev Apr 8, 2024
1f644d0
feat: rework more ssr.target webworker branches
patak-dev Apr 9, 2024
9f9a716
feat: environment aware define
patak-dev Apr 9, 2024
4cd3183
chore: merge main
patak-dev Apr 9, 2024
46c8910
chore: update
patak-dev Apr 9, 2024
9c5321b
release: v6.0.0-alpha.2
patak-dev Apr 9, 2024
84299f3
feat: environment.dev.warmup
patak-dev Apr 10, 2024
59b995e
refactor: proxy environment logger, remove hardcoded `[vite]` from hm…
sheremet-va Apr 12, 2024
52a71e6
refactor: environments have colors in the logger, update logger.info …
sheremet-va Apr 12, 2024
ae1798f
chore: rename runner to evaluator in serverModuleRunner
sheremet-va Apr 16, 2024
5b57f63
feat: deprecate ssrLoadModule (#16431)
sheremet-va Apr 16, 2024
b4fdfaf
feat: keep url queries in ssr mode (#16400)
sheremet-va Apr 16, 2024
319b8e0
feat: decouple DevEnvironment and server (#16460)
patak-dev Apr 19, 2024
635e6d5
chore: merge main
patak-dev Apr 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ export function removeStyle(id: string): void {
}

export function createHotContext(ownerPath: string): ViteHotContext {
return new HMRContext(hmrClient, ownerPath)
return new HMRContext(hmrClient, ownerPath, 'browser')
}

/**
Expand Down
24 changes: 24 additions & 0 deletions packages/vite/src/node/environment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// We are using command: 'serve' | 'build' to aling with the command flag passed to hooks.
// It would be better if we would use 'dev' here but can tackle that if we managed to modify
// command at the hooks level. There could also be Preview environments later on.

export class Environment {
id: string
type: string
constructor(
id: string,
options: {
type: string
},
) {
this.id = id
this.type = options.type
}
}

export class BuildEnvironment extends Environment {
command = 'build' as const
constructor(id: string, options: { type: string }) {
super(id, options)
}
}
10 changes: 8 additions & 2 deletions packages/vite/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,20 @@ export type {
WebSocketCustomListener,
} from './server/ws'
export type { PluginContainer } from './server/pluginContainer'
export type { ModuleGraph, ModuleNode, ResolvedUrl } from './server/moduleGraph'
export type {
ModuleGraph,
ModuleNode,
EnvironmentModuleGraph,
EnvironmentModuleNode,
ResolvedUrl,
} from './server/moduleGraph'
export type { SendOptions } from './server/send'
export type { ProxyOptions } from './server/middlewares/proxy'
export type {
TransformOptions,
TransformResult,
} from './server/transformRequest'
export type { HmrOptions, HmrContext } from './server/hmr'
export type { HmrOptions, HmrContext, HotUpdateContext } from './server/hmr'

export type {
HMRBroadcaster,
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ async function createDepsOptimizer(
// Cached transform results have stale imports (resolved to
// old locations) so they need to be invalidated before the page is
// reloaded.
server.moduleGraph.invalidateAll()
server.browserEnvironment.moduleGraph.invalidateAll()

server.hot.send({
type: 'full-reload',
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ export function watchPackageDataPlugin(packageCache: PackageCache): Plugin {
invalidatePackageData(packageCache, path.normalize(id))
}
},
handleHotUpdate({ file }) {
hotUpdate({ file }) {
if (file.endsWith('/package.json')) {
invalidatePackageData(packageCache, path.normalize(file))
}
Expand Down
39 changes: 32 additions & 7 deletions packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ export type { PluginContext } from 'rollup'
import type { ConfigEnv, ResolvedConfig, UserConfig } from './config'
import type { ServerHook } from './server'
import type { IndexHtmlTransform } from './plugins/html'
import type { ModuleNode } from './server/moduleGraph'
import type { HmrContext } from './server/hmr'
import type { EnvironmentModuleNode, ModuleNode } from './server/moduleGraph'
import type { HmrContext, HotUpdateContext } from './server/hmr'
import type { PreviewServerHook } from './preview'
import type { ModuleExecutionEnvironment } from './server/environment'
import type { BuildEnvironment } from './environment'

/**
* Vite plugins extends the Rollup plugin interface with a few extra
Expand Down Expand Up @@ -119,6 +121,19 @@ export interface Plugin<A = any> extends RollupPlugin<A> {
* `{ order: 'pre', handler: hook }`
*/
transformIndexHtml?: IndexHtmlTransform

/**
* @deprecated
* Compat support, ctx.modules is a backward compatible ModuleNode array
* with the mixed client and ssr moduleGraph. Use hotUpdate instead
*/
handleHotUpdate?: ObjectHook<
(
this: void,
ctx: HmrContext,
) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>
>

/**
* Perform custom handling of HMR updates.
* The handler receives a context containing changed filename, timestamp, a
Expand All @@ -134,11 +149,14 @@ export interface Plugin<A = any> extends RollupPlugin<A> {
* - If the hook doesn't return a value, the hmr update will be performed as
* normal.
*/
handleHotUpdate?: ObjectHook<
hotUpdate?: ObjectHook<
(
this: void,
ctx: HmrContext,
) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>
ctx: HotUpdateContext,
) =>
| Array<EnvironmentModuleNode>
| void
| Promise<Array<EnvironmentModuleNode> | void>
>

/**
Expand All @@ -153,6 +171,7 @@ export interface Plugin<A = any> extends RollupPlugin<A> {
attributes: Record<string, string>
custom?: CustomPluginOptions
ssr?: boolean
environment?: ModuleExecutionEnvironment | BuildEnvironment
/**
* @internal
*/
Expand All @@ -165,15 +184,21 @@ export interface Plugin<A = any> extends RollupPlugin<A> {
(
this: PluginContext,
id: string,
options?: { ssr?: boolean },
options?: {
ssr?: boolean
environment?: ModuleExecutionEnvironment | BuildEnvironment
},
) => Promise<LoadResult> | LoadResult
>
transform?: ObjectHook<
(
this: TransformPluginContext,
code: string,
id: string,
options?: { ssr?: boolean },
options?: {
ssr?: boolean
environment?: ModuleExecutionEnvironment | BuildEnvironment
Copy link
Member

@sheremet-va sheremet-va Mar 11, 2024

Choose a reason for hiding this comment

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

Can we guarantee it exists somehow? (non undefined)

Copy link
Member Author

Choose a reason for hiding this comment

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

The problem is that during scan, we didn't pass the moduleGraph. See here

const container = await createPluginContainer(config)

So I didn't pass the environment either. I thought that it may make the scan slower if we need to update info in a module graph that we are going to throw away. But I think it is wrong that we don't pass an environment, more once we will have environment specific config. I'll check what needs to be done here. I think we only need the plugins for resolveId that shouldn't mess with the moduleGraph, so maybe we can create a new temporal browser environment with a new module graph and pass that. I'll check this out, it would be a lot better if there is always an environment defined.

Copy link
Member Author

@patak-dev patak-dev Mar 11, 2024

Choose a reason for hiding this comment

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

Let's see if there isn't some internalish use cases of these hooks in the ecosystem, but for now, core works with options and environment being required for hooks. See e30b858

I fixed some issues were I missed passing the environment, so even if we revert, it was worth it. We currently have a design issue because an environment needs a resolveId function when it is created, that should be implemented as container.resolveId(id, undefined, { environment }). I'll rework this next so we can simplify the code. Edit: done in 03d3889

Copy link
Member Author

Choose a reason for hiding this comment

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

It seems we'll need to relax the types. See failing test for Vitest. We could leave them as is for a bit more if they help us work with this draft though.

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 already moved back to optional options and environment. If not, we were forced to have a new GlobalEnvironment that would be used when we don't have a server available (in the plugin containers created during config resolution for example).
Still, this was quite helpful to identify issues. And things looks better after fcebb7d

},
) => Promise<TransformResult> | TransformResult
>
}
Expand Down
19 changes: 11 additions & 8 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ import {
urlRE,
} from '../utils'
import { DEFAULT_ASSETS_INLINE_LIMIT, FS_PREFIX } from '../constants'
import type { ModuleGraph } from '../server/moduleGraph'
import { cleanUrl, withTrailingSlash } from '../../shared/utils'
import type { ViteDevServer } from '../server'
import type { ModuleExecutionEnvironment } from '../server/environment'

// referenceId is base64url but replaces - with $
export const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g
Expand Down Expand Up @@ -140,8 +141,7 @@ const viteBuildPublicIdPrefix = '\0vite:asset:public'
*/
export function assetPlugin(config: ResolvedConfig): Plugin {
registerCustomMime()

let moduleGraph: ModuleGraph | undefined
let server: ViteDevServer

return {
name: 'vite:asset',
Expand All @@ -151,8 +151,8 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
generatedAssets.set(config, new Map())
},

configureServer(server) {
moduleGraph = server.moduleGraph
configureServer(_server) {
server = _server
},

resolveId(id) {
Expand All @@ -169,7 +169,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
}
},

async load(id) {
async load(id, options) {
if (id.startsWith(viteBuildPublicIdPrefix)) {
id = id.slice(viteBuildPublicIdPrefix.length)
}
Expand Down Expand Up @@ -198,8 +198,11 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
let url = await fileToUrl(id, config, this)

// Inherit HMR timestamp if this asset was invalidated
if (moduleGraph) {
const mod = moduleGraph.getModuleById(id)
if (server) {
const environment = options?.environment as
| ModuleExecutionEnvironment
| undefined
const mod = environment?.moduleGraph.getModuleById(id)
if (mod && mod.lastHMRTimestamp > 0) {
url = injectQuery(url, `t=${mod.lastHMRTimestamp}`)
}
Expand Down
27 changes: 10 additions & 17 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ import { formatMessages, transform } from 'esbuild'
import type { RawSourceMap } from '@ampproject/remapping'
import { WorkerWithFallback } from 'artichokie'
import { getCodeWithSourcemap, injectSourcesContent } from '../server/sourcemap'
import type { ModuleNode } from '../server/moduleGraph'
import type { ResolveFn, ViteDevServer } from '../'
import type { EnvironmentModuleNode } from '../server/moduleGraph'
import type { ResolveFn } from '../'
import {
createToImportMetaURLBasedRelativeRuntime,
resolveUserExternal,
Expand Down Expand Up @@ -923,15 +923,9 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
}

export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
let server: ViteDevServer

return {
name: 'vite:css-analysis',

configureServer(_server) {
server = _server
},

async transform(_, id, options) {
if (
!isCSSRequest(id) ||
Expand All @@ -941,9 +935,10 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
return
}

const ssr = options?.ssr === true
const { moduleGraph } = server
const thisModule = moduleGraph.getModuleById(id)
const environment = options?.environment
const moduleGraph =
environment?.command === 'serve' ? environment.moduleGraph : undefined
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.
Expand All @@ -960,22 +955,21 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
if (pluginImports) {
// record deps in the module graph so edits to @import css can trigger
// main import to hot update
const depModules = new Set<string | ModuleNode>()
const depModules = new Set<string | EnvironmentModuleNode>()
const devBase = config.base
for (const file of pluginImports) {
depModules.add(
isCSSRequest(file)
? moduleGraph.createFileOnlyEntry(file)
: await moduleGraph.ensureEntryFromUrl(
? moduleGraph!.createFileOnlyEntry(file)
: await moduleGraph!.ensureEntryFromUrl(
stripBase(
await fileToUrl(file, config, this),
(config.server?.origin ?? '') + devBase,
),
ssr,
),
)
}
moduleGraph.updateModuleInfo(
moduleGraph!.updateModuleInfo(
thisModule,
depModules,
null,
Expand All @@ -984,7 +978,6 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
new Set(),
null,
isSelfAccepting,
ssr,
)
} else {
thisModule.isSelfAccepting = isSelfAccepting
Expand Down
4 changes: 3 additions & 1 deletion packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,9 @@ async function reloadOnTsconfigChange(changedFile: string) {
)

// clear module graph to remove code compiled with outdated config
server.moduleGraph.invalidateAll()
server.environments.forEach((environment) =>
environment.moduleGraph.invalidateAll(),
)

// reset tsconfck so that recompile works with up2date configs
tsconfckCache?.clear()
Expand Down
24 changes: 11 additions & 13 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import { checkPublicFile } from '../publicDir'
import { getDepOptimizationConfig } from '../config'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import type { ModuleExecutionEnvironment } from '../server/environment'
import { shouldExternalizeForSSR } from '../ssr/ssrExternal'
import { getDepsOptimizer, optimizedDepNeedsInterop } from '../optimizer'
import {
Expand Down Expand Up @@ -209,11 +210,16 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
async transform(source, importer, options) {
// In a real app `server` is always defined, but it is undefined when
// running src/node/server/__tests__/pluginContainer.spec.ts
if (!server) {

const ssr = options?.ssr === true
const environment =
(options?.environment as ModuleExecutionEnvironment) || undefined

if (!server || !environment) {
return null
}

const ssr = options?.ssr === true
const moduleGraph = environment.moduleGraph

if (canSkipImportAnalysis(importer)) {
debug?.(colors.dim(`[skipped] ${prettifyUrl(importer, root)}`))
Expand All @@ -238,10 +244,9 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {

const depsOptimizer = getDepsOptimizer(config, ssr)

const { moduleGraph } = server
// since we are already in the transform phase of the importer, it must
// have been loaded so its entry is guaranteed in the module graph.
const importerModule = moduleGraph.getModuleById(importer)!
const importerModule = moduleGraph.getModuleById(importer)
if (!importerModule) {
// This request is no longer valid. It could happen for optimized deps
// requests. A full reload is going to request this id again.
Expand Down Expand Up @@ -380,7 +385,6 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
// We use an internal function to avoid resolving the url again
const depModule = await moduleGraph._ensureEntryFromUrl(
unwrapId(url),
ssr,
canSkipImportAnalysis(url) || forceSkipImportAnalysis,
resolved,
)
Expand Down Expand Up @@ -525,9 +529,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
// record as safe modules
// safeModulesPath should not include the base prefix.
// See https://github.com/vitejs/vite/issues/9438#issuecomment-1465270409
server?.moduleGraph.safeModulesPath.add(
fsPathFromUrl(stripBase(url, base)),
)
server?._safeModulesPath.add(fsPathFromUrl(stripBase(url, base)))

if (url !== specifier) {
let rewriteDone = false
Expand Down Expand Up @@ -727,10 +729,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
// normalize and rewrite accepted urls
const normalizedAcceptedUrls = new Set<string>()
for (const { url, start, end } of acceptedUrls) {
const [normalized] = await moduleGraph.resolveUrl(
toAbsoluteUrl(url),
ssr,
)
const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(url))
normalizedAcceptedUrls.add(normalized)
str().overwrite(start, end, JSON.stringify(normalized), {
contentOnly: true,
Expand Down Expand Up @@ -775,7 +774,6 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
normalizedAcceptedUrls,
isPartiallySelfAccepting ? acceptedExports : null,
isSelfAccepting,
ssr,
staticImportedUrls,
)
if (hasHMR && prunedImports) {
Expand Down
Loading