CommonJsExportsParserPlugin.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("../RuntimeGlobals");
  7. const formatLocation = require("../formatLocation");
  8. const { evaluateToString } = require("../javascript/JavascriptParserHelpers");
  9. const propertyAccess = require("../util/propertyAccess");
  10. const CommonJsExportRequireDependency = require("./CommonJsExportRequireDependency");
  11. const CommonJsExportsDependency = require("./CommonJsExportsDependency");
  12. const CommonJsSelfReferenceDependency = require("./CommonJsSelfReferenceDependency");
  13. const DynamicExports = require("./DynamicExports");
  14. const HarmonyExports = require("./HarmonyExports");
  15. const ModuleDecoratorDependency = require("./ModuleDecoratorDependency");
  16. /** @typedef {import("estree").AssignmentExpression} AssignmentExpression */
  17. /** @typedef {import("estree").CallExpression} CallExpression */
  18. /** @typedef {import("estree").Expression} Expression */
  19. /** @typedef {import("estree").Super} Super */
  20. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  21. /** @typedef {import("../NormalModule")} NormalModule */
  22. /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
  23. /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
  24. /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */
  25. /**
  26. * This function takes a generic expression and detects whether it is an ObjectExpression.
  27. * This is used in the context of parsing CommonJS exports to get the value of the property descriptor
  28. * when the `exports` object is assigned to `Object.defineProperty`.
  29. *
  30. * In CommonJS modules, the `exports` object can be assigned to `Object.defineProperty` and therefore
  31. * webpack has to detect this case and get the value key of the property descriptor. See the following example
  32. * for more information: https://astexplorer.net/#/gist/83ce51a4e96e59d777df315a6d111da6/8058ead48a1bb53c097738225db0967ef7f70e57
  33. *
  34. * This would be an example of a CommonJS module that exports an object with a property descriptor:
  35. * ```js
  36. * Object.defineProperty(exports, "__esModule", { value: true });
  37. * exports.foo = void 0;
  38. * exports.foo = "bar";
  39. * ```
  40. *
  41. * @param {TODO} expr expression
  42. * @returns {Expression | undefined} returns the value of property descriptor
  43. */
  44. const getValueOfPropertyDescription = expr => {
  45. if (expr.type !== "ObjectExpression") return;
  46. for (const property of expr.properties) {
  47. if (property.computed) continue;
  48. const key = property.key;
  49. if (key.type !== "Identifier" || key.name !== "value") continue;
  50. return property.value;
  51. }
  52. };
  53. /**
  54. * The purpose of this function is to check whether an expression is a truthy literal or not. This is
  55. * useful when parsing CommonJS exports, because CommonJS modules can export any value, including falsy
  56. * values like `null` and `false`. However, exports should only be created if the exported value is truthy.
  57. *
  58. * @param {Expression} expr expression being checked
  59. * @returns {boolean} true, when the expression is a truthy literal
  60. *
  61. */
  62. const isTruthyLiteral = expr => {
  63. switch (expr.type) {
  64. case "Literal":
  65. return !!expr.value;
  66. case "UnaryExpression":
  67. if (expr.operator === "!") return isFalsyLiteral(expr.argument);
  68. }
  69. return false;
  70. };
  71. /**
  72. * The purpose of this function is to check whether an expression is a falsy literal or not. This is
  73. * useful when parsing CommonJS exports, because CommonJS modules can export any value, including falsy
  74. * values like `null` and `false`. However, exports should only be created if the exported value is truthy.
  75. *
  76. * @param {Expression} expr expression being checked
  77. * @returns {boolean} true, when the expression is a falsy literal
  78. */
  79. const isFalsyLiteral = expr => {
  80. switch (expr.type) {
  81. case "Literal":
  82. return !expr.value;
  83. case "UnaryExpression":
  84. if (expr.operator === "!") return isTruthyLiteral(expr.argument);
  85. }
  86. return false;
  87. };
  88. /**
  89. * @param {JavascriptParser} parser the parser
  90. * @param {Expression} expr expression
  91. * @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call
  92. */
  93. const parseRequireCall = (parser, expr) => {
  94. const ids = [];
  95. while (expr.type === "MemberExpression") {
  96. if (expr.object.type === "Super") return;
  97. if (!expr.property) return;
  98. const prop = expr.property;
  99. if (expr.computed) {
  100. if (prop.type !== "Literal") return;
  101. ids.push(`${prop.value}`);
  102. } else {
  103. if (prop.type !== "Identifier") return;
  104. ids.push(prop.name);
  105. }
  106. expr = expr.object;
  107. }
  108. if (expr.type !== "CallExpression" || expr.arguments.length !== 1) return;
  109. const callee = expr.callee;
  110. if (
  111. callee.type !== "Identifier" ||
  112. parser.getVariableInfo(callee.name) !== "require"
  113. ) {
  114. return;
  115. }
  116. const arg = expr.arguments[0];
  117. if (arg.type === "SpreadElement") return;
  118. const argValue = parser.evaluateExpression(arg);
  119. return { argument: argValue, ids: ids.reverse() };
  120. };
  121. class CommonJsExportsParserPlugin {
  122. /**
  123. * @param {ModuleGraph} moduleGraph module graph
  124. */
  125. constructor(moduleGraph) {
  126. this.moduleGraph = moduleGraph;
  127. }
  128. /**
  129. * @param {JavascriptParser} parser the parser
  130. * @returns {void}
  131. */
  132. apply(parser) {
  133. const enableStructuredExports = () => {
  134. DynamicExports.enable(parser.state);
  135. };
  136. /**
  137. * @param {boolean} topLevel true, when the export is on top level
  138. * @param {string[]} members members of the export
  139. * @param {Expression | undefined} valueExpr expression for the value
  140. * @returns {void}
  141. */
  142. const checkNamespace = (topLevel, members, valueExpr) => {
  143. if (!DynamicExports.isEnabled(parser.state)) return;
  144. if (members.length > 0 && members[0] === "__esModule") {
  145. if (valueExpr && isTruthyLiteral(valueExpr) && topLevel) {
  146. DynamicExports.setFlagged(parser.state);
  147. } else {
  148. DynamicExports.setDynamic(parser.state);
  149. }
  150. }
  151. };
  152. /**
  153. * @param {string=} reason reason
  154. */
  155. const bailout = reason => {
  156. DynamicExports.bailout(parser.state);
  157. if (reason) bailoutHint(reason);
  158. };
  159. /**
  160. * @param {string} reason reason
  161. */
  162. const bailoutHint = reason => {
  163. this.moduleGraph
  164. .getOptimizationBailout(parser.state.module)
  165. .push(`CommonJS bailout: ${reason}`);
  166. };
  167. // metadata //
  168. parser.hooks.evaluateTypeof
  169. .for("module")
  170. .tap("CommonJsExportsParserPlugin", evaluateToString("object"));
  171. parser.hooks.evaluateTypeof
  172. .for("exports")
  173. .tap("CommonJsPlugin", evaluateToString("object"));
  174. // exporting //
  175. /**
  176. * @param {AssignmentExpression} expr expression
  177. * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords
  178. * @param {string[]} members members of the export
  179. * @returns {boolean} true, when the expression was handled
  180. */
  181. const handleAssignExport = (expr, base, members) => {
  182. if (HarmonyExports.isEnabled(parser.state)) return;
  183. // Handle reexporting
  184. const requireCall = parseRequireCall(parser, expr.right);
  185. if (
  186. requireCall &&
  187. requireCall.argument.isString() &&
  188. (members.length === 0 || members[0] !== "__esModule")
  189. ) {
  190. enableStructuredExports();
  191. // It's possible to reexport __esModule, so we must convert to a dynamic module
  192. if (members.length === 0) DynamicExports.setDynamic(parser.state);
  193. const dep = new CommonJsExportRequireDependency(
  194. expr.range,
  195. null,
  196. base,
  197. members,
  198. requireCall.argument.string,
  199. requireCall.ids,
  200. !parser.isStatementLevelExpression(expr)
  201. );
  202. dep.loc = expr.loc;
  203. dep.optional = !!parser.scope.inTry;
  204. parser.state.module.addDependency(dep);
  205. return true;
  206. }
  207. if (members.length === 0) return;
  208. enableStructuredExports();
  209. const remainingMembers = members;
  210. checkNamespace(
  211. parser.statementPath.length === 1 &&
  212. parser.isStatementLevelExpression(expr),
  213. remainingMembers,
  214. expr.right
  215. );
  216. const dep = new CommonJsExportsDependency(
  217. expr.left.range,
  218. null,
  219. base,
  220. remainingMembers
  221. );
  222. dep.loc = expr.loc;
  223. parser.state.module.addDependency(dep);
  224. parser.walkExpression(expr.right);
  225. return true;
  226. };
  227. parser.hooks.assignMemberChain
  228. .for("exports")
  229. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  230. return handleAssignExport(expr, "exports", members);
  231. });
  232. parser.hooks.assignMemberChain
  233. .for("this")
  234. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  235. if (!parser.scope.topLevelScope) return;
  236. return handleAssignExport(expr, "this", members);
  237. });
  238. parser.hooks.assignMemberChain
  239. .for("module")
  240. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  241. if (members[0] !== "exports") return;
  242. return handleAssignExport(expr, "module.exports", members.slice(1));
  243. });
  244. parser.hooks.call
  245. .for("Object.defineProperty")
  246. .tap("CommonJsExportsParserPlugin", expression => {
  247. const expr = /** @type {CallExpression} */ (expression);
  248. if (!parser.isStatementLevelExpression(expr)) return;
  249. if (expr.arguments.length !== 3) return;
  250. if (expr.arguments[0].type === "SpreadElement") return;
  251. if (expr.arguments[1].type === "SpreadElement") return;
  252. if (expr.arguments[2].type === "SpreadElement") return;
  253. const exportsArg = parser.evaluateExpression(expr.arguments[0]);
  254. if (!exportsArg.isIdentifier()) return;
  255. if (
  256. exportsArg.identifier !== "exports" &&
  257. exportsArg.identifier !== "module.exports" &&
  258. (exportsArg.identifier !== "this" || !parser.scope.topLevelScope)
  259. ) {
  260. return;
  261. }
  262. const propertyArg = parser.evaluateExpression(expr.arguments[1]);
  263. const property = propertyArg.asString();
  264. if (typeof property !== "string") return;
  265. enableStructuredExports();
  266. const descArg = expr.arguments[2];
  267. checkNamespace(
  268. parser.statementPath.length === 1,
  269. [property],
  270. getValueOfPropertyDescription(descArg)
  271. );
  272. const dep = new CommonJsExportsDependency(
  273. expr.range,
  274. expr.arguments[2].range,
  275. `Object.defineProperty(${exportsArg.identifier})`,
  276. [property]
  277. );
  278. dep.loc = expr.loc;
  279. parser.state.module.addDependency(dep);
  280. parser.walkExpression(expr.arguments[2]);
  281. return true;
  282. });
  283. // Self reference //
  284. /**
  285. * @param {Expression | Super} expr expression
  286. * @param {CommonJSDependencyBaseKeywords} base commonjs base keywords
  287. * @param {string[]} members members of the export
  288. * @param {CallExpression=} call call expression
  289. * @returns {boolean | void} true, when the expression was handled
  290. */
  291. const handleAccessExport = (expr, base, members, call = undefined) => {
  292. if (HarmonyExports.isEnabled(parser.state)) return;
  293. if (members.length === 0) {
  294. bailout(`${base} is used directly at ${formatLocation(expr.loc)}`);
  295. }
  296. if (call && members.length === 1) {
  297. bailoutHint(
  298. `${base}${propertyAccess(
  299. members
  300. )}(...) prevents optimization as ${base} is passed as call context at ${formatLocation(
  301. expr.loc
  302. )}`
  303. );
  304. }
  305. const dep = new CommonJsSelfReferenceDependency(
  306. expr.range,
  307. base,
  308. members,
  309. !!call
  310. );
  311. dep.loc = expr.loc;
  312. parser.state.module.addDependency(dep);
  313. if (call) {
  314. parser.walkExpressions(call.arguments);
  315. }
  316. return true;
  317. };
  318. parser.hooks.callMemberChain
  319. .for("exports")
  320. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  321. return handleAccessExport(expr.callee, "exports", members, expr);
  322. });
  323. parser.hooks.expressionMemberChain
  324. .for("exports")
  325. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  326. return handleAccessExport(expr, "exports", members);
  327. });
  328. parser.hooks.expression
  329. .for("exports")
  330. .tap("CommonJsExportsParserPlugin", expr => {
  331. return handleAccessExport(expr, "exports", []);
  332. });
  333. parser.hooks.callMemberChain
  334. .for("module")
  335. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  336. if (members[0] !== "exports") return;
  337. return handleAccessExport(
  338. expr.callee,
  339. "module.exports",
  340. members.slice(1),
  341. expr
  342. );
  343. });
  344. parser.hooks.expressionMemberChain
  345. .for("module")
  346. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  347. if (members[0] !== "exports") return;
  348. return handleAccessExport(expr, "module.exports", members.slice(1));
  349. });
  350. parser.hooks.expression
  351. .for("module.exports")
  352. .tap("CommonJsExportsParserPlugin", expr => {
  353. return handleAccessExport(expr, "module.exports", []);
  354. });
  355. parser.hooks.callMemberChain
  356. .for("this")
  357. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  358. if (!parser.scope.topLevelScope) return;
  359. return handleAccessExport(expr.callee, "this", members, expr);
  360. });
  361. parser.hooks.expressionMemberChain
  362. .for("this")
  363. .tap("CommonJsExportsParserPlugin", (expr, members) => {
  364. if (!parser.scope.topLevelScope) return;
  365. return handleAccessExport(expr, "this", members);
  366. });
  367. parser.hooks.expression
  368. .for("this")
  369. .tap("CommonJsExportsParserPlugin", expr => {
  370. if (!parser.scope.topLevelScope) return;
  371. return handleAccessExport(expr, "this", []);
  372. });
  373. // Bailouts //
  374. parser.hooks.expression.for("module").tap("CommonJsPlugin", expr => {
  375. bailout();
  376. const isHarmony = HarmonyExports.isEnabled(parser.state);
  377. const dep = new ModuleDecoratorDependency(
  378. isHarmony
  379. ? RuntimeGlobals.harmonyModuleDecorator
  380. : RuntimeGlobals.nodeModuleDecorator,
  381. !isHarmony
  382. );
  383. dep.loc = expr.loc;
  384. parser.state.module.addDependency(dep);
  385. return true;
  386. });
  387. }
  388. }
  389. module.exports = CommonJsExportsParserPlugin;