提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

411 lines
13 KiB

  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource, PrefixSource } = require("webpack-sources");
  7. const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
  8. const RuntimeGlobals = require("./RuntimeGlobals");
  9. /** @typedef {import("webpack-sources").Source} Source */
  10. /** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
  11. /** @typedef {import("./Chunk")} Chunk */
  12. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  13. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  14. /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
  15. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  16. /** @typedef {import("./Compilation").PathData} PathData */
  17. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  18. /** @typedef {import("./Module")} Module */
  19. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  20. /** @typedef {import("./ModuleTemplate")} ModuleTemplate */
  21. /** @typedef {import("./RuntimeModule")} RuntimeModule */
  22. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  23. /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
  24. /** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
  25. /** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  26. const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
  27. const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
  28. const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
  29. const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $
  30. const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
  31. NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9
  32. const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g;
  33. const INDENT_MULTILINE_REGEX = /^\t/gm;
  34. const LINE_SEPARATOR_REGEX = /\r?\n/g;
  35. const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/;
  36. const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g;
  37. const COMMENT_END_REGEX = /\*\//g;
  38. const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g;
  39. const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
  40. /**
  41. * @typedef {object} RenderManifestOptions
  42. * @property {Chunk} chunk the chunk used to render
  43. * @property {string} hash
  44. * @property {string} fullHash
  45. * @property {OutputOptions} outputOptions
  46. * @property {CodeGenerationResults} codeGenerationResults
  47. * @property {{ javascript: ModuleTemplate }} moduleTemplates
  48. * @property {DependencyTemplates} dependencyTemplates
  49. * @property {RuntimeTemplate} runtimeTemplate
  50. * @property {ModuleGraph} moduleGraph
  51. * @property {ChunkGraph} chunkGraph
  52. */
  53. /** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */
  54. /**
  55. * @typedef {object} RenderManifestEntryTemplated
  56. * @property {() => Source} render
  57. * @property {TemplatePath} filenameTemplate
  58. * @property {PathData=} pathOptions
  59. * @property {AssetInfo=} info
  60. * @property {string} identifier
  61. * @property {string=} hash
  62. * @property {boolean=} auxiliary
  63. */
  64. /**
  65. * @typedef {object} RenderManifestEntryStatic
  66. * @property {() => Source} render
  67. * @property {string} filename
  68. * @property {AssetInfo} info
  69. * @property {string} identifier
  70. * @property {string=} hash
  71. * @property {boolean=} auxiliary
  72. */
  73. /**
  74. * @typedef {(module: Module) => boolean} ModuleFilterPredicate
  75. */
  76. class Template {
  77. /**
  78. * @template {EXPECTED_FUNCTION} T
  79. * @param {T} fn a runtime function (.runtime.js) "template"
  80. * @returns {string} the updated and normalized function string
  81. */
  82. static getFunctionContent(fn) {
  83. return fn
  84. .toString()
  85. .replace(FUNCTION_CONTENT_REGEX, "")
  86. .replace(INDENT_MULTILINE_REGEX, "")
  87. .replace(LINE_SEPARATOR_REGEX, "\n");
  88. }
  89. /**
  90. * @param {string} str the string converted to identifier
  91. * @returns {string} created identifier
  92. */
  93. static toIdentifier(str) {
  94. if (typeof str !== "string") return "";
  95. return str
  96. .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1")
  97. .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
  98. }
  99. /**
  100. * @param {string} str string to be converted to commented in bundle code
  101. * @returns {string} returns a commented version of string
  102. */
  103. static toComment(str) {
  104. if (!str) return "";
  105. return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`;
  106. }
  107. /**
  108. * @param {string} str string to be converted to "normal comment"
  109. * @returns {string} returns a commented version of string
  110. */
  111. static toNormalComment(str) {
  112. if (!str) return "";
  113. return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`;
  114. }
  115. /**
  116. * @param {string} str string path to be normalized
  117. * @returns {string} normalized bundle-safe path
  118. */
  119. static toPath(str) {
  120. if (typeof str !== "string") return "";
  121. return str
  122. .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-")
  123. .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
  124. }
  125. // map number to a single character a-z, A-Z or multiple characters if number is too big
  126. /**
  127. * @param {number} n number to convert to ident
  128. * @returns {string} returns single character ident
  129. */
  130. static numberToIdentifier(n) {
  131. if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) {
  132. // use multiple letters
  133. return (
  134. Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) +
  135. Template.numberToIdentifierContinuation(
  136. Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS)
  137. )
  138. );
  139. }
  140. // lower case
  141. if (n < DELTA_A_TO_Z) {
  142. return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
  143. }
  144. n -= DELTA_A_TO_Z;
  145. // upper case
  146. if (n < DELTA_A_TO_Z) {
  147. return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
  148. }
  149. if (n === DELTA_A_TO_Z) return "_";
  150. return "$";
  151. }
  152. /**
  153. * @param {number} n number to convert to ident
  154. * @returns {string} returns single character ident
  155. */
  156. static numberToIdentifierContinuation(n) {
  157. if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) {
  158. // use multiple letters
  159. return (
  160. Template.numberToIdentifierContinuation(
  161. n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS
  162. ) +
  163. Template.numberToIdentifierContinuation(
  164. Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS)
  165. )
  166. );
  167. }
  168. // lower case
  169. if (n < DELTA_A_TO_Z) {
  170. return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
  171. }
  172. n -= DELTA_A_TO_Z;
  173. // upper case
  174. if (n < DELTA_A_TO_Z) {
  175. return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
  176. }
  177. n -= DELTA_A_TO_Z;
  178. // numbers
  179. if (n < 10) {
  180. return `${n}`;
  181. }
  182. if (n === 10) return "_";
  183. return "$";
  184. }
  185. /**
  186. * @param {string | string[]} s string to convert to identity
  187. * @returns {string} converted identity
  188. */
  189. static indent(s) {
  190. if (Array.isArray(s)) {
  191. return s.map(Template.indent).join("\n");
  192. }
  193. const str = s.trimEnd();
  194. if (!str) return "";
  195. const ind = str[0] === "\n" ? "" : "\t";
  196. return ind + str.replace(/\n([^\n])/g, "\n\t$1");
  197. }
  198. /**
  199. * @param {string | string[]} s string to create prefix for
  200. * @param {string} prefix prefix to compose
  201. * @returns {string} returns new prefix string
  202. */
  203. static prefix(s, prefix) {
  204. const str = Template.asString(s).trim();
  205. if (!str) return "";
  206. const ind = str[0] === "\n" ? "" : prefix;
  207. return ind + str.replace(/\n([^\n])/g, `\n${prefix}$1`);
  208. }
  209. /**
  210. * @param {string | string[]} str string or string collection
  211. * @returns {string} returns a single string from array
  212. */
  213. static asString(str) {
  214. if (Array.isArray(str)) {
  215. return str.join("\n");
  216. }
  217. return str;
  218. }
  219. /**
  220. * @typedef {object} WithId
  221. * @property {string | number} id
  222. */
  223. /**
  224. * @param {WithId[]} modules a collection of modules to get array bounds for
  225. * @returns {[number, number] | false} returns the upper and lower array bounds
  226. * or false if not every module has a number based id
  227. */
  228. static getModulesArrayBounds(modules) {
  229. let maxId = -Infinity;
  230. let minId = Infinity;
  231. for (const module of modules) {
  232. const moduleId = module.id;
  233. if (typeof moduleId !== "number") return false;
  234. if (maxId < moduleId) maxId = moduleId;
  235. if (minId > moduleId) minId = moduleId;
  236. }
  237. if (minId < 16 + String(minId).length) {
  238. // add minId x ',' instead of 'Array(minId).concat(…)'
  239. minId = 0;
  240. }
  241. // start with -1 because the first module needs no comma
  242. let objectOverhead = -1;
  243. for (const module of modules) {
  244. // module id + colon + comma
  245. objectOverhead += `${module.id}`.length + 2;
  246. }
  247. // number of commas, or when starting non-zero the length of Array(minId).concat()
  248. const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId;
  249. return arrayOverhead < objectOverhead ? [minId, maxId] : false;
  250. }
  251. /**
  252. * @param {ChunkRenderContext} renderContext render context
  253. * @param {Module[]} modules modules to render (should be ordered by identifier)
  254. * @param {(module: Module) => Source | null} renderModule function to render a module
  255. * @param {string=} prefix applying prefix strings
  256. * @returns {Source | null} rendered chunk modules in a Source object or null if no modules
  257. */
  258. static renderChunkModules(renderContext, modules, renderModule, prefix = "") {
  259. const { chunkGraph } = renderContext;
  260. const source = new ConcatSource();
  261. if (modules.length === 0) {
  262. return null;
  263. }
  264. /** @type {{ id: ModuleId, source: Source | "false" }[]} */
  265. const allModules = modules.map((module) => ({
  266. id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
  267. source: renderModule(module) || "false"
  268. }));
  269. const bounds = Template.getModulesArrayBounds(allModules);
  270. if (bounds) {
  271. // Render a spare array
  272. const minId = bounds[0];
  273. const maxId = bounds[1];
  274. if (minId !== 0) {
  275. source.add(`Array(${minId}).concat(`);
  276. }
  277. source.add("[\n");
  278. /** @type {Map<ModuleId, { id: ModuleId, source: Source | "false" }>} */
  279. const modules = new Map();
  280. for (const module of allModules) {
  281. modules.set(module.id, module);
  282. }
  283. for (let idx = minId; idx <= maxId; idx++) {
  284. const module = modules.get(idx);
  285. if (idx !== minId) {
  286. source.add(",\n");
  287. }
  288. source.add(`/* ${idx} */`);
  289. if (module) {
  290. source.add("\n");
  291. source.add(module.source);
  292. }
  293. }
  294. source.add(`\n${prefix}]`);
  295. if (minId !== 0) {
  296. source.add(")");
  297. }
  298. } else {
  299. // Render an object
  300. source.add("{\n");
  301. for (let i = 0; i < allModules.length; i++) {
  302. const module = allModules[i];
  303. if (i !== 0) {
  304. source.add(",\n");
  305. }
  306. source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
  307. source.add(module.source);
  308. }
  309. source.add(`\n\n${prefix}}`);
  310. }
  311. return source;
  312. }
  313. /**
  314. * @param {RuntimeModule[]} runtimeModules array of runtime modules in order
  315. * @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context
  316. * @returns {Source} rendered runtime modules in a Source object
  317. */
  318. static renderRuntimeModules(runtimeModules, renderContext) {
  319. const source = new ConcatSource();
  320. for (const module of runtimeModules) {
  321. const codeGenerationResults = renderContext.codeGenerationResults;
  322. let runtimeSource;
  323. if (codeGenerationResults) {
  324. runtimeSource = codeGenerationResults.getSource(
  325. module,
  326. renderContext.chunk.runtime,
  327. WEBPACK_MODULE_TYPE_RUNTIME
  328. );
  329. } else {
  330. const codeGenResult = module.codeGeneration({
  331. chunkGraph: renderContext.chunkGraph,
  332. dependencyTemplates: renderContext.dependencyTemplates,
  333. moduleGraph: renderContext.moduleGraph,
  334. runtimeTemplate: renderContext.runtimeTemplate,
  335. runtime: renderContext.chunk.runtime,
  336. codeGenerationResults
  337. });
  338. if (!codeGenResult) continue;
  339. runtimeSource = codeGenResult.sources.get("runtime");
  340. }
  341. if (runtimeSource) {
  342. source.add(`${Template.toNormalComment(module.identifier())}\n`);
  343. if (!module.shouldIsolate()) {
  344. source.add(runtimeSource);
  345. source.add("\n\n");
  346. } else if (renderContext.runtimeTemplate.supportsArrowFunction()) {
  347. source.add("(() => {\n");
  348. source.add(new PrefixSource("\t", runtimeSource));
  349. source.add("\n})();\n\n");
  350. } else {
  351. source.add("!function() {\n");
  352. source.add(new PrefixSource("\t", runtimeSource));
  353. source.add("\n}();\n\n");
  354. }
  355. }
  356. }
  357. return source;
  358. }
  359. /**
  360. * @param {RuntimeModule[]} runtimeModules array of runtime modules in order
  361. * @param {RenderContext} renderContext render context
  362. * @returns {Source} rendered chunk runtime modules in a Source object
  363. */
  364. static renderChunkRuntimeModules(runtimeModules, renderContext) {
  365. return new PrefixSource(
  366. "/******/ ",
  367. new ConcatSource(
  368. `function(${RuntimeGlobals.require}) { // webpackRuntimeModules\n`,
  369. this.renderRuntimeModules(runtimeModules, renderContext),
  370. "}\n"
  371. )
  372. );
  373. }
  374. }
  375. module.exports = Template;
  376. module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
  377. NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS;
  378. module.exports.NUMBER_OF_IDENTIFIER_START_CHARS =
  379. NUMBER_OF_IDENTIFIER_START_CHARS;