@@ -18,6 +18,7 @@ const {
1818 ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING ,
1919 ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX ,
2020} = require ( 'internal/errors' ) . codes ;
21+ const { getOptionValue } = require ( 'internal/options' ) ;
2122const assert = require ( 'internal/assert' ) ;
2223const {
2324 getCompileCacheEntry,
@@ -141,6 +142,28 @@ function stripTypeScriptTypesForCoverage(code) {
141142}
142143
143144
145+ /**
146+ * Whether type-stripping is allowed for files under node_modules belonging
147+ * to packages whose package.json contains `"private": true`.
148+ * @returns {boolean }
149+ */
150+ const isStripPrivateModulesEnabled = getLazy (
151+ ( ) => getOptionValue ( '--experimental-strip-private-modules' ) ,
152+ ) ;
153+
154+ /**
155+ * Checks if the nearest parent package.json of a file marks its package
156+ * as private.
157+ * @param {string } filename The filename (path or file URL) of the source code.
158+ * @returns {boolean } Whether the file belongs to a package with `"private": true`.
159+ */
160+ function isInsidePrivatePackage ( filename ) {
161+ const { getNearestParentPackageJSON } = require ( 'internal/modules/package_json_reader' ) ;
162+ const { urlToFilename } = require ( 'internal/modules/helpers' ) ;
163+ const packageJSON = getNearestParentPackageJSON ( urlToFilename ( filename ) ) ;
164+ return packageJSON ?. data . private === true ;
165+ }
166+
144167/**
145168 * Performs type-stripping to TypeScript source code internally.
146169 * It is used by internal loaders.
@@ -152,7 +175,10 @@ function stripTypeScriptTypesForCoverage(code) {
152175function stripTypeScriptModuleTypes ( source , filename , sourceURL ) {
153176 assert ( typeof source === 'string' ) ;
154177 if ( isUnderNodeModules ( filename ) ) {
155- throw new ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING ( filename ) ;
178+ if ( ! isStripPrivateModulesEnabled ( ) || ! isInsidePrivatePackage ( filename ) ) {
179+ throw new ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING ( filename ) ;
180+ }
181+ emitExperimentalWarning ( 'Type stripping in node_modules' ) ;
156182 }
157183 // Get a compile cache entry into the native compile cache store,
158184 // keyed by the filename. If the cache can already be loaded on disk,
0 commit comments