|
| 1 | +/** |
| 2 | + * Copyright (c) 2015-present, Facebook, Inc. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | +'use strict'; |
| 8 | + |
| 9 | +function base64SourceMap(source) { |
| 10 | + const base64 = Buffer.from(JSON.stringify(source.map()), 'utf8').toString( |
| 11 | + 'base64' |
| 12 | + ); |
| 13 | + return `data:application/json;charset=utf-8;base64,${base64}`; |
| 14 | +} |
| 15 | + |
| 16 | +function getSourceById(server, id) { |
| 17 | + const module = server._stats.compilation.modules.find(m => m.id == id); |
| 18 | + return module.originalSource(); |
| 19 | +} |
| 20 | + |
| 21 | +/* |
| 22 | + * Middleware responsible for retrieving a generated source |
| 23 | + * Receives a webpack internal url: "webpack-internal:///<module-id>" |
| 24 | + * Returns a generated source: "<source-text><sourceMappingURL><sourceURL>" |
| 25 | + * |
| 26 | + * Based on EvalSourceMapDevToolModuleTemplatePlugin.js |
| 27 | + */ |
| 28 | +module.exports = function createEvalSourceMapMiddleware(server) { |
| 29 | + return function handleWebpackInternalMiddleware(req, res, next) { |
| 30 | + if (req.url.startsWith('/__get-internal-source')) { |
| 31 | + const fileName = req.query.fileName; |
| 32 | + const id = fileName.match(/webpack-internal:\/\/\/(.+)/)[1]; |
| 33 | + if (!id || !server._stats) { |
| 34 | + next(); |
| 35 | + } |
| 36 | + |
| 37 | + const source = getSourceById(server, id); |
| 38 | + const sourceMapURL = `//# sourceMappingURL=${base64SourceMap(source)}`; |
| 39 | + const sourceURL = `//# sourceURL=webpack-internal:///${module.id}`; |
| 40 | + res.end(`${source.source()}\n${sourceMapURL}\n${sourceURL}`); |
| 41 | + } else { |
| 42 | + next(); |
| 43 | + } |
| 44 | + }; |
| 45 | +}; |
0 commit comments