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: make Worker constructors configurable #16422

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
17 changes: 17 additions & 0 deletions packages/vite/LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1319,6 +1319,23 @@ Repository: component/escape-html

---------------------------------------

## escape-string-regexp
License: MIT
By: Sindre Sorhus
Repository: sindresorhus/escape-string-regexp

> MIT License
>
> Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

---------------------------------------

## estree-walker
License: MIT
By: Rich Harris
Expand Down
1 change: 1 addition & 0 deletions packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
"dotenv-expand": "^11.0.6",
"es-module-lexer": "^1.5.0",
"escape-html": "^1.0.3",
"escape-string-regexp": "^5.0.0",
"estree-walker": "^3.0.3",
"etag": "^1.8.1",
"fast-glob": "^3.3.2",
Expand Down
31 changes: 31 additions & 0 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
DEFAULT_MAIN_FIELDS,
ENV_ENTRY,
FS_PREFIX,
type WORKER_KINDS,
} from './constants'
import type { HookHandler, Plugin, PluginWithRequiredHook } from './plugin'
import type {
Expand Down Expand Up @@ -95,6 +96,12 @@ export interface ConfigEnv {
*/
export type AppType = 'spa' | 'mpa' | 'custom'

/**
* worker: a normal web worker (e.g. via `new Worker()`)
* sharedWorker: a shared worker (e.g. via `new SharedWorker()`)
*/
export type WorkerKind = (typeof WORKER_KINDS)[number] // = 'worker' | 'sharedworker'

export type UserConfigFnObject = (env: ConfigEnv) => UserConfig
export type UserConfigFnPromise = (env: ConfigEnv) => Promise<UserConfig>
export type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>
Expand Down Expand Up @@ -278,6 +285,12 @@ export interface UserConfig {
RollupOptions,
'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'
>
/**
* The list of constructors to detect as Web Workers and their worker type.
* Use `defaults` as item to include the built-in default values in your custom configuration.
* @default [{constructor:'Worker',kind:'worker'},{constructor:'SharedWorker',kind:'sharedWorker'}]
*/
constructors?: ('defaults' | { constructor: string; kind: WorkerKind })[]
}
/**
* Whether your application is a Single Page Application (SPA),
Expand Down Expand Up @@ -346,6 +359,7 @@ export interface ResolvedWorkerOptions {
format: 'es' | 'iife'
plugins: (bundleChain: string[]) => Promise<Plugin[]>
rollupOptions: RollupOptions
constructors: { constructor: string; kind: WorkerKind }[]
}

export interface InlineConfig extends UserConfig {
Expand Down Expand Up @@ -756,10 +770,27 @@ export async function resolveConfig(
return resolvedWorkerPlugins
}

const defaultWorkerConstructors: ResolvedWorkerOptions['constructors'] = [
{ constructor: 'Worker', kind: 'worker' },
{ constructor: 'SharedWorker', kind: 'sharedworker' },
]

const resolvedWorkerOptions: ResolvedWorkerOptions = {
format: config.worker?.format || 'iife',
plugins: createWorkerPlugins,
rollupOptions: config.worker?.rollupOptions || {},
constructors:
config.worker?.constructors?.reduce(
(prev, c) => {
if (c === 'defaults') {
prev.push(...defaultWorkerConstructors)
} else {
prev.push(c)
}
return prev
},
[] as ResolvedWorkerOptions['constructors'],
) || defaultWorkerConstructors,
}

resolved = {
Expand Down
5 changes: 4 additions & 1 deletion packages/vite/src/node/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ export const CSS_LANGS_RE =

export const OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/

export const SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/
export const WORKER_KINDS = ['worker', 'sharedworker'] as const
export const SPECIAL_QUERY_RE = new RegExp(
`[?&](?:${WORKER_KINDS.join('|')}|raw|url)\\b`,
)

/**
* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
Expand Down
12 changes: 8 additions & 4 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import path from 'node:path'
import MagicString from 'magic-string'
import type { OutputChunk } from 'rollup'
import type { ResolvedConfig } from '../config'
import type { ResolvedConfig, WorkerKind } from '../config'
import type { Plugin } from '../plugin'
import type { ViteDevServer } from '../server'
import { ENV_ENTRY, ENV_PUBLIC_PATH } from '../constants'
import { ENV_ENTRY, ENV_PUBLIC_PATH, WORKER_KINDS } from '../constants'
import {
encodeURIPath,
getHash,
Expand Down Expand Up @@ -37,7 +37,9 @@ interface WorkerCache {

export type WorkerType = 'classic' | 'module' | 'ignore'

export const workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/
export const workerOrSharedWorkerRE = new RegExp(
`(?:\\?|&)(${WORKER_KINDS.join('|')})(?:&|$)`,
)
const workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/
const inlineRE = /[?&]inline\b/

Expand Down Expand Up @@ -278,8 +280,10 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
if (!workerMatch) return

const { format } = config.worker
const workerKind = workerMatch[1] as WorkerKind
const workerConstructor =
workerMatch[1] === 'sharedworker' ? 'SharedWorker' : 'Worker'
workerKind === 'sharedworker' ? 'SharedWorker' : 'Worker'

const workerType = isBuild
? format === 'es'
? 'module'
Expand Down
42 changes: 32 additions & 10 deletions packages/vite/src/node/plugins/workerImportMetaUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import path from 'node:path'
import MagicString from 'magic-string'
import type { RollupError } from 'rollup'
import { stripLiteral } from 'strip-literal'
import escapeStringRegexp from 'escape-string-regexp'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { evalValue, injectQuery, transformStableResult } from '../utils'
Expand Down Expand Up @@ -89,12 +90,8 @@ function getWorkerType(raw: string, clean: string, i: number): WorkerType {
return 'classic'
}

function isIncludeWorkerImportMetaUrl(code: string): boolean {
if (
(code.includes('new Worker') || code.includes('new SharedWorker')) &&
code.includes('new URL') &&
code.includes(`import.meta.url`)
) {
function includesWorkerImportMetaUrl(code: string): boolean {
if (code.includes('new URL') && code.includes(`import.meta.url`)) {
return true
}
return false
Expand All @@ -114,21 +111,46 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
asSrc: true,
}

function includesWorkerConstructor(code: string): boolean {
for (const c of config.worker.constructors) {
if (code.includes(`new ${c.constructor}`)) {
return true
}
}
return false
}

const workerConstructorRE = config.worker.constructors
.map((c) => escapeStringRegexp(c.constructor))
.join('|')

return {
name: 'vite:worker-import-meta-url',

shouldTransformCachedModule({ code }) {
if (isBuild && config.build.watch && isIncludeWorkerImportMetaUrl(code)) {
if (
isBuild &&
config.build.watch &&
includesWorkerConstructor(code) &&
includesWorkerImportMetaUrl(code)
) {
return true
}
},

async transform(code, id, options) {
if (!options?.ssr && isIncludeWorkerImportMetaUrl(code)) {
if (
!options?.ssr &&
includesWorkerConstructor(code) &&
includesWorkerImportMetaUrl(code)
) {
let s: MagicString | undefined
const cleanString = stripLiteral(code)
const workerImportMetaUrlRE =
/\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg

const workerImportMetaUrlRE = new RegExp(
`\\bnew\\s+(?:${workerConstructorRE})\\s*\\(\\s*(new\\s+URL\\s*\\(\\s*('[^']+'|"[^"]+"|\`[^\`]+\`)\\s*,\\s*import\\.meta\\.url\\s*\\))`,
'dg',
)

let match: RegExpExecArray | null
while ((match = workerImportMetaUrlRE.exec(cleanString))) {
Expand Down
10 changes: 9 additions & 1 deletion playground/worker/__tests__/es/worker-es.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ describe.runIf(isBuild)('build', () => {
test('inlined code generation', async () => {
const assetsDir = path.resolve(testDir, 'dist/es/assets')
const files = fs.readdirSync(assetsDir)
expect(files.length).toBe(34)
expect(files.length).toBe(35)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const worker = files.find((f) => f.includes('my-worker'))
Expand Down Expand Up @@ -240,3 +240,11 @@ test('self reference url worker', async () => {
'pong: main\npong: nested\n',
)
})

test('custom constructor', async () => {
await untilUpdated(
() => page.textContent('.worker-custom-constructor'),
'A string',
true,
)
})
10 changes: 9 additions & 1 deletion playground/worker/__tests__/iife/worker-iife.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ describe.runIf(isBuild)('build', () => {
test('inlined code generation', async () => {
const assetsDir = path.resolve(testDir, 'dist/iife/assets')
const files = fs.readdirSync(assetsDir)
expect(files.length).toBe(22)
expect(files.length).toBe(23)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const worker = files.find((f) => f.includes('worker_entry-my-worker'))
Expand Down Expand Up @@ -192,3 +192,11 @@ function decodeSourceMapUrl(content: string) {
).toString(),
)
}

test('custom constructor', async () => {
await untilUpdated(
() => page.textContent('.worker-custom-constructor'),
'A string',
true,
)
})
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe.runIf(isBuild)('build', () => {

const files = fs.readdirSync(assetsDir)
// should have 2 worker chunk
expect(files.length).toBe(44)
expect(files.length).toBe(46)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const indexSourcemap = getSourceMapUrl(content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe.runIf(isBuild)('build', () => {

const files = fs.readdirSync(assetsDir)
// should have 2 worker chunk
expect(files.length).toBe(22)
expect(files.length).toBe(23)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const indexSourcemap = getSourceMapUrl(content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe.runIf(isBuild)('build', () => {
const assetsDir = path.resolve(testDir, 'dist/iife-sourcemap/assets')
const files = fs.readdirSync(assetsDir)
// should have 2 worker chunk
expect(files.length).toBe(44)
expect(files.length).toBe(46)
const index = files.find((f) => f.includes('main-module'))
const content = fs.readFileSync(path.resolve(assetsDir, index), 'utf-8')
const indexSourcemap = getSourceMapUrl(content)
Expand Down
7 changes: 7 additions & 0 deletions playground/worker/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,13 @@ <h2 class="format-es"></h2>
</p>
<code class="module-and-worker-worker"></code>

<p>
new Custom.Constructor(new URL('./url-worker.js', import.meta.url), { type:
'module' })
<span class="classname">.worker-custom-constructor</span>
</p>
<code class="worker-custom-constructor"></code>

<style>
p {
background: rgba(0, 0, 0, 0.1);
Expand Down
12 changes: 12 additions & 0 deletions playground/worker/url-worker-custom-constructor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
self.postMessage(
[
'A string',
import.meta.env.BASE_URL,
self.location.url,
import.meta && import.meta.url,
import.meta.url,
].join(' '),
)

// for sourcemap
console.log('url-worker-custom-constructor.js')
4 changes: 4 additions & 0 deletions playground/worker/vite.config-es.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export default defineConfig({
entryFileNames: 'assets/worker_entry-[name].js',
},
},
constructors: [
'defaults',
{ constructor: 'Custom.Constructor', kind: 'worker' },
],
},
build: {
outDir: 'dist/es',
Expand Down
8 changes: 8 additions & 0 deletions playground/worker/vite.config-iife.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ export default defineConfig({
entryFileNames: 'assets/worker_-[name].js',
},
},
constructors: [
'defaults',
{ constructor: 'Custom.Constructor', kind: 'worker' },
],
},
build: {
outDir: 'dist/iife',
Expand All @@ -45,6 +49,10 @@ export default defineConfig({
entryFileNames: 'assets/worker_entry-[name].js',
},
},
constructors: [
'defaults',
{ constructor: 'Custom.Constructor', kind: 'worker' },
],
},
}
},
Expand Down
4 changes: 4 additions & 0 deletions playground/worker/vite.config-relative-base-iife.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export default defineConfig(({ isPreview }) => ({
entryFileNames: 'worker-entries/worker_entry-[name]-[hash].js',
},
},
constructors: [
'defaults',
{ constructor: 'Custom.Constructor', kind: 'worker' },
],
},
build: {
outDir: 'dist/relative-base-iife',
Expand Down
4 changes: 4 additions & 0 deletions playground/worker/vite.config-relative-base.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export default defineConfig(({ isPreview }) => ({
entryFileNames: 'worker-entries/worker_entry-[name]-[hash].js',
},
},
constructors: [
'defaults',
{ constructor: 'Custom.Constructor', kind: 'worker' },
],
},
build: {
outDir: 'dist/relative-base',
Expand Down
4 changes: 4 additions & 0 deletions playground/worker/worker-sourcemap-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ export default (sourcemap) => {
entryFileNames: 'assets/[name]-worker_entry[hash].js',
},
},
constructors: [
'defaults',
{ constructor: 'Custom.Constructor', kind: 'worker' },
],
},
build: {
outDir: `dist/iife-${typeName}/`,
Expand Down
Loading