WorkerAndWorkletPlugin.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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 {
  9. JAVASCRIPT_MODULE_TYPE_AUTO,
  10. JAVASCRIPT_MODULE_TYPE_ESM
  11. } = require("../ModuleTypeConstants");
  12. const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin");
  13. const parseResourceHintOptions = require("../prefetch/parseResourceHintOptions");
  14. const { equals } = require("../util/ArrayHelpers");
  15. const createHash = require("../util/createHash");
  16. const { contextify } = require("../util/identifier");
  17. const memoize = require("../util/memoize");
  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 { isImportMetaFieldEnabled } = require("./ImportMetaPlugin");
  25. const WorkerDependency = require("./WorkerDependency");
  26. const WorkletDependency = require("./WorkletDependency");
  27. const getUnsupportedFeatureWarning = memoize(() =>
  28. require("../errors/UnsupportedFeatureWarning")
  29. );
  30. const getCommentCompilationWarning = memoize(() =>
  31. require("../errors/CommentCompilationWarning")
  32. );
  33. /**
  34. * @import {
  35. * CallExpression,
  36. * Expression,
  37. * MemberExpression,
  38. * ObjectExpression,
  39. * Pattern,
  40. * Property,
  41. * SpreadElement
  42. * } from "estree"
  43. */
  44. /**
  45. * @import {
  46. * ChunkLoading,
  47. * JavascriptParserOptions,
  48. * OutputModule,
  49. * WasmLoading,
  50. * WorkerPublicPath
  51. * } from "../../declarations/WebpackOptions"
  52. */
  53. /** @import Compiler from "../Compiler" */
  54. /** @import { DependencyLocation } from "../Dependency" */
  55. /** @import { EntryOptions } from "../Entrypoint" */
  56. /** @import NormalModule from "../NormalModule" */
  57. /**
  58. * @import JavascriptParser, {
  59. * JavascriptParserState,
  60. * Range
  61. * } from "../javascript/JavascriptParser"
  62. */
  63. /** @import Parser from "../javascript/JavascriptParser" */
  64. /** @import { HarmonySettings } from "./HarmonyImportDependencyParserPlugin" */
  65. /** @import { ResourceHint } from "./WorkerDependency" */
  66. /**
  67. * Returns url.
  68. * @param {NormalModule} module module
  69. * @returns {string} url
  70. */
  71. const getUrl = (module) => pathToFileURL(module.resource).toString();
  72. const WorkerSpecifierTag = Symbol("worker specifier tag");
  73. const WorkletSpecifierTag = Symbol("worklet specifier tag");
  74. const WORKER_DEFAULT_SYNTAX = [
  75. "Worker",
  76. "SharedWorker",
  77. "navigator.serviceWorker.register()",
  78. "Worker from worker_threads"
  79. ];
  80. // Worklets are always module scripts loaded through `addModule` and — unlike Web
  81. // Workers — cannot load additional chunks at runtime (no `importScripts`, no
  82. // dynamic `import()`). The WorkletDependency wraps the call so every chunk is
  83. // pre-added via `addModule` from the calling scope (see WorkletDependency).
  84. const WORKLET_DEFAULT_SYNTAX = [
  85. "*context.audioWorklet.addModule()",
  86. "*audioWorklet.addModule()",
  87. "CSS.paintWorklet.addModule()",
  88. "CSS.layoutWorklet.addModule()",
  89. "CSS.animationWorklet.addModule()"
  90. ];
  91. /** @type {WeakMap<JavascriptParserState, number>} */
  92. const workerIndexMap = new WeakMap();
  93. const PLUGIN_NAME = "WorkerAndWorkletPlugin";
  94. class WorkerAndWorkletPlugin {
  95. /**
  96. * Creates an instance of WorkerAndWorkletPlugin.
  97. * @param {ChunkLoading=} chunkLoading chunk loading
  98. * @param {WasmLoading=} wasmLoading wasm loading
  99. * @param {OutputModule=} module output module
  100. * @param {WorkerPublicPath=} workerPublicPath worker public path
  101. * @param {boolean=} workletDefault whether worklet parsing is on when `parser.worklet` is unset (enabled by `futureDefaults`)
  102. */
  103. constructor(
  104. chunkLoading,
  105. wasmLoading,
  106. module,
  107. workerPublicPath,
  108. workletDefault
  109. ) {
  110. /** @type {ChunkLoading | undefined} */
  111. this._chunkLoading = chunkLoading;
  112. /** @type {WasmLoading | undefined} */
  113. this._wasmLoading = wasmLoading;
  114. /** @type {boolean | undefined} */
  115. this._module = module;
  116. /** @type {string | undefined} */
  117. this._workerPublicPath = workerPublicPath;
  118. /** @type {boolean} */
  119. this._workletDefault = Boolean(workletDefault);
  120. }
  121. /**
  122. * Applies the plugin by registering its hooks on the compiler.
  123. * @param {Compiler} compiler the compiler instance
  124. * @returns {void}
  125. */
  126. apply(compiler) {
  127. if (this._chunkLoading) {
  128. new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler);
  129. }
  130. if (this._wasmLoading) {
  131. new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler);
  132. }
  133. const cachedContextify = contextify.bindContextCache(
  134. compiler.context,
  135. compiler.root
  136. );
  137. compiler.hooks.thisCompilation.tap(
  138. PLUGIN_NAME,
  139. (compilation, { normalModuleFactory }) => {
  140. compilation.dependencyFactories.set(
  141. WorkerDependency,
  142. normalModuleFactory
  143. );
  144. compilation.dependencyTemplates.set(
  145. WorkerDependency,
  146. new WorkerDependency.Template()
  147. );
  148. compilation.dependencyFactories.set(
  149. WorkletDependency,
  150. normalModuleFactory
  151. );
  152. compilation.dependencyTemplates.set(
  153. WorkletDependency,
  154. new WorkletDependency.Template()
  155. );
  156. compilation.dependencyTemplates.set(
  157. CreateScriptUrlDependency,
  158. new CreateScriptUrlDependency.Template()
  159. );
  160. /**
  161. * Checks whether the expression is `import.meta.url`.
  162. * @param {JavascriptParser} parser the parser
  163. * @param {MemberExpression} expr expression
  164. * @returns {boolean} is `import.meta.url`
  165. */
  166. const isMetaUrl = (parser, expr) => {
  167. const chain = parser.extractMemberExpressionChain(expr);
  168. if (
  169. chain.members.length !== 1 ||
  170. chain.object.type !== "MetaProperty" ||
  171. chain.object.meta.name !== "import" ||
  172. chain.object.property.name !== "meta" ||
  173. chain.members[0] !== "url"
  174. ) {
  175. return false;
  176. }
  177. return true;
  178. };
  179. /**
  180. * Resolves a `new URL(..., import.meta.url)` argument to its module url.
  181. * @param {JavascriptParser} parser the parser
  182. * @param {Expression} expr expression
  183. * @param {boolean} importMetaUrlEnabled true when import.meta.url should be handled
  184. * @returns {[string, Range] | void} parsed
  185. */
  186. const parseModuleUrl = (parser, expr, importMetaUrlEnabled) => {
  187. if (expr.type !== "NewExpression" || expr.callee.type === "Super") {
  188. return;
  189. }
  190. if (
  191. importMetaUrlEnabled &&
  192. expr.arguments.length === 1 &&
  193. expr.arguments[0].type === "MemberExpression" &&
  194. isMetaUrl(parser, expr.arguments[0])
  195. ) {
  196. const arg1 = expr.arguments[0];
  197. return [
  198. getUrl(parser.state.module),
  199. [
  200. /** @type {Range} */ (arg1.range)[0],
  201. /** @type {Range} */ (arg1.range)[1]
  202. ]
  203. ];
  204. } else if (expr.arguments.length === 2) {
  205. const [arg1, arg2] = expr.arguments;
  206. if (arg1.type === "SpreadElement") return;
  207. if (arg2.type === "SpreadElement") return;
  208. const callee = parser.evaluateExpression(expr.callee);
  209. if (!callee.isIdentifier() || callee.identifier !== "URL") return;
  210. const arg2Value = parser.evaluateExpression(arg2);
  211. if (
  212. !arg2Value.isString() ||
  213. !(
  214. /** @type {string} */ (arg2Value.string).startsWith("file://")
  215. ) ||
  216. arg2Value.string !== getUrl(parser.state.module)
  217. ) {
  218. return;
  219. }
  220. const arg1Value = parser.evaluateExpression(arg1);
  221. if (!arg1Value.isString()) return;
  222. return [
  223. /** @type {string} */ (arg1Value.string),
  224. [
  225. /** @type {Range} */ (arg1.range)[0],
  226. /** @type {Range} */ (arg2.range)[1]
  227. ]
  228. ];
  229. }
  230. };
  231. /** @typedef {Record<string, EXPECTED_ANY>} Values */
  232. /**
  233. * Parses object expression.
  234. * @param {JavascriptParser} parser the parser
  235. * @param {ObjectExpression} expr expression
  236. * @returns {{ expressions: Record<string, Expression | Pattern>, otherElements: (Property | SpreadElement)[], values: Values, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object
  237. */
  238. const parseObjectExpression = (parser, expr) => {
  239. /** @type {Values} */
  240. const values = {};
  241. /** @type {Record<string, Expression | Pattern>} */
  242. const expressions = {};
  243. /** @type {(Property | SpreadElement)[]} */
  244. const otherElements = [];
  245. let spread = false;
  246. for (const prop of expr.properties) {
  247. if (prop.type === "SpreadElement") {
  248. spread = true;
  249. } else if (
  250. prop.type === "Property" &&
  251. !prop.method &&
  252. !prop.computed &&
  253. prop.key.type === "Identifier"
  254. ) {
  255. expressions[prop.key.name] = prop.value;
  256. if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) {
  257. const value = parser.evaluateExpression(
  258. /** @type {Expression} */
  259. (prop.value)
  260. );
  261. if (value.isCompileTimeValue()) {
  262. values[prop.key.name] = value.asCompileTimeValue();
  263. }
  264. }
  265. } else {
  266. otherElements.push(prop);
  267. }
  268. }
  269. const insertType = expr.properties.length > 0 ? "comma" : "single";
  270. const insertLocation =
  271. expr.properties.length > 0
  272. ? /** @type {Range} */ (
  273. expr.properties[expr.properties.length - 1].range
  274. )[1]
  275. : /** @type {Range} */ (expr.range)[0] + 1;
  276. return {
  277. expressions,
  278. otherElements,
  279. values,
  280. spread,
  281. insertType,
  282. insertLocation
  283. };
  284. };
  285. /**
  286. * Processes the provided parser.
  287. * @param {Parser} parser parser parser
  288. * @param {JavascriptParserOptions} parserOptions parserOptions
  289. * @returns {void}
  290. */
  291. const parserPlugin = (parser, parserOptions) => {
  292. const importMetaUrlEnabled = isImportMetaFieldEnabled(
  293. parserOptions.importMeta,
  294. "url"
  295. );
  296. /**
  297. * Resolves the url argument (the `new URL(...)` / bare `import.meta.url`).
  298. * @param {CallExpression} expr expression
  299. * @returns {{ url: string, range: Range, needNewUrl: boolean, arg1: Expression | SpreadElement, arg2: Expression | SpreadElement | undefined } | void} resolved url info
  300. */
  301. const resolveWorkerUrl = (expr) => {
  302. if (expr.arguments.length === 0 || expr.arguments.length > 2) {
  303. return;
  304. }
  305. const [arg1, arg2] = expr.arguments;
  306. if (arg1.type === "SpreadElement") return;
  307. if (arg2 && arg2.type === "SpreadElement") return;
  308. /** @type {string} */
  309. let url;
  310. /** @type {Range} */
  311. let range;
  312. let needNewUrl = false;
  313. if (
  314. arg1.type === "MemberExpression" &&
  315. importMetaUrlEnabled &&
  316. isMetaUrl(parser, arg1)
  317. ) {
  318. url = getUrl(parser.state.module);
  319. range = [
  320. /** @type {Range} */ (arg1.range)[0],
  321. /** @type {Range} */ (arg1.range)[1]
  322. ];
  323. needNewUrl = true;
  324. } else {
  325. const parsedUrl = parseModuleUrl(
  326. parser,
  327. arg1,
  328. importMetaUrlEnabled
  329. );
  330. if (!parsedUrl) return;
  331. [url, range] = parsedUrl;
  332. }
  333. return { url, range, needNewUrl, arg1, arg2 };
  334. };
  335. /**
  336. * Reads the magic-comment entry options for the matched expression.
  337. * @param {CallExpression} expr expression
  338. * @returns {EntryOptions | false} entry options, or false when `webpackIgnore`
  339. */
  340. const parseEntryOptions = (expr) => {
  341. const { options: importOptions, errors: commentErrors } =
  342. parser.parseCommentOptions(/** @type {Range} */ (expr.range));
  343. if (commentErrors) {
  344. for (const e of commentErrors) {
  345. const { comment } = e;
  346. parser.state.module.addWarning(
  347. new (getCommentCompilationWarning())(
  348. `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
  349. parser.getLocation(comment)
  350. )
  351. );
  352. }
  353. }
  354. /** @type {EntryOptions} */
  355. const entryOptions = {};
  356. if (importOptions) {
  357. if (importOptions.webpackIgnore !== undefined) {
  358. if (typeof importOptions.webpackIgnore !== "boolean") {
  359. parser.state.module.addWarning(
  360. new (getUnsupportedFeatureWarning())(
  361. `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`,
  362. parser.getLocation(expr)
  363. )
  364. );
  365. } else if (importOptions.webpackIgnore) {
  366. return false;
  367. }
  368. }
  369. if (importOptions.webpackEntryOptions !== undefined) {
  370. if (
  371. typeof importOptions.webpackEntryOptions !== "object" ||
  372. importOptions.webpackEntryOptions === null
  373. ) {
  374. parser.state.module.addWarning(
  375. new (getUnsupportedFeatureWarning())(
  376. `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`,
  377. parser.getLocation(expr)
  378. )
  379. );
  380. } else {
  381. // `webpackEntryOptions` is user input from a magic
  382. // comment, so copy only safe own keys to avoid
  383. // prototype pollution via `__proto__`/`constructor`/
  384. // `prototype`.
  385. const userEntryOptions = importOptions.webpackEntryOptions;
  386. for (const key of Object.keys(userEntryOptions)) {
  387. if (
  388. key === "__proto__" ||
  389. key === "constructor" ||
  390. key === "prototype"
  391. ) {
  392. continue;
  393. }
  394. /** @type {EXPECTED_ANY} */
  395. (entryOptions)[key] = /** @type {EXPECTED_ANY} */ (
  396. userEntryOptions
  397. )[key];
  398. }
  399. }
  400. }
  401. if (importOptions.webpackChunkName !== undefined) {
  402. if (typeof importOptions.webpackChunkName !== "string") {
  403. parser.state.module.addWarning(
  404. new (getUnsupportedFeatureWarning())(
  405. `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`,
  406. parser.getLocation(expr)
  407. )
  408. );
  409. } else {
  410. entryOptions.name = importOptions.webpackChunkName;
  411. }
  412. }
  413. }
  414. return entryOptions;
  415. };
  416. /**
  417. * Assigns a unique runtime to the entry so each worker gets its own runtime chunk.
  418. * @param {EntryOptions} entryOptions entry options
  419. * @returns {void}
  420. */
  421. const ensureRuntime = (entryOptions) => {
  422. if (entryOptions.runtime !== undefined) return;
  423. const i = workerIndexMap.get(parser.state) || 0;
  424. workerIndexMap.set(parser.state, i + 1);
  425. const name = `${cachedContextify(
  426. parser.state.module.identifier()
  427. )}|${i}`;
  428. const hash = createHash(compilation.outputOptions.hashFunction);
  429. hash.update(name);
  430. const digest = hash.digest(compilation.outputOptions.hashDigest);
  431. entryOptions.runtime = digest.slice(
  432. 0,
  433. compilation.outputOptions.hashDigestLength
  434. );
  435. };
  436. /**
  437. * Handles a matched `new Worker(...)` expression.
  438. * @param {CallExpression} expr expression
  439. * @param {boolean=} isGlobalWorker matched the global `new Worker()` syntax (eligible for universal rewrite)
  440. * @returns {boolean | void} true when handled
  441. */
  442. const handleNewWorker = (expr, isGlobalWorker = false) => {
  443. const parsedUrl = resolveWorkerUrl(expr);
  444. if (!parsedUrl) return;
  445. const { url, range, needNewUrl, arg1, arg2 } = parsedUrl;
  446. const {
  447. expressions,
  448. otherElements,
  449. values: options,
  450. spread: hasSpreadInOptions,
  451. insertType,
  452. insertLocation
  453. } = arg2 && arg2.type === "ObjectExpression"
  454. ? parseObjectExpression(parser, arg2)
  455. : {
  456. expressions:
  457. /** @type {Record<string, Expression | Pattern>} */ ({}),
  458. otherElements: [],
  459. /** @type {Values} */
  460. values: {},
  461. spread: false,
  462. insertType: arg2 ? "spread" : "argument",
  463. insertLocation: arg2
  464. ? /** @type {Range} */ (arg2.range)
  465. : /** @type {Range} */ (arg1.range)[1]
  466. };
  467. const entryOptions = parseEntryOptions(expr);
  468. if (entryOptions === false) return false;
  469. /** @type {ResourceHint | undefined} */
  470. let resourceHint;
  471. // Resource-hint comments belong to the asset expression — read
  472. // them from the inner `new URL(...)` range only, never from
  473. // elsewhere inside `new Worker(...)`. When `arg1` is bare
  474. // `import.meta.url` there is no `new URL` and no place for
  475. // the comments to go, so resource hints are skipped.
  476. if (arg1.type === "NewExpression") {
  477. const { options: urlImportOptions } = parser.parseCommentOptions(
  478. /** @type {Range} */ (arg1.range)
  479. );
  480. const hints = parseResourceHintOptions(
  481. urlImportOptions,
  482. parser.state.module,
  483. /** @type {DependencyLocation} */ (expr.loc)
  484. );
  485. if (hints.prefetch || hints.preload) {
  486. resourceHint = {
  487. prefetch: hints.prefetch,
  488. preload: hints.preload,
  489. fetchPriority: hints.fetchPriority,
  490. as: hints.as,
  491. type: hints.type,
  492. media: hints.media
  493. };
  494. }
  495. }
  496. if (
  497. !Object.prototype.hasOwnProperty.call(entryOptions, "name") &&
  498. options &&
  499. typeof options.name === "string"
  500. ) {
  501. entryOptions.name = options.name;
  502. }
  503. ensureRuntime(entryOptions);
  504. const block = new AsyncDependenciesBlock({
  505. name: entryOptions.name,
  506. circular: false,
  507. entryOptions: {
  508. chunkLoading: this._chunkLoading,
  509. wasmLoading: this._wasmLoading,
  510. ...entryOptions,
  511. worker: true
  512. }
  513. });
  514. block.loc = parser.getLocation(expr);
  515. const dep = new WorkerDependency(url, range, {
  516. publicPath: this._workerPublicPath,
  517. needNewUrl,
  518. workerConstructorRange: isGlobalWorker
  519. ? /** @type {Range} */ (expr.callee.range)
  520. : undefined,
  521. resourceHint
  522. });
  523. dep.loc = parser.getLocation(expr);
  524. block.addDependency(dep);
  525. parser.state.module.addBlock(block);
  526. if (compilation.outputOptions.trustedTypes) {
  527. const dep = new CreateScriptUrlDependency(
  528. /** @type {Range} */ (expr.arguments[0].range)
  529. );
  530. dep.loc = parser.getLocation(expr);
  531. parser.state.module.addDependency(dep);
  532. }
  533. if (expressions.type) {
  534. const expr = expressions.type;
  535. if (options.type !== false) {
  536. const dep = new ConstDependency(
  537. this._module ? '"module"' : "undefined",
  538. /** @type {Range} */ (expr.range)
  539. );
  540. dep.loc = parser.getLocation(expr);
  541. parser.state.module.addPresentationalDependency(dep);
  542. /** @type {EXPECTED_ANY} */
  543. (expressions).type = undefined;
  544. }
  545. } else if (insertType === "comma") {
  546. if (this._module || hasSpreadInOptions) {
  547. const dep = new ConstDependency(
  548. `, type: ${this._module ? '"module"' : "undefined"}`,
  549. insertLocation
  550. );
  551. dep.loc = parser.getLocation(expr);
  552. parser.state.module.addPresentationalDependency(dep);
  553. }
  554. } else if (insertType === "spread") {
  555. const type = this._module ? '"module"' : "undefined";
  556. // `{ ...(opts), type }` is equivalent to `Object.assign({}, opts, { type })`
  557. const useSpread = compilation.outputOptions.environment.spread;
  558. const dep1 = new ConstDependency(
  559. useSpread ? "{ ...(" : "Object.assign({}, ",
  560. /** @type {Range} */ (insertLocation)[0]
  561. );
  562. const dep2 = new ConstDependency(
  563. useSpread ? `), type: ${type} }` : `, { type: ${type} })`,
  564. /** @type {Range} */ (insertLocation)[1]
  565. );
  566. dep1.loc = parser.getLocation(expr);
  567. dep2.loc = parser.getLocation(expr);
  568. parser.state.module.addPresentationalDependency(dep1);
  569. parser.state.module.addPresentationalDependency(dep2);
  570. } else if (insertType === "argument" && this._module) {
  571. const dep = new ConstDependency(
  572. ', { type: "module" }',
  573. insertLocation
  574. );
  575. dep.loc = parser.getLocation(expr);
  576. parser.state.module.addPresentationalDependency(dep);
  577. }
  578. parser.walkExpression(expr.callee);
  579. for (const key of Object.keys(expressions)) {
  580. if (expressions[key]) {
  581. if (expressions[key].type.endsWith("Pattern")) continue;
  582. parser.walkExpression(
  583. /** @type {Expression} */
  584. (expressions[key])
  585. );
  586. }
  587. }
  588. for (const prop of otherElements) {
  589. parser.walkProperty(prop);
  590. }
  591. if (insertType === "spread") {
  592. parser.walkExpression(/** @type {Expression} */ (arg2));
  593. }
  594. return true;
  595. };
  596. /**
  597. * Handles a matched `addModule(...)` worklet expression.
  598. * @param {CallExpression} expr expression
  599. * @returns {boolean | void} true when handled
  600. */
  601. const handleNewWorklet = (expr) => {
  602. const parsedUrl = resolveWorkerUrl(expr);
  603. if (!parsedUrl) return;
  604. const { url } = parsedUrl;
  605. const entryOptions = parseEntryOptions(expr);
  606. if (entryOptions === false) return false;
  607. const block = new AsyncDependenciesBlock({
  608. name: entryOptions.name,
  609. circular: false,
  610. entryOptions: {
  611. // A module worklet links its split chunks via native `import`
  612. // (resolved by `addModule`), so it keeps the module chunk
  613. // loading. A script worklet can't load chunks at runtime, so its
  614. // chunks use import-scripts and are pre-added from the calling scope.
  615. chunkLoading: this._module
  616. ? this._chunkLoading
  617. : "import-scripts",
  618. wasmLoading: false,
  619. ...entryOptions,
  620. worker: true,
  621. // `addModule` always loads the chunk as a module, so its
  622. // auto public-path can read `import.meta.url` (no shim needed).
  623. worklet: true
  624. }
  625. });
  626. block.loc = parser.getLocation(expr);
  627. // The dependency rewrites the call site: the fast path swaps the URL
  628. // argument directly, the multi-chunk path wraps it in a bootstrap.
  629. const dep = new WorkletDependency(
  630. url,
  631. [
  632. /** @type {Range} */ (expr.range)[0],
  633. /** @type {Range} */ (expr.range)[0]
  634. ],
  635. [
  636. /** @type {Range} */ (expr.callee.range)[1],
  637. /** @type {Range} */ (expr.range)[1]
  638. ],
  639. { publicPath: this._workerPublicPath }
  640. );
  641. dep.loc = parser.getLocation(expr);
  642. block.addDependency(dep);
  643. parser.state.module.addBlock(block);
  644. parser.walkExpression(expr.callee);
  645. return true;
  646. };
  647. /**
  648. * Registers the parser hooks matching a single syntax item.
  649. * @param {string} item item
  650. * @param {(expr: CallExpression, isGlobalWorker?: boolean) => boolean | void} handle handler invoked on a match
  651. * @param {symbol} specifierTag tag used for `*variable` syntax
  652. */
  653. const processItem = (item, handle, specifierTag) => {
  654. if (
  655. item.startsWith("*") &&
  656. item.includes(".") &&
  657. item.endsWith("()")
  658. ) {
  659. const firstDot = item.indexOf(".");
  660. const pattern = item.slice(1, firstDot);
  661. const itemMembers = item.slice(firstDot + 1, -2);
  662. parser.hooks.preDeclarator.tap(
  663. PLUGIN_NAME,
  664. (decl, _statement) => {
  665. if (
  666. decl.id.type === "Identifier" &&
  667. decl.id.name === pattern
  668. ) {
  669. parser.tagVariable(decl.id.name, specifierTag);
  670. return true;
  671. }
  672. }
  673. );
  674. parser.hooks.pattern.for(pattern).tap(PLUGIN_NAME, (pattern) => {
  675. parser.tagVariable(pattern.name, specifierTag);
  676. return true;
  677. });
  678. parser.hooks.callMemberChain
  679. .for(specifierTag)
  680. .tap(PLUGIN_NAME, (expression, members) => {
  681. if (itemMembers !== members.join(".")) {
  682. return;
  683. }
  684. return handle(expression);
  685. });
  686. } else if (item.endsWith("()")) {
  687. parser.hooks.call.for(item.slice(0, -2)).tap(PLUGIN_NAME, handle);
  688. } else {
  689. const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item);
  690. if (match) {
  691. const ids = match[1].split(".");
  692. const call = match[2];
  693. const source = match[3];
  694. (call ? parser.hooks.call : parser.hooks.new)
  695. .for(harmonySpecifierTag)
  696. .tap(PLUGIN_NAME, (expr) => {
  697. const settings = /** @type {HarmonySettings} */ (
  698. parser.currentTagData
  699. );
  700. if (
  701. !settings ||
  702. settings.source !== source ||
  703. !equals(settings.ids, ids)
  704. ) {
  705. return;
  706. }
  707. return handle(expr);
  708. });
  709. } else {
  710. parser.hooks.new
  711. .for(item)
  712. .tap(PLUGIN_NAME, (expr) => handle(expr, item === "Worker"));
  713. }
  714. }
  715. };
  716. /**
  717. * Expands and registers a syntax list.
  718. * @param {string[]} syntaxList syntax list (may contain "...")
  719. * @param {string[]} defaultSyntax default syntax used for "..."
  720. * @param {(expr: CallExpression, isGlobalWorker?: boolean) => boolean | void} handle handler
  721. * @param {symbol} specifierTag tag used for `*variable` syntax
  722. */
  723. const processList = (
  724. syntaxList,
  725. defaultSyntax,
  726. handle,
  727. specifierTag
  728. ) => {
  729. for (const item of syntaxList) {
  730. if (item === "...") {
  731. for (const itemFromDefault of defaultSyntax) {
  732. processItem(itemFromDefault, handle, specifierTag);
  733. }
  734. } else {
  735. processItem(item, handle, specifierTag);
  736. }
  737. }
  738. };
  739. if (parserOptions.worker !== false) {
  740. const workerSyntax = !Array.isArray(parserOptions.worker)
  741. ? ["..."]
  742. : parserOptions.worker;
  743. processList(
  744. workerSyntax,
  745. WORKER_DEFAULT_SYNTAX,
  746. handleNewWorker,
  747. WorkerSpecifierTag
  748. );
  749. }
  750. // Worklet parsing is opt-in: unset falls back to the `futureDefaults`
  751. // default, `false` disables it. It is not defaulted in
  752. // `config/defaults.js` because that would splice into the `"..."`
  753. // merge sentinel of a user-provided list.
  754. const workletOption =
  755. parserOptions.worklet === undefined
  756. ? this._workletDefault
  757. : parserOptions.worklet;
  758. if (workletOption) {
  759. const workletSyntax = !Array.isArray(workletOption)
  760. ? ["..."]
  761. : workletOption;
  762. processList(
  763. workletSyntax,
  764. WORKLET_DEFAULT_SYNTAX,
  765. handleNewWorklet,
  766. WorkletSpecifierTag
  767. );
  768. }
  769. };
  770. normalModuleFactory.hooks.parser
  771. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  772. .tap(PLUGIN_NAME, parserPlugin);
  773. normalModuleFactory.hooks.parser
  774. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  775. .tap(PLUGIN_NAME, parserPlugin);
  776. }
  777. );
  778. }
  779. }
  780. module.exports = WorkerAndWorkletPlugin;