RuntimeTemplate.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const InitFragment = require("./InitFragment");
  7. const RuntimeGlobals = require("./RuntimeGlobals");
  8. const Template = require("./Template");
  9. const { equals } = require("./util/ArrayHelpers");
  10. const compileBooleanMatcher = require("./util/compileBooleanMatcher");
  11. const propertyAccess = require("./util/propertyAccess");
  12. const { forEachRuntime, subtractRuntime } = require("./util/runtime");
  13. /** @typedef {import("../declarations/WebpackOptions").Environment} Environment */
  14. /** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
  15. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  16. /** @typedef {import("./Chunk")} Chunk */
  17. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  18. /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
  19. /** @typedef {import("./CodeGenerationResults").CodeGenerationResult} CodeGenerationResult */
  20. /** @typedef {import("./Compilation")} Compilation */
  21. /** @typedef {import("./Dependency")} Dependency */
  22. /** @typedef {import("./Module")} Module */
  23. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  24. /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
  25. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  26. /** @typedef {import("./RequestShortener")} RequestShortener */
  27. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  28. /**
  29. * @param {Module} module the module
  30. * @param {ChunkGraph} chunkGraph the chunk graph
  31. * @returns {string} error message
  32. */
  33. const noModuleIdErrorMessage = (
  34. module,
  35. chunkGraph
  36. ) => `Module ${module.identifier()} has no id assigned.
  37. This should not happen.
  38. It's in these chunks: ${
  39. Array.from(
  40. chunkGraph.getModuleChunksIterable(module),
  41. c => c.name || c.id || c.debugId
  42. ).join(", ") || "none"
  43. } (If module is in no chunk this indicates a bug in some chunk/module optimization logic)
  44. Module has these incoming connections: ${Array.from(
  45. chunkGraph.moduleGraph.getIncomingConnections(module),
  46. connection =>
  47. `\n - ${
  48. connection.originModule && connection.originModule.identifier()
  49. } ${connection.dependency && connection.dependency.type} ${
  50. (connection.explanations &&
  51. Array.from(connection.explanations).join(", ")) ||
  52. ""
  53. }`
  54. ).join("")}`;
  55. /**
  56. * @param {string | undefined} definition global object definition
  57. * @returns {string | undefined} save to use global object
  58. */
  59. function getGlobalObject(definition) {
  60. if (!definition) return definition;
  61. const trimmed = definition.trim();
  62. if (
  63. // identifier, we do not need real identifier regarding ECMAScript/Unicode
  64. /^[_\p{L}][_0-9\p{L}]*$/iu.test(trimmed) ||
  65. // iife
  66. // call expression
  67. // expression in parentheses
  68. /^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu.test(trimmed)
  69. )
  70. return trimmed;
  71. return `Object(${trimmed})`;
  72. }
  73. class RuntimeTemplate {
  74. /**
  75. * @param {Compilation} compilation the compilation
  76. * @param {OutputOptions} outputOptions the compilation output options
  77. * @param {RequestShortener} requestShortener the request shortener
  78. */
  79. constructor(compilation, outputOptions, requestShortener) {
  80. this.compilation = compilation;
  81. this.outputOptions = /** @type {OutputOptions} */ (outputOptions || {});
  82. this.requestShortener = requestShortener;
  83. this.globalObject =
  84. /** @type {string} */
  85. (getGlobalObject(outputOptions.globalObject));
  86. this.contentHashReplacement = "X".repeat(
  87. /** @type {NonNullable<OutputOptions["hashDigestLength"]>} */
  88. (outputOptions.hashDigestLength)
  89. );
  90. }
  91. isIIFE() {
  92. return this.outputOptions.iife;
  93. }
  94. isModule() {
  95. return this.outputOptions.module;
  96. }
  97. isNeutralPlatform() {
  98. return (
  99. !this.outputOptions.environment.document &&
  100. !this.compilation.compiler.platform.node
  101. );
  102. }
  103. supportsConst() {
  104. return this.outputOptions.environment.const;
  105. }
  106. supportsArrowFunction() {
  107. return this.outputOptions.environment.arrowFunction;
  108. }
  109. supportsAsyncFunction() {
  110. return this.outputOptions.environment.asyncFunction;
  111. }
  112. supportsOptionalChaining() {
  113. return this.outputOptions.environment.optionalChaining;
  114. }
  115. supportsForOf() {
  116. return this.outputOptions.environment.forOf;
  117. }
  118. supportsDestructuring() {
  119. return this.outputOptions.environment.destructuring;
  120. }
  121. supportsBigIntLiteral() {
  122. return this.outputOptions.environment.bigIntLiteral;
  123. }
  124. supportsDynamicImport() {
  125. return this.outputOptions.environment.dynamicImport;
  126. }
  127. supportsEcmaScriptModuleSyntax() {
  128. return this.outputOptions.environment.module;
  129. }
  130. supportTemplateLiteral() {
  131. return this.outputOptions.environment.templateLiteral;
  132. }
  133. supportNodePrefixForCoreModules() {
  134. return this.outputOptions.environment.nodePrefixForCoreModules;
  135. }
  136. /**
  137. * @param {string} returnValue return value
  138. * @param {string} args arguments
  139. * @returns {string} returning function
  140. */
  141. returningFunction(returnValue, args = "") {
  142. return this.supportsArrowFunction()
  143. ? `(${args}) => (${returnValue})`
  144. : `function(${args}) { return ${returnValue}; }`;
  145. }
  146. /**
  147. * @param {string} args arguments
  148. * @param {string | string[]} body body
  149. * @returns {string} basic function
  150. */
  151. basicFunction(args, body) {
  152. return this.supportsArrowFunction()
  153. ? `(${args}) => {\n${Template.indent(body)}\n}`
  154. : `function(${args}) {\n${Template.indent(body)}\n}`;
  155. }
  156. /**
  157. * @param {Array<string|{expr: string}>} args args
  158. * @returns {string} result expression
  159. */
  160. concatenation(...args) {
  161. const len = args.length;
  162. if (len === 2) return this._es5Concatenation(args);
  163. if (len === 0) return '""';
  164. if (len === 1) {
  165. return typeof args[0] === "string"
  166. ? JSON.stringify(args[0])
  167. : `"" + ${args[0].expr}`;
  168. }
  169. if (!this.supportTemplateLiteral()) return this._es5Concatenation(args);
  170. // cost comparison between template literal and concatenation:
  171. // both need equal surroundings: `xxx` vs "xxx"
  172. // template literal has constant cost of 3 chars for each expression
  173. // es5 concatenation has cost of 3 + n chars for n expressions in row
  174. // when a es5 concatenation ends with an expression it reduces cost by 3
  175. // when a es5 concatenation starts with an single expression it reduces cost by 3
  176. // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3)
  177. // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12)
  178. let templateCost = 0;
  179. let concatenationCost = 0;
  180. let lastWasExpr = false;
  181. for (const arg of args) {
  182. const isExpr = typeof arg !== "string";
  183. if (isExpr) {
  184. templateCost += 3;
  185. concatenationCost += lastWasExpr ? 1 : 4;
  186. }
  187. lastWasExpr = isExpr;
  188. }
  189. if (lastWasExpr) concatenationCost -= 3;
  190. if (typeof args[0] !== "string" && typeof args[1] === "string")
  191. concatenationCost -= 3;
  192. if (concatenationCost <= templateCost) return this._es5Concatenation(args);
  193. return `\`${args
  194. .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`))
  195. .join("")}\``;
  196. }
  197. /**
  198. * @param {Array<string|{expr: string}>} args args (len >= 2)
  199. * @returns {string} result expression
  200. * @private
  201. */
  202. _es5Concatenation(args) {
  203. const str = args
  204. .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr))
  205. .join(" + ");
  206. // when the first two args are expression, we need to prepend "" + to force string
  207. // concatenation instead of number addition.
  208. return typeof args[0] !== "string" && typeof args[1] !== "string"
  209. ? `"" + ${str}`
  210. : str;
  211. }
  212. /**
  213. * @param {string} expression expression
  214. * @param {string} args arguments
  215. * @returns {string} expression function code
  216. */
  217. expressionFunction(expression, args = "") {
  218. return this.supportsArrowFunction()
  219. ? `(${args}) => (${expression})`
  220. : `function(${args}) { ${expression}; }`;
  221. }
  222. /**
  223. * @returns {string} empty function code
  224. */
  225. emptyFunction() {
  226. return this.supportsArrowFunction() ? "x => {}" : "function() {}";
  227. }
  228. /**
  229. * @param {string[]} items items
  230. * @param {string} value value
  231. * @returns {string} destructure array code
  232. */
  233. destructureArray(items, value) {
  234. return this.supportsDestructuring()
  235. ? `var [${items.join(", ")}] = ${value};`
  236. : Template.asString(
  237. items.map((item, i) => `var ${item} = ${value}[${i}];`)
  238. );
  239. }
  240. /**
  241. * @param {string[]} items items
  242. * @param {string} value value
  243. * @returns {string} destructure object code
  244. */
  245. destructureObject(items, value) {
  246. return this.supportsDestructuring()
  247. ? `var {${items.join(", ")}} = ${value};`
  248. : Template.asString(
  249. items.map(item => `var ${item} = ${value}${propertyAccess([item])};`)
  250. );
  251. }
  252. /**
  253. * @param {string} args arguments
  254. * @param {string} body body
  255. * @returns {string} IIFE code
  256. */
  257. iife(args, body) {
  258. return `(${this.basicFunction(args, body)})()`;
  259. }
  260. /**
  261. * @param {string} variable variable
  262. * @param {string} array array
  263. * @param {string | string[]} body body
  264. * @returns {string} for each code
  265. */
  266. forEach(variable, array, body) {
  267. return this.supportsForOf()
  268. ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}`
  269. : `${array}.forEach(function(${variable}) {\n${Template.indent(
  270. body
  271. )}\n});`;
  272. }
  273. /**
  274. * Add a comment
  275. * @param {object} options Information content of the comment
  276. * @param {string=} options.request request string used originally
  277. * @param {(string | null)=} options.chunkName name of the chunk referenced
  278. * @param {string=} options.chunkReason reason information of the chunk
  279. * @param {string=} options.message additional message
  280. * @param {string=} options.exportName name of the export
  281. * @returns {string} comment
  282. */
  283. comment({ request, chunkName, chunkReason, message, exportName }) {
  284. let content;
  285. if (this.outputOptions.pathinfo) {
  286. content = [message, request, chunkName, chunkReason]
  287. .filter(Boolean)
  288. .map(item => this.requestShortener.shorten(item))
  289. .join(" | ");
  290. } else {
  291. content = [message, chunkName, chunkReason]
  292. .filter(Boolean)
  293. .map(item => this.requestShortener.shorten(item))
  294. .join(" | ");
  295. }
  296. if (!content) return "";
  297. if (this.outputOptions.pathinfo) {
  298. return `${Template.toComment(content)} `;
  299. }
  300. return `${Template.toNormalComment(content)} `;
  301. }
  302. /**
  303. * @param {object} options generation options
  304. * @param {string=} options.request request string used originally
  305. * @returns {string} generated error block
  306. */
  307. throwMissingModuleErrorBlock({ request }) {
  308. const err = `Cannot find module '${request}'`;
  309. return `var e = new Error(${JSON.stringify(
  310. err
  311. )}); e.code = 'MODULE_NOT_FOUND'; throw e;`;
  312. }
  313. /**
  314. * @param {object} options generation options
  315. * @param {string=} options.request request string used originally
  316. * @returns {string} generated error function
  317. */
  318. throwMissingModuleErrorFunction({ request }) {
  319. return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock(
  320. { request }
  321. )} }`;
  322. }
  323. /**
  324. * @param {object} options generation options
  325. * @param {string=} options.request request string used originally
  326. * @returns {string} generated error IIFE
  327. */
  328. missingModule({ request }) {
  329. return `Object(${this.throwMissingModuleErrorFunction({ request })}())`;
  330. }
  331. /**
  332. * @param {object} options generation options
  333. * @param {string=} options.request request string used originally
  334. * @returns {string} generated error statement
  335. */
  336. missingModuleStatement({ request }) {
  337. return `${this.missingModule({ request })};\n`;
  338. }
  339. /**
  340. * @param {object} options generation options
  341. * @param {string=} options.request request string used originally
  342. * @returns {string} generated error code
  343. */
  344. missingModulePromise({ request }) {
  345. return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({
  346. request
  347. })})`;
  348. }
  349. /**
  350. * @param {object} options options object
  351. * @param {ChunkGraph} options.chunkGraph the chunk graph
  352. * @param {Module} options.module the module
  353. * @param {string=} options.request the request that should be printed as comment
  354. * @param {string=} options.idExpr expression to use as id expression
  355. * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned
  356. * @returns {string} the code
  357. */
  358. weakError({ module, chunkGraph, request, idExpr, type }) {
  359. const moduleId = chunkGraph.getModuleId(module);
  360. const errorMessage =
  361. moduleId === null
  362. ? JSON.stringify("Module is not available (weak dependency)")
  363. : idExpr
  364. ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"`
  365. : JSON.stringify(
  366. `Module '${moduleId}' is not available (weak dependency)`
  367. );
  368. const comment = request ? `${Template.toNormalComment(request)} ` : "";
  369. const errorStatements = `var e = new Error(${errorMessage}); ${
  370. comment
  371. }e.code = 'MODULE_NOT_FOUND'; throw e;`;
  372. switch (type) {
  373. case "statements":
  374. return errorStatements;
  375. case "promise":
  376. return `Promise.resolve().then(${this.basicFunction(
  377. "",
  378. errorStatements
  379. )})`;
  380. case "expression":
  381. return this.iife("", errorStatements);
  382. }
  383. }
  384. /**
  385. * @param {object} options options object
  386. * @param {Module} options.module the module
  387. * @param {ChunkGraph} options.chunkGraph the chunk graph
  388. * @param {string=} options.request the request that should be printed as comment
  389. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  390. * @returns {string} the expression
  391. */
  392. moduleId({ module, chunkGraph, request, weak }) {
  393. if (!module) {
  394. return this.missingModule({
  395. request
  396. });
  397. }
  398. const moduleId = chunkGraph.getModuleId(module);
  399. if (moduleId === null) {
  400. if (weak) {
  401. return "null /* weak dependency, without id */";
  402. }
  403. throw new Error(
  404. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  405. module,
  406. chunkGraph
  407. )}`
  408. );
  409. }
  410. return `${this.comment({ request })}${JSON.stringify(moduleId)}`;
  411. }
  412. /**
  413. * @param {object} options options object
  414. * @param {Module | null} options.module the module
  415. * @param {ChunkGraph} options.chunkGraph the chunk graph
  416. * @param {string=} options.request the request that should be printed as comment
  417. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  418. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  419. * @returns {string} the expression
  420. */
  421. moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) {
  422. if (!module) {
  423. return this.missingModule({
  424. request
  425. });
  426. }
  427. const moduleId = chunkGraph.getModuleId(module);
  428. if (moduleId === null) {
  429. if (weak) {
  430. // only weak referenced modules don't get an id
  431. // we can always emit an error emitting code here
  432. return this.weakError({
  433. module,
  434. chunkGraph,
  435. request,
  436. type: "expression"
  437. });
  438. }
  439. throw new Error(
  440. `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage(
  441. module,
  442. chunkGraph
  443. )}`
  444. );
  445. }
  446. runtimeRequirements.add(RuntimeGlobals.require);
  447. return `${RuntimeGlobals.require}(${this.moduleId({
  448. module,
  449. chunkGraph,
  450. request,
  451. weak
  452. })})`;
  453. }
  454. /**
  455. * @param {object} options options object
  456. * @param {Module | null} options.module the module
  457. * @param {ChunkGraph} options.chunkGraph the chunk graph
  458. * @param {string} options.request the request that should be printed as comment
  459. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  460. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  461. * @returns {string} the expression
  462. */
  463. moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) {
  464. return this.moduleRaw({
  465. module,
  466. chunkGraph,
  467. request,
  468. weak,
  469. runtimeRequirements
  470. });
  471. }
  472. /**
  473. * @param {object} options options object
  474. * @param {Module} options.module the module
  475. * @param {ChunkGraph} options.chunkGraph the chunk graph
  476. * @param {string} options.request the request that should be printed as comment
  477. * @param {boolean=} options.strict if the current module is in strict esm mode
  478. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  479. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  480. * @returns {string} the expression
  481. */
  482. moduleNamespace({
  483. module,
  484. chunkGraph,
  485. request,
  486. strict,
  487. weak,
  488. runtimeRequirements
  489. }) {
  490. if (!module) {
  491. return this.missingModule({
  492. request
  493. });
  494. }
  495. if (chunkGraph.getModuleId(module) === null) {
  496. if (weak) {
  497. // only weak referenced modules don't get an id
  498. // we can always emit an error emitting code here
  499. return this.weakError({
  500. module,
  501. chunkGraph,
  502. request,
  503. type: "expression"
  504. });
  505. }
  506. throw new Error(
  507. `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage(
  508. module,
  509. chunkGraph
  510. )}`
  511. );
  512. }
  513. const moduleId = this.moduleId({
  514. module,
  515. chunkGraph,
  516. request,
  517. weak
  518. });
  519. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  520. switch (exportsType) {
  521. case "namespace":
  522. return this.moduleRaw({
  523. module,
  524. chunkGraph,
  525. request,
  526. weak,
  527. runtimeRequirements
  528. });
  529. case "default-with-named":
  530. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  531. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`;
  532. case "default-only":
  533. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  534. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`;
  535. case "dynamic":
  536. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  537. return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`;
  538. }
  539. }
  540. /**
  541. * @param {object} options options object
  542. * @param {ChunkGraph} options.chunkGraph the chunk graph
  543. * @param {AsyncDependenciesBlock=} options.block the current dependencies block
  544. * @param {Module} options.module the module
  545. * @param {string} options.request the request that should be printed as comment
  546. * @param {string} options.message a message for the comment
  547. * @param {boolean=} options.strict if the current module is in strict esm mode
  548. * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
  549. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  550. * @returns {string} the promise expression
  551. */
  552. moduleNamespacePromise({
  553. chunkGraph,
  554. block,
  555. module,
  556. request,
  557. message,
  558. strict,
  559. weak,
  560. runtimeRequirements
  561. }) {
  562. if (!module) {
  563. return this.missingModulePromise({
  564. request
  565. });
  566. }
  567. const moduleId = chunkGraph.getModuleId(module);
  568. if (moduleId === null) {
  569. if (weak) {
  570. // only weak referenced modules don't get an id
  571. // we can always emit an error emitting code here
  572. return this.weakError({
  573. module,
  574. chunkGraph,
  575. request,
  576. type: "promise"
  577. });
  578. }
  579. throw new Error(
  580. `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage(
  581. module,
  582. chunkGraph
  583. )}`
  584. );
  585. }
  586. const promise = this.blockPromise({
  587. chunkGraph,
  588. block,
  589. message,
  590. runtimeRequirements
  591. });
  592. let appending;
  593. let idExpr = JSON.stringify(chunkGraph.getModuleId(module));
  594. const comment = this.comment({
  595. request
  596. });
  597. let header = "";
  598. if (weak) {
  599. if (idExpr.length > 8) {
  600. // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"'
  601. header += `var id = ${idExpr}; `;
  602. idExpr = "id";
  603. }
  604. runtimeRequirements.add(RuntimeGlobals.moduleFactories);
  605. header += `if(!${
  606. RuntimeGlobals.moduleFactories
  607. }[${idExpr}]) { ${this.weakError({
  608. module,
  609. chunkGraph,
  610. request,
  611. idExpr,
  612. type: "statements"
  613. })} } `;
  614. }
  615. const moduleIdExpr = this.moduleId({
  616. module,
  617. chunkGraph,
  618. request,
  619. weak
  620. });
  621. const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
  622. let fakeType = 16;
  623. switch (exportsType) {
  624. case "namespace":
  625. if (header) {
  626. const rawModule = this.moduleRaw({
  627. module,
  628. chunkGraph,
  629. request,
  630. weak,
  631. runtimeRequirements
  632. });
  633. appending = `.then(${this.basicFunction(
  634. "",
  635. `${header}return ${rawModule};`
  636. )})`;
  637. } else {
  638. runtimeRequirements.add(RuntimeGlobals.require);
  639. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  640. }
  641. break;
  642. case "dynamic":
  643. fakeType |= 4;
  644. /* fall through */
  645. case "default-with-named":
  646. fakeType |= 2;
  647. /* fall through */
  648. case "default-only":
  649. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  650. if (chunkGraph.moduleGraph.isAsync(module)) {
  651. if (header) {
  652. const rawModule = this.moduleRaw({
  653. module,
  654. chunkGraph,
  655. request,
  656. weak,
  657. runtimeRequirements
  658. });
  659. appending = `.then(${this.basicFunction(
  660. "",
  661. `${header}return ${rawModule};`
  662. )})`;
  663. } else {
  664. runtimeRequirements.add(RuntimeGlobals.require);
  665. appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
  666. }
  667. appending += `.then(${this.returningFunction(
  668. `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`,
  669. "m"
  670. )})`;
  671. } else {
  672. fakeType |= 1;
  673. if (header) {
  674. const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`;
  675. appending = `.then(${this.basicFunction(
  676. "",
  677. `${header}return ${returnExpression};`
  678. )})`;
  679. } else {
  680. appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${fakeType}))`;
  681. }
  682. }
  683. break;
  684. }
  685. return `${promise || "Promise.resolve()"}${appending}`;
  686. }
  687. /**
  688. * @param {object} options options object
  689. * @param {ChunkGraph} options.chunkGraph the chunk graph
  690. * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated
  691. * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes
  692. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  693. * @returns {string} expression
  694. */
  695. runtimeConditionExpression({
  696. chunkGraph,
  697. runtimeCondition,
  698. runtime,
  699. runtimeRequirements
  700. }) {
  701. if (runtimeCondition === undefined) return "true";
  702. if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`;
  703. /** @type {Set<string>} */
  704. const positiveRuntimeIds = new Set();
  705. forEachRuntime(runtimeCondition, runtime =>
  706. positiveRuntimeIds.add(
  707. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  708. )
  709. );
  710. /** @type {Set<string>} */
  711. const negativeRuntimeIds = new Set();
  712. forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime =>
  713. negativeRuntimeIds.add(
  714. `${chunkGraph.getRuntimeId(/** @type {string} */ (runtime))}`
  715. )
  716. );
  717. runtimeRequirements.add(RuntimeGlobals.runtimeId);
  718. return compileBooleanMatcher.fromLists(
  719. Array.from(positiveRuntimeIds),
  720. Array.from(negativeRuntimeIds)
  721. )(RuntimeGlobals.runtimeId);
  722. }
  723. /**
  724. * @param {object} options options object
  725. * @param {boolean=} options.update whether a new variable should be created or the existing one updated
  726. * @param {Module} options.module the module
  727. * @param {ChunkGraph} options.chunkGraph the chunk graph
  728. * @param {string} options.request the request that should be printed as comment
  729. * @param {string} options.importVar name of the import variable
  730. * @param {Module} options.originModule module in which the statement is emitted
  731. * @param {boolean=} options.weak true, if this is a weak dependency
  732. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  733. * @returns {[string, string]} the import statement and the compat statement
  734. */
  735. importStatement({
  736. update,
  737. module,
  738. chunkGraph,
  739. request,
  740. importVar,
  741. originModule,
  742. weak,
  743. runtimeRequirements
  744. }) {
  745. if (!module) {
  746. return [
  747. this.missingModuleStatement({
  748. request
  749. }),
  750. ""
  751. ];
  752. }
  753. if (chunkGraph.getModuleId(module) === null) {
  754. if (weak) {
  755. // only weak referenced modules don't get an id
  756. // we can always emit an error emitting code here
  757. return [
  758. this.weakError({
  759. module,
  760. chunkGraph,
  761. request,
  762. type: "statements"
  763. }),
  764. ""
  765. ];
  766. }
  767. throw new Error(
  768. `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage(
  769. module,
  770. chunkGraph
  771. )}`
  772. );
  773. }
  774. const moduleId = this.moduleId({
  775. module,
  776. chunkGraph,
  777. request,
  778. weak
  779. });
  780. const optDeclaration = update ? "" : "var ";
  781. const exportsType = module.getExportsType(
  782. chunkGraph.moduleGraph,
  783. /** @type {BuildMeta} */
  784. (originModule.buildMeta).strictHarmonyModule
  785. );
  786. runtimeRequirements.add(RuntimeGlobals.require);
  787. const importContent = `/* harmony import */ ${optDeclaration}${importVar} = ${RuntimeGlobals.require}(${moduleId});\n`;
  788. if (exportsType === "dynamic") {
  789. runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport);
  790. return [
  791. importContent,
  792. `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n`
  793. ];
  794. }
  795. return [importContent, ""];
  796. }
  797. /**
  798. * @param {object} options options
  799. * @param {ModuleGraph} options.moduleGraph the module graph
  800. * @param {Module} options.module the module
  801. * @param {string} options.request the request
  802. * @param {string | string[]} options.exportName the export name
  803. * @param {Module} options.originModule the origin module
  804. * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
  805. * @param {boolean} options.isCall true, if expression will be called
  806. * @param {boolean | null} options.callContext when false, call context will not be preserved
  807. * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated
  808. * @param {string} options.importVar the identifier name of the import variable
  809. * @param {InitFragment<TODO>[]} options.initFragments init fragments will be added here
  810. * @param {RuntimeSpec} options.runtime runtime for which this code will be generated
  811. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  812. * @returns {string} expression
  813. */
  814. exportFromImport({
  815. moduleGraph,
  816. module,
  817. request,
  818. exportName,
  819. originModule,
  820. asiSafe,
  821. isCall,
  822. callContext,
  823. defaultInterop,
  824. importVar,
  825. initFragments,
  826. runtime,
  827. runtimeRequirements
  828. }) {
  829. if (!module) {
  830. return this.missingModule({
  831. request
  832. });
  833. }
  834. if (!Array.isArray(exportName)) {
  835. exportName = exportName ? [exportName] : [];
  836. }
  837. const exportsType = module.getExportsType(
  838. moduleGraph,
  839. /** @type {BuildMeta} */
  840. (originModule.buildMeta).strictHarmonyModule
  841. );
  842. if (defaultInterop) {
  843. if (exportName.length > 0 && exportName[0] === "default") {
  844. switch (exportsType) {
  845. case "dynamic":
  846. if (isCall) {
  847. return `${importVar}_default()${propertyAccess(exportName, 1)}`;
  848. }
  849. return asiSafe
  850. ? `(${importVar}_default()${propertyAccess(exportName, 1)})`
  851. : asiSafe === false
  852. ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
  853. : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
  854. case "default-only":
  855. case "default-with-named":
  856. exportName = exportName.slice(1);
  857. break;
  858. }
  859. } else if (exportName.length > 0) {
  860. if (exportsType === "default-only") {
  861. return `/* non-default import from non-esm module */undefined${propertyAccess(
  862. exportName,
  863. 1
  864. )}`;
  865. } else if (
  866. exportsType !== "namespace" &&
  867. exportName[0] === "__esModule"
  868. ) {
  869. return "/* __esModule */true";
  870. }
  871. } else if (
  872. exportsType === "default-only" ||
  873. exportsType === "default-with-named"
  874. ) {
  875. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  876. initFragments.push(
  877. new InitFragment(
  878. `var ${importVar}_namespace_cache;\n`,
  879. InitFragment.STAGE_CONSTANTS,
  880. -1,
  881. `${importVar}_namespace_cache`
  882. )
  883. );
  884. return `/*#__PURE__*/ ${
  885. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  886. }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${
  887. RuntimeGlobals.createFakeNamespaceObject
  888. }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`;
  889. }
  890. }
  891. if (exportName.length > 0) {
  892. const exportsInfo = moduleGraph.getExportsInfo(module);
  893. const used = exportsInfo.getUsedName(exportName, runtime);
  894. if (!used) {
  895. const comment = Template.toNormalComment(
  896. `unused export ${propertyAccess(exportName)}`
  897. );
  898. return `${comment} undefined`;
  899. }
  900. const comment = equals(used, exportName)
  901. ? ""
  902. : `${Template.toNormalComment(propertyAccess(exportName))} `;
  903. const access = `${importVar}${comment}${propertyAccess(used)}`;
  904. if (isCall && callContext === false) {
  905. return asiSafe
  906. ? `(0,${access})`
  907. : asiSafe === false
  908. ? `;(0,${access})`
  909. : `/*#__PURE__*/Object(${access})`;
  910. }
  911. return access;
  912. }
  913. return importVar;
  914. }
  915. /**
  916. * @param {object} options options
  917. * @param {AsyncDependenciesBlock | undefined} options.block the async block
  918. * @param {string} options.message the message
  919. * @param {ChunkGraph} options.chunkGraph the chunk graph
  920. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  921. * @returns {string} expression
  922. */
  923. blockPromise({ block, message, chunkGraph, runtimeRequirements }) {
  924. if (!block) {
  925. const comment = this.comment({
  926. message
  927. });
  928. return `Promise.resolve(${comment.trim()})`;
  929. }
  930. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  931. if (!chunkGroup || chunkGroup.chunks.length === 0) {
  932. const comment = this.comment({
  933. message
  934. });
  935. return `Promise.resolve(${comment.trim()})`;
  936. }
  937. const chunks = chunkGroup.chunks.filter(
  938. chunk => !chunk.hasRuntime() && chunk.id !== null
  939. );
  940. const comment = this.comment({
  941. message,
  942. chunkName: block.chunkName
  943. });
  944. if (chunks.length === 1) {
  945. const chunkId = JSON.stringify(chunks[0].id);
  946. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  947. const fetchPriority = chunkGroup.options.fetchPriority;
  948. if (fetchPriority) {
  949. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  950. }
  951. return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId}${
  952. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  953. })`;
  954. } else if (chunks.length > 0) {
  955. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  956. const fetchPriority = chunkGroup.options.fetchPriority;
  957. if (fetchPriority) {
  958. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  959. }
  960. /**
  961. * @param {Chunk} chunk chunk
  962. * @returns {string} require chunk id code
  963. */
  964. const requireChunkId = chunk =>
  965. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)}${
  966. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  967. })`;
  968. return `Promise.all(${comment.trim()}[${chunks
  969. .map(requireChunkId)
  970. .join(", ")}])`;
  971. }
  972. return `Promise.resolve(${comment.trim()})`;
  973. }
  974. /**
  975. * @param {object} options options
  976. * @param {AsyncDependenciesBlock} options.block the async block
  977. * @param {ChunkGraph} options.chunkGraph the chunk graph
  978. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  979. * @param {string=} options.request request string used originally
  980. * @returns {string} expression
  981. */
  982. asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) {
  983. const dep = block.dependencies[0];
  984. const module = chunkGraph.moduleGraph.getModule(dep);
  985. const ensureChunk = this.blockPromise({
  986. block,
  987. message: "",
  988. chunkGraph,
  989. runtimeRequirements
  990. });
  991. const factory = this.returningFunction(
  992. this.moduleRaw({
  993. module,
  994. chunkGraph,
  995. request,
  996. runtimeRequirements
  997. })
  998. );
  999. return this.returningFunction(
  1000. ensureChunk.startsWith("Promise.resolve(")
  1001. ? `${factory}`
  1002. : `${ensureChunk}.then(${this.returningFunction(factory)})`
  1003. );
  1004. }
  1005. /**
  1006. * @param {object} options options
  1007. * @param {Dependency} options.dependency the dependency
  1008. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1009. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1010. * @param {string=} options.request request string used originally
  1011. * @returns {string} expression
  1012. */
  1013. syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) {
  1014. const module = chunkGraph.moduleGraph.getModule(dependency);
  1015. const factory = this.returningFunction(
  1016. this.moduleRaw({
  1017. module,
  1018. chunkGraph,
  1019. request,
  1020. runtimeRequirements
  1021. })
  1022. );
  1023. return this.returningFunction(factory);
  1024. }
  1025. /**
  1026. * @param {object} options options
  1027. * @param {string} options.exportsArgument the name of the exports object
  1028. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1029. * @returns {string} statement
  1030. */
  1031. defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) {
  1032. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  1033. runtimeRequirements.add(RuntimeGlobals.exports);
  1034. return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`;
  1035. }
  1036. }
  1037. module.exports = RuntimeTemplate;