SourceMapDevToolPlugin.js 20 KB

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