Skip to content

feat: track dependencies when loading config with native #19374

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
"#module-sync-enabled": {
"module-sync": "./misc/true.js",
"default": "./misc/false.js"
}
},
"#deps-tracker": "./dist/node/deps-tracker.js"
},
"files": [
"bin",
Expand Down
9 changes: 9 additions & 0 deletions packages/vite/rollup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,14 @@ const moduleRunnerConfig = defineConfig({
],
})

const depsTrackerConfig = defineConfig({
...sharedNodeOptions,
input: {
'deps-tracker': path.resolve(__dirname, 'src/deps-tracker/index.ts'),
},
plugins: [...createSharedNodePlugins({}), bundleSizeLimit(2)],
})

const cjsConfig = defineConfig({
...sharedNodeOptions,
input: {
Expand All @@ -223,6 +231,7 @@ export default defineConfig([
clientConfig,
nodeConfig,
moduleRunnerConfig,
depsTrackerConfig,
cjsConfig,
])

Expand Down
47 changes: 47 additions & 0 deletions packages/vite/src/deps-tracker/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { MessagePort } from 'node:worker_threads'
import type { InitializeHook, ResolveHook } from 'node:module'

const tQueryRE = /(?:\?|&)t=(\d+),([^&]+)(?:&|$)/
const relativeImportRE = /^\.{1,2}(?:\/|\\)/

let port: MessagePort

export const initialize: InitializeHook = async ({
port: _port,
time: _time,
}: {
port: MessagePort
time: string
}) => {
port = _port
}

export const resolve: ResolveHook = async (specifier, context, nextResolve) => {
const isRelativeImport = relativeImportRE.test(specifier)
const result = await nextResolve(specifier, context)
if (result.format === 'builtin' || !isRelativeImport) return result

if (
// when parent does not exist (it is not a dependency of config file)
!context.parentURL ||
// if the t query is already present, do not add it
tQueryRE.test(result.url) ||
// if it's not a file url, no need to add the t query
!result.url.startsWith('file:')
)
return result

// propergate the t query
const m = tQueryRE.exec(context.parentURL)
if (m) {
const [, time, contextFile] = m
// all dependencies from the config should have the t query
port.postMessage({ context: contextFile, url: result.url })

result.url = result.url.replace(
/(\?)|$/,
(_n, n1) => `?t=${time},${contextFile}${n1 === '?' ? '&' : ''}`,
)
}
return result
}
11 changes: 11 additions & 0 deletions packages/vite/src/deps-tracker/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"include": ["./"],
"compilerOptions": {
// https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping#node-18
"lib": ["ES2023"],
"target": "ES2022",
"skipLibCheck": true, // lib check is done on final types
"stripInternal": true
}
}
83 changes: 80 additions & 3 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import fs from 'node:fs'
import path from 'node:path'
import fsp from 'node:fs/promises'
import { pathToFileURL } from 'node:url'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { promisify } from 'node:util'
import { performance } from 'node:perf_hooks'
import { createRequire } from 'node:module'
import { Module, createRequire } from 'node:module'
import crypto from 'node:crypto'
import { MessageChannel } from 'node:worker_threads'
import colors from 'picocolors'
import type { Alias, AliasOptions } from 'dep-types/alias'
import type { RollupOptions } from 'rollup'
Expand Down Expand Up @@ -1776,7 +1777,21 @@ export async function loadConfigFromFile(
}
}

async function nativeImportConfigFile(resolvedPath: string) {
async function nativeImportConfigFile(
resolvedPath: string,
): Promise<{ configExport: any; dependencies: string[] }> {
depsTracker ??= createDepsTracker()
if (depsTracker) {
const { result, dependencies } = await depsTracker.collect(
resolvedPath,
() =>
import(
pathToFileURL(resolvedPath).href + `?t=${Date.now()},${resolvedPath}`
),
)
return { configExport: result.default, dependencies }
}

const module = await import(
pathToFileURL(resolvedPath).href + '?t=' + Date.now()
)
Expand All @@ -1786,6 +1801,68 @@ async function nativeImportConfigFile(resolvedPath: string) {
}
}

// rather than a singleton, it would be better to unregister the loader
// so that it doesn't incur the overhead when not needed
// but unregistering a loader is not supported
let depsTracker: DepsTracker | undefined

type DepsTracker = {
collect: <T>(
context: string,
cb: () => Promise<T>,
) => Promise<{ result: T; dependencies: string[] }>
}

// This only tracks ESM dependencies that are statically imported (not dynamic imports)
function createDepsTracker(): DepsTracker | undefined {
// register only exists in Node.js 18.19.0+, 20.6.0+
// bail out if it is not supported
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const register = Module.register
if (!register) {
return
}

// we want to register this loader as the last one
// this is ensured for the first config load,
// but for the subsequent config loads, a different loader may be registered.
// we hope that that doesn't happen
const { port1, port2 } = new MessageChannel()
register('#deps-tracker', {
parentURL: import.meta.url,
data: { port: port2 },
transferList: [port2],
})
port1.unref()

return {
async collect(context, cb) {
const depsList: string[] = []
const onMessage = (e: { context: string; url: string }) => {
if (e.context === context) {
depsList.push(e.url)
}
}
port1.on('message', onMessage)
port1.unref()

let result: Awaited<ReturnType<typeof cb>>
try {
result = await cb()
} finally {
port1.off('message', onMessage)
}

return {
result,
dependencies: depsList
.filter((url) => url.startsWith('file:'))
.map((url) => fileURLToPath(url)),
}
},
}
}

async function runnerImportConfigFile(resolvedPath: string) {
const { module, dependencies } = await runnerImport<{
default: UserConfigExport
Expand Down