Skip to content

Commit 1ba2000

Browse files
marco-ippolitotargos
authored andcommitted
module: refactor ts parser loading
PR-URL: #54243 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Reviewed-By: Tierney Cyren <hello@bnb.im> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Jake Yuesong Li <jake.yuesong@gmail.com>
1 parent 2f68a74 commit 1ba2000

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

Diff for: lib/internal/modules/helpers.js

+25-6
Original file line numberDiff line numberDiff line change
@@ -300,11 +300,29 @@ function getBuiltinModule(id) {
300300
return normalizedId ? require(normalizedId) : undefined;
301301
}
302302

303-
let parseTS;
303+
let typeScriptParser;
304304

305-
function lazyLoadTSParser() {
306-
parseTS ??= require('internal/deps/amaro/dist/index').transformSync;
307-
return parseTS;
305+
/**
306+
* Load the TypeScript parser.
307+
* @param {Function} parser - A function that takes a string of TypeScript code
308+
* and returns an object with a `code` property.
309+
* @returns {Function} The TypeScript parser function.
310+
*/
311+
function loadTypeScriptParser(parser) {
312+
if (typeScriptParser) {
313+
return typeScriptParser;
314+
}
315+
316+
if (parser) {
317+
typeScriptParser = parser;
318+
} else {
319+
const amaro = require('internal/deps/amaro/dist/index');
320+
// Default option for Amaro is to perform Type Stripping only.
321+
const defaultOptions = { __proto__: null, mode: 'strip-only' };
322+
// Curry the transformSync function with the default options.
323+
typeScriptParser = (source) => amaro.transformSync(source, defaultOptions);
324+
}
325+
return typeScriptParser;
308326
}
309327

310328
/**
@@ -313,9 +331,10 @@ function lazyLoadTSParser() {
313331
* @returns {string} JavaScript code.
314332
*/
315333
function tsParse(source) {
334+
// TODO(@marco-ippolito) Checking empty string or non string input should be handled in Amaro.
316335
if (!source || typeof source !== 'string') { return ''; }
317-
const transformSync = lazyLoadTSParser();
318-
const { code } = transformSync(source, { __proto__: null, mode: 'strip-only' });
336+
const parse = loadTypeScriptParser();
337+
const { code } = parse(source);
319338
return code;
320339
}
321340

0 commit comments

Comments
 (0)