Skip to content

Commit abb35e8

Browse files
fix(worker): preserve SharedWorker string names (#22770)
* fix(worker): preserve SharedWorker string names * fix(worker): preserve names passed to a qualified SharedWorker syntax A configured syntax such as `window.SharedWorker` matched as written, so the exact `SharedWorker` check fell back to the generic options wrapper. --------- Co-authored-by: alexander-akait <[email protected]>
1 parent ee9909d commit abb35e8

7 files changed

Lines changed: 220 additions & 20 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Preserve string names passed to SharedWorker constructors.

‎lib/dependencies/worker/WorkerAndWorkletPlugin.js‎

Lines changed: 51 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -464,10 +464,10 @@ class WorkerAndWorkletPlugin {
464464
/**
465465
* Handles a matched `new Worker(...)` expression.
466466
* @param {CallExpression} expr expression
467-
* @param {boolean=} isGlobalWorker matched the global `new Worker()` syntax (eligible for universal rewrite)
467+
* @param {string=} workerSyntax matched global constructor syntax
468468
* @returns {boolean | void} true when handled
469469
*/
470-
const handleNewWorker = (expr, isGlobalWorker = false) => {
470+
const handleNewWorker = (expr, workerSyntax) => {
471471
const parsedUrl = resolveWorkerUrl(expr);
472472
if (!parsedUrl) return;
473473
const { url, range, needNewUrl, arg1, arg2 } = parsedUrl;
@@ -547,9 +547,10 @@ class WorkerAndWorkletPlugin {
547547
const dep = new WorkerDependency(url, range, {
548548
publicPath: this._workerPublicPath,
549549
needNewUrl,
550-
workerConstructorRange: isGlobalWorker
551-
? /** @type {Range} */ (expr.callee.range)
552-
: undefined,
550+
workerConstructorRange:
551+
workerSyntax === "Worker"
552+
? /** @type {Range} */ (expr.callee.range)
553+
: undefined,
553554
resourceHint
554555
});
555556
dep.loc = parser.getLocation(expr);
@@ -588,18 +589,48 @@ class WorkerAndWorkletPlugin {
588589
const type = this._module ? '"module"' : "undefined";
589590
// `{ ...(opts), type }` is equivalent to `Object.assign({}, opts, { type })`
590591
const useSpread = compilation.outputOptions.environment.spread;
591-
const dep1 = new ConstDependency(
592-
useSpread ? "{ ...(" : "Object.assign({}, ",
593-
/** @type {Range} */ (insertLocation)[0]
594-
);
595-
const dep2 = new ConstDependency(
596-
useSpread ? `), type: ${type} }` : `, { type: ${type} })`,
597-
/** @type {Range} */ (insertLocation)[1]
598-
);
599-
dep1.loc = parser.getLocation(expr);
600-
dep2.loc = parser.getLocation(expr);
601-
parser.state.module.addPresentationalDependency(dep1);
602-
parser.state.module.addPresentationalDependency(dep2);
592+
let prefix = useSpread ? "{ ...(" : "Object.assign({}, ";
593+
let suffix = useSpread
594+
? `), type: ${type} }`
595+
: `, { type: ${type} })`;
596+
if (
597+
workerSyntax !== undefined &&
598+
(workerSyntax === "SharedWorker" ||
599+
workerSyntax.endsWith(".SharedWorker"))
600+
) {
601+
const optionsExpression = /** @type {Expression} */ (arg2);
602+
if (
603+
optionsExpression.type === "Literal" &&
604+
typeof optionsExpression.value === "string"
605+
) {
606+
prefix = this._module ? "{ name: " : "";
607+
suffix = this._module ? `, type: ${type} }` : "";
608+
} else {
609+
const stringOptions = this._module
610+
? `{ name: options, type: ${type} }`
611+
: "options";
612+
// Evaluate the argument once, outside the wrapper's scope.
613+
prefix = `(${compilation.runtimeTemplate.returningFunction(
614+
`typeof options === "string" ? ${stringOptions} : ${prefix}options${suffix}`,
615+
"options"
616+
)})((`;
617+
suffix = "))";
618+
}
619+
}
620+
if (prefix) {
621+
const dep1 = new ConstDependency(
622+
prefix,
623+
/** @type {Range} */ (insertLocation)[0]
624+
);
625+
const dep2 = new ConstDependency(
626+
suffix,
627+
/** @type {Range} */ (insertLocation)[1]
628+
);
629+
dep1.loc = parser.getLocation(expr);
630+
dep2.loc = parser.getLocation(expr);
631+
parser.state.module.addPresentationalDependency(dep1);
632+
parser.state.module.addPresentationalDependency(dep2);
633+
}
603634
} else if (insertType === "argument" && this._module) {
604635
const dep = new ConstDependency(
605636
', { type: "module" }',
@@ -687,7 +718,7 @@ class WorkerAndWorkletPlugin {
687718
/**
688719
* Registers the parser hooks matching a single syntax item.
689720
* @param {string} item item
690-
* @param {(expr: CallExpression, isGlobalWorker?: boolean) => boolean | void} handle handler invoked on a match
721+
* @param {(expr: CallExpression, workerSyntax?: string) => boolean | void} handle handler invoked on a match
691722
* @param {symbol} specifierTag tag used for `*variable` syntax
692723
*/
693724
const processItem = (item, handle, specifierTag) => {
@@ -752,7 +783,7 @@ class WorkerAndWorkletPlugin {
752783
} else {
753784
parser.hooks.new
754785
.for(item)
755-
.tap(PLUGIN_NAME, (expr) => handle(expr, item === "Worker"));
786+
.tap(PLUGIN_NAME, (expr) => handle(expr, item));
756787
}
757788
}
758789
};
@@ -761,7 +792,7 @@ class WorkerAndWorkletPlugin {
761792
* Expands and registers a syntax list.
762793
* @param {string[]} syntaxList syntax list (may contain "...")
763794
* @param {string[]} defaultSyntax default syntax used for "..."
764-
* @param {(expr: CallExpression, isGlobalWorker?: boolean) => boolean | void} handle handler
795+
* @param {(expr: CallExpression, workerSyntax?: string) => boolean | void} handle handler
765796
* @param {symbol} specifierTag tag used for `*variable` syntax
766797
*/
767798
const processList = (
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { name } from "./name";
2+
3+
it("should preserve a literal SharedWorker name", () => {
4+
const worker = new SharedWorker(new URL("./worker.js", import.meta.url), "chat");
5+
expect(worker.options).toEqual(
6+
expectedWorkerType ? { name: "chat", type: "module" } : "chat"
7+
);
8+
});
9+
10+
it("should preserve an empty SharedWorker name", () => {
11+
const worker = new SharedWorker(new URL("./worker.js", import.meta.url), "");
12+
expect(worker.options).toEqual(
13+
expectedWorkerType ? { name: "", type: "module" } : ""
14+
);
15+
});
16+
17+
it("should evaluate a SharedWorker name only once", () => {
18+
let calls = 0;
19+
const worker = new SharedWorker(
20+
new URL("./worker.js", import.meta.url),
21+
(() => {
22+
calls++;
23+
return "dynamic";
24+
})()
25+
);
26+
expect(calls).toBe(1);
27+
expect(worker.options).toEqual(
28+
expectedWorkerType ? { name: "dynamic", type: "module" } : "dynamic"
29+
);
30+
});
31+
32+
it("should preserve an imported SharedWorker name", () => {
33+
const worker = new SharedWorker(new URL("./worker.js", import.meta.url), name);
34+
expect(worker.options).toEqual(
35+
expectedWorkerType ? { name: "imported", type: "module" } : "imported"
36+
);
37+
});
38+
39+
it("should preserve sequence expressions used as SharedWorker names", () => {
40+
let calls = 0;
41+
const worker = new SharedWorker(
42+
new URL("./worker.js", import.meta.url),
43+
(calls++, "sequence")
44+
);
45+
expect(calls).toBe(1);
46+
expect(worker.options).toEqual(
47+
expectedWorkerType ? { name: "sequence", type: "module" } : "sequence"
48+
);
49+
});
50+
51+
it("should preserve SharedWorker option objects without mutating them", () => {
52+
let calls = 0;
53+
const options = Object.freeze({ name: "object", type: "classic" });
54+
const worker = new SharedWorker(
55+
new URL("./worker.js", import.meta.url),
56+
(() => {
57+
calls++;
58+
return options;
59+
})()
60+
);
61+
expect(calls).toBe(1);
62+
expect(options.type).toBe("classic");
63+
expect(worker.options).toEqual({ name: "object", type: expectedWorkerType });
64+
});
65+
66+
it("should preserve literal SharedWorker options", () => {
67+
const worker = new SharedWorker(new URL("./worker.js", import.meta.url), {
68+
name: "literal-object",
69+
type: "classic"
70+
});
71+
expect(worker.options).toEqual({
72+
name: "literal-object",
73+
type: expectedWorkerType
74+
});
75+
});
76+
77+
it("should handle omitted SharedWorker options", () => {
78+
const worker = new SharedWorker(new URL("./worker.js", import.meta.url));
79+
expect(worker.options).toEqual(
80+
expectedWorkerType ? { type: "module" } : undefined
81+
);
82+
});
83+
84+
it("should handle null and undefined SharedWorker options", () => {
85+
const nullOptions = new SharedWorker(
86+
new URL("./worker.js", import.meta.url),
87+
null
88+
);
89+
const undefinedOptions = new SharedWorker(
90+
new URL("./worker.js", import.meta.url),
91+
undefined
92+
);
93+
expect(nullOptions.options).toEqual({ type: expectedWorkerType });
94+
expect(undefinedOptions.options).toEqual({ type: expectedWorkerType });
95+
});
96+
97+
it("should preserve a SharedWorker name through a qualified syntax", () => {
98+
const worker = new workers.SharedWorker(
99+
new URL("./worker.js", import.meta.url),
100+
"chat"
101+
);
102+
expect(worker.options).toEqual(
103+
expectedWorkerType ? { name: "chat", type: "module" } : "chat"
104+
);
105+
});
106+
107+
it("should keep ordinary and custom worker option handling", () => {
108+
const worker = new Worker(new URL("./worker.js", import.meta.url), "chat");
109+
const custom = new CustomWorker(new URL("./worker.js", import.meta.url), "chat");
110+
const expected = { 0: "c", 1: "h", 2: "a", 3: "t", type: expectedWorkerType };
111+
expect(worker.options).toEqual(expected);
112+
expect(custom.options).toEqual(expected);
113+
});
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const name = "imported";
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"use strict";
2+
3+
module.exports = {
4+
/**
5+
* @param {Record<string, unknown>} scope module scope
6+
* @param {import("../../../../").Configuration} options webpack options
7+
*/
8+
moduleScope(scope, options) {
9+
scope.URL = URL;
10+
scope.expectedWorkerType = options.output.module ? "module" : undefined;
11+
scope.SharedWorker =
12+
scope.Worker =
13+
scope.CustomWorker =
14+
class {
15+
/**
16+
* @param {URL} url worker URL
17+
* @param {string | WorkerOptions=} options worker options
18+
*/
19+
constructor(url, options) {
20+
this.url = url;
21+
this.options = options;
22+
}
23+
};
24+
scope.workers = { SharedWorker: scope.SharedWorker };
25+
}
26+
};
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration[]} */
4+
module.exports = [
5+
[false, false],
6+
[false, true],
7+
[true, false],
8+
[true, true],
9+
[true, true, true]
10+
].map(([module, modern, universal]) => ({
11+
target: universal ? ["web", "node"] : "web",
12+
output: {
13+
module,
14+
publicPath: "/assets/",
15+
environment: { spread: modern, arrowFunction: modern }
16+
},
17+
optimization: { minimize: false },
18+
module: {
19+
parser: {
20+
javascript: { worker: ["...", "CustomWorker", "workers.SharedWorker"] }
21+
}
22+
}
23+
}));
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
self.onconnect = () => {};

0 commit comments

Comments
 (0)