SourceMapDevToolPlugin.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("neo-async");
  7. const { ConcatSource, RawSource } = require("webpack-sources");
  8. const Compilation = require("./Compilation");
  9. const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
  10. const ProgressPlugin = require("./ProgressPlugin");
  11. const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
  12. const createSchemaValidation = require("./util/create-schema-validation");
  13. const createHash = require("./util/createHash");
  14. const { dirname, relative } = require("./util/fs");
  15. const generateDebugId = require("./util/generateDebugId");
  16. const { makePathsAbsolute } = require("./util/identifier");
  17. /** @typedef {import("webpack-sources").MapOptions} MapOptions */
  18. /** @typedef {import("webpack-sources").Source} Source */
  19. /** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
  20. /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
  21. /** @typedef {import("./Cache").Etag} Etag */
  22. /** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */
  23. /** @typedef {import("./Chunk")} Chunk */
  24. /** @typedef {import("./Compilation").Asset} Asset */
  25. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  26. /** @typedef {import("./Compiler")} Compiler */
  27. /** @typedef {import("./Module")} Module */
  28. /** @typedef {import("./NormalModule").RawSourceMap} RawSourceMap */
  29. /** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
  30. /** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
  31. const validate = createSchemaValidation(
  32. require("../schemas/plugins/SourceMapDevToolPlugin.check"),
  33. () => require("../schemas/plugins/SourceMapDevToolPlugin.json"),
  34. {
  35. name: "SourceMap DevTool Plugin",
  36. baseDataPath: "options"
  37. }
  38. );
  39. /**
  40. * @typedef {object} SourceMapTask
  41. * @property {Source} asset
  42. * @property {AssetInfo} assetInfo
  43. * @property {(string | Module)[]} modules
  44. * @property {string} source
  45. * @property {string} file
  46. * @property {RawSourceMap} sourceMap
  47. * @property {ItemCacheFacade} cacheItem cache item
  48. */
  49. const METACHARACTERS_REGEXP = /[-[\]\\/{}()*+?.^$|]/g;
  50. const CONTENT_HASH_DETECT_REGEXP = /\[contenthash(:\w+)?\]/;
  51. const CSS_AND_JS_MODULE_EXTENSIONS_REGEXP = /\.((c|m)?js|css)($|\?)/i;
  52. const CSS_EXTENSION_DETECT_REGEXP = /\.css($|\?)/i;
  53. const MAP_URL_COMMENT_REGEXP = /\[map\]/g;
  54. const URL_COMMENT_REGEXP = /\[url\]/g;
  55. const URL_FORMATTING_REGEXP = /^\n\/\/(.*)$/;
  56. /**
  57. * Reset's .lastIndex of stateful Regular Expressions
  58. * For when `test` or `exec` is called on them
  59. * @param {RegExp} regexp Stateful Regular Expression to be reset
  60. * @returns {void}
  61. */
  62. const resetRegexpState = regexp => {
  63. regexp.lastIndex = -1;
  64. };
  65. /**
  66. * Escapes regular expression metacharacters
  67. * @param {string} str String to quote
  68. * @returns {string} Escaped string
  69. */
  70. const quoteMeta = str => str.replace(METACHARACTERS_REGEXP, "\\$&");
  71. /**
  72. * Creating {@link SourceMapTask} for given file
  73. * @param {string} file current compiled file
  74. * @param {Source} asset the asset
  75. * @param {AssetInfo} assetInfo the asset info
  76. * @param {MapOptions} options source map options
  77. * @param {Compilation} compilation compilation instance
  78. * @param {ItemCacheFacade} cacheItem cache item
  79. * @returns {SourceMapTask | undefined} created task instance or `undefined`
  80. */
  81. const getTaskForFile = (
  82. file,
  83. asset,
  84. assetInfo,
  85. options,
  86. compilation,
  87. cacheItem
  88. ) => {
  89. let source;
  90. /** @type {RawSourceMap} */
  91. let sourceMap;
  92. /**
  93. * Check if asset can build source map
  94. */
  95. if (asset.sourceAndMap) {
  96. const sourceAndMap = asset.sourceAndMap(options);
  97. sourceMap = /** @type {RawSourceMap} */ (sourceAndMap.map);
  98. source = sourceAndMap.source;
  99. } else {
  100. sourceMap = /** @type {RawSourceMap} */ (asset.map(options));
  101. source = asset.source();
  102. }
  103. if (!sourceMap || typeof source !== "string") return;
  104. const context = /** @type {string} */ (compilation.options.context);
  105. const root = compilation.compiler.root;
  106. const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root);
  107. const modules = sourceMap.sources.map(source => {
  108. if (!source.startsWith("webpack://")) return source;
  109. source = cachedAbsolutify(source.slice(10));
  110. const module = compilation.findModule(source);
  111. return module || source;
  112. });
  113. return {
  114. file,
  115. asset,
  116. source,
  117. assetInfo,
  118. sourceMap,
  119. modules,
  120. cacheItem
  121. };
  122. };
  123. const PLUGIN_NAME = "SourceMapDevToolPlugin";
  124. class SourceMapDevToolPlugin {
  125. /**
  126. * @param {SourceMapDevToolPluginOptions=} options options object
  127. * @throws {Error} throws error, if got more than 1 arguments
  128. */
  129. constructor(options = {}) {
  130. validate(options);
  131. this.sourceMapFilename = /** @type {string | false} */ (options.filename);
  132. /** @type {false | TemplatePath}} */
  133. this.sourceMappingURLComment =
  134. options.append === false
  135. ? false
  136. : // eslint-disable-next-line no-useless-concat
  137. options.append || "\n//# source" + "MappingURL=[url]";
  138. this.moduleFilenameTemplate =
  139. options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]";
  140. this.fallbackModuleFilenameTemplate =
  141. options.fallbackModuleFilenameTemplate ||
  142. "webpack://[namespace]/[resourcePath]?[hash]";
  143. this.namespace = options.namespace || "";
  144. this.options = options;
  145. }
  146. /**
  147. * Apply the plugin
  148. * @param {Compiler} compiler compiler instance
  149. * @returns {void}
  150. */
  151. apply(compiler) {
  152. const outputFs = /** @type {OutputFileSystem} */ (
  153. compiler.outputFileSystem
  154. );
  155. const sourceMapFilename = this.sourceMapFilename;
  156. const sourceMappingURLComment = this.sourceMappingURLComment;
  157. const moduleFilenameTemplate = this.moduleFilenameTemplate;
  158. const namespace = this.namespace;
  159. const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
  160. const requestShortener = compiler.requestShortener;
  161. const options = this.options;
  162. options.test = options.test || CSS_AND_JS_MODULE_EXTENSIONS_REGEXP;
  163. const matchObject = ModuleFilenameHelpers.matchObject.bind(
  164. undefined,
  165. options
  166. );
  167. compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
  168. new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
  169. compilation.hooks.processAssets.tapAsync(
  170. {
  171. name: PLUGIN_NAME,
  172. stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
  173. additionalAssets: true
  174. },
  175. (assets, callback) => {
  176. const chunkGraph = compilation.chunkGraph;
  177. const cache = compilation.getCache(PLUGIN_NAME);
  178. /** @type {Map<string | Module, string>} */
  179. const moduleToSourceNameMapping = new Map();
  180. const reportProgress =
  181. ProgressPlugin.getReporter(compilation.compiler) || (() => {});
  182. /** @type {Map<string, Chunk>} */
  183. const fileToChunk = new Map();
  184. for (const chunk of compilation.chunks) {
  185. for (const file of chunk.files) {
  186. fileToChunk.set(file, chunk);
  187. }
  188. for (const file of chunk.auxiliaryFiles) {
  189. fileToChunk.set(file, chunk);
  190. }
  191. }
  192. /** @type {string[]} */
  193. const files = [];
  194. for (const file of Object.keys(assets)) {
  195. if (matchObject(file)) {
  196. files.push(file);
  197. }
  198. }
  199. reportProgress(0);
  200. /** @type {SourceMapTask[]} */
  201. const tasks = [];
  202. let fileIndex = 0;
  203. asyncLib.each(
  204. files,
  205. (file, callback) => {
  206. const asset =
  207. /** @type {Readonly<Asset>} */
  208. (compilation.getAsset(file));
  209. if (asset.info.related && asset.info.related.sourceMap) {
  210. fileIndex++;
  211. return callback();
  212. }
  213. const chunk = fileToChunk.get(file);
  214. const sourceMapNamespace = compilation.getPath(this.namespace, {
  215. chunk
  216. });
  217. const cacheItem = cache.getItemCache(
  218. file,
  219. cache.mergeEtags(
  220. cache.getLazyHashedEtag(asset.source),
  221. sourceMapNamespace
  222. )
  223. );
  224. cacheItem.get((err, cacheEntry) => {
  225. if (err) {
  226. return callback(err);
  227. }
  228. /**
  229. * If presented in cache, reassigns assets. Cache assets already have source maps.
  230. */
  231. if (cacheEntry) {
  232. const { assets, assetsInfo } = cacheEntry;
  233. for (const cachedFile of Object.keys(assets)) {
  234. if (cachedFile === file) {
  235. compilation.updateAsset(
  236. cachedFile,
  237. assets[cachedFile],
  238. assetsInfo[cachedFile]
  239. );
  240. } else {
  241. compilation.emitAsset(
  242. cachedFile,
  243. assets[cachedFile],
  244. assetsInfo[cachedFile]
  245. );
  246. }
  247. /**
  248. * Add file to chunk, if not presented there
  249. */
  250. if (cachedFile !== file && chunk !== undefined) {
  251. chunk.auxiliaryFiles.add(cachedFile);
  252. }
  253. }
  254. reportProgress(
  255. (0.5 * ++fileIndex) / files.length,
  256. file,
  257. "restored cached SourceMap"
  258. );
  259. return callback();
  260. }
  261. reportProgress(
  262. (0.5 * fileIndex) / files.length,
  263. file,
  264. "generate SourceMap"
  265. );
  266. /** @type {SourceMapTask | undefined} */
  267. const task = getTaskForFile(
  268. file,
  269. asset.source,
  270. asset.info,
  271. {
  272. module: options.module,
  273. columns: options.columns
  274. },
  275. compilation,
  276. cacheItem
  277. );
  278. if (task) {
  279. const modules = task.modules;
  280. for (let idx = 0; idx < modules.length; idx++) {
  281. const module = modules[idx];
  282. if (
  283. typeof module === "string" &&
  284. /^(data|https?):/.test(module)
  285. ) {
  286. moduleToSourceNameMapping.set(module, module);
  287. continue;
  288. }
  289. if (!moduleToSourceNameMapping.get(module)) {
  290. moduleToSourceNameMapping.set(
  291. module,
  292. ModuleFilenameHelpers.createFilename(
  293. module,
  294. {
  295. moduleFilenameTemplate,
  296. namespace: sourceMapNamespace
  297. },
  298. {
  299. requestShortener,
  300. chunkGraph,
  301. hashFunction: compilation.outputOptions.hashFunction
  302. }
  303. )
  304. );
  305. }
  306. }
  307. tasks.push(task);
  308. }
  309. reportProgress(
  310. (0.5 * ++fileIndex) / files.length,
  311. file,
  312. "generated SourceMap"
  313. );
  314. callback();
  315. });
  316. },
  317. err => {
  318. if (err) {
  319. return callback(err);
  320. }
  321. reportProgress(0.5, "resolve sources");
  322. /** @type {Set<string>} */
  323. const usedNamesSet = new Set(moduleToSourceNameMapping.values());
  324. /** @type {Set<string>} */
  325. const conflictDetectionSet = new Set();
  326. /**
  327. * all modules in defined order (longest identifier first)
  328. * @type {Array<string | Module>}
  329. */
  330. const allModules = [...moduleToSourceNameMapping.keys()].sort(
  331. (a, b) => {
  332. const ai = typeof a === "string" ? a : a.identifier();
  333. const bi = typeof b === "string" ? b : b.identifier();
  334. return ai.length - bi.length;
  335. }
  336. );
  337. // find modules with conflicting source names
  338. for (let idx = 0; idx < allModules.length; idx++) {
  339. const module = allModules[idx];
  340. let sourceName =
  341. /** @type {string} */
  342. (moduleToSourceNameMapping.get(module));
  343. let hasName = conflictDetectionSet.has(sourceName);
  344. if (!hasName) {
  345. conflictDetectionSet.add(sourceName);
  346. continue;
  347. }
  348. // try the fallback name first
  349. sourceName = ModuleFilenameHelpers.createFilename(
  350. module,
  351. {
  352. moduleFilenameTemplate: fallbackModuleFilenameTemplate,
  353. namespace
  354. },
  355. {
  356. requestShortener,
  357. chunkGraph,
  358. hashFunction: compilation.outputOptions.hashFunction
  359. }
  360. );
  361. hasName = usedNamesSet.has(sourceName);
  362. if (!hasName) {
  363. moduleToSourceNameMapping.set(module, sourceName);
  364. usedNamesSet.add(sourceName);
  365. continue;
  366. }
  367. // otherwise just append stars until we have a valid name
  368. while (hasName) {
  369. sourceName += "*";
  370. hasName = usedNamesSet.has(sourceName);
  371. }
  372. moduleToSourceNameMapping.set(module, sourceName);
  373. usedNamesSet.add(sourceName);
  374. }
  375. let taskIndex = 0;
  376. asyncLib.each(
  377. tasks,
  378. (task, callback) => {
  379. const assets = Object.create(null);
  380. const assetsInfo = Object.create(null);
  381. const file = task.file;
  382. const chunk = fileToChunk.get(file);
  383. const sourceMap = task.sourceMap;
  384. const source = task.source;
  385. const modules = task.modules;
  386. reportProgress(
  387. 0.5 + (0.5 * taskIndex) / tasks.length,
  388. file,
  389. "attach SourceMap"
  390. );
  391. const moduleFilenames = modules.map(m =>
  392. moduleToSourceNameMapping.get(m)
  393. );
  394. sourceMap.sources = /** @type {string[]} */ (moduleFilenames);
  395. if (options.noSources) {
  396. sourceMap.sourcesContent = undefined;
  397. }
  398. sourceMap.sourceRoot = options.sourceRoot || "";
  399. sourceMap.file = file;
  400. const usesContentHash =
  401. sourceMapFilename &&
  402. CONTENT_HASH_DETECT_REGEXP.test(sourceMapFilename);
  403. resetRegexpState(CONTENT_HASH_DETECT_REGEXP);
  404. // If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file`
  405. if (usesContentHash && task.assetInfo.contenthash) {
  406. const contenthash = task.assetInfo.contenthash;
  407. const pattern = Array.isArray(contenthash)
  408. ? contenthash.map(quoteMeta).join("|")
  409. : quoteMeta(contenthash);
  410. sourceMap.file = sourceMap.file.replace(
  411. new RegExp(pattern, "g"),
  412. m => "x".repeat(m.length)
  413. );
  414. }
  415. /** @type {false | TemplatePath} */
  416. let currentSourceMappingURLComment = sourceMappingURLComment;
  417. const cssExtensionDetected =
  418. CSS_EXTENSION_DETECT_REGEXP.test(file);
  419. resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
  420. if (
  421. currentSourceMappingURLComment !== false &&
  422. typeof currentSourceMappingURLComment !== "function" &&
  423. cssExtensionDetected
  424. ) {
  425. currentSourceMappingURLComment =
  426. currentSourceMappingURLComment.replace(
  427. URL_FORMATTING_REGEXP,
  428. "\n/*$1*/"
  429. );
  430. }
  431. if (options.debugIds) {
  432. const debugId = generateDebugId(source, sourceMap.file);
  433. sourceMap.debugId = debugId;
  434. currentSourceMappingURLComment = `\n//# debugId=${debugId}${currentSourceMappingURLComment}`;
  435. }
  436. const sourceMapString = JSON.stringify(sourceMap);
  437. if (sourceMapFilename) {
  438. const filename = file;
  439. const sourceMapContentHash =
  440. /** @type {string} */
  441. (
  442. usesContentHash &&
  443. createHash(
  444. /** @type {HashFunction} */
  445. (compilation.outputOptions.hashFunction)
  446. )
  447. .update(sourceMapString)
  448. .digest("hex")
  449. );
  450. const pathParams = {
  451. chunk,
  452. filename: options.fileContext
  453. ? relative(
  454. outputFs,
  455. `/${options.fileContext}`,
  456. `/${filename}`
  457. )
  458. : filename,
  459. contentHash: sourceMapContentHash
  460. };
  461. const { path: sourceMapFile, info: sourceMapInfo } =
  462. compilation.getPathWithInfo(
  463. sourceMapFilename,
  464. pathParams
  465. );
  466. const sourceMapUrl = options.publicPath
  467. ? options.publicPath + sourceMapFile
  468. : relative(
  469. outputFs,
  470. dirname(outputFs, `/${file}`),
  471. `/${sourceMapFile}`
  472. );
  473. /** @type {Source} */
  474. let asset = new RawSource(source);
  475. if (currentSourceMappingURLComment !== false) {
  476. // Add source map url to compilation asset, if currentSourceMappingURLComment is set
  477. asset = new ConcatSource(
  478. asset,
  479. compilation.getPath(currentSourceMappingURLComment, {
  480. url: sourceMapUrl,
  481. ...pathParams
  482. })
  483. );
  484. }
  485. const assetInfo = {
  486. related: { sourceMap: sourceMapFile }
  487. };
  488. assets[file] = asset;
  489. assetsInfo[file] = assetInfo;
  490. compilation.updateAsset(file, asset, assetInfo);
  491. // Add source map file to compilation assets and chunk files
  492. const sourceMapAsset = new RawSource(sourceMapString);
  493. const sourceMapAssetInfo = {
  494. ...sourceMapInfo,
  495. development: true
  496. };
  497. assets[sourceMapFile] = sourceMapAsset;
  498. assetsInfo[sourceMapFile] = sourceMapAssetInfo;
  499. compilation.emitAsset(
  500. sourceMapFile,
  501. sourceMapAsset,
  502. sourceMapAssetInfo
  503. );
  504. if (chunk !== undefined) {
  505. chunk.auxiliaryFiles.add(sourceMapFile);
  506. }
  507. } else {
  508. if (currentSourceMappingURLComment === false) {
  509. throw new Error(
  510. `${PLUGIN_NAME}: append can't be false when no filename is provided`
  511. );
  512. }
  513. if (typeof currentSourceMappingURLComment === "function") {
  514. throw new Error(
  515. `${PLUGIN_NAME}: append can't be a function when no filename is provided`
  516. );
  517. }
  518. /**
  519. * Add source map as data url to asset
  520. */
  521. const asset = new ConcatSource(
  522. new RawSource(source),
  523. currentSourceMappingURLComment
  524. .replace(MAP_URL_COMMENT_REGEXP, () => sourceMapString)
  525. .replace(
  526. URL_COMMENT_REGEXP,
  527. () =>
  528. `data:application/json;charset=utf-8;base64,${Buffer.from(
  529. sourceMapString,
  530. "utf8"
  531. ).toString("base64")}`
  532. )
  533. );
  534. assets[file] = asset;
  535. assetsInfo[file] = undefined;
  536. compilation.updateAsset(file, asset);
  537. }
  538. task.cacheItem.store({ assets, assetsInfo }, err => {
  539. reportProgress(
  540. 0.5 + (0.5 * ++taskIndex) / tasks.length,
  541. task.file,
  542. "attached SourceMap"
  543. );
  544. if (err) {
  545. return callback(err);
  546. }
  547. callback();
  548. });
  549. },
  550. err => {
  551. reportProgress(1);
  552. callback(err);
  553. }
  554. );
  555. }
  556. );
  557. }
  558. );
  559. });
  560. }
  561. }
  562. module.exports = SourceMapDevToolPlugin;