Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

module: refactor ts parser loading #54243

Merged
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
31 changes: 25 additions & 6 deletions lib/internal/modules/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -300,11 +300,29 @@ function getBuiltinModule(id) {
return normalizedId ? require(normalizedId) : undefined;
}

let parseTS;
let typeScriptParser;

function lazyLoadTSParser() {
parseTS ??= require('internal/deps/amaro/dist/index').transformSync;
return parseTS;
/**
* Load the TypeScript parser.
* @param {Function} parser - A function that takes a string of TypeScript code
* and returns an object with a `code` property.
* @returns {Function} The TypeScript parser function.
*/
function loadTypeScriptParser(parser) {
if (typeScriptParser) {
return typeScriptParser;
}

if (parser) {
typeScriptParser = parser;
} else {
const amaro = require('internal/deps/amaro/dist/index');
// Default option for Amaro is to perform Type Stripping only.
const defaultOptions = { __proto__: null, mode: 'strip-only' };
// Curry the transformSync function with the default options.
typeScriptParser = (source) => amaro.transformSync(source, defaultOptions);
}
return typeScriptParser;
}

/**
Expand All @@ -313,9 +331,10 @@ function lazyLoadTSParser() {
* @returns {string} JavaScript code.
*/
function tsParse(source) {
// TODO(@marco-ippolito) Checking empty string or non string input should be handled in Amaro.
if (!source || typeof source !== 'string') { return ''; }
const transformSync = lazyLoadTSParser();
const { code } = transformSync(source, { __proto__: null, mode: 'strip-only' });
const parse = loadTypeScriptParser();
const { code } = parse(source);
return code;
}

Expand Down
Loading