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.

291 lines
8.0 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. /** @typedef {import("./Module")} Module */
  6. /** @typedef {import("./Chunk")} Chunk */
  7. /** @typedef {import("./ModuleTemplate")} ModuleTemplate */
  8. /** @typedef {import("webpack-sources").ConcatSource} ConcatSource */
  9. const { ConcatSource } = require("webpack-sources");
  10. const HotUpdateChunk = require("./HotUpdateChunk");
  11. const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
  12. const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
  13. const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
  14. const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g;
  15. const INDENT_MULTILINE_REGEX = /^\t/gm;
  16. const LINE_SEPARATOR_REGEX = /\r?\n/g;
  17. const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/;
  18. const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g;
  19. const COMMENT_END_REGEX = /\*\//g;
  20. const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g;
  21. const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
  22. /** @typedef {import("webpack-sources").Source} Source */
  23. /**
  24. * @typedef {Object} HasId
  25. * @property {number | string} id
  26. */
  27. /**
  28. * @typedef {function(Module, number): boolean} ModuleFilterPredicate
  29. */
  30. /**
  31. * @param {HasId} a first id object to be sorted
  32. * @param {HasId} b second id object to be sorted against
  33. * @returns {-1|0|1} the sort value
  34. */
  35. const stringifyIdSortPredicate = (a, b) => {
  36. const aId = a.id + "";
  37. const bId = b.id + "";
  38. if (aId < bId) return -1;
  39. if (aId > bId) return 1;
  40. return 0;
  41. };
  42. class Template {
  43. /**
  44. *
  45. * @param {Function} fn a runtime function (.runtime.js) "template"
  46. * @returns {string} the updated and normalized function string
  47. */
  48. static getFunctionContent(fn) {
  49. return fn
  50. .toString()
  51. .replace(FUNCTION_CONTENT_REGEX, "")
  52. .replace(INDENT_MULTILINE_REGEX, "")
  53. .replace(LINE_SEPARATOR_REGEX, "\n");
  54. }
  55. /**
  56. * @param {string} str the string converted to identifier
  57. * @returns {string} created identifier
  58. */
  59. static toIdentifier(str) {
  60. if (typeof str !== "string") return "";
  61. return str
  62. .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1")
  63. .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_");
  64. }
  65. /**
  66. *
  67. * @param {string} str string to be converted to commented in bundle code
  68. * @returns {string} returns a commented version of string
  69. */
  70. static toComment(str) {
  71. if (!str) return "";
  72. return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`;
  73. }
  74. /**
  75. *
  76. * @param {string} str string to be converted to "normal comment"
  77. * @returns {string} returns a commented version of string
  78. */
  79. static toNormalComment(str) {
  80. if (!str) return "";
  81. return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`;
  82. }
  83. /**
  84. * @param {string} str string path to be normalized
  85. * @returns {string} normalized bundle-safe path
  86. */
  87. static toPath(str) {
  88. if (typeof str !== "string") return "";
  89. return str
  90. .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-")
  91. .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
  92. }
  93. // map number to a single character a-z, A-Z or <_ + number> if number is too big
  94. /**
  95. *
  96. * @param {number} n number to convert to ident
  97. * @returns {string} returns single character ident
  98. */
  99. static numberToIdentifer(n) {
  100. // lower case
  101. if (n < DELTA_A_TO_Z) {
  102. return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
  103. }
  104. // upper case
  105. if (n < DELTA_A_TO_Z * 2) {
  106. return String.fromCharCode(
  107. START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z
  108. );
  109. }
  110. // use multiple letters
  111. return (
  112. Template.numberToIdentifer(n % (2 * DELTA_A_TO_Z)) +
  113. Template.numberToIdentifer(Math.floor(n / (2 * DELTA_A_TO_Z)))
  114. );
  115. }
  116. /**
  117. *
  118. * @param {string | string[]} s string to convert to identity
  119. * @returns {string} converted identity
  120. */
  121. static indent(s) {
  122. if (Array.isArray(s)) {
  123. return s.map(Template.indent).join("\n");
  124. } else {
  125. const str = s.trimRight();
  126. if (!str) return "";
  127. const ind = str[0] === "\n" ? "" : "\t";
  128. return ind + str.replace(/\n([^\n])/g, "\n\t$1");
  129. }
  130. }
  131. /**
  132. *
  133. * @param {string|string[]} s string to create prefix for
  134. * @param {string} prefix prefix to compose
  135. * @returns {string} returns new prefix string
  136. */
  137. static prefix(s, prefix) {
  138. const str = Template.asString(s).trim();
  139. if (!str) return "";
  140. const ind = str[0] === "\n" ? "" : prefix;
  141. return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
  142. }
  143. /**
  144. *
  145. * @param {string|string[]} str string or string collection
  146. * @returns {string} returns a single string from array
  147. */
  148. static asString(str) {
  149. if (Array.isArray(str)) {
  150. return str.join("\n");
  151. }
  152. return str;
  153. }
  154. /**
  155. * @typedef {Object} WithId
  156. * @property {string|number} id
  157. */
  158. /**
  159. * @param {WithId[]} modules a collection of modules to get array bounds for
  160. * @returns {[number, number] | false} returns the upper and lower array bounds
  161. * or false if not every module has a number based id
  162. */
  163. static getModulesArrayBounds(modules) {
  164. let maxId = -Infinity;
  165. let minId = Infinity;
  166. for (const module of modules) {
  167. if (typeof module.id !== "number") return false;
  168. if (maxId < module.id) maxId = /** @type {number} */ (module.id);
  169. if (minId > module.id) minId = /** @type {number} */ (module.id);
  170. }
  171. if (minId < 16 + ("" + minId).length) {
  172. // add minId x ',' instead of 'Array(minId).concat(…)'
  173. minId = 0;
  174. }
  175. const objectOverhead = modules
  176. .map(module => (module.id + "").length + 2)
  177. .reduce((a, b) => a + b, -1);
  178. const arrayOverhead =
  179. minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
  180. return arrayOverhead < objectOverhead ? [minId, maxId] : false;
  181. }
  182. /**
  183. * @param {Chunk} chunk chunk whose modules will be rendered
  184. * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render
  185. * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules
  186. * @param {TODO | TODO[]} dependencyTemplates templates needed for each module to render dependencies
  187. * @param {string=} prefix applying prefix strings
  188. * @returns {ConcatSource} rendered chunk modules in a Source object
  189. */
  190. static renderChunkModules(
  191. chunk,
  192. filterFn,
  193. moduleTemplate,
  194. dependencyTemplates,
  195. prefix = ""
  196. ) {
  197. const source = new ConcatSource();
  198. const modules = chunk.getModules().filter(filterFn);
  199. let removedModules;
  200. if (chunk instanceof HotUpdateChunk) {
  201. removedModules = chunk.removedModules;
  202. }
  203. if (
  204. modules.length === 0 &&
  205. (!removedModules || removedModules.length === 0)
  206. ) {
  207. source.add("[]");
  208. return source;
  209. }
  210. /** @type {{id: string|number, source: Source|string}[]} */
  211. const allModules = modules.map(module => {
  212. return {
  213. id: module.id,
  214. source: moduleTemplate.render(module, dependencyTemplates, {
  215. chunk
  216. })
  217. };
  218. });
  219. if (removedModules && removedModules.length > 0) {
  220. for (const id of removedModules) {
  221. allModules.push({
  222. id,
  223. source: "false"
  224. });
  225. }
  226. }
  227. const bounds = Template.getModulesArrayBounds(allModules);
  228. if (bounds) {
  229. // Render a spare array
  230. const minId = bounds[0];
  231. const maxId = bounds[1];
  232. if (minId !== 0) {
  233. source.add(`Array(${minId}).concat(`);
  234. }
  235. source.add("[\n");
  236. /** @type {Map<string|number, {id: string|number, source: Source|string}>} */
  237. const modules = new Map();
  238. for (const module of allModules) {
  239. modules.set(module.id, module);
  240. }
  241. for (let idx = minId; idx <= maxId; idx++) {
  242. const module = modules.get(idx);
  243. if (idx !== minId) {
  244. source.add(",\n");
  245. }
  246. source.add(`/* ${idx} */`);
  247. if (module) {
  248. source.add("\n");
  249. source.add(module.source);
  250. }
  251. }
  252. source.add("\n" + prefix + "]");
  253. if (minId !== 0) {
  254. source.add(")");
  255. }
  256. } else {
  257. // Render an object
  258. source.add("{\n");
  259. allModules.sort(stringifyIdSortPredicate).forEach((module, idx) => {
  260. if (idx !== 0) {
  261. source.add(",\n");
  262. }
  263. source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
  264. source.add(module.source);
  265. });
  266. source.add(`\n\n${prefix}}`);
  267. }
  268. return source;
  269. }
  270. }
  271. module.exports = Template;