MCPcopy
hub / github.com/TypeStrong/ts-node / updateOutput

Function updateOutput

src/index.ts:1633–1684  ·  view source on GitHub ↗

* Update the output remapping the source map.

(
  outputText: string,
  fileName: string,
  sourceMap: string,
  getEmitExtension: (fileName: string) => string
)

Source from the content-addressed store, hash-verified

1631 * Update the output remapping the source map.
1632 */
1633function updateOutput(
1634 outputText: string,
1635 fileName: string,
1636 sourceMap: string,
1637 getEmitExtension: (fileName: string) => string
1638) {
1639 const base64Map = Buffer.from(
1640 updateSourceMap(sourceMap, fileName),
1641 'utf8'
1642 ).toString('base64');
1643 const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
1644 // Expected form: `//# sourceMappingURL=foo bar.js.map` or `//# sourceMappingURL=foo%20bar.js.map` for input file "foo bar.tsx"
1645 // Percent-encoding behavior added in TS 4.1.1: https://github.com/microsoft/TypeScript/issues/40951
1646 const prefix = '//# sourceMappingURL=';
1647 const prefixLength = prefix.length;
1648 const baseName = /*foo.tsx*/ basename(fileName);
1649 const extName = /*.tsx*/ extname(fileName);
1650 const extension = /*.js*/ getEmitExtension(fileName);
1651 const sourcemapFilename =
1652 baseName.slice(0, -extName.length) + extension + '.map';
1653 const sourceMapLengthWithoutPercentEncoding =
1654 prefixLength + sourcemapFilename.length;
1655 /*
1656 * Only rewrite if existing directive exists at the location we expect, to support:
1657 * a) compilers that do not append a sourcemap directive
1658 * b) situations where we did the math wrong
1659 * Not ideal, but appending our sourcemap *after* a pre-existing sourcemap still overrides, so the end-user is happy.
1660 */
1661 if (
1662 outputText.substr(-sourceMapLengthWithoutPercentEncoding, prefixLength) ===
1663 prefix
1664 ) {
1665 return (
1666 outputText.slice(0, -sourceMapLengthWithoutPercentEncoding) +
1667 sourceMapContent
1668 );
1669 }
1670 // 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);
1671 const sourceMapLengthWithPercentEncoding =
1672 prefixLength + encodeURI(sourcemapFilename).length;
1673 if (
1674 outputText.substr(-sourceMapLengthWithPercentEncoding, prefixLength) ===
1675 prefix
1676 ) {
1677 return (
1678 outputText.slice(0, -sourceMapLengthWithPercentEncoding) +
1679 sourceMapContent
1680 );
1681 }
1682
1683 return `${outputText}\n${sourceMapContent}`;
1684}
1685
1686/**
1687 * Update the source map contents for improved output.

Callers 1

compileFunction · 0.85

Calls 3

updateSourceMapFunction · 0.85
getEmitExtensionFunction · 0.85
toStringMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…