WorkerPlugin.js 18 KB

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