Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 40 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1318,20 +1318,46 @@ function updateOutput(
'utf8'
).toString('base64');
const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
// Expected form: `//# sourceMappingURL=foo.js.map` for input file foo.tsx
const sourceMapLength =
/*//# sourceMappingURL=*/ 21 +
/*foo.tsx*/ basename(fileName).length -
/*.tsx*/ extname(fileName).length +
/*.js*/ getExtension(fileName).length +
/*.map*/ 4;
// Only rewrite if existing directive exists, to support compilers that do not append a sourcemap directive
return (
(outputText.slice(-sourceMapLength, -sourceMapLength + 21) ===
'//# sourceMappingURL='
? outputText.slice(0, -sourceMapLength)
: outputText) + sourceMapContent
);
// Expected form: `//# sourceMappingURL=foo bar.js.map` or `//# sourceMappingURL=foo%20bar.js.map` for input file "foo bar.tsx"
// Percent-encoding behavior added in TS 4.1.1: https://github.com/microsoft/TypeScript/issues/40951
const prefix = '//# sourceMappingURL=';
const prefixLength = prefix.length;
const baseName = /*foo.tsx*/ basename(fileName);
const extName = /*.tsx*/ extname(fileName);
const extension = /*.js*/ getExtension(fileName);
const sourcemapFilename =
baseName.slice(0, -extName.length) + extension + '.map';
const sourceMapLengthWithoutPercentEncoding =
prefixLength + sourcemapFilename.length;
/*
* Only rewrite if existing directive exists at the location we expect, to support:
* a) compilers that do not append a sourcemap directive
* b) situations where we did the math wrong
* Not ideal, but appending our sourcemap *after* a pre-existing sourcemap still overrides, so the end-user is happy.
*/
if (
outputText.substr(-sourceMapLengthWithoutPercentEncoding, prefixLength) ===
prefix
) {
return (
outputText.slice(0, -sourceMapLengthWithoutPercentEncoding) +
sourceMapContent
);
}
// If anyone asks why we're not using URL, the URL equivalent is: `u = new URL('http://d'); u.pathname = "/" + sourcemapFilename; return u.pathname.slice(1);
const sourceMapLengthWithPercentEncoding =
prefixLength + encodeURI(sourcemapFilename).length;
if (
outputText.substr(-sourceMapLengthWithPercentEncoding, prefixLength) ===
prefix
) {
return (
outputText.slice(0, -sourceMapLengthWithPercentEncoding) +
sourceMapContent
);
}

return `${outputText}\n${sourceMapContent}`;
}

/**
Expand Down