Unverified Commit 443a9e7a authored by Jimmy Miller's avatar Jimmy Miller Committed by GitHub

More parity for webpack loader build dependencies (#99549)

Track transitive modules, resolution requests, and package directories.
parent 0954164b
......@@ -9967,6 +9967,7 @@ dependencies = [
"turbo-tasks-fs",
"turbo-tasks-hash",
"turbo-tasks-testing",
"turbo-unix-path",
"turbopack-cli-utils",
"turbopack-core",
"turbopack-ecmascript",
......
const path = require('node:path')
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
turbopack: {
resolveAlias: {
'build-dependency-package': './aliased-build-dependency.js',
},
rules: {
'*.ts': {
loaders: [path.resolve(__dirname, './loader.js')],
},
},
},
webpack: (config) => {
config.resolve.alias['build-dependency-package'] = path.resolve(
__dirname,
'./aliased-build-dependency.js'
)
config.module.rules.push({
test: /\.ts$/,
use: [path.resolve(__dirname, './loader.js')],
})
return config
},
}
module.exports = nextConfig
import { utilFn } from '../../utils/dynamic-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
}
import { utilFn } from '../../utils/external-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
}
import { utilFn } from '../utils/file-to-transform'
import { utilFn } from '../../utils/native-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
......
import { utilFn } from '../../utils/package-directory-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
}
import { utilFn } from '../utils/file-to-transform'
import postcssOutput from '../utils/file.postcss-test'
import stylusOutput from '../utils/file.stylus-test'
export default function Page() {
return (
<>
<p>{utilFn()}</p>
<p id="postcss-output">{postcssOutput}</p>
<p id="stylus-output">{stylusOutput}</p>
</>
)
}
import { utilFn } from '../../utils/tracking-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
}
import { utilFn } from '../../utils/unresolved-build-dependency'
export default function Page() {
return <p>{utilFn()}</p>
}
module.exports = function (source) {
return `export default ${JSON.stringify(source)}`
}
......@@ -15,9 +15,62 @@ const loader = async function (content) {
)
}
const directoryBuildDependency = this.resourcePath.endsWith(
'directory-build-dependency.ts'
)
const resourceName = path.basename(this.resourcePath)
if (resourceName === 'external-build-dependency.ts') {
const value = require(process.env.EXTERNAL_BUILD_DEPENDENCY)
return this.callback(
null,
`export const utilFn = () => ${JSON.stringify(value)};`
)
}
if (resourceName === 'native-build-dependency.ts') {
// Model a native addon already loaded by Node outside the project's watched roots.
const { Module } = require('node:module')
const filename = process.env.NATIVE_BUILD_DEPENDENCY
const nativeModule = new Module(filename, module)
nativeModule.filename = filename
nativeModule.loaded = true
require.cache[filename] = nativeModule
return this.callback(
null,
`export const utilFn = () => ${JSON.stringify(fs.readFileSync(filename, 'utf8'))};`
)
}
if (resourceName === 'dynamic-build-dependency.ts') {
const dependency = process.env.DYNAMIC_BUILD_DEPENDENCY
this.addBuildDependency(require.resolve(dependency))
const value = require(dependency)
return this.callback(
null,
`export const utilFn = () => ${JSON.stringify(`dynamic: ${value}`)};`
)
}
if (resourceName === 'tracking-build-dependency.ts') {
const cached = require('./tracking/cached')
this.addBuildDependency(path.join(__dirname, 'tracking', 'uncached.mjs'))
const uncached = fs
.readFileSync(
path.join(__dirname, 'tracking', 'uncached-value.js'),
'utf8'
)
.match(/'([^']+)'/)[1]
return this.callback(
null,
`export const utilFn = () => ${JSON.stringify(`${cached}; uncached: ${uncached}`)};`
)
}
if (resourceName === 'unresolved-build-dependency.ts') {
this.addBuildDependency('missing-build-dependency-package/')
this.addBuildDependency('missing-build-dependency-module')
return this.callback(
null,
"export const utilFn = () => 'unresolved dependency warning';"
)
}
const directoryBuildDependency =
resourceName === 'directory-build-dependency.ts'
const packageDirectoryBuildDependency =
resourceName === 'package-directory-build-dependency.ts'
if (directoryBuildDependency) {
const packageDirectory = path.join(__dirname, 'build-dependency-package')
const nestedEntry = path.join(packageDirectory, 'nested', 'value.js')
......@@ -61,6 +114,25 @@ const loader = async function (content) {
)
}
if (packageDirectoryBuildDependency) {
this.addBuildDependency('directory-only-package/')
const value = fs
.readFileSync(
path.join(
__dirname,
'node_modules',
'directory-only-package',
'data.txt'
),
'utf8'
)
.trim()
return this.callback(
null,
`export const utilFn = () => 'package directory build dependency: ${value}';`
)
}
if (!this.resourcePath.endsWith('file-to-transform.ts')) {
return this.callback(null, content)
}
......
const path = require('node:path')
const cssToJsLoader = path.resolve(__dirname, './css-to-js-loader.js')
const postcssLoader = require.resolve('postcss-loader')
const postcssPlugin = path.resolve(
__dirname,
'./postcss-build-dependency-plugin.js'
)
const stylusLoader = require.resolve('stylus-loader')
const stylusPlugin = path.resolve(
__dirname,
'./stylus-build-dependency-plugin.js'
)
const testLoader = './loader.js'
// Check require conditions and application aliases independently in the existing loader chain.
const testLoaders = [
'test-resolution-loader',
'test-resolution-loader/aliased',
testLoader,
]
const postcssLoaders = [
cssToJsLoader,
{
loader: postcssLoader,
options: {
postcssOptions: {
config: false,
plugins: {
[postcssPlugin]: {
dependency: path.resolve(
__dirname,
'./utils/postcss-build-dependency.txt'
),
},
},
},
},
},
]
const stylusLoaders = [
cssToJsLoader,
{
loader: stylusLoader,
options: { stylusOptions: { use: [stylusPlugin] } },
},
]
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
turbopackFileSystemCacheForDev: true,
},
turbopack: {
resolveAlias: {
'build-dependency-package': './aliased-build-dependency.js',
'test-resolution-loader/aliased': './resolution-loader/wrong.js',
},
rules: {
'*.ts': {
loaders: testLoaders,
},
'*.postcss-test': {
loaders: postcssLoaders,
as: '*.js',
},
'*.stylus-test': {
loaders: stylusLoaders,
as: '*.js',
},
},
},
webpack: (config) => {
config.resolve.alias['build-dependency-package'] = path.resolve(
__dirname,
'./aliased-build-dependency.js'
)
config.resolve.alias['test-resolution-loader/aliased'] = path.resolve(
__dirname,
'./resolution-loader/wrong.js'
)
config.module.rules.push({
test: /\.ts$/,
use: testLoaders,
})
config.module.rules.push({
test: /\.postcss-test$/,
use: postcssLoaders,
})
config.module.rules.push({
test: /\.stylus-test$/,
use: stylusLoaders,
})
return config
},
}
module.exports = nextConfig
const fs = require('node:fs')
module.exports = function ({ dependency }) {
return {
postcssPlugin: 'build-dependency-test',
Once(root, { result }) {
result.messages.push({ type: 'build-dependency', file: dependency })
const value = fs.readFileSync(dependency, 'utf8').trim()
root.walkDecls((declaration) => {
declaration.value = declaration.value.replace(
'__BUILD_DEPENDENCY__',
value
)
})
},
}
}
module.exports.postcss = true
{
"name": "test-resolution-loader",
"version": "1.0.0",
"exports": {
".": {
"import": "./wrong.js",
"require": "./index.js"
},
"./aliased": "./index.js"
}
}
throw new Error('Application resolution must not be used for webpack loaders')
const stylus = require('stylus')
module.exports = function () {
return function (style) {
style.define(
'buildDependencyValue',
new stylus.nodes.String('stylus-value')
)
}
}
{
"name": "tracking-package",
"version": "1.0.0",
"exports": {
"./value": "./value.js"
}
}
const transitive = require('../tracking-value')
const candidate = require('./candidate')
const packageValue = require('tracking-package/value')
module.exports = `cached: ${transitive}; candidate: ${candidate}; package: ${packageValue}`
import value from './uncached-value.js'
export default value
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { gate, retry } from 'next-test-utils'
import {
mkdtempSync,
readdirSync,
realpathSync,
rmSync,
writeFileSync,
} from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
describe('webpack-loader-file-dependencies', () => {
const externalDependencyDirectory = mkdtempSync(
join(realpathSync(tmpdir()), 'loader-build-dependency-')
)
const nativeDependency = join(externalDependencyDirectory, 'addon.node')
const externalDependency = join(externalDependencyDirectory, 'dependency.js')
writeFileSync(nativeDependency, 'native-one')
writeFileSync(externalDependency, "module.exports = 'external-one'")
describe('turbopack-loader-file-dependencies', () => {
const { next } = nextTestSetup({
files: __dirname,
env: {
// Do not let optional loader dependencies resolve from the repository's pnpm installation.
NODE_PATH: '',
DYNAMIC_BUILD_DEPENDENCY: './tracking/dynamic.js',
NATIVE_BUILD_DEPENDENCY: nativeDependency,
EXTERNAL_BUILD_DEPENDENCY: externalDependency,
TURBO_ENGINE_IGNORE_DIRTY: '1',
TURBO_ENGINE_SNAPSHOT_IDLE_TIMEOUT_MILLIS: '0',
TURBO_ENGINE_SNAPSHOT_MIN_ACTIVE_TIME_MILLIS: '0',
// Wait for turbo-tasks to persist the cache before the dev process exits.
__NEXT_DEV_WAIT_FOR_TURBOPACK_SHUTDOWN: '1',
},
dependencies: {
'build-dependency-esm-package': 'file:./build-dependency-esm-package',
'build-dependency-package': 'file:./build-dependency-package',
'directory-only-package': 'file:./directory-only-package',
'tracking-package': 'file:./tracking-package',
'test-resolution-loader': 'file:./resolution-loader',
postcss: '8.5.28',
'postcss-loader': '8.2.1',
stylus: '0.64.0',
'stylus-loader': '9.0.0',
},
})
afterAll(() => {
rmSync(externalDependencyDirectory, { recursive: true, force: true })
})
// The harness stops with SIGKILL by default, which can exit before the persistent cache is
// written, so a restart would recompile instead of restoring cached results.
const stop = () => next.stop('SIGTERM')
it('should update when the dependency file changes', async () => {
const $ = await next.render$('/')
const initialText = await $('p').text()
......@@ -27,6 +71,40 @@ describe('turbopack-loader-file-dependencies', () => {
})
})
for (const [route, filename, initial, updated] of [
['/native', nativeDependency, 'native-one', 'native-two'],
['/external', externalDependency, 'external-one', 'external-two'],
]) {
it(`does not reuse stale ${route} results across restarts`, async () => {
const $ = await next.render$(route)
expect($('p').text()).toBe(initial)
if (await gate('turbopack')) {
await retry(() => {
const files = readdirSync(
join(next.testDir, next.distDir, 'cache', 'turbopack'),
{ recursive: true }
)
expect(files.some((file) => String(file).endsWith('.sst'))).toBe(true)
})
}
await stop()
const contents =
route === '/native' ? updated : `module.exports = '${updated}'`
writeFileSync(filename, contents)
try {
await next.start()
const $ = await next.render$(route)
expect($('p').text()).toBe(updated)
} finally {
await stop()
const contents =
route === '/native' ? initial : `module.exports = '${initial}'`
writeFileSync(filename, contents)
await next.start()
}
})
}
it('should update when a missing dependency is created', async () => {
const $ = await next.render$('/')
const initialText = $('p').text()
......@@ -61,6 +139,61 @@ describe('turbopack-loader-file-dependencies', () => {
)
})
it('should support build dependencies from postcss-loader', async () => {
const $ = await next.render$('/')
expect($('#postcss-output').text()).toContain('postcss-one')
})
// @force-gate turbopack
it('updates when a postcss-loader build dependency changes', async () => {
await next.render$('/')
await next.patchFile(
'utils/postcss-build-dependency.txt',
'postcss-two',
async () => {
await retry(async () => {
const $ = await next.render$('/')
expect($('#postcss-output').text()).toContain('postcss-two')
})
}
)
})
it('should support build dependencies from stylus-loader', async () => {
const $ = await next.render$('/')
expect($('#stylus-output').text()).toContain('stylus-value')
})
it('loads an edited stylus-loader plugin after restarting the dev server', async () => {
const $ = await next.render$('/')
expect($('#stylus-output').text()).toContain('stylus-value')
// Stylus uses import(), whose Node module cache requires a fresh process.
await stop()
try {
await next.patchFile(
'stylus-build-dependency-plugin.js',
(content) => content.replace('stylus-value', 'stylus-two'),
async () => {
await next.start()
try {
await retry(async () => {
const $ = await next.render$('/')
expect($('#stylus-output').text()).toContain('stylus-two')
})
} finally {
await stop()
}
}
)
} finally {
await next.start()
}
await retry(async () => {
const $ = await next.render$('/')
expect($('#stylus-output').text()).toContain('stylus-value')
})
})
// @force-gate turbopack
it('updates when a package entry added as a build dependency changes', async () => {
const $ = await next.render$('/package')
......@@ -144,4 +277,134 @@ describe('turbopack-loader-file-dependencies', () => {
}
)
})
it('resolves a package directory build dependency', async () => {
const $ = await next.render$('/package-directory')
expect($('p').text()).toContain(
'package directory build dependency: directory-one'
)
})
// @force-gate turbopack
it('updates a directory-only package build dependency', async () => {
await next.render$('/package-directory')
await next.patchFile(
'node_modules/directory-only-package/data.txt',
'directory-two',
async () => {
await retry(async () => {
const $ = await next.render$('/package-directory')
expect($('p').text()).toContain(
'package directory build dependency: directory-two'
)
})
}
)
})
// Shared workers keep required CommonJS modules cached until the server restarts.
it.each([
[
'an edited cached transitive loader dependency',
'tracking-value.js',
"module.exports = 'transitive-two'",
'cached: transitive-one',
'cached: transitive-two',
],
[
'a higher-priority CommonJS candidate',
'tracking/candidate',
"module.exports = 'extensionless-two'",
'candidate: js-one',
'candidate: extensionless-two',
],
[
'a nearer CommonJS package',
'tracking/node_modules/tracking-package/value.js',
"module.exports = 'nearer-two'",
'package: package-one',
'package: nearer-two',
],
])(
'loads %s after restarting the dev server',
async (_name, fileName, content, initial, expected) => {
const $ = await next.render$('/tracking')
expect($('p').text()).toContain(initial)
await stop()
try {
await next.patchFile(fileName, content, async () => {
await next.start()
try {
const $ = await next.render$('/tracking')
expect($('p').text()).toContain(expected)
} finally {
await stop()
}
})
} finally {
await next.start()
}
}
)
// @force-gate turbopack
it('updates when an uncached build dependency import changes', async () => {
const $ = await next.render$('/tracking')
expect($('p').text()).toContain('uncached: uncached-one')
await next.patchFile(
'tracking/uncached-value.js',
"module.exports = 'uncached-two'",
async () => {
await retry(async () => {
const $ = await next.render$('/tracking')
expect($('p').text()).toContain('uncached: uncached-two')
})
}
)
})
it('loads an edited dynamic CommonJS build dependency after restarting the dev server', async () => {
const $ = await next.render$('/dynamic')
expect($('p').text()).toContain('dynamic: dynamic-one')
// CommonJS modules stay cached in the shared worker pool until the server restarts.
await stop()
try {
await next.patchFile(
'tracking/dynamic-value.js',
"module.exports = 'dynamic-two'",
async () => {
await next.start()
try {
await retry(async () => {
const $ = await next.render$('/dynamic')
expect($('p').text()).toContain('dynamic: dynamic-two')
})
} finally {
await stop()
}
}
)
} finally {
await next.start()
}
await retry(async () => {
const $ = await next.render$('/dynamic')
expect($('p').text()).toContain('dynamic: dynamic-one')
})
})
// @force-gate turbopack
it('warns without failing for unresolved module and package-directory dependencies', async () => {
const outputIndex = next.cliOutput.length
const $ = await next.render$('/unresolved')
expect($('p').text()).toContain('unresolved dependency warning')
await retry(() => {
const output = next.cliOutput.slice(outputIndex)
expect(output).toContain(
'Unable to resolve webpack loader build dependency'
)
expect(output).toContain('missing-build-dependency-package')
expect(output).toContain('missing-build-dependency-module')
})
})
})
......@@ -1973,22 +1973,6 @@
"flakey": [],
"runtimeError": false
},
"test/development/app-dir/turbopack-loader-file-dependencies/turbopack-loader-file-dependencies.test.ts": {
"passed": [
"turbopack-loader-file-dependencies should update when a missing dependency is created",
"turbopack-loader-file-dependencies should update when the dependency file changes"
],
"failed": [],
"pending": [
"turbopack-loader-file-dependencies resolves .mjs build dependencies with ESM conditions",
"turbopack-loader-file-dependencies should update when a build dependency changes",
"turbopack-loader-file-dependencies updates when a nested file in a build dependency directory changes",
"turbopack-loader-file-dependencies updates when a package entry added as a build dependency changes",
"turbopack-loader-file-dependencies warns for unsupported build dependency inputs"
],
"flakey": [],
"runtimeError": false
},
"test/development/app-dir/turbopack-reexport-hmr/turbopack-reexport-hmr.test.ts": {
"passed": [
"Turbopack re-export HMR updates forwarded exports and namespace members without stale values"
......@@ -2133,6 +2117,22 @@
"flakey": [],
"runtimeError": false
},
"test/development/app-dir/webpack-loader-file-dependencies/webpack-loader-file-dependencies.test.ts": {
"passed": [
"webpack-loader-file-dependencies should update when a missing dependency is created",
"webpack-loader-file-dependencies should update when the dependency file changes"
],
"failed": [],
"pending": [
"webpack-loader-file-dependencies resolves .mjs build dependencies with ESM conditions",
"webpack-loader-file-dependencies should update when a build dependency changes",
"webpack-loader-file-dependencies updates when a nested file in a build dependency directory changes",
"webpack-loader-file-dependencies updates when a package entry added as a build dependency changes",
"webpack-loader-file-dependencies warns for unsupported build dependency inputs"
],
"flakey": [],
"runtimeError": false
},
"test/development/app-document-add-hmr/app-document-add-hmr.test.ts": {
"passed": [],
"failed": [],
......@@ -46,6 +46,7 @@ turbo-tasks = { workspace = true }
turbo-tasks-env = { workspace = true }
turbo-tasks-fs = { workspace = true }
turbo-tasks-hash = { workspace = true }
turbo-unix-path = { workspace = true }
turbopack-cli-utils = { workspace = true }
turbopack-core = { workspace = true }
turbopack-ecmascript = { workspace = true }
......
......@@ -120,6 +120,7 @@ export default async function transform(
filePaths,
directories,
buildFilePaths,
buildModulePaths: buildFilePaths,
envVariables: getReadEnvVariables(),
})
return {
......
......@@ -6,6 +6,13 @@ import type { Channel as Ipc } from '../types'
import { type StructuredError } from '../error'
import { type StackFrame } from '../compiled/stacktrace-parser'
export type BuildModuleRequest = {
lookupPath: string
request: string
expectedPath: string
bypassExports: boolean
}
export type IpcInfoMessage =
| {
type: 'dependencies'
......@@ -14,6 +21,8 @@ export type IpcInfoMessage =
filePaths?: string[]
buildFilePaths?: string[]
buildDependencyRequests?: Array<[string, boolean]>
buildModulePaths?: string[]
buildModuleRequests?: BuildModuleRequest[]
}
| {
type: 'emittedError'
......@@ -31,6 +40,11 @@ export type IpcInfoMessage =
}
export type IpcRequestMessage =
| {
type: 'resolveLoader'
lookupPaths: string[]
request: string
}
| {
type: 'resolve'
options: any
......
declare const __turbopack_external_require__: {
resolve: (name: string, opt?: { paths: string[] }) => string
} & ((id: string, thunk: () => any, esm?: boolean) => any)
import type { Channel as Ipc } from '../types'
import { dirname, resolve as pathResolve } from 'path'
import {
StackFrame,
parse as parseStackTrace,
} from '../compiled/stacktrace-parser'
import { structuredError, type StructuredError } from '../error'
import { getReadEnvVariables, type TransformIpc } from './transforms'
import { structuredError } from '../error'
import {
getReadEnvVariables,
type BuildModuleRequest,
type IpcInfoMessage,
type IpcRequestMessage,
type TransformIpc,
} from './transforms'
import {
evaluateBundle,
type ImportModuleResult,
} from './webpack-loaders-runtime'
import fs from 'fs'
import path from 'path'
export type IpcInfoMessage =
| {
type: 'dependencies'
envVariables?: string[]
directories?: Array<[string, string]>
filePaths?: string[]
buildFilePaths?: string[]
buildDependencyRequests?: Array<[string, boolean]>
}
| {
type: 'emittedError'
severity: 'warning' | 'error'
error: StructuredError
}
| {
type: 'log'
logs: Array<{
time: number
logType: string
args: any[]
trace?: StackFrame[]
}>
}
export type IpcRequestMessage =
| {
type: 'resolve'
options: any
lookupPath: string
request: string
import Module, { createRequire } from 'module'
export type { IpcInfoMessage, IpcRequestMessage } from './transforms'
// CommonJS requests Node resolved, keyed by lookup directory and then resolved filename. Cached
// modules only expose their children's filenames, and a request reconstructed from a symlinked
// package's real path loses the package name, so a nearer package would not invalidate it. Node
// skips resolution for repeated requests from the same directory, so requests are keyed by it.
const resolvedRequests = new Map<string, Map<string, Set<string>>>()
const moduleWithResolveFilename = Module as typeof Module & {
_resolveFilename(
request: string,
parent: NodeJS.Module | undefined,
isMain: boolean,
options?: { paths?: string[] }
): string
}
const originalResolveFilename = moduleWithResolveFilename._resolveFilename
moduleWithResolveFilename._resolveFilename = function (
request,
parent,
isMain,
options
) {
const resolved = originalResolveFilename.call(
this,
request,
parent,
isMain,
options
)
// Requests resolved with custom lookup paths cannot be reproduced from the parent's directory.
if (parent?.filename && !options?.paths && path.isAbsolute(resolved)) {
const lookupPath = path.dirname(parent.filename)
let requestsByFilename = resolvedRequests.get(lookupPath)
if (!requestsByFilename) {
requestsByFilename = new Map()
resolvedRequests.set(lookupPath, requestsByFilename)
}
| {
type: 'importModule'
lookupPath: string
request: string
let requests = requestsByFilename.get(resolved)
if (!requests) {
requests = new Set()
requestsByFilename.set(resolved, requests)
}
requests.add(request)
}
return resolved
}
type LoaderConfig =
| string
......@@ -152,7 +165,7 @@ type ResolveOptions = {
importFields?: string[]
}
const transform = (
const transform = async (
ipc: TransformIpc,
content: string | { binary: string },
name: string,
......@@ -162,14 +175,59 @@ const transform = (
mode: 'development' | 'production',
sourceMap: boolean
) => {
const resource = pathResolve(contextDir, name)
const resourceDir = dirname(resource)
const resolvedLoaders = await Promise.all(
loaders.map(async (config) => {
const { loader, options } =
typeof config === 'string' ? { loader: config, options: {} } : config
const result = (await ipc.sendRequest({
type: 'resolveLoader',
lookupPaths: [contextDir, resourceDir],
request: loader,
})) as { path: string }
return { loader: result.path, options }
})
)
return new Promise((resolve, reject) => {
const resource = pathResolve(contextDir, name)
const resourceDir = dirname(resource)
const loadersWithOptions = loaders.map((loader) =>
typeof loader === 'string' ? { loader, options: {} } : loader
const nodeRequire = createRequire(path.join(contextDir, 'package.json'))
const buildDependencies = new Set(
resolvedLoaders.map((loader) => loader.loader)
)
const buildDependencies = new Set<string>()
const buildModuleRequests = new Map<string, BuildModuleRequest>()
const buildDependencyRequests = new Set<string>()
const addBuildModuleRequest = (
dependency: string,
lookupPath: string,
expectedPath: string,
bypassExports = false
) => {
let request = dependency
if (path.isAbsolute(request)) {
request = path.relative(lookupPath, request)
if (!path.isAbsolute(request) && request.split(path.sep)[0] !== '..') {
request = `./${request}`
}
}
request = request.replaceAll(path.sep, '/')
buildModuleRequests.set(`${lookupPath}\0${request}\0${bypassExports}`, {
lookupPath,
request,
expectedPath,
bypassExports,
})
}
const addBuildDependency = (dependency: string) => {
buildDependencyRequests.add(dependency)
if (!/[\\/]$/.test(dependency)) {
try {
// Node resolution is only used to inspect the runtime cache. Rust tracks the request,
// classifies filesystem inputs, and reports unresolved dependencies.
const resolved = nodeRequire.resolve(dependency)
buildDependencies.add(resolved)
} catch {}
}
}
const logs: Array<{
time: number
......@@ -199,9 +257,7 @@ const transform = (
? entry.options
: {}
},
addBuildDependency(dependency: string) {
buildDependencies.add(dependency)
},
addBuildDependency,
fs: {
readFile(p: string, optionsOrCb: any, maybeCb: any) {
ipc
......@@ -531,12 +587,7 @@ const transform = (
},
},
loaders: loadersWithOptions.map((loader) => ({
loader: __turbopack_external_require__.resolve(loader.loader, {
paths: [contextDir, resourceDir],
}),
options: loader.options,
})),
loaders: resolvedLoaders,
readResource: (_filename, callback) => {
// TODO assuming that filename === resource, but loaders might change that
let data =
......@@ -551,6 +602,55 @@ const transform = (
ipc.sendInfo({ type: 'log', logs: logs })
logs.length = 0
}
const pendingBuildDependencies = [...buildDependencies]
for (const dependency of pendingBuildDependencies) {
const loadedModule = nodeRequire.cache[dependency]
if (!loadedModule) continue
for (const child of loadedModule.children) {
if (!buildDependencies.has(child.filename)) {
buildDependencies.add(child.filename)
pendingBuildDependencies.push(child.filename)
}
const lookupPath = path.dirname(dependency)
const requests = resolvedRequests
.get(lookupPath)
?.get(child.filename)
if (requests) {
for (const request of requests) {
addBuildModuleRequest(request, lookupPath, child.filename)
}
continue
}
// Modules resolved before the hook was installed, or with custom lookup paths, fall
// back to webpack's cached-child reconstruction, which bypasses exports for package
// subpaths that Node has already loaded.
// https://github.com/webpack/webpack/blob/f1bdec5cc70236083e45b665831d5d79d6485db7/lib/FileSystemInfo.js#L1835-L1895
const modulePath = loadedModule.paths.find((modulePath) =>
child.filename.startsWith(`${modulePath}${path.sep}`)
)
let request = modulePath
? child.filename.slice(modulePath.length + 1)
: path.relative(lookupPath, child.filename)
if (request.endsWith('.js')) request = request.slice(0, -3)
request = request.replaceAll(path.sep, '/')
if (
!modulePath &&
!request.startsWith('../') &&
!path.isAbsolute(request)
) {
request = `./${request}`
}
addBuildModuleRequest(
request,
lookupPath,
child.filename,
!!modulePath
)
}
}
const buildModuleDependencies = [...buildDependencies].filter(
(dependency) => !nodeRequire.cache[dependency]
)
ipc.sendInfo({
type: 'dependencies',
envVariables: getReadEnvVariables(),
......@@ -559,10 +659,12 @@ const transform = (
...result.missingDependencies,
],
directories: result.contextDependencies.map((dep) => [dep, '**']),
buildDependencyRequests: [...buildDependencies]
buildFilePaths: [...buildDependencies],
buildModulePaths: buildModuleDependencies,
buildDependencyRequests: [...buildDependencyRequests]
.map((dependency) => {
// Webpack uses a trailing slash or backslash to identify directory build dependencies:
// https://github.com/webpack/webpack/blob/v5.98.0/lib/FileSystemInfo.js#L1741-L1748
// Webpack identifies directory build dependencies by a trailing slash or backslash.
// https://github.com/webpack/webpack/blob/f1bdec5cc70236083e45b665831d5d79d6485db7/lib/FileSystemInfo.js#L1741-L1748
const isDirectory = /[\\/]$/.test(dependency)
let request = isDirectory ? dependency.slice(0, -1) : dependency
if (path.isAbsolute(request)) {
......@@ -579,19 +681,12 @@ const transform = (
return [request, isDirectory] as [string, boolean]
})
.sort(([a], [b]) => a.localeCompare(b)),
buildModuleRequests: [...buildModuleRequests.values()],
})
if (err) {
// Resolve loader paths to include in the error message using
// Include resolved loader paths in the error message using
// the same "(from ...)" style as webpack's format-webpack-messages.
const loaderPathList = loadersWithOptions.map((l) => {
try {
return __turbopack_external_require__.resolve(l.loader, {
paths: [contextDir, resourceDir],
})
} catch {
return l.loader
}
})
const loaderPathList = resolvedLoaders.map((loader) => loader.loader)
const loaderPaths = loaderPathList.join(', ')
if (!(err instanceof Error)) {
......
......@@ -559,6 +559,7 @@ impl PostCssTransformedAsset {
context_source_for_issue: self.source,
chunking_context: *chunking_context,
evaluate_context: self.evaluate_context,
build_dependency_context: self.config_tracing_context,
module_graph,
resolve_options_context: None,
asset_context: self.asset_context,
......
......@@ -23,6 +23,7 @@ use turbo_tasks_fs::{
rope::Rope,
to_sys_path,
};
use turbo_unix_path::sys_to_unix;
use turbopack_core::{
asset::{Asset, AssetContent},
changed::any_source_content_changed_of_module,
......@@ -73,6 +74,11 @@ use crate::{
transforms::util::{EmittedAsset, emitted_assets_to_virtual_sources},
};
// Webpack parses uncached .js and .mjs build dependencies as ESM. Turbopack's config tracer also
// supports the corresponding explicit CommonJS and TypeScript extensions.
const TRACEABLE_BUILD_DEPENDENCY_EXTENSIONS: [&str; 6] =
[".js", ".cjs", ".mjs", ".ts", ".cts", ".mts"];
#[serde_as]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Encode, Decode)]
struct BytesBase64 {
......@@ -233,58 +239,72 @@ async fn webpack_loaders_executor(
))
}
async fn loader_path(cwd: &FileSystemPath, path: &str) -> Result<FileSystemPath> {
async fn try_loader_path(cwd: &FileSystemPath, path: &str) -> Result<Option<FileSystemPath>> {
let fs = ResolvedVc::try_downcast_type::<DiskFileSystem>(cwd.fs)
.context("webpack loader working directory must be on a disk filesystem")?;
fs.await?
.try_from_sys_path_across_roots(fs, Path::new(path), cwd)
.await
}
async fn loader_path(cwd: &FileSystemPath, path: &str) -> Result<FileSystemPath> {
try_loader_path(cwd, path)
.await?
.with_context(|| format!("webpack loader path {path:?} is outside configured roots"))
}
// TODO: This creates a task that's keyed on the list of file paths, which might churn through tasks
// (creating more pressure for task GC).
async fn build_dependency_path(
cwd: &FileSystemPath,
path: &RcStr,
) -> Result<Option<FileSystemPath>> {
let path = try_loader_path(cwd, path).await?;
if path.is_none() {
Completion::session_dependent().await?;
}
Ok(path)
}
async fn build_dependency_paths(
cwd: &FileSystemPath,
paths: &[RcStr],
) -> Result<Vec<FileSystemPath>> {
Ok(paths
.iter()
.map(|path| build_dependency_path(cwd, path))
.try_join()
.await?
.into_iter()
.flatten()
.collect())
}
#[turbo_tasks::function]
async fn build_files_changed(
paths: Vec<FileSystemPath>,
source: ResolvedVc<Box<dyn Source>>,
) -> Result<Vc<Completion>> {
for path in paths {
let entry_type = path.get_type().await?;
let supported = match &*entry_type {
FileSystemEntryType::File => {
path.read().await?;
true
}
FileSystemEntryType::NotFound => {
path.read().await?;
false
async fn build_files_changed(paths: Vec<FileSystemPath>) -> Result<Vc<Completion>> {
paths
.iter()
.map(async |path| {
let realpath = path.realpath_with_links().await?;
for symlink in realpath.symlinks.iter() {
symlink.read_link().await?;
}
FileSystemEntryType::Directory
| FileSystemEntryType::Symlink
| FileSystemEntryType::Other
| FileSystemEntryType::Error => false,
};
if !supported {
BuildDependencyIssue {
source: IssueSource::from_source_only(source),
path,
match &realpath.path_result {
Ok(path)
if matches!(
&*path.get_type().await?,
FileSystemEntryType::File | FileSystemEntryType::NotFound
) =>
{
path.read().await?;
}
_ => {}
}
.resolved_cell()
.emit();
}
}
Ok::<_, anyhow::Error>(())
})
.try_join()
.await?;
Ok(Completion::new())
}
/// Returns a completion that changes when any of the loader modules (or their
/// transitive dependencies) change. This makes editing a loader file invalidate
/// the cached transform of every module processed by that loader.
///
/// Loaders are resolved relative to the resource's directory, matching webpack
/// semantics (`paths: [contextDir, resourceDir]` in `webpack-loaders.ts`).
/// Loaders that fail to resolve are skipped so that the transform degrades to
/// the previous (non-invalidating) behavior instead of breaking the build.
#[turbo_tasks::function]
async fn loaders_changed(
loaders: Vc<WebpackLoaderItems>,
......@@ -293,8 +313,7 @@ async fn loaders_changed(
resolve_options_context: Vc<ResolveOptionsContext>,
) -> Result<Vc<Completion>> {
let options = resolve_options(project_path.clone(), resolve_options_context);
let origin_path = project_path.clone().join("_")?;
let origin_path = project_path.join("_")?;
let completions = loaders
.await?
.iter()
......@@ -309,12 +328,64 @@ async fn loaders_changed(
.await?;
result
.primary_modules_raw_iter()
.map(|m| any_source_content_changed_of_module(*m).to_resolved())
.map(|module| any_source_content_changed_of_module(*module).to_resolved())
.try_join()
.await
})
.try_flat_join()
.await?;
Ok(Vc::<Completions>::cell(completions).completed())
}
#[turbo_tasks::function]
async fn build_modules_changed(
asset_context: Vc<Box<dyn AssetContext>>,
paths: Vec<FileSystemPath>,
) -> Result<Vc<Completion>> {
let completions = paths
.into_iter()
.map(async |path| {
let realpath = path.realpath_with_links().await?;
for symlink in realpath.symlinks.iter() {
symlink.read_link().await?;
}
let path = match &realpath.path_result {
Ok(realpath) => realpath.clone(),
Err(_) => return Ok(vec![]),
};
if !matches!(
&*path.get_type().await?,
FileSystemEntryType::File | FileSystemEntryType::NotFound
) {
return Ok(vec![]);
}
path.read().await?;
let mut completions = vec![Completion::new().to_resolved().await?];
let path_string = path.to_string();
let trace_module = TRACEABLE_BUILD_DEPENDENCY_EXTENSIONS
.iter()
.any(|extension| path_string.ends_with(extension));
if trace_module
&& matches!(&*path.get_type().await?, FileSystemEntryType::File)
&& let Some(module) = *asset_context
.process(
Vc::upcast(FileSource::new(path)),
ReferenceType::Internal(InnerAssets::empty().to_resolved().await?),
)
.try_into_module()
.await?
{
completions.push(
any_source_content_changed_of_module(*module)
.to_resolved()
.await?,
);
}
Ok(completions)
})
.try_flat_join()
.await?;
Ok(Vc::<Completions>::cell(completions).completed())
}
......@@ -324,6 +395,8 @@ async fn build_dependency_requests_changed(
cwd: FileSystemPath,
requests: Vec<(RcStr, bool)>,
source: ResolvedVc<Box<dyn Source>>,
tracing_context: Vc<Box<dyn AssetContext>>,
known_module_paths: Vec<FileSystemPath>,
) -> Result<Vc<Completion>> {
for (request, is_directory) in requests {
let request_path = cwd.join(&request)?;
......@@ -340,7 +413,46 @@ async fn build_dependency_requests_changed(
continue;
}
let path = if is_directory {
request_path.clone()
match &*Request::parse(Pattern::Constant(request.clone())).await? {
Request::Module {
module: Pattern::Constant(module),
path: Pattern::Constant(subpath),
..
} => {
// Webpack's directory resolver ignores exports and does not require a module
// entry. Track each candidate so a nearer package invalidates this lookup.
let mut directory = cwd.clone();
let path = loop {
let candidate =
directory.join(&format!("node_modules/{module}{subpath}"))?;
let realpath = candidate.realpath_with_links().await?;
for symlink in realpath.symlinks.iter() {
symlink.read_link().await?;
}
if let Ok(path) = &realpath.path_result
&& matches!(&*path.get_type().await?, FileSystemEntryType::Directory)
{
break Some(path.clone());
}
if directory.is_root() {
break None;
}
directory = directory.parent();
};
let Some(path) = path else {
UnresolvedBuildDependencyIssue {
source: IssueSource::from_source_only(source),
request,
error: None,
}
.resolved_cell()
.emit();
continue;
};
path
}
_ => request_path.clone(),
}
} else {
let parsed_request = Request::parse(Pattern::Constant(request.clone()));
let options = if request.ends_with(".mjs") {
......@@ -377,6 +489,9 @@ async fn build_dependency_requests_changed(
let supported = match &*entry_type {
FileSystemEntryType::File if !is_directory => {
path.read().await?;
if !known_module_paths.contains(&path) {
build_modules_changed(tracing_context, vec![path.clone()]).await?;
}
true
}
FileSystemEntryType::Directory if is_directory => {
......@@ -406,6 +521,91 @@ async fn build_dependency_requests_changed(
Ok(Completion::new())
}
#[derive(Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "camelCase")]
pub struct BuildModuleRequest {
lookup_path: RcStr,
request: RcStr,
expected_path: RcStr,
bypass_exports: bool,
}
#[turbo_tasks::task_input]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Encode, Decode)]
struct ResolvedBuildModuleRequest {
lookup_path: FileSystemPath,
request: RcStr,
expected_path: FileSystemPath,
bypass_exports: bool,
}
async fn resolve_build_module_request(
cwd: &FileSystemPath,
request: BuildModuleRequest,
) -> Result<Option<ResolvedBuildModuleRequest>> {
match build_dependency_path(cwd, &request.expected_path).await? {
None => Ok(None),
Some(expected_path) => {
let lookup_path = build_dependency_path(cwd, &request.lookup_path).await?;
Ok(lookup_path.map(|lookup_path| ResolvedBuildModuleRequest {
lookup_path,
request: request.request,
expected_path,
bypass_exports: request.bypass_exports,
}))
}
}
}
#[turbo_tasks::function]
async fn build_module_requests_changed(
requests: Vec<ResolvedBuildModuleRequest>,
) -> Result<Vc<Completion>> {
requests
.into_iter()
.map(
async |ResolvedBuildModuleRequest {
lookup_path,
request,
expected_path,
bypass_exports,
}| {
// Build dependencies use Node's resolver, not application aliases or the tracer's
// TypeScript-first extension order. Cached package children bypass exports in
// webpack.
let mut options = node_cjs_resolve_options().owned().await?;
if bypass_exports {
options.into_package.retain(|option| {
!matches!(option, ResolveIntoPackage::ExportsField { .. })
});
}
let result = resolve(
lookup_path,
ReferenceType::Undefined,
Request::parse(Pattern::Constant(request)),
options.cell(),
)
.await?;
assert!(result.primary_sources().count() <= 1);
let tracked = match result.first_source() {
Some(resolved) => resolved.ident().await?.path == expected_path,
None => false,
};
// The request does not reproduce the module Node loaded, so a change to which
// module it resolves to cannot be detected.
if !tracked {
Completion::session_dependent().await?;
}
Ok::<_, anyhow::Error>(())
},
)
.try_join()
.await?;
Ok(Completion::new())
}
#[turbo_tasks::value_impl]
impl WebpackLoadersProcessedAsset {
#[turbo_tasks::function]
......@@ -508,6 +708,7 @@ impl WebpackLoadersProcessedAsset {
context_source_for_issue: self.source,
chunking_context: *chunking_context,
evaluate_context: transform.evaluate_context,
build_dependency_context: transform.config_tracing_context,
module_graph,
resolve_options_context: Some(transform.resolve_options_context),
asset_context: self.asset_context,
......@@ -630,6 +831,10 @@ pub enum InfoMessage {
build_file_paths: Vec<RcStr>,
#[serde(default)]
build_dependency_requests: Vec<(RcStr, bool)>,
#[serde(default)]
build_module_paths: Vec<RcStr>,
#[serde(default)]
build_module_requests: Vec<BuildModuleRequest>,
},
EmittedError {
severity: IssueSeverity,
......@@ -658,6 +863,11 @@ pub struct WebpackResolveOptions {
#[derive(Deserialize, Debug)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum RequestMessage {
#[serde(rename_all = "camelCase")]
ResolveLoader {
lookup_paths: Vec<RcStr>,
request: RcStr,
},
#[serde(rename_all = "camelCase")]
Resolve {
options: WebpackResolveOptions,
......@@ -708,6 +918,7 @@ pub struct WebpackLoaderContext {
pub module_graph: ResolvedVc<ModuleGraph>,
pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
pub evaluate_context: ResolvedVc<Box<dyn AssetContext>>,
pub build_dependency_context: ResolvedVc<Box<dyn AssetContext>>,
pub resolve_options_context: Option<ResolvedVc<ResolveOptionsContext>>,
pub asset_context: ResolvedVc<Box<dyn AssetContext>>,
pub args: Vec<ResolvedVc<JsonValue>>,
......@@ -812,10 +1023,24 @@ impl EvaluateContext for WebpackLoaderContext {
directories,
build_file_paths,
build_dependency_requests,
build_module_paths,
build_module_requests,
} => {
// We only process these dependencies to help with tracking, so if it is disabled
// dont bother.
if turbo_tasks::turbo_tasks().is_tracking_dependencies() {
// Canonicalize dependency sets so their ordering does not create new task keys.
let normalize = |mut paths: Vec<RcStr>| {
paths.sort_unstable();
paths.dedup();
paths
};
let build_file_paths = normalize(build_file_paths);
let build_module_paths = normalize(build_module_paths);
let mut build_module_requests = build_module_requests;
build_module_requests.sort_unstable();
build_module_requests.dedup();
// Track dependencies of the loader task
// TODO: Because these are reported _after_ the loader actually read the
// dependency there is a race condition where we may miss
......@@ -832,15 +1057,29 @@ impl EvaluateContext for WebpackLoaderContext {
.map(async |p| loader_path(&self.cwd, p).await?.read().await)
.try_join();
let build_file_subscriptions = async {
// Resolve to `FileSystemPath`s before calling the task: system paths
// aren't valid task inputs, as they aren't portable across machines.
let build_file_paths = build_file_paths
.iter()
.map(|p| loader_path(&self.cwd, p))
let paths = build_dependency_paths(&self.cwd, &build_file_paths).await?;
build_files_changed(paths).await?;
Ok::<_, anyhow::Error>(())
};
let build_module_subscriptions = async {
build_modules_changed(
*self.build_dependency_context,
build_dependency_paths(&self.cwd, &build_module_paths).await?,
)
.await?;
Ok::<_, anyhow::Error>(())
};
let build_module_request_subscriptions = async {
// Convert system paths before they enter persistent task inputs.
let requests = build_module_requests
.into_iter()
.map(|request| resolve_build_module_request(&self.cwd, request))
.try_join()
.await?;
build_files_changed(build_file_paths, *self.context_source_for_issue)
.await?;
.await?
.into_iter()
.flatten()
.collect();
build_module_requests_changed(requests).await?;
Ok::<_, anyhow::Error>(())
};
let build_dependency_request_subscriptions = async {
......@@ -848,6 +1087,8 @@ impl EvaluateContext for WebpackLoaderContext {
self.cwd.clone(),
build_dependency_requests,
*self.context_source_for_issue,
*self.build_dependency_context,
build_dependency_paths(&self.cwd, &build_file_paths).await?,
)
.await?;
Ok::<_, anyhow::Error>(())
......@@ -865,6 +1106,8 @@ impl EvaluateContext for WebpackLoaderContext {
env_subscriptions,
file_subscriptions,
build_file_subscriptions,
build_module_subscriptions,
build_module_request_subscriptions,
build_dependency_request_subscriptions,
directory_subscriptions
)?;
......@@ -896,6 +1139,52 @@ impl EvaluateContext for WebpackLoaderContext {
_pool: &EvaluatePool,
) -> Result<Self::ResponseMessage> {
match data {
RequestMessage::ResolveLoader {
lookup_paths,
request,
} => {
let (paths, parsed_request) = if Path::new(&*request).has_root() {
let path = loader_path(&self.cwd, &request).await?;
let parent = path.parent();
let relative = parent.get_relative_request_to(&path).unwrap();
(
vec![parent],
Request::relative(
Pattern::Constant(relative),
RcStr::default(),
RcStr::default(),
false,
),
)
} else {
(
lookup_paths
.iter()
.map(|path| loader_path(&self.cwd, path))
.try_join()
.await?,
Request::parse(Pattern::Constant(RcStr::from(sys_to_unix(&request)))),
)
};
for path in paths {
let resolved = resolve(
path,
ReferenceType::Undefined,
parsed_request,
node_cjs_resolve_options(),
);
if let Some(source) = resolved.await?.first_source() {
let path = to_sys_path(source.ident().await?.path.clone())
.await?
.context("resolved loader path is not on a disk filesystem")?;
let path = path
.to_str()
.context("resolved loader path is not valid UTF-8")?;
return Ok(ResponseMessage::Resolve { path: path.into() });
}
}
bail!("Unable to resolve loader {request:?} in {lookup_paths:?}");
}
RequestMessage::Resolve {
options: webpack_options,
lookup_path,
......@@ -918,7 +1207,6 @@ impl EvaluateContext for WebpackLoaderContext {
);
if let Some(source) = resolved.await?.first_source() {
// Always return absolute paths from the resolve function.
let path = to_sys_path(source.ident().await?.path.clone())
.await?
.context("resolved path is not on a disk filesystem")?;
......@@ -1187,7 +1475,6 @@ async fn apply_webpack_resolve_options(
Ok(resolve_options.cell())
}
/// An issue that occurred while evaluating node code.
#[turbo_tasks::value(shared)]
pub struct BuildDependencyIssue {
pub path: FileSystemPath,
......@@ -1200,21 +1487,17 @@ impl Issue for BuildDependencyIssue {
fn severity(&self) -> IssueSeverity {
IssueSeverity::Warning
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!(
"Unsupported webpack loader build dependency"
)))
}
fn stage(&self) -> IssueStage {
IssueStage::Unsupported
}
async fn file_path(&self) -> Result<FileSystemPath> {
self.source.file_path().await
}
async fn description(&self) -> Result<Option<StyledString>> {
Ok(Some(StyledString::Line(vec![
StyledString::Text(rcstr!("The path at ")),
......@@ -1226,7 +1509,6 @@ impl Issue for BuildDependencyIssue {
),
])))
}
fn source(&self) -> Option<IssueSource> {
Some(self.source)
}
......@@ -1245,21 +1527,17 @@ impl Issue for UnresolvedBuildDependencyIssue {
fn severity(&self) -> IssueSeverity {
IssueSeverity::Warning
}
async fn title(&self) -> Result<StyledString> {
Ok(StyledString::Text(rcstr!(
"Unable to resolve webpack loader build dependency"
)))
}
fn stage(&self) -> IssueStage {
IssueStage::Resolve
}
async fn file_path(&self) -> Result<FileSystemPath> {
self.source.file_path().await
}
async fn description(&self) -> Result<Option<StyledString>> {
let mut description = vec![
StyledString::Text(rcstr!("The build dependency request ")),
......@@ -1273,7 +1551,6 @@ impl Issue for UnresolvedBuildDependencyIssue {
}
Ok(Some(StyledString::Line(description)))
}
fn source(&self) -> Option<IssueSource> {
Some(self.source)
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment