node-internal-modules-esm-resolve.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. // Copied from https://raw.githubusercontent.com/nodejs/node/v15.3.0/lib/internal/modules/esm/resolve.js
  2. 'use strict';
  3. const {versionGteLt} = require('../dist/util');
  4. // Test for node >14.13.1 || (>=12.20.0 && <13)
  5. const builtinModuleProtocol =
  6. versionGteLt(process.versions.node, '14.13.1') ||
  7. versionGteLt(process.versions.node, '12.20.0', '13.0.0')
  8. ? 'node:'
  9. : 'nodejs:';
  10. const {
  11. ArrayIsArray,
  12. ArrayPrototypeJoin,
  13. ArrayPrototypeShift,
  14. JSONParse,
  15. JSONStringify,
  16. ObjectFreeze,
  17. ObjectGetOwnPropertyNames,
  18. ObjectPrototypeHasOwnProperty,
  19. RegExpPrototypeTest,
  20. SafeMap,
  21. SafeSet,
  22. StringPrototypeEndsWith,
  23. StringPrototypeIndexOf,
  24. StringPrototypeLastIndexOf,
  25. StringPrototypeReplace,
  26. StringPrototypeSlice,
  27. StringPrototypeSplit,
  28. StringPrototypeStartsWith,
  29. StringPrototypeSubstr,
  30. } = require('./node-primordials');
  31. // const internalFS = require('internal/fs/utils');
  32. const Module = require('module');
  33. const { NativeModule } = require('./node-nativemodule');
  34. const {
  35. realpathSync,
  36. statSync,
  37. Stats,
  38. } = require('fs');
  39. // const { getOptionValue } = require('internal/options');
  40. const { getOptionValue } = require('./node-options');
  41. // // Do not eagerly grab .manifest, it may be in TDZ
  42. // const policy = getOptionValue('--experimental-policy') ?
  43. // require('internal/process/policy') :
  44. // null;
  45. // disabled for now. I am not sure if/how we should support this
  46. const policy = null;
  47. const { sep, relative } = require('path');
  48. const preserveSymlinks = getOptionValue('--preserve-symlinks');
  49. const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
  50. const typeFlag = getOptionValue('--input-type');
  51. // const { URL, pathToFileURL, fileURLToPath } = require('internal/url');
  52. const { URL, pathToFileURL, fileURLToPath } = require('url');
  53. const {
  54. ERR_INPUT_TYPE_NOT_ALLOWED,
  55. ERR_INVALID_ARG_VALUE,
  56. ERR_INVALID_MODULE_SPECIFIER,
  57. ERR_INVALID_PACKAGE_CONFIG,
  58. ERR_INVALID_PACKAGE_TARGET,
  59. ERR_MANIFEST_DEPENDENCY_MISSING,
  60. ERR_MODULE_NOT_FOUND,
  61. ERR_PACKAGE_IMPORT_NOT_DEFINED,
  62. ERR_PACKAGE_PATH_NOT_EXPORTED,
  63. ERR_UNSUPPORTED_DIR_IMPORT,
  64. ERR_UNSUPPORTED_ESM_URL_SCHEME,
  65. // } = require('internal/errors').codes;
  66. } = require('./node-internal-errors').codes;
  67. // const { Module: CJSModule } = require('internal/modules/cjs/loader');
  68. const CJSModule = Module;
  69. // const packageJsonReader = require('internal/modules/package_json_reader');
  70. const packageJsonReader = require('./node-internal-modules-package_json_reader');
  71. const userConditions = getOptionValue('--conditions');
  72. const DEFAULT_CONDITIONS = ObjectFreeze(['node', 'import', ...userConditions]);
  73. const DEFAULT_CONDITIONS_SET = new SafeSet(DEFAULT_CONDITIONS);
  74. const pendingDeprecation = getOptionValue('--pending-deprecation');
  75. /**
  76. * @param {{
  77. * extensions: import('../src/file-extensions').Extensions,
  78. * preferTsExts: boolean | undefined;
  79. * tsNodeExperimentalSpecifierResolution: import('../src/index').ExperimentalSpecifierResolution | undefined;
  80. * }} opts
  81. */
  82. function createResolve(opts) {
  83. // TODO receive cached fs implementations here
  84. const {preferTsExts, tsNodeExperimentalSpecifierResolution, extensions} = opts;
  85. const esrnExtensions = extensions.experimentalSpecifierResolutionAddsIfOmitted;
  86. const {legacyMainResolveAddsIfOmitted, replacementsForCjs, replacementsForJs, replacementsForMjs, replacementsForJsx} = extensions;
  87. // const experimentalSpecifierResolution = tsNodeExperimentalSpecifierResolution ?? getOptionValue('--experimental-specifier-resolution');
  88. const experimentalSpecifierResolution = tsNodeExperimentalSpecifierResolution != null ? tsNodeExperimentalSpecifierResolution : getOptionValue('--experimental-specifier-resolution');
  89. const emittedPackageWarnings = new SafeSet();
  90. function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) {
  91. const pjsonPath = fileURLToPath(pjsonUrl);
  92. if (!pendingDeprecation) {
  93. const nodeModulesIndex = StringPrototypeLastIndexOf(pjsonPath,
  94. '/node_modules/');
  95. if (nodeModulesIndex !== -1) {
  96. const afterNodeModulesPath = StringPrototypeSlice(pjsonPath,
  97. nodeModulesIndex + 14,
  98. -13);
  99. try {
  100. const { packageSubpath } = parsePackageName(afterNodeModulesPath);
  101. if (packageSubpath === '.')
  102. return;
  103. } catch {}
  104. }
  105. }
  106. if (emittedPackageWarnings.has(pjsonPath + '|' + match))
  107. return;
  108. emittedPackageWarnings.add(pjsonPath + '|' + match);
  109. process.emitWarning(
  110. `Use of deprecated folder mapping "${match}" in the ${isExports ?
  111. '"exports"' : '"imports"'} field module resolution of the package at ${
  112. pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ''}.\n` +
  113. `Update this package.json to use a subpath pattern like "${match}*".`,
  114. 'DeprecationWarning',
  115. 'DEP0148'
  116. );
  117. }
  118. function getConditionsSet(conditions) {
  119. if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) {
  120. if (!ArrayIsArray(conditions)) {
  121. throw new ERR_INVALID_ARG_VALUE('conditions', conditions,
  122. 'expected an array');
  123. }
  124. return new SafeSet(conditions);
  125. }
  126. return DEFAULT_CONDITIONS_SET;
  127. }
  128. const realpathCache = new SafeMap();
  129. const packageJSONCache = new SafeMap(); /* string -> PackageConfig */
  130. const statSupportsThrowIfNoEntry = versionGteLt(process.versions.node, '15.3.0') ||
  131. versionGteLt(process.versions.node, '14.17.0', '15.0.0');
  132. const tryStatSync = statSupportsThrowIfNoEntry ? tryStatSyncWithoutErrors : tryStatSyncWithErrors;
  133. const statsIfNotFound = new Stats();
  134. function tryStatSyncWithoutErrors(path) {
  135. const stats = statSync(path, { throwIfNoEntry: false });
  136. if(stats != null) return stats;
  137. return statsIfNotFound;
  138. }
  139. function tryStatSyncWithErrors(path) {
  140. try {
  141. return statSync(path);
  142. } catch {
  143. return statsIfNotFound;
  144. }
  145. }
  146. function getPackageConfig(path, specifier, base) {
  147. const existing = packageJSONCache.get(path);
  148. if (existing !== undefined) {
  149. return existing;
  150. }
  151. const source = packageJsonReader.read(path).string;
  152. if (source === undefined) {
  153. const packageConfig = {
  154. pjsonPath: path,
  155. exists: false,
  156. main: undefined,
  157. name: undefined,
  158. type: 'none',
  159. exports: undefined,
  160. imports: undefined,
  161. };
  162. packageJSONCache.set(path, packageConfig);
  163. return packageConfig;
  164. }
  165. let packageJSON;
  166. try {
  167. packageJSON = JSONParse(source);
  168. } catch (error) {
  169. throw new ERR_INVALID_PACKAGE_CONFIG(
  170. path,
  171. (base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
  172. error.message
  173. );
  174. }
  175. let { imports, main, name, type } = packageJSON;
  176. const { exports } = packageJSON;
  177. if (typeof imports !== 'object' || imports === null) imports = undefined;
  178. if (typeof main !== 'string') main = undefined;
  179. if (typeof name !== 'string') name = undefined;
  180. // Ignore unknown types for forwards compatibility
  181. if (type !== 'module' && type !== 'commonjs') type = 'none';
  182. const packageConfig = {
  183. pjsonPath: path,
  184. exists: true,
  185. main,
  186. name,
  187. type,
  188. exports,
  189. imports,
  190. };
  191. packageJSONCache.set(path, packageConfig);
  192. return packageConfig;
  193. }
  194. function getPackageScopeConfig(resolved) {
  195. let packageJSONUrl = new URL('./package.json', resolved);
  196. while (true) {
  197. const packageJSONPath = packageJSONUrl.pathname;
  198. if (StringPrototypeEndsWith(packageJSONPath, 'node_modules/package.json'))
  199. break;
  200. const packageConfig = getPackageConfig(fileURLToPath(packageJSONUrl),
  201. resolved);
  202. if (packageConfig.exists) return packageConfig;
  203. const lastPackageJSONUrl = packageJSONUrl;
  204. packageJSONUrl = new URL('../package.json', packageJSONUrl);
  205. // Terminates at root where ../package.json equals ../../package.json
  206. // (can't just check "/package.json" for Windows support).
  207. if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break;
  208. }
  209. const packageJSONPath = fileURLToPath(packageJSONUrl);
  210. const packageConfig = {
  211. pjsonPath: packageJSONPath,
  212. exists: false,
  213. main: undefined,
  214. name: undefined,
  215. type: 'none',
  216. exports: undefined,
  217. imports: undefined,
  218. };
  219. packageJSONCache.set(packageJSONPath, packageConfig);
  220. return packageConfig;
  221. }
  222. /*
  223. * Legacy CommonJS main resolution:
  224. * 1. let M = pkg_url + (json main field)
  225. * 2. TRY(M, M.js, M.json, M.node)
  226. * 3. TRY(M/index.js, M/index.json, M/index.node)
  227. * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
  228. * 5. NOT_FOUND
  229. */
  230. function fileExists(url) {
  231. return tryStatSync(fileURLToPath(url)).isFile();
  232. }
  233. function legacyMainResolve(packageJSONUrl, packageConfig, base) {
  234. let guess;
  235. if (packageConfig.main !== undefined) {
  236. // Note: fs check redundances will be handled by Descriptor cache here.
  237. if(guess = resolveReplacementExtensions(new URL(`./${packageConfig.main}`, packageJSONUrl))) {
  238. return guess;
  239. }
  240. if (fileExists(guess = new URL(`./${packageConfig.main}`,
  241. packageJSONUrl))) {
  242. return guess;
  243. }
  244. for(const extension of legacyMainResolveAddsIfOmitted) {
  245. if (fileExists(guess = new URL(`./${packageConfig.main}${extension}`,
  246. packageJSONUrl))) {
  247. return guess;
  248. }
  249. }
  250. for(const extension of legacyMainResolveAddsIfOmitted) {
  251. if (fileExists(guess = new URL(`./${packageConfig.main}/index${extension}`,
  252. packageJSONUrl))) {
  253. return guess;
  254. }
  255. }
  256. // Fallthrough.
  257. }
  258. for(const extension of legacyMainResolveAddsIfOmitted) {
  259. if (fileExists(guess = new URL(`./index${extension}`, packageJSONUrl))) {
  260. return guess;
  261. }
  262. }
  263. // Not found.
  264. throw new ERR_MODULE_NOT_FOUND(
  265. fileURLToPath(new URL('.', packageJSONUrl)), fileURLToPath(base));
  266. }
  267. /** attempts replacement extensions, then tries exact name, then attempts appending extensions */
  268. function resolveExtensionsWithTryExactName(search) {
  269. const resolvedReplacementExtension = resolveReplacementExtensions(search);
  270. if(resolvedReplacementExtension) return resolvedReplacementExtension;
  271. if (fileExists(search)) return search;
  272. return resolveExtensions(search);
  273. }
  274. // This appends missing extensions
  275. function resolveExtensions(search) {
  276. for (let i = 0; i < esrnExtensions.length; i++) {
  277. const extension = esrnExtensions[i];
  278. const guess = new URL(`${search.pathname}${extension}`, search);
  279. if (fileExists(guess)) return guess;
  280. }
  281. return undefined;
  282. }
  283. /** This replaces JS with TS extensions */
  284. function resolveReplacementExtensions(search) {
  285. const lastDotIndex = search.pathname.lastIndexOf('.');
  286. if(lastDotIndex >= 0) {
  287. const ext = search.pathname.slice(lastDotIndex);
  288. if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
  289. const pathnameWithoutExtension = search.pathname.slice(0, lastDotIndex);
  290. const replacementExts =
  291. ext === '.js' ? replacementsForJs
  292. : ext === '.jsx' ? replacementsForJsx
  293. : ext === '.mjs' ? replacementsForMjs
  294. : replacementsForCjs;
  295. const guess = new URL(search.toString());
  296. for (let i = 0; i < replacementExts.length; i++) {
  297. const extension = replacementExts[i];
  298. guess.pathname = `${pathnameWithoutExtension}${extension}`;
  299. if (fileExists(guess)) return guess;
  300. }
  301. }
  302. }
  303. return undefined;
  304. }
  305. function resolveIndex(search) {
  306. return resolveExtensions(new URL('index', search));
  307. }
  308. const encodedSepRegEx = /%2F|%2C/i;
  309. function finalizeResolution(resolved, base) {
  310. if (RegExpPrototypeTest(encodedSepRegEx, resolved.pathname))
  311. throw new ERR_INVALID_MODULE_SPECIFIER(
  312. resolved.pathname, 'must not include encoded "/" or "\\" characters',
  313. fileURLToPath(base));
  314. if (experimentalSpecifierResolution === 'node') {
  315. const path = fileURLToPath(resolved);
  316. let file = resolveExtensionsWithTryExactName(resolved);
  317. if (file !== undefined) return file;
  318. if (!StringPrototypeEndsWith(path, '/')) {
  319. file = resolveIndex(new URL(`${resolved}/`));
  320. if (file !== undefined) return file;
  321. } else {
  322. return resolveIndex(resolved) || resolved;
  323. }
  324. throw new ERR_MODULE_NOT_FOUND(
  325. resolved.pathname, fileURLToPath(base), 'module');
  326. }
  327. const file = resolveReplacementExtensions(resolved) || resolved;
  328. const path = fileURLToPath(file);
  329. const stats = tryStatSync(StringPrototypeEndsWith(path, '/') ?
  330. StringPrototypeSlice(path, -1) : path);
  331. if (stats.isDirectory()) {
  332. const err = new ERR_UNSUPPORTED_DIR_IMPORT(path, fileURLToPath(base));
  333. err.url = String(resolved);
  334. throw err;
  335. } else if (!stats.isFile()) {
  336. throw new ERR_MODULE_NOT_FOUND(
  337. path || resolved.pathname, fileURLToPath(base), 'module');
  338. }
  339. return file;
  340. }
  341. function throwImportNotDefined(specifier, packageJSONUrl, base) {
  342. throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(
  343. specifier, packageJSONUrl && fileURLToPath(new URL('.', packageJSONUrl)),
  344. fileURLToPath(base));
  345. }
  346. function throwExportsNotFound(subpath, packageJSONUrl, base) {
  347. throw new ERR_PACKAGE_PATH_NOT_EXPORTED(
  348. fileURLToPath(new URL('.', packageJSONUrl)), subpath,
  349. base && fileURLToPath(base));
  350. }
  351. function throwInvalidSubpath(subpath, packageJSONUrl, internal, base) {
  352. const reason = `request is not a valid subpath for the "${internal ?
  353. 'imports' : 'exports'}" resolution of ${fileURLToPath(packageJSONUrl)}`;
  354. throw new ERR_INVALID_MODULE_SPECIFIER(subpath, reason,
  355. base && fileURLToPath(base));
  356. }
  357. function throwInvalidPackageTarget(
  358. subpath, target, packageJSONUrl, internal, base) {
  359. if (typeof target === 'object' && target !== null) {
  360. target = JSONStringify(target, null, '');
  361. } else {
  362. target = `${target}`;
  363. }
  364. throw new ERR_INVALID_PACKAGE_TARGET(
  365. fileURLToPath(new URL('.', packageJSONUrl)), subpath, target,
  366. internal, base && fileURLToPath(base));
  367. }
  368. const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/;
  369. const patternRegEx = /\*/g;
  370. function resolvePackageTargetString(
  371. target, subpath, match, packageJSONUrl, base, pattern, internal, conditions) {
  372. if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
  373. throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
  374. if (!StringPrototypeStartsWith(target, './')) {
  375. if (internal && !StringPrototypeStartsWith(target, '../') &&
  376. !StringPrototypeStartsWith(target, '/')) {
  377. let isURL = false;
  378. try {
  379. new URL(target);
  380. isURL = true;
  381. } catch {}
  382. if (!isURL) {
  383. const exportTarget = pattern ?
  384. StringPrototypeReplace(target, patternRegEx, subpath) :
  385. target + subpath;
  386. return packageResolve(exportTarget, packageJSONUrl, conditions);
  387. }
  388. }
  389. throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
  390. }
  391. if (RegExpPrototypeTest(invalidSegmentRegEx, StringPrototypeSlice(target, 2)))
  392. throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
  393. const resolved = new URL(target, packageJSONUrl);
  394. const resolvedPath = resolved.pathname;
  395. const packagePath = new URL('.', packageJSONUrl).pathname;
  396. if (!StringPrototypeStartsWith(resolvedPath, packagePath))
  397. throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
  398. if (subpath === '') return resolved;
  399. if (RegExpPrototypeTest(invalidSegmentRegEx, subpath))
  400. throwInvalidSubpath(match + subpath, packageJSONUrl, internal, base);
  401. if (pattern)
  402. return new URL(StringPrototypeReplace(resolved.href, patternRegEx,
  403. subpath));
  404. return new URL(subpath, resolved);
  405. }
  406. /**
  407. * @param {string} key
  408. * @returns {boolean}
  409. */
  410. function isArrayIndex(key) {
  411. const keyNum = +key;
  412. if (`${keyNum}` !== key) return false;
  413. return keyNum >= 0 && keyNum < 0xFFFF_FFFF;
  414. }
  415. function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath,
  416. base, pattern, internal, conditions) {
  417. if (typeof target === 'string') {
  418. return resolvePackageTargetString(
  419. target, subpath, packageSubpath, packageJSONUrl, base, pattern, internal,
  420. conditions);
  421. } else if (ArrayIsArray(target)) {
  422. if (target.length === 0)
  423. return null;
  424. let lastException;
  425. for (let i = 0; i < target.length; i++) {
  426. const targetItem = target[i];
  427. let resolved;
  428. try {
  429. resolved = resolvePackageTarget(
  430. packageJSONUrl, targetItem, subpath, packageSubpath, base, pattern,
  431. internal, conditions);
  432. } catch (e) {
  433. lastException = e;
  434. if (e.code === 'ERR_INVALID_PACKAGE_TARGET')
  435. continue;
  436. throw e;
  437. }
  438. if (resolved === undefined)
  439. continue;
  440. if (resolved === null) {
  441. lastException = null;
  442. continue;
  443. }
  444. return resolved;
  445. }
  446. if (lastException === undefined || lastException === null)
  447. return lastException;
  448. throw lastException;
  449. } else if (typeof target === 'object' && target !== null) {
  450. const keys = ObjectGetOwnPropertyNames(target);
  451. for (let i = 0; i < keys.length; i++) {
  452. const key = keys[i];
  453. if (isArrayIndex(key)) {
  454. throw new ERR_INVALID_PACKAGE_CONFIG(
  455. fileURLToPath(packageJSONUrl), base,
  456. '"exports" cannot contain numeric property keys.');
  457. }
  458. }
  459. for (let i = 0; i < keys.length; i++) {
  460. const key = keys[i];
  461. if (key === 'default' || conditions.has(key)) {
  462. const conditionalTarget = target[key];
  463. const resolved = resolvePackageTarget(
  464. packageJSONUrl, conditionalTarget, subpath, packageSubpath, base,
  465. pattern, internal, conditions);
  466. if (resolved === undefined)
  467. continue;
  468. return resolved;
  469. }
  470. }
  471. return undefined;
  472. } else if (target === null) {
  473. return null;
  474. }
  475. throwInvalidPackageTarget(packageSubpath, target, packageJSONUrl, internal,
  476. base);
  477. }
  478. function isConditionalExportsMainSugar(exports, packageJSONUrl, base) {
  479. if (typeof exports === 'string' || ArrayIsArray(exports)) return true;
  480. if (typeof exports !== 'object' || exports === null) return false;
  481. const keys = ObjectGetOwnPropertyNames(exports);
  482. let isConditionalSugar = false;
  483. let i = 0;
  484. for (let j = 0; j < keys.length; j++) {
  485. const key = keys[j];
  486. const curIsConditionalSugar = key === '' || key[0] !== '.';
  487. if (i++ === 0) {
  488. isConditionalSugar = curIsConditionalSugar;
  489. } else if (isConditionalSugar !== curIsConditionalSugar) {
  490. throw new ERR_INVALID_PACKAGE_CONFIG(
  491. fileURLToPath(packageJSONUrl), base,
  492. '"exports" cannot contain some keys starting with \'.\' and some not.' +
  493. ' The exports object must either be an object of package subpath keys' +
  494. ' or an object of main entry condition name keys only.');
  495. }
  496. }
  497. return isConditionalSugar;
  498. }
  499. /**
  500. * @param {URL} packageJSONUrl
  501. * @param {string} packageSubpath
  502. * @param {object} packageConfig
  503. * @param {string} base
  504. * @param {Set<string>} conditions
  505. * @returns {{resolved: URL, exact: boolean}}
  506. */
  507. function packageExportsResolve(
  508. packageJSONUrl, packageSubpath, packageConfig, base, conditions) {
  509. let exports = packageConfig.exports;
  510. if (isConditionalExportsMainSugar(exports, packageJSONUrl, base))
  511. exports = { '.': exports };
  512. if (ObjectPrototypeHasOwnProperty(exports, packageSubpath)) {
  513. const target = exports[packageSubpath];
  514. const resolved = resolvePackageTarget(
  515. packageJSONUrl, target, '', packageSubpath, base, false, false, conditions
  516. );
  517. if (resolved === null || resolved === undefined)
  518. throwExportsNotFound(packageSubpath, packageJSONUrl, base);
  519. return { resolved, exact: true };
  520. }
  521. let bestMatch = '';
  522. const keys = ObjectGetOwnPropertyNames(exports);
  523. for (let i = 0; i < keys.length; i++) {
  524. const key = keys[i];
  525. if (key[key.length - 1] === '*' &&
  526. StringPrototypeStartsWith(packageSubpath,
  527. StringPrototypeSlice(key, 0, -1)) &&
  528. packageSubpath.length >= key.length &&
  529. key.length > bestMatch.length) {
  530. bestMatch = key;
  531. } else if (key[key.length - 1] === '/' &&
  532. StringPrototypeStartsWith(packageSubpath, key) &&
  533. key.length > bestMatch.length) {
  534. bestMatch = key;
  535. }
  536. }
  537. if (bestMatch) {
  538. const target = exports[bestMatch];
  539. const pattern = bestMatch[bestMatch.length - 1] === '*';
  540. const subpath = StringPrototypeSubstr(packageSubpath, bestMatch.length -
  541. (pattern ? 1 : 0));
  542. const resolved = resolvePackageTarget(packageJSONUrl, target, subpath,
  543. bestMatch, base, pattern, false,
  544. conditions);
  545. if (resolved === null || resolved === undefined)
  546. throwExportsNotFound(packageSubpath, packageJSONUrl, base);
  547. if (!pattern)
  548. emitFolderMapDeprecation(bestMatch, packageJSONUrl, true, base);
  549. return { resolved, exact: pattern };
  550. }
  551. throwExportsNotFound(packageSubpath, packageJSONUrl, base);
  552. }
  553. function packageImportsResolve(name, base, conditions) {
  554. if (name === '#' || StringPrototypeStartsWith(name, '#/')) {
  555. const reason = 'is not a valid internal imports specifier name';
  556. throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base));
  557. }
  558. let packageJSONUrl;
  559. const packageConfig = getPackageScopeConfig(base);
  560. if (packageConfig.exists) {
  561. packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
  562. const imports = packageConfig.imports;
  563. if (imports) {
  564. if (ObjectPrototypeHasOwnProperty(imports, name)) {
  565. const resolved = resolvePackageTarget(
  566. packageJSONUrl, imports[name], '', name, base, false, true, conditions
  567. );
  568. if (resolved !== null)
  569. return { resolved, exact: true };
  570. } else {
  571. let bestMatch = '';
  572. const keys = ObjectGetOwnPropertyNames(imports);
  573. for (let i = 0; i < keys.length; i++) {
  574. const key = keys[i];
  575. if (key[key.length - 1] === '*' &&
  576. StringPrototypeStartsWith(name,
  577. StringPrototypeSlice(key, 0, -1)) &&
  578. name.length >= key.length &&
  579. key.length > bestMatch.length) {
  580. bestMatch = key;
  581. } else if (key[key.length - 1] === '/' &&
  582. StringPrototypeStartsWith(name, key) &&
  583. key.length > bestMatch.length) {
  584. bestMatch = key;
  585. }
  586. }
  587. if (bestMatch) {
  588. const target = imports[bestMatch];
  589. const pattern = bestMatch[bestMatch.length - 1] === '*';
  590. const subpath = StringPrototypeSubstr(name, bestMatch.length -
  591. (pattern ? 1 : 0));
  592. const resolved = resolvePackageTarget(
  593. packageJSONUrl, target, subpath, bestMatch, base, pattern, true,
  594. conditions);
  595. if (resolved !== null) {
  596. if (!pattern)
  597. emitFolderMapDeprecation(bestMatch, packageJSONUrl, false, base);
  598. return { resolved, exact: pattern };
  599. }
  600. }
  601. }
  602. }
  603. }
  604. throwImportNotDefined(name, packageJSONUrl, base);
  605. }
  606. function getPackageType(url) {
  607. const packageConfig = getPackageScopeConfig(url);
  608. return packageConfig.type;
  609. }
  610. function parsePackageName(specifier, base) {
  611. let separatorIndex = StringPrototypeIndexOf(specifier, '/');
  612. let validPackageName = true;
  613. let isScoped = false;
  614. if (specifier[0] === '@') {
  615. isScoped = true;
  616. if (separatorIndex === -1 || specifier.length === 0) {
  617. validPackageName = false;
  618. } else {
  619. separatorIndex = StringPrototypeIndexOf(
  620. specifier, '/', separatorIndex + 1);
  621. }
  622. }
  623. const packageName = separatorIndex === -1 ?
  624. specifier : StringPrototypeSlice(specifier, 0, separatorIndex);
  625. // Package name cannot have leading . and cannot have percent-encoding or
  626. // separators.
  627. for (let i = 0; i < packageName.length; i++) {
  628. if (packageName[i] === '%' || packageName[i] === '\\') {
  629. validPackageName = false;
  630. break;
  631. }
  632. }
  633. if (!validPackageName) {
  634. throw new ERR_INVALID_MODULE_SPECIFIER(
  635. specifier, 'is not a valid package name', fileURLToPath(base));
  636. }
  637. const packageSubpath = '.' + (separatorIndex === -1 ? '' :
  638. StringPrototypeSlice(specifier, separatorIndex));
  639. return { packageName, packageSubpath, isScoped };
  640. }
  641. /**
  642. * @param {string} specifier
  643. * @param {URL} base
  644. * @param {Set<string>} conditions
  645. * @returns {URL}
  646. */
  647. function packageResolve(specifier, base, conditions) {
  648. const { packageName, packageSubpath, isScoped } =
  649. parsePackageName(specifier, base);
  650. // ResolveSelf
  651. const packageConfig = getPackageScopeConfig(base);
  652. if (packageConfig.exists) {
  653. const packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
  654. if (packageConfig.name === packageName &&
  655. packageConfig.exports !== undefined && packageConfig.exports !== null) {
  656. return packageExportsResolve(
  657. packageJSONUrl, packageSubpath, packageConfig, base, conditions
  658. ).resolved;
  659. }
  660. }
  661. let packageJSONUrl =
  662. new URL('./node_modules/' + packageName + '/package.json', base);
  663. let packageJSONPath = fileURLToPath(packageJSONUrl);
  664. let lastPath;
  665. do {
  666. const stat = tryStatSync(StringPrototypeSlice(packageJSONPath, 0,
  667. packageJSONPath.length - 13));
  668. if (!stat.isDirectory()) {
  669. lastPath = packageJSONPath;
  670. packageJSONUrl = new URL((isScoped ?
  671. '../../../../node_modules/' : '../../../node_modules/') +
  672. packageName + '/package.json', packageJSONUrl);
  673. packageJSONPath = fileURLToPath(packageJSONUrl);
  674. continue;
  675. }
  676. // Package match.
  677. const packageConfig = getPackageConfig(packageJSONPath, specifier, base);
  678. if (packageConfig.exports !== undefined && packageConfig.exports !== null)
  679. return packageExportsResolve(
  680. packageJSONUrl, packageSubpath, packageConfig, base, conditions
  681. ).resolved;
  682. if (packageSubpath === '.')
  683. return legacyMainResolve(packageJSONUrl, packageConfig, base);
  684. return new URL(packageSubpath, packageJSONUrl);
  685. // Cross-platform root check.
  686. } while (packageJSONPath.length !== lastPath.length);
  687. // eslint can't handle the above code.
  688. // eslint-disable-next-line no-unreachable
  689. throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base));
  690. }
  691. function isBareSpecifier(specifier) {
  692. return specifier[0] && specifier[0] !== '/' && specifier[0] !== '.';
  693. }
  694. function isRelativeSpecifier(specifier) {
  695. if (specifier[0] === '.') {
  696. if (specifier.length === 1 || specifier[1] === '/') return true;
  697. if (specifier[1] === '.') {
  698. if (specifier.length === 2 || specifier[2] === '/') return true;
  699. }
  700. }
  701. return false;
  702. }
  703. function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
  704. if (specifier === '') return false;
  705. if (specifier[0] === '/') return true;
  706. return isRelativeSpecifier(specifier);
  707. }
  708. /**
  709. * @param {string} specifier
  710. * @param {URL} base
  711. * @param {Set<string>} conditions
  712. * @returns {URL}
  713. */
  714. function moduleResolve(specifier, base, conditions) {
  715. // Order swapped from spec for minor perf gain.
  716. // Ok since relative URLs cannot parse as URLs.
  717. let resolved;
  718. if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
  719. resolved = new URL(specifier, base);
  720. } else if (specifier[0] === '#') {
  721. ({ resolved } = packageImportsResolve(specifier, base, conditions));
  722. } else {
  723. try {
  724. resolved = new URL(specifier);
  725. } catch {
  726. resolved = packageResolve(specifier, base, conditions);
  727. }
  728. }
  729. return finalizeResolution(resolved, base);
  730. }
  731. /**
  732. * Try to resolve an import as a CommonJS module
  733. * @param {string} specifier
  734. * @param {string} parentURL
  735. * @returns {boolean|string}
  736. */
  737. function resolveAsCommonJS(specifier, parentURL) {
  738. try {
  739. const parent = fileURLToPath(parentURL);
  740. const tmpModule = new CJSModule(parent, null);
  741. tmpModule.paths = CJSModule._nodeModulePaths(parent);
  742. let found = CJSModule._resolveFilename(specifier, tmpModule, false);
  743. // If it is a relative specifier return the relative path
  744. // to the parent
  745. if (isRelativeSpecifier(specifier)) {
  746. found = relative(parent, found);
  747. // Add '.separator if the path does not start with '..separator'
  748. // This should be a safe assumption because when loading
  749. // esm modules there should be always a file specified so
  750. // there should not be a specifier like '..' or '.'
  751. if (!StringPrototypeStartsWith(found, `..${sep}`)) {
  752. found = `.${sep}${found}`;
  753. }
  754. } else if (isBareSpecifier(specifier)) {
  755. // If it is a bare specifier return the relative path within the
  756. // module
  757. const pkg = StringPrototypeSplit(specifier, '/')[0];
  758. const index = StringPrototypeIndexOf(found, pkg);
  759. if (index !== -1) {
  760. found = StringPrototypeSlice(found, index);
  761. }
  762. }
  763. // Normalize the path separator to give a valid suggestion
  764. // on Windows
  765. if (process.platform === 'win32') {
  766. found = StringPrototypeReplace(found, new RegExp(`\\${sep}`, 'g'), '/');
  767. }
  768. return found;
  769. } catch {
  770. return false;
  771. }
  772. }
  773. function defaultResolve(specifier, context = {}, defaultResolveUnused) {
  774. let { parentURL, conditions } = context;
  775. if (parentURL && policy != null && policy.manifest) {
  776. const redirects = policy.manifest.getDependencyMapper(parentURL);
  777. if (redirects) {
  778. const { resolve, reaction } = redirects;
  779. const destination = resolve(specifier, new SafeSet(conditions));
  780. let missing = true;
  781. if (destination === true) {
  782. missing = false;
  783. } else if (destination) {
  784. const href = destination.href;
  785. return { url: href };
  786. }
  787. if (missing) {
  788. reaction(new ERR_MANIFEST_DEPENDENCY_MISSING(
  789. parentURL,
  790. specifier,
  791. ArrayPrototypeJoin([...conditions], ', '))
  792. );
  793. }
  794. }
  795. }
  796. let parsed;
  797. try {
  798. parsed = new URL(specifier);
  799. if (parsed.protocol === 'data:') {
  800. return {
  801. url: specifier
  802. };
  803. }
  804. } catch {}
  805. if (parsed && parsed.protocol === builtinModuleProtocol)
  806. return { url: specifier };
  807. if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:')
  808. throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed);
  809. if (NativeModule.canBeRequiredByUsers(specifier)) {
  810. return {
  811. url: builtinModuleProtocol + specifier
  812. };
  813. }
  814. if (parentURL && StringPrototypeStartsWith(parentURL, 'data:')) {
  815. // This is gonna blow up, we want the error
  816. new URL(specifier, parentURL);
  817. }
  818. const isMain = parentURL === undefined;
  819. if (isMain) {
  820. parentURL = pathToFileURL(`${process.cwd()}/`).href;
  821. // This is the initial entry point to the program, and --input-type has
  822. // been passed as an option; but --input-type can only be used with
  823. // --eval, --print or STDIN string input. It is not allowed with file
  824. // input, to avoid user confusion over how expansive the effect of the
  825. // flag should be (i.e. entry point only, package scope surrounding the
  826. // entry point, etc.).
  827. if (typeFlag)
  828. throw new ERR_INPUT_TYPE_NOT_ALLOWED();
  829. }
  830. conditions = getConditionsSet(conditions);
  831. let url;
  832. try {
  833. url = moduleResolve(specifier, parentURL, conditions);
  834. } catch (error) {
  835. // Try to give the user a hint of what would have been the
  836. // resolved CommonJS module
  837. if (error.code === 'ERR_MODULE_NOT_FOUND' ||
  838. error.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
  839. if (StringPrototypeStartsWith(specifier, 'file://')) {
  840. specifier = fileURLToPath(specifier);
  841. }
  842. const found = resolveAsCommonJS(specifier, parentURL);
  843. if (found) {
  844. // Modify the stack and message string to include the hint
  845. const lines = StringPrototypeSplit(error.stack, '\n');
  846. const hint = `Did you mean to import ${found}?`;
  847. error.stack =
  848. ArrayPrototypeShift(lines) + '\n' +
  849. hint + '\n' +
  850. ArrayPrototypeJoin(lines, '\n');
  851. error.message += `\n${hint}`;
  852. }
  853. }
  854. throw error;
  855. }
  856. if (isMain ? !preserveSymlinksMain : !preserveSymlinks) {
  857. const urlPath = fileURLToPath(url);
  858. const real = realpathSync(urlPath, {
  859. // [internalFS.realpathCacheKey]: realpathCache
  860. });
  861. const old = url;
  862. url = pathToFileURL(
  863. real + (StringPrototypeEndsWith(urlPath, sep) ? '/' : ''));
  864. url.search = old.search;
  865. url.hash = old.hash;
  866. }
  867. return { url: `${url}` };
  868. }
  869. return {
  870. DEFAULT_CONDITIONS,
  871. defaultResolve,
  872. encodedSepRegEx,
  873. getPackageType,
  874. packageExportsResolve,
  875. packageImportsResolve
  876. };
  877. }
  878. module.exports = {
  879. createResolve
  880. };