VirtualUrlPlugin.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Natsu @xiaoxiaojx
  4. */
  5. "use strict";
  6. const { NormalModule } = require("..");
  7. const ModuleNotFoundError = require("../ModuleNotFoundError");
  8. const { parseResourceWithoutFragment } = require("../util/identifier");
  9. /** @typedef {import("../Compiler")} Compiler */
  10. /** @typedef {import("../NormalModule")} NormalModule */
  11. /**
  12. * @template T
  13. * @typedef {import("../../declarations/LoaderContext").LoaderContext<T>} LoaderContext
  14. */
  15. const PLUGIN_NAME = "VirtualUrlPlugin";
  16. const DEFAULT_SCHEME = "virtual";
  17. /** @typedef {(loaderContext: LoaderContext<EXPECTED_ANY>) => Promise<string | Buffer> | string | Buffer} SourceFn */
  18. /** @typedef {() => string} VersionFn */
  19. /**
  20. * @typedef {object} VirtualModuleConfig
  21. * @property {string=} type the module type
  22. * @property {SourceFn} source the source function
  23. * @property {VersionFn | true | string=} version optional version function or value
  24. */
  25. /**
  26. * @typedef {string | SourceFn | VirtualModuleConfig} VirtualModuleInput
  27. */
  28. /** @typedef {{ [key: string]: VirtualModuleInput }} VirtualModules */
  29. /**
  30. * Normalizes a virtual module definition into a standard format
  31. * @param {VirtualModuleInput} virtualConfig The virtual module to normalize
  32. * @returns {VirtualModuleConfig} The normalized virtual module
  33. */
  34. function normalizeModule(virtualConfig) {
  35. if (typeof virtualConfig === "string") {
  36. return {
  37. type: "",
  38. source() {
  39. return virtualConfig;
  40. }
  41. };
  42. } else if (typeof virtualConfig === "function") {
  43. return {
  44. type: "",
  45. source: virtualConfig
  46. };
  47. }
  48. return virtualConfig;
  49. }
  50. /** @typedef {{ [key: string]: VirtualModuleConfig }} NormalizedModules */
  51. /**
  52. * Normalizes all virtual modules with the given scheme
  53. * @param {VirtualModules} virtualConfigs The virtual modules to normalize
  54. * @param {string} scheme The URL scheme to use
  55. * @returns {NormalizedModules} The normalized virtual modules
  56. */
  57. function normalizeModules(virtualConfigs, scheme) {
  58. return Object.keys(virtualConfigs).reduce((pre, id) => {
  59. pre[toVid(id, scheme)] = normalizeModule(virtualConfigs[id]);
  60. return pre;
  61. }, /** @type {NormalizedModules} */ ({}));
  62. }
  63. /**
  64. * Converts a module id and scheme to a virtual module id
  65. * @param {string} id The module id
  66. * @param {string} scheme The URL scheme
  67. * @returns {string} The virtual module id
  68. */
  69. function toVid(id, scheme) {
  70. return `${scheme}:${id}`;
  71. }
  72. const VALUE_DEP_VERSION = `webpack/${PLUGIN_NAME}/version`;
  73. /**
  74. * Converts a module id and scheme to a cache key
  75. * @param {string} id The module id
  76. * @param {string} scheme The URL scheme
  77. * @returns {string} The cache key
  78. */
  79. function toCacheKey(id, scheme) {
  80. return `${VALUE_DEP_VERSION}/${toVid(id, scheme)}`;
  81. }
  82. /**
  83. * @typedef {object} VirtualUrlPluginOptions
  84. * @property {VirtualModules} modules - The virtual modules
  85. * @property {string=} scheme - The URL scheme to use
  86. */
  87. class VirtualUrlPlugin {
  88. /**
  89. * @param {VirtualModules} modules The virtual modules
  90. * @param {string=} scheme The URL scheme to use
  91. */
  92. constructor(modules, scheme) {
  93. /** @type {string} */
  94. this.scheme = scheme || DEFAULT_SCHEME;
  95. /** @type {NormalizedModules} */
  96. this.modules = normalizeModules(modules, this.scheme);
  97. }
  98. /**
  99. * Apply the plugin
  100. * @param {Compiler} compiler the compiler instance
  101. * @returns {void}
  102. */
  103. apply(compiler) {
  104. const scheme = this.scheme;
  105. const cachedParseResourceWithoutFragment =
  106. parseResourceWithoutFragment.bindCache(compiler.root);
  107. compiler.hooks.compilation.tap(
  108. PLUGIN_NAME,
  109. (compilation, { normalModuleFactory }) => {
  110. compilation.hooks.assetPath.tap(
  111. { name: PLUGIN_NAME, before: "TemplatedPathPlugin" },
  112. (path, data) => {
  113. if (data.filename && this.modules[data.filename]) {
  114. /**
  115. * @param {string} str path
  116. * @returns {string} safe path
  117. */
  118. const toSafePath = (str) =>
  119. `__${str
  120. .replace(/:/g, "__")
  121. .replace(/^[^a-z0-9]+|[^a-z0-9]+$/gi, "")
  122. .replace(/[^a-z0-9._-]+/gi, "_")}`;
  123. // filename: virtual:logo.svg -> __virtual__logo.svg
  124. data.filename = toSafePath(data.filename);
  125. }
  126. return path;
  127. }
  128. );
  129. normalModuleFactory.hooks.resolveForScheme
  130. .for(scheme)
  131. .tap(PLUGIN_NAME, (resourceData) => {
  132. const virtualConfig = this.findVirtualModuleConfigById(
  133. resourceData.resource
  134. );
  135. const url = cachedParseResourceWithoutFragment(
  136. resourceData.resource
  137. );
  138. const path = url.path;
  139. const type = virtualConfig.type;
  140. resourceData.path = path + type;
  141. resourceData.resource = path;
  142. resourceData.context = compiler.context;
  143. if (virtualConfig.version) {
  144. const cacheKey = toCacheKey(resourceData.resource, scheme);
  145. const cacheVersion = this.getCacheVersion(virtualConfig.version);
  146. compilation.valueCacheVersions.set(
  147. cacheKey,
  148. /** @type {string} */ (cacheVersion)
  149. );
  150. }
  151. return true;
  152. });
  153. const hooks = NormalModule.getCompilationHooks(compilation);
  154. hooks.readResource
  155. .for(scheme)
  156. .tapAsync(PLUGIN_NAME, async (loaderContext, callback) => {
  157. const { resourcePath } = loaderContext;
  158. const module = /** @type {NormalModule} */ (loaderContext._module);
  159. const cacheKey = toCacheKey(resourcePath, scheme);
  160. const addVersionValueDependency = () => {
  161. if (!module || !module.buildInfo) return;
  162. const buildInfo = module.buildInfo;
  163. if (!buildInfo.valueDependencies) {
  164. buildInfo.valueDependencies = new Map();
  165. }
  166. const cacheVersion = compilation.valueCacheVersions.get(cacheKey);
  167. if (compilation.valueCacheVersions.has(cacheKey)) {
  168. buildInfo.valueDependencies.set(
  169. cacheKey,
  170. /** @type {string} */ (cacheVersion)
  171. );
  172. }
  173. };
  174. try {
  175. const virtualConfig =
  176. this.findVirtualModuleConfigById(resourcePath);
  177. const content = await virtualConfig.source(loaderContext);
  178. addVersionValueDependency();
  179. callback(null, content);
  180. } catch (err) {
  181. callback(/** @type {Error} */ (err));
  182. }
  183. });
  184. }
  185. );
  186. }
  187. /**
  188. * @param {string} id The module id
  189. * @returns {VirtualModuleConfig} The virtual module config
  190. */
  191. findVirtualModuleConfigById(id) {
  192. const config = this.modules[id];
  193. if (!config) {
  194. throw new ModuleNotFoundError(
  195. null,
  196. new Error(`Can't resolve virtual module ${id}`),
  197. {
  198. name: `virtual module ${id}`
  199. }
  200. );
  201. }
  202. return config;
  203. }
  204. /**
  205. * Get the cache version for a given version value
  206. * @param {VersionFn | true | string} version The version value or function
  207. * @returns {string | undefined} The cache version
  208. */
  209. getCacheVersion(version) {
  210. return version === true
  211. ? undefined
  212. : (typeof version === "function" ? version() : version) || "unset";
  213. }
  214. }
  215. VirtualUrlPlugin.DEFAULT_SCHEME = DEFAULT_SCHEME;
  216. module.exports = VirtualUrlPlugin;