@backtrace/sourcemap-tools
Version:
Backtrace-JavaScript sourcemap tools
65 lines • 2.87 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.DebugIdGenerator = exports.SOURCEMAP_DEBUG_ID_KEY = exports.SOURCE_DEBUG_ID_COMMENT = exports.SOURCE_DEBUG_ID_VARIABLE = void 0;
exports.SOURCE_DEBUG_ID_VARIABLE = '_btDebugIds';
exports.SOURCE_DEBUG_ID_COMMENT = 'debugId';
exports.SOURCEMAP_DEBUG_ID_KEY = 'debugId';
/**
* Matches leading and trailing semicolons, e.g. in `;;foo;bar;;`
*/
const MATCH_SEMICOLONS_REGEX = /^;+|;+$/;
class DebugIdGenerator {
generateSourceSnippet(uuid) {
return `;!function(){try{var k="${exports.SOURCE_DEBUG_ID_VARIABLE}",u="undefined",v="${uuid}",a=function(x){try{x[k]=x[k]||{};x[k][n]=v}catch{}},n=(new Error).stack;n&&(u!=typeof window?a(window):u);n&&(u!=typeof global?a(global):u);n&&(u!=typeof self?a(self):u);n&&(u!=typeof globalThis?a(globalThis):u)}catch{}}();`;
}
generateSourceComment(uuid) {
return `//# ${exports.SOURCE_DEBUG_ID_COMMENT}=${uuid}`;
}
replaceDebugId(source, oldDebugId, newDebugId) {
const replaceAll = () => source.replace(oldDebugId, newDebugId);
// Try to replace more safely first
const oldSourceSnippet = this.generateSourceSnippet(oldDebugId).replace(MATCH_SEMICOLONS_REGEX, '');
if (source.indexOf(oldSourceSnippet) !== -1) {
source = source.replace(oldSourceSnippet, this.generateSourceSnippet(newDebugId));
}
else {
return replaceAll();
}
const oldCommentSnippet = this.generateSourceComment(oldDebugId);
if (source.indexOf(oldCommentSnippet) !== -1) {
source = source.replace(oldCommentSnippet, this.generateSourceComment(newDebugId));
}
else {
return replaceAll();
}
return source;
}
hasCodeSnippet(source, debugId) {
const sourceSnippet = this.generateSourceSnippet(debugId).replace(MATCH_SEMICOLONS_REGEX, '');
return source.includes(sourceSnippet);
}
hasCommentSnippet(source, debugId) {
const commentSnippet = this.generateSourceComment(debugId);
return source.includes(commentSnippet);
}
getSourceDebugIdFromComment(source) {
const regex = new RegExp(`^//# ${exports.SOURCE_DEBUG_ID_COMMENT}=(.+)$`, 'm');
const match = source.match(regex);
if (!match) {
return undefined;
}
return match[1];
}
addSourceMapDebugId(sourceMap, uuid) {
return Object.assign(Object.assign({}, sourceMap), { [exports.SOURCEMAP_DEBUG_ID_KEY]: uuid });
}
getSourceMapDebugId(sourcemap) {
const debugId = sourcemap[exports.SOURCEMAP_DEBUG_ID_KEY];
if (typeof debugId !== 'string') {
return undefined;
}
return debugId;
}
}
exports.DebugIdGenerator = DebugIdGenerator;
//# sourceMappingURL=DebugIdGenerator.js.map
;