Skip to content
Open
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
4 changes: 2 additions & 2 deletions src/rspack/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { resolve } from 'node:path'
import { version as unpluginVersion } from '../../package.json'
import { normalizeObjectHook } from '../utils/filter'
import { toArray } from '../utils/general'
import { createCachedIdFilter, normalizeAbsolutePath, transformUse } from '../utils/webpack-like'
import { createCachedIdFilter, normalizeAbsolutePath, realContext, transformUse } from '../utils/webpack-like'
import { createBuildContext, normalizeMessage } from './context'
import { decodeVirtualModuleId, encodeVirtualModuleId, FakeVirtualModulesPlugin, isVirtualModuleId } from './utils'

Expand Down Expand Up @@ -79,7 +79,7 @@ function applyRspackPlugins(
) {
// We need the prefix of virtual modules to be an absolute path so rspack lets us load them (even if it's made up)
// In the loader we strip the made up prefix path again
const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process.cwd(), 'node_modules/.virtual', compiler.rspack.experiments.VirtualModulesPlugin
const VIRTUAL_MODULE_PREFIX = resolve(realContext(compiler.options.context ?? process.cwd()), 'node_modules/.virtual', compiler.rspack.experiments.VirtualModulesPlugin
? ''
: process.pid.toString())

Expand Down
26 changes: 26 additions & 0 deletions src/utils/webpack-like.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RuleSetUseItem } from '@rspack/core'
import type { ResolvedUnpluginOptions, UnpluginOptions } from '../types'
import type { PluginFilter } from './filter'
import { realpathSync } from 'node:fs'
import { isAbsolute, normalize } from 'node:path'
import { normalizeObjectHook } from './filter'

Expand Down Expand Up @@ -60,6 +61,31 @@ export function normalizeAbsolutePath(path: string): string {
return path
}

/**
* Returns the build context with its symlinks resolved, to build the virtual module prefix on.
*
* Webpack and Rspack resolve symlinks in module paths (`resolve.symlinks` is on by default), so
* a virtual module path made from a context that goes through a link, such as any project under
* macOS's `/var` or a linked project folder, resolves to a path where the virtual module was
* never written, and the build fails with ENOENT.
*
* With no link left in the prefix, neither resolver rewrites a virtual path built on it.
* `realpathSync` and not `realpathSync.native`: it resolves links and junctions only, and leaves
* Windows short names and letter case as the context gave them. A context that does not exist
* is returned as is.
*
* @param context - The `context` option of the compiler, or the current directory.
* @returns the real path of the context.
*/
export function realContext(context: string): string {
try {
return realpathSync(context)
}
catch {
return context
}
}

/**
* Webpack escapes special characters in a resource path, such as the `#` of `msg#hash.js`, by
* prefixing them with an escape character. Rspack does the same with a different one.
Expand Down
4 changes: 2 additions & 2 deletions src/webpack/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import process from 'node:process'
import { version as unpluginVersion } from '../../package.json'
import { normalizeObjectHook } from '../utils/filter'
import { toArray } from '../utils/general'
import { createCachedIdFilter, normalizeAbsolutePath, transformUse } from '../utils/webpack-like'
import { createCachedIdFilter, normalizeAbsolutePath, realContext, transformUse } from '../utils/webpack-like'
import { contextOptionsFromCompilation, createBuildContext, normalizeMessage } from './context'

const TRANSFORM_LOADER = resolve(
Expand Down Expand Up @@ -77,7 +77,7 @@ export function getWebpackPlugin<UserOptions = Record<string, never>>(
apply(compiler: WebpackCompiler) {
// We need the prefix of virtual modules to be an absolute path so webpack let's us load them (even if it's made up)
// In the loader we strip the made up prefix path again
const VIRTUAL_MODULE_PREFIX = resolve(compiler.options.context ?? process.cwd(), '_virtual_')
const VIRTUAL_MODULE_PREFIX = resolve(realContext(compiler.options.context ?? process.cwd()), '_virtual_')

const version = (compiler as any).webpack?.version
const meta: UnpluginContextMeta = {
Expand Down
93 changes: 93 additions & 0 deletions test/unit-tests/symlinked-context/symlinked-context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createUnplugin } from 'unplugin'
import { afterAll, describe, expect, it } from 'vitest'
import { runRspack, runWebpack } from '../utils'

// The project is reached through a link, the way every project under macOS's `/var` is
// (`/var` -> `/private/var`), or a linked project folder anywhere. A junction on Windows
// needs no privilege; other platforms ignore the type.
const root = realpathSync(mkdtempSync(join(tmpdir(), 'unplugin-symlinked-context-')))
const real = join(root, 'real')
const link = join(root, 'link')

mkdirSync(real, { recursive: true })
symlinkSync(real, link, 'junction')
writeFileSync(join(real, 'entry.js'), [
`import a from 'virtual-a'`,
`console.log(a)`,
].join('\n'))

afterAll(() => rmSync(root, { recursive: true, force: true }))

function createPlugin() {
const seen = { resolveId: [] as [string, string | undefined][], load: [] as string[] }
const plugin = createUnplugin(() => ({
name: 'symlinked-context',
resolveId(id, importer) {
seen.resolveId.push([id, importer])
if (id === 'virtual-a' || id === 'virtual-b')
return `\0${id}`
},
load(id) {
seen.load.push(id)
if (id === '\0virtual-a')
return `import b from 'virtual-b'\nexport default 'virtual-a:' + b`
if (id === '\0virtual-b')
return `export default 'from-virtual-b'`
},
}))
return { seen, plugin }
}

const frameworks = [
[
'webpack',
(plugin: ReturnType<typeof createPlugin>['plugin'], output: string) => runWebpack({
mode: 'development',
devtool: false,
context: link,
entry: join(link, 'entry.js'),
output: { path: output, filename: 'main.js' },
plugins: [
plugin.webpack(),
],
}),
],
[
'rspack',
(plugin: ReturnType<typeof createPlugin>['plugin'], output: string) => runRspack({
mode: 'development',
devtool: false,
context: link,
entry: join(link, 'entry.js'),
output: { path: output, filename: 'main.js' },
plugins: [
plugin.rspack(),
],
}),
],
] as const

describe('a build context reached through a symlink', () => {
for (const [name, run] of frameworks) {
it(name, async () => {
const { seen, plugin } = createPlugin()
const output = join(root, `dist-${name}`)
await run(plugin, output)

// Both virtual modules reach load with their own id, not the made up path
expect(seen.load).toContain('\0virtual-a')
expect(seen.load).toContain('\0virtual-b')
// A virtual importer is decoded before it reaches resolveId, never the made up path.
// rspack keeps a leading separator on it with or without a link, a separate matter.
expect(seen.resolveId).toContainEqual([
'virtual-b',
expect.stringMatching(/^[\\/]?\0virtual-a$/),
])
// and what load returned is what got bundled
expect(readFileSync(join(output, 'main.js'), 'utf8')).toContain('from-virtual-b')
})
}
})
24 changes: 23 additions & 1 deletion test/unit-tests/utils/webpack-like.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { ResolvedUnpluginOptions } from '../../../src/types'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { createCachedIdFilter, normalizeAbsolutePath, transformUse, unescapeResourcePath } from '../../../src/utils/webpack-like'
import { createCachedIdFilter, normalizeAbsolutePath, realContext, transformUse, unescapeResourcePath } from '../../../src/utils/webpack-like'

describe('normalizeAbsolutePath', () => {
it('leaves relative ids alone and normalizes absolute ones', () => {
Expand All @@ -10,6 +12,26 @@ describe('normalizeAbsolutePath', () => {
})
})

describe('realContext', () => {
it('resolves a context reached through a link, and returns a missing one as is', () => {
const root = realpathSync(mkdtempSync(path.join(tmpdir(), 'unplugin-real-context-')))
try {
const real = path.join(root, 'real')
const link = path.join(root, 'link')
mkdirSync(real)
// a junction on Windows needs no privilege; other platforms ignore the type
symlinkSync(real, link, 'junction')
expect(realContext(link)).toBe(real)
expect(realContext(real)).toBe(real)
const missing = path.join(root, 'missing')
expect(realContext(missing)).toBe(missing)
}
finally {
rmSync(root, { recursive: true, force: true })
}
})
})

describe('unescapeResourcePath', () => {
it('removes each bundler\'s own escape character only', () => {
expect(unescapeResourcePath('/a/msg\0#hash.js', 'webpack')).toBe('/a/msg#hash.js')
Expand Down