WorkerPlugin.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { pathToFileURL } = require("url");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const CommentCompilationWarning = require("../CommentCompilationWarning");
  9. const {
  10. JAVASCRIPT_MODULE_TYPE_AUTO,
  11. JAVASCRIPT_MODULE_TYPE_ESM
  12. } = require("../ModuleTypeConstants");
  13. const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");
  14. const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin");
  15. const { equals } = require("../util/ArrayHelpers");
  16. const createHash = require("../util/createHash");
  17. const { contextify } = require("../util/identifier");
  18. const EnableWasmLoadingPlugin = require("../wasm/EnableWasmLoadingPlugin");
  19. const ConstDependency = require("./ConstDependency");
  20. const CreateScriptUrlDependency = require("./CreateScriptUrlDependency");
  21. const {
  22. harmonySpecifierTag
  23. } = require("./HarmonyImportDependencyParserPlugin");
  24. const WorkerDependency = require("./WorkerDependency");
  25. /** @typedef {import("estree").CallExpression} CallExpression */
  26. /** @typedef {import("estree").Expression} Expression */
  27. /** @typedef {import("estree").ObjectExpression} ObjectExpression */
  28. /** @typedef {import("estree").Pattern} Pattern */
  29. /** @typedef {import("estree").Property} Property */
  30. /** @typedef {import("estree").SpreadElement} SpreadElement */
  31. /** @typedef {import("../../declarations/WebpackOptions").ChunkLoading} ChunkLoading */
  32. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  33. /** @typedef {import("../../declarations/WebpackOptions").OutputModule} OutputModule */
  34. /** @typedef {import("../../declarations/WebpackOptions").WasmLoading} WasmLoading */
  35. /** @typedef {import("../../declarations/WebpackOptions").WorkerPublicPath} WorkerPublicPath */
  36. /** @typedef {import("../Compiler")} Compiler */
  37. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  38. /** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */
  39. /** @typedef {import("../NormalModule")} NormalModule */
  40. /** @typedef {import("../Parser").ParserState} ParserState */
  41. /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
  42. /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
  43. /** @typedef {import("../javascript/JavascriptParser")} Parser */
  44. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  45. /** @typedef {import("./HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */
  46. /**
  47. * @param {NormalModule} module module
  48. * @returns {string} url
  49. */
  50. const getUrl = module => {
  51. return pathToFileURL(module.resource).toString();
  52. };
  53. const WorkerSpecifierTag = Symbol("worker specifier tag");
  54. const DEFAULT_SYNTAX = [
  55. "Worker",
  56. "SharedWorker",
  57. "navigator.serviceWorker.register()",
  58. "Worker from worker_threads"
  59. ];
  60. /** @type {WeakMap<ParserState, number>} */
  61. const workerIndexMap = new WeakMap();
  62. const PLUGIN_NAME = "WorkerPlugin";
  63. class WorkerPlugin {
  64. /**
  65. * @param {ChunkLoading} chunkLoading chunk loading
  66. * @param {WasmLoading} wasmLoading wasm loading
  67. * @param {OutputModule} module output module
  68. * @param {WorkerPublicPath} workerPublicPath worker public path
  69. */
  70. constructor(chunkLoading, wasmLoading, module, workerPublicPath) {
  71. this._chunkLoading = chunkLoading;
  72. this._wasmLoading = wasmLoading;
  73. this._module = module;
  74. this._workerPublicPath = workerPublicPath;
  75. }
  76. /**
  77. * Apply the plugin
  78. * @param {Compiler} compiler the compiler instance
  79. * @returns {void}
  80. */
  81. apply(compiler) {
  82. if (this._chunkLoading) {
  83. new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler);
  84. }
  85. if (this._wasmLoading) {
  86. new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler);
  87. }
  88. const cachedContextify = contextify.bindContextCache(
  89. compiler.context,
  90. compiler.root
  91. );
  92. compiler.hooks.thisCompilation.tap(
  93. PLUGIN_NAME,
  94. (compilation, { normalModuleFactory }) => {
  95. compilation.dependencyFactories.set(
  96. WorkerDependency,
  97. normalModuleFactory
  98. );
  99. compilation.dependencyTemplates.set(
  100. WorkerDependency,
  101. new WorkerDependency.Template()
  102. );
  103. compilation.dependencyTemplates.set(
  104. CreateScriptUrlDependency,
  105. new CreateScriptUrlDependency.Template()
  106. );
  107. /**
  108. * @param {JavascriptParser} parser the parser
  109. * @param {Expression} expr expression
  110. * @returns {[BasicEvaluatedExpression, [number, number]] | void} parsed
  111. */
  112. const parseModuleUrl = (parser, expr) => {
  113. if (
  114. expr.type !== "NewExpression" ||
  115. expr.callee.type === "Super" ||
  116. expr.arguments.length !== 2
  117. )
  118. return;
  119. const [arg1, arg2] = expr.arguments;
  120. if (arg1.type === "SpreadElement") return;
  121. if (arg2.type === "SpreadElement") return;
  122. const callee = parser.evaluateExpression(expr.callee);
  123. if (!callee.isIdentifier() || callee.identifier !== "URL") return;
  124. const arg2Value = parser.evaluateExpression(arg2);
  125. if (
  126. !arg2Value.isString() ||
  127. !(/** @type {string} */ (arg2Value.string).startsWith("file://")) ||
  128. arg2Value.string !== getUrl(parser.state.module)
  129. ) {
  130. return;
  131. }
  132. const arg1Value = parser.evaluateExpression(arg1);
  133. return [
  134. arg1Value,
  135. [
  136. /** @type {Range} */ (arg1.range)[0],
  137. /** @type {Range} */ (arg2.range)[1]
  138. ]
  139. ];
  140. };
  141. /**
  142. * @param {JavascriptParser} parser the parser
  143. * @param {ObjectExpression} expr expression
  144. * @returns {{ expressions: Record<string, Expression | Pattern>, otherElements: (Property | SpreadElement)[], values: Record<string, any>, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object
  145. */
  146. const parseObjectExpression = (parser, expr) => {
  147. /** @type {Record<string, any>} */
  148. const values = {};
  149. /** @type {Record<string, Expression | Pattern>} */
  150. const expressions = {};
  151. /** @type {(Property | SpreadElement)[]} */
  152. const otherElements = [];
  153. let spread = false;
  154. for (const prop of expr.properties) {
  155. if (prop.type === "SpreadElement") {
  156. spread = true;
  157. } else if (
  158. prop.type === "Property" &&
  159. !prop.method &&
  160. !prop.computed &&
  161. prop.key.type === "Identifier"
  162. ) {
  163. expressions[prop.key.name] = prop.value;
  164. if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) {
  165. const value = parser.evaluateExpression(
  166. /** @type {Expression} */ (prop.value)
  167. );
  168. if (value.isCompileTimeValue())
  169. values[prop.key.name] = value.asCompileTimeValue();
  170. }
  171. } else {
  172. otherElements.push(prop);
  173. }
  174. }
  175. const insertType = expr.properties.length > 0 ? "comma" : "single";
  176. const insertLocation =
  177. expr.properties[expr.properties.length - 1].range[1];
  178. return {
  179. expressions,
  180. otherElements,
  181. values,
  182. spread,
  183. insertType,
  184. insertLocation
  185. };
  186. };
  187. /**
  188. * @param {Parser} parser parser parser
  189. * @param {JavascriptParserOptions} parserOptions parserOptions
  190. * @returns {void}
  191. */
  192. const parserPlugin = (parser, parserOptions) => {
  193. if (parserOptions.worker === false) return;
  194. const options = !Array.isArray(parserOptions.worker)
  195. ? ["..."]
  196. : parserOptions.worker;
  197. /**
  198. * @param {CallExpression} expr expression
  199. * @returns {boolean | void} true when handled
  200. */
  201. const handleNewWorker = expr => {
  202. if (expr.arguments.length === 0 || expr.arguments.length > 2)
  203. return;
  204. const [arg1, arg2] = expr.arguments;
  205. if (arg1.type === "SpreadElement") return;
  206. if (arg2 && arg2.type === "SpreadElement") return;
  207. const parsedUrl = parseModuleUrl(parser, arg1);
  208. if (!parsedUrl) return;
  209. const [url, range] = parsedUrl;
  210. if (!url.isString()) return;
  211. const {
  212. expressions,
  213. otherElements,
  214. values: options,
  215. spread: hasSpreadInOptions,
  216. insertType,
  217. insertLocation
  218. } = arg2 && arg2.type === "ObjectExpression"
  219. ? parseObjectExpression(parser, arg2)
  220. : {
  221. /** @type {Record<string, Expression | Pattern>} */
  222. expressions: {},
  223. otherElements: [],
  224. /** @type {Record<string, any>} */
  225. values: {},
  226. spread: false,
  227. insertType: arg2 ? "spread" : "argument",
  228. insertLocation: arg2
  229. ? /** @type {Range} */ (arg2.range)
  230. : /** @type {Range} */ (arg1.range)[1]
  231. };
  232. const { options: importOptions, errors: commentErrors } =
  233. parser.parseCommentOptions(/** @type {Range} */ (expr.range));
  234. if (commentErrors) {
  235. for (const e of commentErrors) {
  236. const { comment } = e;
  237. parser.state.module.addWarning(
  238. new CommentCompilationWarning(
  239. `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
  240. comment.loc
  241. )
  242. );
  243. }
  244. }
  245. /** @type {EntryOptions} */
  246. let entryOptions = {};
  247. if (importOptions) {
  248. if (importOptions.webpackIgnore !== undefined) {
  249. if (typeof importOptions.webpackIgnore !== "boolean") {
  250. parser.state.module.addWarning(
  251. new UnsupportedFeatureWarning(
  252. `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`,
  253. /** @type {DependencyLocation} */ (expr.loc)
  254. )
  255. );
  256. } else {
  257. if (importOptions.webpackIgnore) {
  258. return false;
  259. }
  260. }
  261. }
  262. if (importOptions.webpackEntryOptions !== undefined) {
  263. if (
  264. typeof importOptions.webpackEntryOptions !== "object" ||
  265. importOptions.webpackEntryOptions === null
  266. ) {
  267. parser.state.module.addWarning(
  268. new UnsupportedFeatureWarning(
  269. `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`,
  270. /** @type {DependencyLocation} */ (expr.loc)
  271. )
  272. );
  273. } else {
  274. Object.assign(
  275. entryOptions,
  276. importOptions.webpackEntryOptions
  277. );
  278. }
  279. }
  280. if (importOptions.webpackChunkName !== undefined) {
  281. if (typeof importOptions.webpackChunkName !== "string") {
  282. parser.state.module.addWarning(
  283. new UnsupportedFeatureWarning(
  284. `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`,
  285. /** @type {DependencyLocation} */ (expr.loc)
  286. )
  287. );
  288. } else {
  289. entryOptions.name = importOptions.webpackChunkName;
  290. }
  291. }
  292. }
  293. if (
  294. !Object.prototype.hasOwnProperty.call(entryOptions, "name") &&
  295. options &&
  296. typeof options.name === "string"
  297. ) {
  298. entryOptions.name = options.name;
  299. }
  300. if (entryOptions.runtime === undefined) {
  301. let i = workerIndexMap.get(parser.state) || 0;
  302. workerIndexMap.set(parser.state, i + 1);
  303. let name = `${cachedContextify(
  304. parser.state.module.identifier()
  305. )}|${i}`;
  306. const hash = createHash(compilation.outputOptions.hashFunction);
  307. hash.update(name);
  308. const digest = /** @type {string} */ (
  309. hash.digest(compilation.outputOptions.hashDigest)
  310. );
  311. entryOptions.runtime = digest.slice(
  312. 0,
  313. compilation.outputOptions.hashDigestLength
  314. );
  315. }
  316. const block = new AsyncDependenciesBlock({
  317. name: entryOptions.name,
  318. entryOptions: {
  319. chunkLoading: this._chunkLoading,
  320. wasmLoading: this._wasmLoading,
  321. ...entryOptions
  322. }
  323. });
  324. block.loc = expr.loc;
  325. const dep = new WorkerDependency(
  326. /** @type {string} */ (url.string),
  327. range,
  328. {
  329. publicPath: this._workerPublicPath
  330. }
  331. );
  332. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  333. block.addDependency(dep);
  334. parser.state.module.addBlock(block);
  335. if (compilation.outputOptions.trustedTypes) {
  336. const dep = new CreateScriptUrlDependency(
  337. /** @type {Range} */ (expr.arguments[0].range)
  338. );
  339. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  340. parser.state.module.addDependency(dep);
  341. }
  342. if (expressions.type) {
  343. const expr = expressions.type;
  344. if (options.type !== false) {
  345. const dep = new ConstDependency(
  346. this._module ? '"module"' : "undefined",
  347. /** @type {Range} */ (expr.range)
  348. );
  349. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  350. parser.state.module.addPresentationalDependency(dep);
  351. expressions.type = undefined;
  352. }
  353. } else if (insertType === "comma") {
  354. if (this._module || hasSpreadInOptions) {
  355. const dep = new ConstDependency(
  356. `, type: ${this._module ? '"module"' : "undefined"}`,
  357. insertLocation
  358. );
  359. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  360. parser.state.module.addPresentationalDependency(dep);
  361. }
  362. } else if (insertType === "spread") {
  363. const dep1 = new ConstDependency(
  364. "Object.assign({}, ",
  365. /** @type {Range} */ (insertLocation)[0]
  366. );
  367. const dep2 = new ConstDependency(
  368. `, { type: ${this._module ? '"module"' : "undefined"} })`,
  369. /** @type {Range} */ (insertLocation)[1]
  370. );
  371. dep1.loc = /** @type {DependencyLocation} */ (expr.loc);
  372. dep2.loc = /** @type {DependencyLocation} */ (expr.loc);
  373. parser.state.module.addPresentationalDependency(dep1);
  374. parser.state.module.addPresentationalDependency(dep2);
  375. } else if (insertType === "argument") {
  376. if (this._module) {
  377. const dep = new ConstDependency(
  378. ', { type: "module" }',
  379. insertLocation
  380. );
  381. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  382. parser.state.module.addPresentationalDependency(dep);
  383. }
  384. }
  385. parser.walkExpression(expr.callee);
  386. for (const key of Object.keys(expressions)) {
  387. if (expressions[key]) parser.walkExpression(expressions[key]);
  388. }
  389. for (const prop of otherElements) {
  390. parser.walkProperty(prop);
  391. }
  392. if (insertType === "spread") {
  393. parser.walkExpression(arg2);
  394. }
  395. return true;
  396. };
  397. /**
  398. * @param {string} item item
  399. */
  400. const processItem = item => {
  401. if (
  402. item.startsWith("*") &&
  403. item.includes(".") &&
  404. item.endsWith("()")
  405. ) {
  406. const firstDot = item.indexOf(".");
  407. const pattern = item.slice(1, firstDot);
  408. const itemMembers = item.slice(firstDot + 1, -2);
  409. parser.hooks.pattern.for(pattern).tap(PLUGIN_NAME, pattern => {
  410. parser.tagVariable(pattern.name, WorkerSpecifierTag);
  411. return true;
  412. });
  413. parser.hooks.callMemberChain
  414. .for(WorkerSpecifierTag)
  415. .tap(PLUGIN_NAME, (expression, members) => {
  416. if (itemMembers !== members.join(".")) {
  417. return;
  418. }
  419. return handleNewWorker(expression);
  420. });
  421. } else if (item.endsWith("()")) {
  422. parser.hooks.call
  423. .for(item.slice(0, -2))
  424. .tap(PLUGIN_NAME, handleNewWorker);
  425. } else {
  426. const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item);
  427. if (match) {
  428. const ids = match[1].split(".");
  429. const call = match[2];
  430. const source = match[3];
  431. (call ? parser.hooks.call : parser.hooks.new)
  432. .for(harmonySpecifierTag)
  433. .tap(PLUGIN_NAME, expr => {
  434. const settings = /** @type {HarmonySettings} */ (
  435. parser.currentTagData
  436. );
  437. if (
  438. !settings ||
  439. settings.source !== source ||
  440. !equals(settings.ids, ids)
  441. ) {
  442. return;
  443. }
  444. return handleNewWorker(expr);
  445. });
  446. } else {
  447. parser.hooks.new.for(item).tap(PLUGIN_NAME, handleNewWorker);
  448. }
  449. }
  450. };
  451. for (const item of options) {
  452. if (item === "...") {
  453. DEFAULT_SYNTAX.forEach(processItem);
  454. } else processItem(item);
  455. }
  456. };
  457. normalModuleFactory.hooks.parser
  458. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  459. .tap(PLUGIN_NAME, parserPlugin);
  460. normalModuleFactory.hooks.parser
  461. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  462. .tap(PLUGIN_NAME, parserPlugin);
  463. }
  464. );
  465. }
  466. }
  467. module.exports = WorkerPlugin;