Template.js 13 KB

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