Skip to content
Open
Show file tree
Hide file tree
Changes from 14 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
8 changes: 4 additions & 4 deletions packages/vite/src/node/__tests__/plugins/import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,13 @@ describe('runTransform', () => {
test('import all specifier', () => {
expect(runTransformCjsImport('import * as react from "react"', false))
.toMatchInlineSnapshot(`
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 0)"
`)
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 0)"
`)
expect(runTransformCjsImport('import * as react from "react"', true))
.toMatchInlineSnapshot(`
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 1)"
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 1)"
`)
})

Expand Down
49 changes: 49 additions & 0 deletions packages/vite/src/node/optimizer/rolldownDepPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'node:path'
import type { ImportKind, Plugin, RolldownPlugin } from 'rolldown'
import { prefixRegex } from '@rolldown/pluginutils'
import MagicString from 'magic-string'
import { JS_TYPES_RE, KNOWN_ASSET_TYPES } from '../constants'
import type { PackageCache } from '../packages'
import {
Expand All @@ -11,6 +12,7 @@ import {
isExternalUrl,
isNodeBuiltin,
moduleListContains,
normalizePath,
} from '../utils'
import { browserExternalId, optionalPeerDepId } from '../plugins/resolve'
import { isModuleCSSRequest } from '../plugins/css'
Expand Down Expand Up @@ -298,6 +300,53 @@ export function rolldownDepPlugin(
}
},
},
transform: {
filter: { code: /new\s+URL/ },
async handler(code, id) {
if (!id.includes('node_modules')) return null

Comment on lines +306 to +307
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if (!id.includes('node_modules')) return null

If the file is bundled by the optimizer, I think we need to resolve the path in new URL.

const s = new MagicString(code)

const workerRE =
/new\s+URL\s*\(\s*['"]([^'"]+)['"]\s*,\s*import\.meta\.url\s*\)/g

// Optimized dependencies are always written to the 'deps' sub-directory
// within the configured cache directory.
const bundleDir = path.join(environment.config.cacheDir, 'deps')

let hasReplacements = false
let match
while ((match = workerRE.exec(code))) {
hasReplacements = true
const [fullMatch, url] = match
const absolutePath = path.resolve(path.dirname(id), url)
const relativePath = path.relative(bundleDir, absolutePath)
const normalizedRelativePath = normalizePath(relativePath)

// NOTE: add `'' +` to opt-out rolldown's transform: https://github.com/rolldown/rolldown/issues/2745
const replacement = `new URL('' + ${JSON.stringify(normalizedRelativePath)}, import.meta.url)`

s.overwrite(
match.index,
match.index + fullMatch.length,
replacement,
)

const assetDir = path.dirname(absolutePath)

if (
environment.config.server.fs.allow &&
!environment.config.server.fs.allow.includes(assetDir)
) {
environment.config.server.fs.allow.push(assetDir)
}
Comment on lines +335 to +342
Copy link
Member

Choose a reason for hiding this comment

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

I guess this part is not needed because it'll be handled by the other internal plugins.

}

if (!hasReplacements) return null

return { code: s.toString(), map: s.generateMap({ hires: true }) }
},
},
},
]
}
Expand Down
40 changes: 40 additions & 0 deletions playground/optimize-deps/__tests__/optimize-deps.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
import {
browserErrors,
Expand Down Expand Up @@ -370,3 +372,41 @@ test.runIf(isServe)(
expect(scanErrors).toHaveLength(0)
},
)

test('should fix standard web worker URLs in optimized dependencies', async () => {
await expect
.poll(() => browserLogs.join('\n'))
.toMatch(/Message from lib: worker-success/)
await expect
.poll(() => browserLogs.join('\n'))
.toMatch(/Message from nested: worker-success/)

if (isServe) {
const playgroundDir = path.resolve(__dirname, '..')
const depsDir = path.join(playgroundDir, 'node_modules', '.vite', 'deps')

const files = fs.readdirSync(depsDir)
const workerReproFile = files.find(
(f) => f.includes('test-dep-with-worker-repro') && f.endsWith('.js'),
)

if (!workerReproFile) {
throw new Error(
`Could not find optimized bundle for worker repro in ${depsDir}. Available files: ${files.join(', ')}`,
)
}

const content = fs.readFileSync(
path.join(depsDir, workerReproFile),
'utf-8',
)

const urlContentMatch = content.match(/new URL\('' \+ "([^"]+)"/)
const innerUrl = urlContentMatch ? urlContentMatch[1] : ''

expect(innerUrl, `Path "${innerUrl}" should not be absolute`).not.toMatch(
/^\/|^[a-zA-Z]:\\|^\\\\/,
)
expect(innerUrl).toMatch(/^\.\.\//)
}
})
8 changes: 8 additions & 0 deletions playground/optimize-deps/dep-with-worker-repro/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function urlImportWorker() {
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module',
})
return new Promise((res) => {
worker.onmessage = (e) => res(e.data)
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function urlImportWorker() {
// Testing the ../ path traversal
const worker = new Worker(new URL('../worker.js', import.meta.url), {
type: 'module',
})
return new Promise((res) => {
worker.onmessage = (e) => res(e.data)
})
}
9 changes: 9 additions & 0 deletions playground/optimize-deps/dep-with-worker-repro/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@vitejs/test-dep-with-worker-repro",
"version": "1.0.0",
"type": "module",
"exports": {
".": "./index.js",
"./nested": "./nested/index.js"
}
}
1 change: 1 addition & 0 deletions playground/optimize-deps/dep-with-worker-repro/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
self.postMessage('worker-success')
7 changes: 7 additions & 0 deletions playground/optimize-deps/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -386,3 +386,10 @@ <h2>Virtual module with .vue extension</h2>
`${VirtualComponent.name === 'VirtualComponent' ? 'ok' : 'ng'}`,
)
</script>
<script type="module">
import * as lib from '@vitejs/test-dep-with-worker-repro'
import * as nested from '@vitejs/test-dep-with-worker-repro/nested'

lib.urlImportWorker().then((m) => console.log('Message from lib:', m))
nested.urlImportWorker().then((m) => console.log('Message from nested:', m))
</script>
1 change: 1 addition & 0 deletions playground/optimize-deps/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"@vitejs/test-dep-non-optimized": "file:./dep-non-optimized",
"@vitejs/test-added-in-entries": "file:./added-in-entries",
"@vitejs/test-dep-cjs-external-package-omit-js-suffix": "file:./dep-cjs-external-package-omit-js-suffix",
"@vitejs/test-dep-with-worker-repro": "file:./dep-with-worker-repro",
"lodash-es": "^4.17.22",
"@vitejs/test-nested-exclude": "file:./nested-exclude",
"phoenix": "^1.8.3",
Expand Down
Loading
Loading