RuntimeTemplate.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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. * @template GenerateContext
  799. * @param {object} options options
  800. * @param {ModuleGraph} options.moduleGraph the module graph
  801. * @param {Module} options.module the module
  802. * @param {string} options.request the request
  803. * @param {string | string[]} options.exportName the export name
  804. * @param {Module} options.originModule the origin module
  805. * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
  806. * @param {boolean} options.isCall true, if expression will be called
  807. * @param {boolean | null} options.callContext when false, call context will not be preserved
  808. * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated
  809. * @param {string} options.importVar the identifier name of the import variable
  810. * @param {InitFragment<GenerateContext>[]} options.initFragments init fragments will be added here
  811. * @param {RuntimeSpec} options.runtime runtime for which this code will be generated
  812. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  813. * @returns {string} expression
  814. */
  815. exportFromImport({
  816. moduleGraph,
  817. module,
  818. request,
  819. exportName,
  820. originModule,
  821. asiSafe,
  822. isCall,
  823. callContext,
  824. defaultInterop,
  825. importVar,
  826. initFragments,
  827. runtime,
  828. runtimeRequirements
  829. }) {
  830. if (!module) {
  831. return this.missingModule({
  832. request
  833. });
  834. }
  835. if (!Array.isArray(exportName)) {
  836. exportName = exportName ? [exportName] : [];
  837. }
  838. const exportsType = module.getExportsType(
  839. moduleGraph,
  840. /** @type {BuildMeta} */
  841. (originModule.buildMeta).strictHarmonyModule
  842. );
  843. if (defaultInterop) {
  844. if (exportName.length > 0 && exportName[0] === "default") {
  845. switch (exportsType) {
  846. case "dynamic":
  847. if (isCall) {
  848. return `${importVar}_default()${propertyAccess(exportName, 1)}`;
  849. }
  850. return asiSafe
  851. ? `(${importVar}_default()${propertyAccess(exportName, 1)})`
  852. : asiSafe === false
  853. ? `;(${importVar}_default()${propertyAccess(exportName, 1)})`
  854. : `${importVar}_default.a${propertyAccess(exportName, 1)}`;
  855. case "default-only":
  856. case "default-with-named":
  857. exportName = exportName.slice(1);
  858. break;
  859. }
  860. } else if (exportName.length > 0) {
  861. if (exportsType === "default-only") {
  862. return `/* non-default import from non-esm module */undefined${propertyAccess(
  863. exportName,
  864. 1
  865. )}`;
  866. } else if (
  867. exportsType !== "namespace" &&
  868. exportName[0] === "__esModule"
  869. ) {
  870. return "/* __esModule */true";
  871. }
  872. } else if (
  873. exportsType === "default-only" ||
  874. exportsType === "default-with-named"
  875. ) {
  876. runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
  877. initFragments.push(
  878. new InitFragment(
  879. `var ${importVar}_namespace_cache;\n`,
  880. InitFragment.STAGE_CONSTANTS,
  881. -1,
  882. `${importVar}_namespace_cache`
  883. )
  884. );
  885. return `/*#__PURE__*/ ${
  886. asiSafe ? "" : asiSafe === false ? ";" : "Object"
  887. }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${
  888. RuntimeGlobals.createFakeNamespaceObject
  889. }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`;
  890. }
  891. }
  892. if (exportName.length > 0) {
  893. const exportsInfo = moduleGraph.getExportsInfo(module);
  894. const used = exportsInfo.getUsedName(exportName, runtime);
  895. if (!used) {
  896. const comment = Template.toNormalComment(
  897. `unused export ${propertyAccess(exportName)}`
  898. );
  899. return `${comment} undefined`;
  900. }
  901. const comment = equals(used, exportName)
  902. ? ""
  903. : `${Template.toNormalComment(propertyAccess(exportName))} `;
  904. const access = `${importVar}${comment}${propertyAccess(used)}`;
  905. if (isCall && callContext === false) {
  906. return asiSafe
  907. ? `(0,${access})`
  908. : asiSafe === false
  909. ? `;(0,${access})`
  910. : `/*#__PURE__*/Object(${access})`;
  911. }
  912. return access;
  913. }
  914. return importVar;
  915. }
  916. /**
  917. * @param {object} options options
  918. * @param {AsyncDependenciesBlock | undefined} options.block the async block
  919. * @param {string} options.message the message
  920. * @param {ChunkGraph} options.chunkGraph the chunk graph
  921. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  922. * @returns {string} expression
  923. */
  924. blockPromise({ block, message, chunkGraph, runtimeRequirements }) {
  925. if (!block) {
  926. const comment = this.comment({
  927. message
  928. });
  929. return `Promise.resolve(${comment.trim()})`;
  930. }
  931. const chunkGroup = chunkGraph.getBlockChunkGroup(block);
  932. if (!chunkGroup || chunkGroup.chunks.length === 0) {
  933. const comment = this.comment({
  934. message
  935. });
  936. return `Promise.resolve(${comment.trim()})`;
  937. }
  938. const chunks = chunkGroup.chunks.filter(
  939. chunk => !chunk.hasRuntime() && chunk.id !== null
  940. );
  941. const comment = this.comment({
  942. message,
  943. chunkName: block.chunkName
  944. });
  945. if (chunks.length === 1) {
  946. const chunkId = JSON.stringify(chunks[0].id);
  947. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  948. const fetchPriority = chunkGroup.options.fetchPriority;
  949. if (fetchPriority) {
  950. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  951. }
  952. return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId}${
  953. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  954. })`;
  955. } else if (chunks.length > 0) {
  956. runtimeRequirements.add(RuntimeGlobals.ensureChunk);
  957. const fetchPriority = chunkGroup.options.fetchPriority;
  958. if (fetchPriority) {
  959. runtimeRequirements.add(RuntimeGlobals.hasFetchPriority);
  960. }
  961. /**
  962. * @param {Chunk} chunk chunk
  963. * @returns {string} require chunk id code
  964. */
  965. const requireChunkId = chunk =>
  966. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)}${
  967. fetchPriority ? `, ${JSON.stringify(fetchPriority)}` : ""
  968. })`;
  969. return `Promise.all(${comment.trim()}[${chunks
  970. .map(requireChunkId)
  971. .join(", ")}])`;
  972. }
  973. return `Promise.resolve(${comment.trim()})`;
  974. }
  975. /**
  976. * @param {object} options options
  977. * @param {AsyncDependenciesBlock} options.block the async block
  978. * @param {ChunkGraph} options.chunkGraph the chunk graph
  979. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  980. * @param {string=} options.request request string used originally
  981. * @returns {string} expression
  982. */
  983. asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) {
  984. const dep = block.dependencies[0];
  985. const module = chunkGraph.moduleGraph.getModule(dep);
  986. const ensureChunk = this.blockPromise({
  987. block,
  988. message: "",
  989. chunkGraph,
  990. runtimeRequirements
  991. });
  992. const factory = this.returningFunction(
  993. this.moduleRaw({
  994. module,
  995. chunkGraph,
  996. request,
  997. runtimeRequirements
  998. })
  999. );
  1000. return this.returningFunction(
  1001. ensureChunk.startsWith("Promise.resolve(")
  1002. ? `${factory}`
  1003. : `${ensureChunk}.then(${this.returningFunction(factory)})`
  1004. );
  1005. }
  1006. /**
  1007. * @param {object} options options
  1008. * @param {Dependency} options.dependency the dependency
  1009. * @param {ChunkGraph} options.chunkGraph the chunk graph
  1010. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1011. * @param {string=} options.request request string used originally
  1012. * @returns {string} expression
  1013. */
  1014. syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) {
  1015. const module = chunkGraph.moduleGraph.getModule(dependency);
  1016. const factory = this.returningFunction(
  1017. this.moduleRaw({
  1018. module,
  1019. chunkGraph,
  1020. request,
  1021. runtimeRequirements
  1022. })
  1023. );
  1024. return this.returningFunction(factory);
  1025. }
  1026. /**
  1027. * @param {object} options options
  1028. * @param {string} options.exportsArgument the name of the exports object
  1029. * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
  1030. * @returns {string} statement
  1031. */
  1032. defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) {
  1033. runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject);
  1034. runtimeRequirements.add(RuntimeGlobals.exports);
  1035. return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`;
  1036. }
  1037. }
  1038. module.exports = RuntimeTemplate;