版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2252 lines
61 KiB

  1. 'use strict';
  2. const acorn = require('acorn');
  3. const node_module = require('node:module');
  4. const fs = require('node:fs');
  5. const node_url = require('node:url');
  6. const ufo = require('ufo');
  7. const pathe = require('pathe');
  8. const assert = require('node:assert');
  9. const process$1 = require('node:process');
  10. const path = require('node:path');
  11. const v8 = require('node:v8');
  12. const node_util = require('node:util');
  13. const pkgTypes = require('pkg-types');
  14. const BUILTIN_MODULES = new Set(node_module.builtinModules);
  15. function normalizeSlash(string_) {
  16. return string_.replace(/\\/g, "/");
  17. }
  18. function pcall(function_, ...arguments_) {
  19. try {
  20. return Promise.resolve(function_(...arguments_)).catch(
  21. (error) => perr(error)
  22. );
  23. } catch (error) {
  24. return perr(error);
  25. }
  26. }
  27. function perr(_error) {
  28. const error = new Error(_error);
  29. error.code = _error.code;
  30. Error.captureStackTrace(error, pcall);
  31. return Promise.reject(error);
  32. }
  33. function isObject(value) {
  34. return value !== null && typeof value === "object";
  35. }
  36. function matchAll(regex, string, addition) {
  37. const matches = [];
  38. for (const match of string.matchAll(regex)) {
  39. matches.push({
  40. ...addition,
  41. ...match.groups,
  42. code: match[0],
  43. start: match.index,
  44. end: match.index + match[0].length
  45. });
  46. }
  47. return matches;
  48. }
  49. /**
  50. * @typedef ErrnoExceptionFields
  51. * @property {number | undefined} [errnode]
  52. * @property {string | undefined} [code]
  53. * @property {string | undefined} [path]
  54. * @property {string | undefined} [syscall]
  55. * @property {string | undefined} [url]
  56. *
  57. * @typedef {Error & ErrnoExceptionFields} ErrnoException
  58. */
  59. const isWindows = process$1.platform === 'win32';
  60. const own$1 = {}.hasOwnProperty;
  61. const codes = {};
  62. /**
  63. * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
  64. * We cannot use Intl.ListFormat because it's not available in
  65. * --without-intl builds.
  66. *
  67. * @param {Array<string>} array
  68. * An array of strings.
  69. * @param {string} [type]
  70. * The list type to be inserted before the last element.
  71. * @returns {string}
  72. */
  73. function formatList(array, type = 'and') {
  74. return array.length < 3
  75. ? array.join(` ${type} `)
  76. : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
  77. }
  78. /** @type {Map<string, MessageFunction|string>} */
  79. const messages = new Map();
  80. const nodeInternalPrefix = '__node_internal_';
  81. /** @type {number} */
  82. let userStackTraceLimit;
  83. codes.ERR_INVALID_MODULE_SPECIFIER = createError(
  84. 'ERR_INVALID_MODULE_SPECIFIER',
  85. /**
  86. * @param {string} request
  87. * @param {string} reason
  88. * @param {string} [base]
  89. */
  90. (request, reason, base = undefined) => {
  91. return `Invalid module "${request}" ${reason}${
  92. base ? ` imported from ${base}` : ''
  93. }`
  94. },
  95. TypeError
  96. );
  97. codes.ERR_INVALID_PACKAGE_CONFIG = createError(
  98. 'ERR_INVALID_PACKAGE_CONFIG',
  99. /**
  100. * @param {string} path
  101. * @param {string} [base]
  102. * @param {string} [message]
  103. */
  104. (path, base, message) => {
  105. return `Invalid package config ${path}${
  106. base ? ` while importing ${base}` : ''
  107. }${message ? `. ${message}` : ''}`
  108. },
  109. Error
  110. );
  111. codes.ERR_INVALID_PACKAGE_TARGET = createError(
  112. 'ERR_INVALID_PACKAGE_TARGET',
  113. /**
  114. * @param {string} pkgPath
  115. * @param {string} key
  116. * @param {unknown} target
  117. * @param {boolean} [isImport=false]
  118. * @param {string} [base]
  119. */
  120. (pkgPath, key, target, isImport = false, base = undefined) => {
  121. const relError =
  122. typeof target === 'string' &&
  123. !isImport &&
  124. target.length > 0 &&
  125. !target.startsWith('./');
  126. if (key === '.') {
  127. assert(isImport === false);
  128. return (
  129. `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
  130. `in the package config ${pkgPath}package.json${
  131. base ? ` imported from ${base}` : ''
  132. }${relError ? '; targets must start with "./"' : ''}`
  133. )
  134. }
  135. return `Invalid "${
  136. isImport ? 'imports' : 'exports'
  137. }" target ${JSON.stringify(
  138. target
  139. )} defined for '${key}' in the package config ${pkgPath}package.json${
  140. base ? ` imported from ${base}` : ''
  141. }${relError ? '; targets must start with "./"' : ''}`
  142. },
  143. Error
  144. );
  145. codes.ERR_MODULE_NOT_FOUND = createError(
  146. 'ERR_MODULE_NOT_FOUND',
  147. /**
  148. * @param {string} path
  149. * @param {string} base
  150. * @param {string} [type]
  151. */
  152. (path, base, type = 'package') => {
  153. return `Cannot find ${type} '${path}' imported from ${base}`
  154. },
  155. Error
  156. );
  157. codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
  158. 'ERR_NETWORK_IMPORT_DISALLOWED',
  159. "import of '%s' by %s is not supported: %s",
  160. Error
  161. );
  162. codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
  163. 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
  164. /**
  165. * @param {string} specifier
  166. * @param {string} packagePath
  167. * @param {string} base
  168. */
  169. (specifier, packagePath, base) => {
  170. return `Package import specifier "${specifier}" is not defined${
  171. packagePath ? ` in package ${packagePath}package.json` : ''
  172. } imported from ${base}`
  173. },
  174. TypeError
  175. );
  176. codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
  177. 'ERR_PACKAGE_PATH_NOT_EXPORTED',
  178. /**
  179. * @param {string} pkgPath
  180. * @param {string} subpath
  181. * @param {string} [base]
  182. */
  183. (pkgPath, subpath, base = undefined) => {
  184. if (subpath === '.')
  185. return `No "exports" main defined in ${pkgPath}package.json${
  186. base ? ` imported from ${base}` : ''
  187. }`
  188. return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${
  189. base ? ` imported from ${base}` : ''
  190. }`
  191. },
  192. Error
  193. );
  194. codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
  195. 'ERR_UNSUPPORTED_DIR_IMPORT',
  196. "Directory import '%s' is not supported " +
  197. 'resolving ES modules imported from %s',
  198. Error
  199. );
  200. codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
  201. 'ERR_UNKNOWN_FILE_EXTENSION',
  202. /**
  203. * @param {string} ext
  204. * @param {string} path
  205. */
  206. (ext, path) => {
  207. return `Unknown file extension "${ext}" for ${path}`
  208. },
  209. TypeError
  210. );
  211. codes.ERR_INVALID_ARG_VALUE = createError(
  212. 'ERR_INVALID_ARG_VALUE',
  213. /**
  214. * @param {string} name
  215. * @param {unknown} value
  216. * @param {string} [reason='is invalid']
  217. */
  218. (name, value, reason = 'is invalid') => {
  219. let inspected = node_util.inspect(value);
  220. if (inspected.length > 128) {
  221. inspected = `${inspected.slice(0, 128)}...`;
  222. }
  223. const type = name.includes('.') ? 'property' : 'argument';
  224. return `The ${type} '${name}' ${reason}. Received ${inspected}`
  225. },
  226. TypeError
  227. // Note: extra classes have been shaken out.
  228. // , RangeError
  229. );
  230. codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError(
  231. 'ERR_UNSUPPORTED_ESM_URL_SCHEME',
  232. /**
  233. * @param {URL} url
  234. * @param {Array<string>} supported
  235. */
  236. (url, supported) => {
  237. let message = `Only URLs with a scheme in: ${formatList(
  238. supported
  239. )} are supported by the default ESM loader`;
  240. if (isWindows && url.protocol.length === 2) {
  241. message += '. On Windows, absolute paths must be valid file:// URLs';
  242. }
  243. message += `. Received protocol '${url.protocol}'`;
  244. return message
  245. },
  246. Error
  247. );
  248. /**
  249. * Utility function for registering the error codes. Only used here. Exported
  250. * *only* to allow for testing.
  251. * @param {string} sym
  252. * @param {MessageFunction|string} value
  253. * @param {ErrorConstructor} def
  254. * @returns {new (...args: Array<any>) => Error}
  255. */
  256. function createError(sym, value, def) {
  257. // Special case for SystemError that formats the error message differently
  258. // The SystemErrors only have SystemError as their base classes.
  259. messages.set(sym, value);
  260. return makeNodeErrorWithCode(def, sym)
  261. }
  262. /**
  263. * @param {ErrorConstructor} Base
  264. * @param {string} key
  265. * @returns {ErrorConstructor}
  266. */
  267. function makeNodeErrorWithCode(Base, key) {
  268. // @ts-expect-error It’s a Node error.
  269. return NodeError
  270. /**
  271. * @param {Array<unknown>} args
  272. */
  273. function NodeError(...args) {
  274. const limit = Error.stackTraceLimit;
  275. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  276. const error = new Base();
  277. // Reset the limit and setting the name property.
  278. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  279. const message = getMessage(key, args, error);
  280. Object.defineProperties(error, {
  281. // Note: no need to implement `kIsNodeError` symbol, would be hard,
  282. // probably.
  283. message: {
  284. value: message,
  285. enumerable: false,
  286. writable: true,
  287. configurable: true
  288. },
  289. toString: {
  290. /** @this {Error} */
  291. value() {
  292. return `${this.name} [${key}]: ${this.message}`
  293. },
  294. enumerable: false,
  295. writable: true,
  296. configurable: true
  297. }
  298. });
  299. captureLargerStackTrace(error);
  300. // @ts-expect-error It’s a Node error.
  301. error.code = key;
  302. return error
  303. }
  304. }
  305. /**
  306. * @returns {boolean}
  307. */
  308. function isErrorStackTraceLimitWritable() {
  309. // Do no touch Error.stackTraceLimit as V8 would attempt to install
  310. // it again during deserialization.
  311. try {
  312. // @ts-expect-error: not in types?
  313. if (v8.startupSnapshot.isBuildingSnapshot()) {
  314. return false
  315. }
  316. } catch {}
  317. const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
  318. if (desc === undefined) {
  319. return Object.isExtensible(Error)
  320. }
  321. return own$1.call(desc, 'writable') && desc.writable !== undefined
  322. ? desc.writable
  323. : desc.set !== undefined
  324. }
  325. /**
  326. * This function removes unnecessary frames from Node.js core errors.
  327. * @template {(...args: unknown[]) => unknown} T
  328. * @param {T} fn
  329. * @returns {T}
  330. */
  331. function hideStackFrames(fn) {
  332. // We rename the functions that will be hidden to cut off the stacktrace
  333. // at the outermost one
  334. const hidden = nodeInternalPrefix + fn.name;
  335. Object.defineProperty(fn, 'name', {value: hidden});
  336. return fn
  337. }
  338. const captureLargerStackTrace = hideStackFrames(
  339. /**
  340. * @param {Error} error
  341. * @returns {Error}
  342. */
  343. // @ts-expect-error: fine
  344. function (error) {
  345. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  346. if (stackTraceLimitIsWritable) {
  347. userStackTraceLimit = Error.stackTraceLimit;
  348. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  349. }
  350. Error.captureStackTrace(error);
  351. // Reset the limit
  352. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  353. return error
  354. }
  355. );
  356. /**
  357. * @param {string} key
  358. * @param {Array<unknown>} args
  359. * @param {Error} self
  360. * @returns {string}
  361. */
  362. function getMessage(key, args, self) {
  363. const message = messages.get(key);
  364. assert(typeof message !== 'undefined', 'expected `message` to be found');
  365. if (typeof message === 'function') {
  366. assert(
  367. message.length <= args.length, // Default options do not count.
  368. `Code: ${key}; The provided arguments length (${args.length}) does not ` +
  369. `match the required ones (${message.length}).`
  370. );
  371. return Reflect.apply(message, self, args)
  372. }
  373. const regex = /%[dfijoOs]/g;
  374. let expectedLength = 0;
  375. while (regex.exec(message) !== null) expectedLength++;
  376. assert(
  377. expectedLength === args.length,
  378. `Code: ${key}; The provided arguments length (${args.length}) does not ` +
  379. `match the required ones (${expectedLength}).`
  380. );
  381. if (args.length === 0) return message
  382. args.unshift(message);
  383. return Reflect.apply(node_util.format, null, args)
  384. }
  385. // Manually “tree shaken” from:
  386. const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
  387. const hasOwnProperty = {}.hasOwnProperty;
  388. /** @type {Record<string, string>} */
  389. const extensionFormatMap = {
  390. // @ts-expect-error: hush.
  391. __proto__: null,
  392. '.cjs': 'commonjs',
  393. '.js': 'module',
  394. '.json': 'json',
  395. '.mjs': 'module'
  396. };
  397. /**
  398. * @param {string|null} mime
  399. * @returns {string | null}
  400. */
  401. function mimeToFormat(mime) {
  402. if (
  403. mime &&
  404. /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
  405. )
  406. return 'module'
  407. if (mime === 'application/json') return 'json'
  408. return null
  409. }
  410. /**
  411. * @callback ProtocolHandler
  412. * @param {URL} parsed
  413. * @param {{parentURL: string}} context
  414. * @param {boolean} ignoreErrors
  415. * @returns {string|null|void}
  416. */
  417. /**
  418. * @type {Record<string, ProtocolHandler>}
  419. */
  420. const protocolHandlers = {
  421. // @ts-expect-error: hush.
  422. __proto__: null,
  423. 'data:': getDataProtocolModuleFormat,
  424. 'file:': getFileProtocolModuleFormat,
  425. 'http:': getHttpProtocolModuleFormat,
  426. 'https:': getHttpProtocolModuleFormat,
  427. 'node:'() {
  428. return 'builtin'
  429. }
  430. };
  431. /**
  432. * @param {URL} parsed
  433. */
  434. function getDataProtocolModuleFormat(parsed) {
  435. const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
  436. parsed.pathname
  437. ) || [null, null, null];
  438. return mimeToFormat(mime)
  439. }
  440. /**
  441. * @type {ProtocolHandler}
  442. */
  443. function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
  444. const filepath = node_url.fileURLToPath(url);
  445. const ext = path.extname(filepath);
  446. if (ext === '.js') {
  447. return getPackageType(url) === 'module' ? 'module' : 'commonjs'
  448. }
  449. const format = extensionFormatMap[ext];
  450. if (format) return format
  451. // Explicit undefined return indicates load hook should rerun format check
  452. if (ignoreErrors) {
  453. return undefined
  454. }
  455. throw new ERR_UNKNOWN_FILE_EXTENSION(ext, filepath)
  456. }
  457. function getHttpProtocolModuleFormat() {
  458. // To do: HTTPS imports.
  459. }
  460. /**
  461. * @param {URL} url
  462. * @param {{parentURL: string}} context
  463. * @returns {string|null}
  464. */
  465. function defaultGetFormatWithoutErrors(url, context) {
  466. if (!hasOwnProperty.call(protocolHandlers, url.protocol)) {
  467. return null
  468. }
  469. return protocolHandlers[url.protocol](url, context, true) || null
  470. }
  471. // Manually “tree shaken” from:
  472. const reader = {read};
  473. const packageJsonReader = reader;
  474. /**
  475. * @param {string} jsonPath
  476. * @returns {{string: string|undefined}}
  477. */
  478. function read(jsonPath) {
  479. try {
  480. const string = fs.readFileSync(
  481. path.toNamespacedPath(path.join(path.dirname(jsonPath), 'package.json')),
  482. 'utf8'
  483. );
  484. return {string}
  485. } catch (error) {
  486. const exception = /** @type {ErrnoException} */ (error);
  487. if (exception.code === 'ENOENT') {
  488. return {string: undefined}
  489. // Throw all other errors.
  490. /* c8 ignore next 4 */
  491. }
  492. throw exception
  493. }
  494. }
  495. // Manually “tree shaken” from:
  496. const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;
  497. /** @type {Map<string, PackageConfig>} */
  498. const packageJsonCache = new Map();
  499. /**
  500. * @param {string} path
  501. * @param {string|URL} specifier Note: `specifier` is actually optional, not base.
  502. * @param {URL} [base]
  503. * @returns {PackageConfig}
  504. */
  505. function getPackageConfig(path, specifier, base) {
  506. const existing = packageJsonCache.get(path);
  507. if (existing !== undefined) {
  508. return existing
  509. }
  510. const source = packageJsonReader.read(path).string;
  511. if (source === undefined) {
  512. /** @type {PackageConfig} */
  513. const packageConfig = {
  514. pjsonPath: path,
  515. exists: false,
  516. main: undefined,
  517. name: undefined,
  518. type: 'none',
  519. exports: undefined,
  520. imports: undefined
  521. };
  522. packageJsonCache.set(path, packageConfig);
  523. return packageConfig
  524. }
  525. /** @type {Record<string, unknown>} */
  526. let packageJson;
  527. try {
  528. packageJson = JSON.parse(source);
  529. } catch (error) {
  530. const exception = /** @type {ErrnoException} */ (error);
  531. throw new ERR_INVALID_PACKAGE_CONFIG$1(
  532. path,
  533. (base ? `"${specifier}" from ` : '') + node_url.fileURLToPath(base || specifier),
  534. exception.message
  535. )
  536. }
  537. const {exports, imports, main, name, type} = packageJson;
  538. /** @type {PackageConfig} */
  539. const packageConfig = {
  540. pjsonPath: path,
  541. exists: true,
  542. main: typeof main === 'string' ? main : undefined,
  543. name: typeof name === 'string' ? name : undefined,
  544. type: type === 'module' || type === 'commonjs' ? type : 'none',
  545. // @ts-expect-error Assume `Record<string, unknown>`.
  546. exports,
  547. // @ts-expect-error Assume `Record<string, unknown>`.
  548. imports: imports && typeof imports === 'object' ? imports : undefined
  549. };
  550. packageJsonCache.set(path, packageConfig);
  551. return packageConfig
  552. }
  553. /**
  554. * @param {URL} resolved
  555. * @returns {PackageConfig}
  556. */
  557. function getPackageScopeConfig(resolved) {
  558. let packageJsonUrl = new node_url.URL('package.json', resolved);
  559. while (true) {
  560. const packageJsonPath = packageJsonUrl.pathname;
  561. if (packageJsonPath.endsWith('node_modules/package.json')) break
  562. const packageConfig = getPackageConfig(
  563. node_url.fileURLToPath(packageJsonUrl),
  564. resolved
  565. );
  566. if (packageConfig.exists) return packageConfig
  567. const lastPackageJsonUrl = packageJsonUrl;
  568. packageJsonUrl = new node_url.URL('../package.json', packageJsonUrl);
  569. // Terminates at root where ../package.json equals ../../package.json
  570. // (can't just check "/package.json" for Windows support).
  571. if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) break
  572. }
  573. const packageJsonPath = node_url.fileURLToPath(packageJsonUrl);
  574. /** @type {PackageConfig} */
  575. const packageConfig = {
  576. pjsonPath: packageJsonPath,
  577. exists: false,
  578. main: undefined,
  579. name: undefined,
  580. type: 'none',
  581. exports: undefined,
  582. imports: undefined
  583. };
  584. packageJsonCache.set(packageJsonPath, packageConfig);
  585. return packageConfig
  586. }
  587. // Manually “tree shaken” from:
  588. const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
  589. const {
  590. ERR_NETWORK_IMPORT_DISALLOWED,
  591. ERR_INVALID_MODULE_SPECIFIER,
  592. ERR_INVALID_PACKAGE_CONFIG,
  593. ERR_INVALID_PACKAGE_TARGET,
  594. ERR_MODULE_NOT_FOUND,
  595. ERR_PACKAGE_IMPORT_NOT_DEFINED,
  596. ERR_PACKAGE_PATH_NOT_EXPORTED,
  597. ERR_UNSUPPORTED_DIR_IMPORT,
  598. ERR_UNSUPPORTED_ESM_URL_SCHEME
  599. } = codes;
  600. const own = {}.hasOwnProperty;
  601. const invalidSegmentRegEx =
  602. /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
  603. const deprecatedInvalidSegmentRegEx =
  604. /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
  605. const invalidPackageNameRegEx = /^\.|%|\\/;
  606. const patternRegEx = /\*/g;
  607. const encodedSepRegEx = /%2f|%5c/i;
  608. /** @type {Set<string>} */
  609. const emittedPackageWarnings = new Set();
  610. const doubleSlashRegEx = /[/\\]{2}/;
  611. /**
  612. *
  613. * @param {string} target
  614. * @param {string} request
  615. * @param {string} match
  616. * @param {URL} packageJsonUrl
  617. * @param {boolean} internal
  618. * @param {URL} base
  619. * @param {boolean} isTarget
  620. */
  621. function emitInvalidSegmentDeprecation(
  622. target,
  623. request,
  624. match,
  625. packageJsonUrl,
  626. internal,
  627. base,
  628. isTarget
  629. ) {
  630. const pjsonPath = node_url.fileURLToPath(packageJsonUrl);
  631. const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
  632. process$1.emitWarning(
  633. `Use of deprecated ${
  634. double ? 'double slash' : 'leading or trailing slash matching'
  635. } resolving "${target}" for module ` +
  636. `request "${request}" ${
  637. request === match ? '' : `matched to "${match}" `
  638. }in the "${
  639. internal ? 'imports' : 'exports'
  640. }" field module resolution of the package at ${pjsonPath}${
  641. base ? ` imported from ${node_url.fileURLToPath(base)}` : ''
  642. }.`,
  643. 'DeprecationWarning',
  644. 'DEP0166'
  645. );
  646. }
  647. /**
  648. * @param {URL} url
  649. * @param {URL} packageJsonUrl
  650. * @param {URL} base
  651. * @param {unknown} [main]
  652. * @returns {void}
  653. */
  654. function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
  655. const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
  656. if (format !== 'module') return
  657. const path = node_url.fileURLToPath(url.href);
  658. const pkgPath = node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl));
  659. const basePath = node_url.fileURLToPath(base);
  660. if (main)
  661. process$1.emitWarning(
  662. `Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, ` +
  663. `excluding the full filename and extension to the resolved file at "${path.slice(
  664. pkgPath.length
  665. )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is` +
  666. 'deprecated for ES modules.',
  667. 'DeprecationWarning',
  668. 'DEP0151'
  669. );
  670. else
  671. process$1.emitWarning(
  672. `No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path.slice(
  673. pkgPath.length
  674. )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
  675. 'DeprecationWarning',
  676. 'DEP0151'
  677. );
  678. }
  679. /**
  680. * @param {string} path
  681. * @returns {Stats}
  682. */
  683. function tryStatSync(path) {
  684. // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
  685. try {
  686. return fs.statSync(path)
  687. } catch {
  688. return new fs.Stats()
  689. }
  690. }
  691. /**
  692. * Legacy CommonJS main resolution:
  693. * 1. let M = pkg_url + (json main field)
  694. * 2. TRY(M, M.js, M.json, M.node)
  695. * 3. TRY(M/index.js, M/index.json, M/index.node)
  696. * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
  697. * 5. NOT_FOUND
  698. *
  699. * @param {URL} url
  700. * @returns {boolean}
  701. */
  702. function fileExists(url) {
  703. const stats = fs.statSync(url, {throwIfNoEntry: false});
  704. const isFile = stats ? stats.isFile() : undefined;
  705. return isFile === null || isFile === undefined ? false : isFile
  706. }
  707. /**
  708. * @param {URL} packageJsonUrl
  709. * @param {PackageConfig} packageConfig
  710. * @param {URL} base
  711. * @returns {URL}
  712. */
  713. function legacyMainResolve(packageJsonUrl, packageConfig, base) {
  714. /** @type {URL|undefined} */
  715. let guess;
  716. if (packageConfig.main !== undefined) {
  717. guess = new node_url.URL(packageConfig.main, packageJsonUrl);
  718. // Note: fs check redundances will be handled by Descriptor cache here.
  719. if (fileExists(guess)) return guess
  720. const tries = [
  721. `./${packageConfig.main}.js`,
  722. `./${packageConfig.main}.json`,
  723. `./${packageConfig.main}.node`,
  724. `./${packageConfig.main}/index.js`,
  725. `./${packageConfig.main}/index.json`,
  726. `./${packageConfig.main}/index.node`
  727. ];
  728. let i = -1;
  729. while (++i < tries.length) {
  730. guess = new node_url.URL(tries[i], packageJsonUrl);
  731. if (fileExists(guess)) break
  732. guess = undefined;
  733. }
  734. if (guess) {
  735. emitLegacyIndexDeprecation(
  736. guess,
  737. packageJsonUrl,
  738. base,
  739. packageConfig.main
  740. );
  741. return guess
  742. }
  743. // Fallthrough.
  744. }
  745. const tries = ['./index.js', './index.json', './index.node'];
  746. let i = -1;
  747. while (++i < tries.length) {
  748. guess = new node_url.URL(tries[i], packageJsonUrl);
  749. if (fileExists(guess)) break
  750. guess = undefined;
  751. }
  752. if (guess) {
  753. emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
  754. return guess
  755. }
  756. // Not found.
  757. throw new ERR_MODULE_NOT_FOUND(
  758. node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)),
  759. node_url.fileURLToPath(base)
  760. )
  761. }
  762. /**
  763. * @param {URL} resolved
  764. * @param {URL} base
  765. * @param {boolean} [preserveSymlinks]
  766. * @returns {URL}
  767. */
  768. function finalizeResolution(resolved, base, preserveSymlinks) {
  769. if (encodedSepRegEx.exec(resolved.pathname) !== null)
  770. throw new ERR_INVALID_MODULE_SPECIFIER(
  771. resolved.pathname,
  772. 'must not include encoded "/" or "\\" characters',
  773. node_url.fileURLToPath(base)
  774. )
  775. const filePath = node_url.fileURLToPath(resolved);
  776. const stats = tryStatSync(
  777. filePath.endsWith('/') ? filePath.slice(-1) : filePath
  778. );
  779. if (stats.isDirectory()) {
  780. const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, node_url.fileURLToPath(base));
  781. // @ts-expect-error Add this for `import.meta.resolve`.
  782. error.url = String(resolved);
  783. throw error
  784. }
  785. if (!stats.isFile()) {
  786. throw new ERR_MODULE_NOT_FOUND(
  787. filePath || resolved.pathname,
  788. base && node_url.fileURLToPath(base),
  789. 'module'
  790. )
  791. }
  792. if (!preserveSymlinks) {
  793. const real = fs.realpathSync(filePath);
  794. const {search, hash} = resolved;
  795. resolved = node_url.pathToFileURL(real + (filePath.endsWith(path.sep) ? '/' : ''));
  796. resolved.search = search;
  797. resolved.hash = hash;
  798. }
  799. return resolved
  800. }
  801. /**
  802. * @param {string} specifier
  803. * @param {URL|undefined} packageJsonUrl
  804. * @param {URL} base
  805. * @returns {Error}
  806. */
  807. function importNotDefined(specifier, packageJsonUrl, base) {
  808. return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
  809. specifier,
  810. packageJsonUrl && node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)),
  811. node_url.fileURLToPath(base)
  812. )
  813. }
  814. /**
  815. * @param {string} subpath
  816. * @param {URL} packageJsonUrl
  817. * @param {URL} base
  818. * @returns {Error}
  819. */
  820. function exportsNotFound(subpath, packageJsonUrl, base) {
  821. return new ERR_PACKAGE_PATH_NOT_EXPORTED(
  822. node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)),
  823. subpath,
  824. base && node_url.fileURLToPath(base)
  825. )
  826. }
  827. /**
  828. * @param {string} request
  829. * @param {string} match
  830. * @param {URL} packageJsonUrl
  831. * @param {boolean} internal
  832. * @param {URL} [base]
  833. * @returns {never}
  834. */
  835. function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
  836. const reason = `request is not a valid match in pattern "${match}" for the "${
  837. internal ? 'imports' : 'exports'
  838. }" resolution of ${node_url.fileURLToPath(packageJsonUrl)}`;
  839. throw new ERR_INVALID_MODULE_SPECIFIER(
  840. request,
  841. reason,
  842. base && node_url.fileURLToPath(base)
  843. )
  844. }
  845. /**
  846. * @param {string} subpath
  847. * @param {unknown} target
  848. * @param {URL} packageJsonUrl
  849. * @param {boolean} internal
  850. * @param {URL} [base]
  851. * @returns {Error}
  852. */
  853. function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
  854. target =
  855. typeof target === 'object' && target !== null
  856. ? JSON.stringify(target, null, '')
  857. : `${target}`;
  858. return new ERR_INVALID_PACKAGE_TARGET(
  859. node_url.fileURLToPath(new node_url.URL('.', packageJsonUrl)),
  860. subpath,
  861. target,
  862. internal,
  863. base && node_url.fileURLToPath(base)
  864. )
  865. }
  866. /**
  867. * @param {string} target
  868. * @param {string} subpath
  869. * @param {string} match
  870. * @param {URL} packageJsonUrl
  871. * @param {URL} base
  872. * @param {boolean} pattern
  873. * @param {boolean} internal
  874. * @param {boolean} isPathMap
  875. * @param {Set<string>|undefined} conditions
  876. * @returns {URL}
  877. */
  878. function resolvePackageTargetString(
  879. target,
  880. subpath,
  881. match,
  882. packageJsonUrl,
  883. base,
  884. pattern,
  885. internal,
  886. isPathMap,
  887. conditions
  888. ) {
  889. if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
  890. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  891. if (!target.startsWith('./')) {
  892. if (internal && !target.startsWith('../') && !target.startsWith('/')) {
  893. let isURL = false;
  894. try {
  895. new node_url.URL(target);
  896. isURL = true;
  897. } catch {
  898. // Continue regardless of error.
  899. }
  900. if (!isURL) {
  901. const exportTarget = pattern
  902. ? RegExpPrototypeSymbolReplace.call(
  903. patternRegEx,
  904. target,
  905. () => subpath
  906. )
  907. : target + subpath;
  908. return packageResolve(exportTarget, packageJsonUrl, conditions)
  909. }
  910. }
  911. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  912. }
  913. if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
  914. if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
  915. if (!isPathMap) {
  916. const request = pattern
  917. ? match.replace('*', () => subpath)
  918. : match + subpath;
  919. const resolvedTarget = pattern
  920. ? RegExpPrototypeSymbolReplace.call(
  921. patternRegEx,
  922. target,
  923. () => subpath
  924. )
  925. : target;
  926. emitInvalidSegmentDeprecation(
  927. resolvedTarget,
  928. request,
  929. match,
  930. packageJsonUrl,
  931. internal,
  932. base,
  933. true
  934. );
  935. }
  936. } else {
  937. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  938. }
  939. }
  940. const resolved = new node_url.URL(target, packageJsonUrl);
  941. const resolvedPath = resolved.pathname;
  942. const packagePath = new node_url.URL('.', packageJsonUrl).pathname;
  943. if (!resolvedPath.startsWith(packagePath))
  944. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  945. if (subpath === '') return resolved
  946. if (invalidSegmentRegEx.exec(subpath) !== null) {
  947. const request = pattern
  948. ? match.replace('*', () => subpath)
  949. : match + subpath;
  950. if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
  951. if (!isPathMap) {
  952. const resolvedTarget = pattern
  953. ? RegExpPrototypeSymbolReplace.call(
  954. patternRegEx,
  955. target,
  956. () => subpath
  957. )
  958. : target;
  959. emitInvalidSegmentDeprecation(
  960. resolvedTarget,
  961. request,
  962. match,
  963. packageJsonUrl,
  964. internal,
  965. base,
  966. false
  967. );
  968. }
  969. } else {
  970. throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
  971. }
  972. }
  973. if (pattern) {
  974. return new node_url.URL(
  975. RegExpPrototypeSymbolReplace.call(
  976. patternRegEx,
  977. resolved.href,
  978. () => subpath
  979. )
  980. )
  981. }
  982. return new node_url.URL(subpath, resolved)
  983. }
  984. /**
  985. * @param {string} key
  986. * @returns {boolean}
  987. */
  988. function isArrayIndex(key) {
  989. const keyNumber = Number(key);
  990. if (`${keyNumber}` !== key) return false
  991. return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
  992. }
  993. /**
  994. * @param {URL} packageJsonUrl
  995. * @param {unknown} target
  996. * @param {string} subpath
  997. * @param {string} packageSubpath
  998. * @param {URL} base
  999. * @param {boolean} pattern
  1000. * @param {boolean} internal
  1001. * @param {boolean} isPathMap
  1002. * @param {Set<string>|undefined} conditions
  1003. * @returns {URL|null}
  1004. */
  1005. function resolvePackageTarget(
  1006. packageJsonUrl,
  1007. target,
  1008. subpath,
  1009. packageSubpath,
  1010. base,
  1011. pattern,
  1012. internal,
  1013. isPathMap,
  1014. conditions
  1015. ) {
  1016. if (typeof target === 'string') {
  1017. return resolvePackageTargetString(
  1018. target,
  1019. subpath,
  1020. packageSubpath,
  1021. packageJsonUrl,
  1022. base,
  1023. pattern,
  1024. internal,
  1025. isPathMap,
  1026. conditions
  1027. )
  1028. }
  1029. if (Array.isArray(target)) {
  1030. /** @type {Array<unknown>} */
  1031. const targetList = target;
  1032. if (targetList.length === 0) return null
  1033. /** @type {ErrnoException|null|undefined} */
  1034. let lastException;
  1035. let i = -1;
  1036. while (++i < targetList.length) {
  1037. const targetItem = targetList[i];
  1038. /** @type {URL|null} */
  1039. let resolveResult;
  1040. try {
  1041. resolveResult = resolvePackageTarget(
  1042. packageJsonUrl,
  1043. targetItem,
  1044. subpath,
  1045. packageSubpath,
  1046. base,
  1047. pattern,
  1048. internal,
  1049. isPathMap,
  1050. conditions
  1051. );
  1052. } catch (error) {
  1053. const exception = /** @type {ErrnoException} */ (error);
  1054. lastException = exception;
  1055. if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
  1056. throw error
  1057. }
  1058. if (resolveResult === undefined) continue
  1059. if (resolveResult === null) {
  1060. lastException = null;
  1061. continue
  1062. }
  1063. return resolveResult
  1064. }
  1065. if (lastException === undefined || lastException === null) {
  1066. return null
  1067. }
  1068. throw lastException
  1069. }
  1070. if (typeof target === 'object' && target !== null) {
  1071. const keys = Object.getOwnPropertyNames(target);
  1072. let i = -1;
  1073. while (++i < keys.length) {
  1074. const key = keys[i];
  1075. if (isArrayIndex(key)) {
  1076. throw new ERR_INVALID_PACKAGE_CONFIG(
  1077. node_url.fileURLToPath(packageJsonUrl),
  1078. base,
  1079. '"exports" cannot contain numeric property keys.'
  1080. )
  1081. }
  1082. }
  1083. i = -1;
  1084. while (++i < keys.length) {
  1085. const key = keys[i];
  1086. if (key === 'default' || (conditions && conditions.has(key))) {
  1087. // @ts-expect-error: indexable.
  1088. const conditionalTarget = /** @type {unknown} */ (target[key]);
  1089. const resolveResult = resolvePackageTarget(
  1090. packageJsonUrl,
  1091. conditionalTarget,
  1092. subpath,
  1093. packageSubpath,
  1094. base,
  1095. pattern,
  1096. internal,
  1097. isPathMap,
  1098. conditions
  1099. );
  1100. if (resolveResult === undefined) continue
  1101. return resolveResult
  1102. }
  1103. }
  1104. return null
  1105. }
  1106. if (target === null) {
  1107. return null
  1108. }
  1109. throw invalidPackageTarget(
  1110. packageSubpath,
  1111. target,
  1112. packageJsonUrl,
  1113. internal,
  1114. base
  1115. )
  1116. }
  1117. /**
  1118. * @param {unknown} exports
  1119. * @param {URL} packageJsonUrl
  1120. * @param {URL} base
  1121. * @returns {boolean}
  1122. */
  1123. function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
  1124. if (typeof exports === 'string' || Array.isArray(exports)) return true
  1125. if (typeof exports !== 'object' || exports === null) return false
  1126. const keys = Object.getOwnPropertyNames(exports);
  1127. let isConditionalSugar = false;
  1128. let i = 0;
  1129. let j = -1;
  1130. while (++j < keys.length) {
  1131. const key = keys[j];
  1132. const curIsConditionalSugar = key === '' || key[0] !== '.';
  1133. if (i++ === 0) {
  1134. isConditionalSugar = curIsConditionalSugar;
  1135. } else if (isConditionalSugar !== curIsConditionalSugar) {
  1136. throw new ERR_INVALID_PACKAGE_CONFIG(
  1137. node_url.fileURLToPath(packageJsonUrl),
  1138. base,
  1139. '"exports" cannot contain some keys starting with \'.\' and some not.' +
  1140. ' The exports object must either be an object of package subpath keys' +
  1141. ' or an object of main entry condition name keys only.'
  1142. )
  1143. }
  1144. }
  1145. return isConditionalSugar
  1146. }
  1147. /**
  1148. * @param {string} match
  1149. * @param {URL} pjsonUrl
  1150. * @param {URL} base
  1151. */
  1152. function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
  1153. const pjsonPath = node_url.fileURLToPath(pjsonUrl);
  1154. if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
  1155. emittedPackageWarnings.add(pjsonPath + '|' + match);
  1156. process$1.emitWarning(
  1157. `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
  1158. `"exports" field module resolution of the package at ${pjsonPath}${
  1159. base ? ` imported from ${node_url.fileURLToPath(base)}` : ''
  1160. }. Mapping specifiers ending in "/" is no longer supported.`,
  1161. 'DeprecationWarning',
  1162. 'DEP0155'
  1163. );
  1164. }
  1165. /**
  1166. * @param {URL} packageJsonUrl
  1167. * @param {string} packageSubpath
  1168. * @param {Record<string, unknown>} packageConfig
  1169. * @param {URL} base
  1170. * @param {Set<string>|undefined} conditions
  1171. * @returns {URL}
  1172. */
  1173. function packageExportsResolve(
  1174. packageJsonUrl,
  1175. packageSubpath,
  1176. packageConfig,
  1177. base,
  1178. conditions
  1179. ) {
  1180. let exports = packageConfig.exports;
  1181. if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
  1182. exports = {'.': exports};
  1183. }
  1184. if (
  1185. own.call(exports, packageSubpath) &&
  1186. !packageSubpath.includes('*') &&
  1187. !packageSubpath.endsWith('/')
  1188. ) {
  1189. // @ts-expect-error: indexable.
  1190. const target = exports[packageSubpath];
  1191. const resolveResult = resolvePackageTarget(
  1192. packageJsonUrl,
  1193. target,
  1194. '',
  1195. packageSubpath,
  1196. base,
  1197. false,
  1198. false,
  1199. false,
  1200. conditions
  1201. );
  1202. if (resolveResult === null || resolveResult === undefined) {
  1203. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1204. }
  1205. return resolveResult
  1206. }
  1207. let bestMatch = '';
  1208. let bestMatchSubpath = '';
  1209. const keys = Object.getOwnPropertyNames(exports);
  1210. let i = -1;
  1211. while (++i < keys.length) {
  1212. const key = keys[i];
  1213. const patternIndex = key.indexOf('*');
  1214. if (
  1215. patternIndex !== -1 &&
  1216. packageSubpath.startsWith(key.slice(0, patternIndex))
  1217. ) {
  1218. // When this reaches EOL, this can throw at the top of the whole function:
  1219. //
  1220. // if (StringPrototypeEndsWith(packageSubpath, '/'))
  1221. // throwInvalidSubpath(packageSubpath)
  1222. //
  1223. // To match "imports" and the spec.
  1224. if (packageSubpath.endsWith('/')) {
  1225. emitTrailingSlashPatternDeprecation(
  1226. packageSubpath,
  1227. packageJsonUrl,
  1228. base
  1229. );
  1230. }
  1231. const patternTrailer = key.slice(patternIndex + 1);
  1232. if (
  1233. packageSubpath.length >= key.length &&
  1234. packageSubpath.endsWith(patternTrailer) &&
  1235. patternKeyCompare(bestMatch, key) === 1 &&
  1236. key.lastIndexOf('*') === patternIndex
  1237. ) {
  1238. bestMatch = key;
  1239. bestMatchSubpath = packageSubpath.slice(
  1240. patternIndex,
  1241. packageSubpath.length - patternTrailer.length
  1242. );
  1243. }
  1244. }
  1245. }
  1246. if (bestMatch) {
  1247. // @ts-expect-error: indexable.
  1248. const target = /** @type {unknown} */ (exports[bestMatch]);
  1249. const resolveResult = resolvePackageTarget(
  1250. packageJsonUrl,
  1251. target,
  1252. bestMatchSubpath,
  1253. bestMatch,
  1254. base,
  1255. true,
  1256. false,
  1257. packageSubpath.endsWith('/'),
  1258. conditions
  1259. );
  1260. if (resolveResult === null || resolveResult === undefined) {
  1261. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1262. }
  1263. return resolveResult
  1264. }
  1265. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1266. }
  1267. /**
  1268. * @param {string} a
  1269. * @param {string} b
  1270. */
  1271. function patternKeyCompare(a, b) {
  1272. const aPatternIndex = a.indexOf('*');
  1273. const bPatternIndex = b.indexOf('*');
  1274. const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
  1275. const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
  1276. if (baseLengthA > baseLengthB) return -1
  1277. if (baseLengthB > baseLengthA) return 1
  1278. if (aPatternIndex === -1) return 1
  1279. if (bPatternIndex === -1) return -1
  1280. if (a.length > b.length) return -1
  1281. if (b.length > a.length) return 1
  1282. return 0
  1283. }
  1284. /**
  1285. * @param {string} name
  1286. * @param {URL} base
  1287. * @param {Set<string>} [conditions]
  1288. * @returns {URL}
  1289. */
  1290. function packageImportsResolve(name, base, conditions) {
  1291. if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
  1292. const reason = 'is not a valid internal imports specifier name';
  1293. throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, node_url.fileURLToPath(base))
  1294. }
  1295. /** @type {URL|undefined} */
  1296. let packageJsonUrl;
  1297. const packageConfig = getPackageScopeConfig(base);
  1298. if (packageConfig.exists) {
  1299. packageJsonUrl = node_url.pathToFileURL(packageConfig.pjsonPath);
  1300. const imports = packageConfig.imports;
  1301. if (imports) {
  1302. if (own.call(imports, name) && !name.includes('*')) {
  1303. const resolveResult = resolvePackageTarget(
  1304. packageJsonUrl,
  1305. imports[name],
  1306. '',
  1307. name,
  1308. base,
  1309. false,
  1310. true,
  1311. false,
  1312. conditions
  1313. );
  1314. if (resolveResult !== null && resolveResult !== undefined) {
  1315. return resolveResult
  1316. }
  1317. } else {
  1318. let bestMatch = '';
  1319. let bestMatchSubpath = '';
  1320. const keys = Object.getOwnPropertyNames(imports);
  1321. let i = -1;
  1322. while (++i < keys.length) {
  1323. const key = keys[i];
  1324. const patternIndex = key.indexOf('*');
  1325. if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
  1326. const patternTrailer = key.slice(patternIndex + 1);
  1327. if (
  1328. name.length >= key.length &&
  1329. name.endsWith(patternTrailer) &&
  1330. patternKeyCompare(bestMatch, key) === 1 &&
  1331. key.lastIndexOf('*') === patternIndex
  1332. ) {
  1333. bestMatch = key;
  1334. bestMatchSubpath = name.slice(
  1335. patternIndex,
  1336. name.length - patternTrailer.length
  1337. );
  1338. }
  1339. }
  1340. }
  1341. if (bestMatch) {
  1342. const target = imports[bestMatch];
  1343. const resolveResult = resolvePackageTarget(
  1344. packageJsonUrl,
  1345. target,
  1346. bestMatchSubpath,
  1347. bestMatch,
  1348. base,
  1349. true,
  1350. true,
  1351. false,
  1352. conditions
  1353. );
  1354. if (resolveResult !== null && resolveResult !== undefined) {
  1355. return resolveResult
  1356. }
  1357. }
  1358. }
  1359. }
  1360. }
  1361. throw importNotDefined(name, packageJsonUrl, base)
  1362. }
  1363. /**
  1364. * @param {URL} url
  1365. * @returns {PackageType}
  1366. */
  1367. function getPackageType(url) {
  1368. const packageConfig = getPackageScopeConfig(url);
  1369. return packageConfig.type
  1370. }
  1371. /**
  1372. * @param {string} specifier
  1373. * @param {URL} base
  1374. */
  1375. function parsePackageName(specifier, base) {
  1376. let separatorIndex = specifier.indexOf('/');
  1377. let validPackageName = true;
  1378. let isScoped = false;
  1379. if (specifier[0] === '@') {
  1380. isScoped = true;
  1381. if (separatorIndex === -1 || specifier.length === 0) {
  1382. validPackageName = false;
  1383. } else {
  1384. separatorIndex = specifier.indexOf('/', separatorIndex + 1);
  1385. }
  1386. }
  1387. const packageName =
  1388. separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
  1389. // Package name cannot have leading . and cannot have percent-encoding or
  1390. // \\ separators.
  1391. if (invalidPackageNameRegEx.exec(packageName) !== null) {
  1392. validPackageName = false;
  1393. }
  1394. if (!validPackageName) {
  1395. throw new ERR_INVALID_MODULE_SPECIFIER(
  1396. specifier,
  1397. 'is not a valid package name',
  1398. node_url.fileURLToPath(base)
  1399. )
  1400. }
  1401. const packageSubpath =
  1402. '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
  1403. return {packageName, packageSubpath, isScoped}
  1404. }
  1405. /**
  1406. * @param {string} specifier
  1407. * @param {URL} base
  1408. * @param {Set<string>|undefined} conditions
  1409. * @returns {URL}
  1410. */
  1411. function packageResolve(specifier, base, conditions) {
  1412. if (node_module.builtinModules.includes(specifier)) {
  1413. return new node_url.URL('node:' + specifier)
  1414. }
  1415. const {packageName, packageSubpath, isScoped} = parsePackageName(
  1416. specifier,
  1417. base
  1418. );
  1419. // ResolveSelf
  1420. const packageConfig = getPackageScopeConfig(base);
  1421. // Can’t test.
  1422. /* c8 ignore next 16 */
  1423. if (packageConfig.exists) {
  1424. const packageJsonUrl = node_url.pathToFileURL(packageConfig.pjsonPath);
  1425. if (
  1426. packageConfig.name === packageName &&
  1427. packageConfig.exports !== undefined &&
  1428. packageConfig.exports !== null
  1429. ) {
  1430. return packageExportsResolve(
  1431. packageJsonUrl,
  1432. packageSubpath,
  1433. packageConfig,
  1434. base,
  1435. conditions
  1436. )
  1437. }
  1438. }
  1439. let packageJsonUrl = new node_url.URL(
  1440. './node_modules/' + packageName + '/package.json',
  1441. base
  1442. );
  1443. let packageJsonPath = node_url.fileURLToPath(packageJsonUrl);
  1444. /** @type {string} */
  1445. let lastPath;
  1446. do {
  1447. const stat = tryStatSync(packageJsonPath.slice(0, -13));
  1448. if (!stat.isDirectory()) {
  1449. lastPath = packageJsonPath;
  1450. packageJsonUrl = new node_url.URL(
  1451. (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
  1452. packageName +
  1453. '/package.json',
  1454. packageJsonUrl
  1455. );
  1456. packageJsonPath = node_url.fileURLToPath(packageJsonUrl);
  1457. continue
  1458. }
  1459. // Package match.
  1460. const packageConfig = getPackageConfig(packageJsonPath, specifier, base);
  1461. if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
  1462. return packageExportsResolve(
  1463. packageJsonUrl,
  1464. packageSubpath,
  1465. packageConfig,
  1466. base,
  1467. conditions
  1468. )
  1469. }
  1470. if (packageSubpath === '.') {
  1471. return legacyMainResolve(packageJsonUrl, packageConfig, base)
  1472. }
  1473. return new node_url.URL(packageSubpath, packageJsonUrl)
  1474. // Cross-platform root check.
  1475. } while (packageJsonPath.length !== lastPath.length)
  1476. throw new ERR_MODULE_NOT_FOUND(packageName, node_url.fileURLToPath(base))
  1477. }
  1478. /**
  1479. * @param {string} specifier
  1480. * @returns {boolean}
  1481. */
  1482. function isRelativeSpecifier(specifier) {
  1483. if (specifier[0] === '.') {
  1484. if (specifier.length === 1 || specifier[1] === '/') return true
  1485. if (
  1486. specifier[1] === '.' &&
  1487. (specifier.length === 2 || specifier[2] === '/')
  1488. ) {
  1489. return true
  1490. }
  1491. }
  1492. return false
  1493. }
  1494. /**
  1495. * @param {string} specifier
  1496. * @returns {boolean}
  1497. */
  1498. function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
  1499. if (specifier === '') return false
  1500. if (specifier[0] === '/') return true
  1501. return isRelativeSpecifier(specifier)
  1502. }
  1503. /**
  1504. * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
  1505. * sync and slightly lower-level than `resolve`).
  1506. *
  1507. * @param {string} specifier
  1508. * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
  1509. * @param {URL} base
  1510. * Full URL (to a file) that `specifier` is resolved relative from.
  1511. * @param {Set<string>} [conditions]
  1512. * Conditions.
  1513. * @param {boolean} [preserveSymlinks]
  1514. * Keep symlinks instead of resolving them.
  1515. * @returns {URL}
  1516. * A URL object to the found thing.
  1517. */
  1518. function moduleResolve(specifier, base, conditions, preserveSymlinks) {
  1519. const isRemote = base.protocol === 'http:' || base.protocol === 'https:';
  1520. // Order swapped from spec for minor perf gain.
  1521. // Ok since relative URLs cannot parse as URLs.
  1522. /** @type {URL|undefined} */
  1523. let resolved;
  1524. if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
  1525. resolved = new node_url.URL(specifier, base);
  1526. } else if (!isRemote && specifier[0] === '#') {
  1527. resolved = packageImportsResolve(specifier, base, conditions);
  1528. } else {
  1529. try {
  1530. resolved = new node_url.URL(specifier);
  1531. } catch {
  1532. if (!isRemote) {
  1533. resolved = packageResolve(specifier, base, conditions);
  1534. }
  1535. }
  1536. }
  1537. assert(typeof resolved !== 'undefined', 'expected to be defined');
  1538. if (resolved.protocol !== 'file:') {
  1539. return resolved
  1540. }
  1541. return finalizeResolution(resolved, base, preserveSymlinks)
  1542. }
  1543. function fileURLToPath(id) {
  1544. if (typeof id === "string" && !id.startsWith("file://")) {
  1545. return normalizeSlash(id);
  1546. }
  1547. return normalizeSlash(node_url.fileURLToPath(id));
  1548. }
  1549. const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,/:;<=>?@[\]^`{|}\u007F]+/g;
  1550. function sanitizeURIComponent(name = "", replacement = "_") {
  1551. return name.replace(INVALID_CHAR_RE, replacement).replace(/%../g, replacement);
  1552. }
  1553. function sanitizeFilePath(filePath = "") {
  1554. return filePath.replace(/\?.*$/, "").split(/[/\\]/g).map((p) => sanitizeURIComponent(p)).join("/").replace(/^([A-Za-z])_\//, "$1:/");
  1555. }
  1556. function normalizeid(id) {
  1557. if (typeof id !== "string") {
  1558. id = id.toString();
  1559. }
  1560. if (/(node|data|http|https|file):/.test(id)) {
  1561. return id;
  1562. }
  1563. if (BUILTIN_MODULES.has(id)) {
  1564. return "node:" + id;
  1565. }
  1566. return "file://" + encodeURI(normalizeSlash(id));
  1567. }
  1568. async function loadURL(url) {
  1569. const code = await fs.promises.readFile(fileURLToPath(url), "utf8");
  1570. return code;
  1571. }
  1572. function toDataURL(code) {
  1573. const base64 = Buffer.from(code).toString("base64");
  1574. return `data:text/javascript;base64,${base64}`;
  1575. }
  1576. function isNodeBuiltin(id = "") {
  1577. id = id.replace(/^node:/, "").split("/")[0];
  1578. return BUILTIN_MODULES.has(id);
  1579. }
  1580. const ProtocolRegex = /^(?<proto>.{2,}?):.+$/;
  1581. function getProtocol(id) {
  1582. const proto = id.match(ProtocolRegex);
  1583. return proto ? proto.groups.proto : void 0;
  1584. }
  1585. const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
  1586. const DEFAULT_URL = node_url.pathToFileURL(process.cwd());
  1587. const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
  1588. const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
  1589. "ERR_MODULE_NOT_FOUND",
  1590. "ERR_UNSUPPORTED_DIR_IMPORT",
  1591. "MODULE_NOT_FOUND",
  1592. "ERR_PACKAGE_PATH_NOT_EXPORTED"
  1593. ]);
  1594. function _tryModuleResolve(id, url, conditions) {
  1595. try {
  1596. return moduleResolve(id, url, conditions);
  1597. } catch (error) {
  1598. if (!NOT_FOUND_ERRORS.has(error.code)) {
  1599. throw error;
  1600. }
  1601. }
  1602. }
  1603. function _resolve(id, options = {}) {
  1604. if (/(node|data|http|https):/.test(id)) {
  1605. return id;
  1606. }
  1607. if (BUILTIN_MODULES.has(id)) {
  1608. return "node:" + id;
  1609. }
  1610. if (pathe.isAbsolute(id) && fs.existsSync(id)) {
  1611. const realPath2 = fs.realpathSync(fileURLToPath(id));
  1612. return node_url.pathToFileURL(realPath2).toString();
  1613. }
  1614. const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
  1615. const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((u) => new URL(normalizeid(u.toString())));
  1616. if (_urls.length === 0) {
  1617. _urls.push(DEFAULT_URL);
  1618. }
  1619. const urls = [..._urls];
  1620. for (const url of _urls) {
  1621. if (url.protocol === "file:") {
  1622. urls.push(
  1623. new URL("./", url),
  1624. // If url is directory
  1625. new URL(ufo.joinURL(url.pathname, "_index.js"), url),
  1626. // TODO: Remove in next major version?
  1627. new URL("node_modules", url)
  1628. );
  1629. }
  1630. }
  1631. let resolved;
  1632. for (const url of urls) {
  1633. resolved = _tryModuleResolve(id, url, conditionsSet);
  1634. if (resolved) {
  1635. break;
  1636. }
  1637. for (const prefix of ["", "/index"]) {
  1638. for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
  1639. resolved = _tryModuleResolve(
  1640. id + prefix + extension,
  1641. url,
  1642. conditionsSet
  1643. );
  1644. if (resolved) {
  1645. break;
  1646. }
  1647. }
  1648. if (resolved) {
  1649. break;
  1650. }
  1651. }
  1652. if (resolved) {
  1653. break;
  1654. }
  1655. }
  1656. if (!resolved) {
  1657. const error = new Error(
  1658. `Cannot find module ${id} imported from ${urls.join(", ")}`
  1659. );
  1660. error.code = "ERR_MODULE_NOT_FOUND";
  1661. throw error;
  1662. }
  1663. const realPath = fs.realpathSync(fileURLToPath(resolved));
  1664. return node_url.pathToFileURL(realPath).toString();
  1665. }
  1666. function resolveSync(id, options) {
  1667. return _resolve(id, options);
  1668. }
  1669. function resolve(id, options) {
  1670. return pcall(resolveSync, id, options);
  1671. }
  1672. function resolvePathSync(id, options) {
  1673. return fileURLToPath(resolveSync(id, options));
  1674. }
  1675. function resolvePath(id, options) {
  1676. return pcall(resolvePathSync, id, options);
  1677. }
  1678. function createResolve(defaults) {
  1679. return (id, url) => {
  1680. return resolve(id, { url, ...defaults });
  1681. };
  1682. }
  1683. const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;)import\s*([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm;
  1684. const DYNAMIC_IMPORT_RE = /import\s*\((?<expression>(?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/gm;
  1685. const EXPORT_DECAL_RE = /\bexport\s+(?<declaration>(async function|function|let|const enum|const|enum|var|class))\s+(?<name>[\w$]+)/g;
  1686. const EXPORT_DECAL_TYPE_RE = /\bexport\s+(?<declaration>(interface|type|declare (async function|function|let|const enum|const|enum|var|class)))\s+(?<name>[\w$]+)/g;
  1687. const EXPORT_NAMED_RE = /\bexport\s+{(?<exports>[^}]+?)[\s,]*}(\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
  1688. const EXPORT_NAMED_TYPE_RE = /\bexport\s+type\s+{(?<exports>[^}]+?)[\s,]*}(\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
  1689. const EXPORT_NAMED_DESTRUCT = /\bexport\s+(let|var|const)\s+(?:{(?<exports1>[^}]+?)[\s,]*}|\[(?<exports2>[^\]]+?)[\s,]*])\s+=/gm;
  1690. const EXPORT_STAR_RE = /\bexport\s*(\*)(\s*as\s+(?<name>[\w$]+)\s+)?\s*(\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
  1691. const EXPORT_DEFAULT_RE = /\bexport\s+default\s+/g;
  1692. const TYPE_RE = /^\s*?type\s/;
  1693. function findStaticImports(code) {
  1694. return matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" });
  1695. }
  1696. function findDynamicImports(code) {
  1697. return matchAll(DYNAMIC_IMPORT_RE, code, { type: "dynamic" });
  1698. }
  1699. function parseStaticImport(matched) {
  1700. const cleanedImports = (matched.imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " ");
  1701. const namedImports = {};
  1702. for (const namedImport of cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || []) {
  1703. const [, source = namedImport.trim(), importName = source] = namedImport.match(/^\s*(\S*) as (\S*)\s*$/) || [];
  1704. if (source && !TYPE_RE.test(source)) {
  1705. namedImports[source] = importName;
  1706. }
  1707. }
  1708. const topLevelImports = cleanedImports.replace(/{([^}]*)}/, "");
  1709. const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1];
  1710. const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0;
  1711. return {
  1712. ...matched,
  1713. defaultImport,
  1714. namespacedImport,
  1715. namedImports
  1716. };
  1717. }
  1718. function findExports(code) {
  1719. const declaredExports = matchAll(EXPORT_DECAL_RE, code, {
  1720. type: "declaration"
  1721. });
  1722. const namedExports = normalizeNamedExports(
  1723. matchAll(EXPORT_NAMED_RE, code, {
  1724. type: "named"
  1725. })
  1726. );
  1727. const destructuredExports = matchAll(
  1728. EXPORT_NAMED_DESTRUCT,
  1729. code,
  1730. { type: "named" }
  1731. );
  1732. for (const namedExport of destructuredExports) {
  1733. namedExport.exports = namedExport.exports1 || namedExport.exports2;
  1734. namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map(
  1735. (name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim()
  1736. );
  1737. }
  1738. const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, {
  1739. type: "default",
  1740. name: "default"
  1741. });
  1742. const starExports = matchAll(EXPORT_STAR_RE, code, {
  1743. type: "star"
  1744. });
  1745. const exports = normalizeExports([
  1746. ...declaredExports,
  1747. ...namedExports,
  1748. ...destructuredExports,
  1749. ...defaultExport,
  1750. ...starExports
  1751. ]);
  1752. if (exports.length === 0) {
  1753. return [];
  1754. }
  1755. const exportLocations = _tryGetExportLocations(code);
  1756. if (exportLocations && exportLocations.length === 0) {
  1757. return [];
  1758. }
  1759. return exports.filter(
  1760. (exp) => !exportLocations || _isExportStatement(exportLocations, exp)
  1761. ).filter((exp, index, exports2) => {
  1762. const nextExport = exports2[index + 1];
  1763. return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
  1764. });
  1765. }
  1766. function findTypeExports(code) {
  1767. const declaredExports = matchAll(
  1768. EXPORT_DECAL_TYPE_RE,
  1769. code,
  1770. { type: "declaration" }
  1771. );
  1772. const namedExports = normalizeNamedExports(
  1773. matchAll(EXPORT_NAMED_TYPE_RE, code, {
  1774. type: "named"
  1775. })
  1776. );
  1777. const exports = normalizeExports([
  1778. ...declaredExports,
  1779. ...namedExports
  1780. ]);
  1781. if (exports.length === 0) {
  1782. return [];
  1783. }
  1784. const exportLocations = _tryGetExportLocations(code);
  1785. if (exportLocations && exportLocations.length === 0) {
  1786. return [];
  1787. }
  1788. return exports.filter(
  1789. (exp) => !exportLocations || _isExportStatement(exportLocations, exp)
  1790. ).filter((exp, index, exports2) => {
  1791. const nextExport = exports2[index + 1];
  1792. return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
  1793. });
  1794. }
  1795. function normalizeExports(exports) {
  1796. for (const exp of exports) {
  1797. if (!exp.name && exp.names && exp.names.length === 1) {
  1798. exp.name = exp.names[0];
  1799. }
  1800. if (exp.name === "default" && exp.type !== "default") {
  1801. exp._type = exp.type;
  1802. exp.type = "default";
  1803. }
  1804. if (!exp.names && exp.name) {
  1805. exp.names = [exp.name];
  1806. }
  1807. }
  1808. return exports;
  1809. }
  1810. function normalizeNamedExports(namedExports) {
  1811. for (const namedExport of namedExports) {
  1812. namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim());
  1813. }
  1814. return namedExports;
  1815. }
  1816. function findExportNames(code) {
  1817. return findExports(code).flatMap((exp) => exp.names).filter(Boolean);
  1818. }
  1819. async function resolveModuleExportNames(id, options) {
  1820. const url = await resolvePath(id, options);
  1821. const code = await loadURL(url);
  1822. const exports = findExports(code);
  1823. const exportNames = new Set(
  1824. exports.flatMap((exp) => exp.names).filter(Boolean)
  1825. );
  1826. for (const exp of exports) {
  1827. if (exp.type === "star") {
  1828. const subExports = await resolveModuleExportNames(exp.specifier, {
  1829. ...options,
  1830. url
  1831. });
  1832. for (const subExport of subExports) {
  1833. exportNames.add(subExport);
  1834. }
  1835. }
  1836. }
  1837. return [...exportNames];
  1838. }
  1839. function _isExportStatement(exportsLocation, exp) {
  1840. return exportsLocation.some((location) => {
  1841. return exp.start <= location.start && exp.end >= location.end;
  1842. });
  1843. }
  1844. function _tryGetExportLocations(code) {
  1845. try {
  1846. return _getExportLocations(code);
  1847. } catch {
  1848. }
  1849. }
  1850. function _getExportLocations(code) {
  1851. const tokens = acorn.tokenizer(code, {
  1852. ecmaVersion: "latest",
  1853. sourceType: "module",
  1854. allowHashBang: true,
  1855. allowAwaitOutsideFunction: true,
  1856. allowImportExportEverywhere: true
  1857. });
  1858. const locations = [];
  1859. for (const token of tokens) {
  1860. if (token.type.label === "export") {
  1861. locations.push({
  1862. start: token.start,
  1863. end: token.end
  1864. });
  1865. }
  1866. }
  1867. return locations;
  1868. }
  1869. function createCommonJS(url) {
  1870. const __filename = fileURLToPath(url);
  1871. const __dirname = path.dirname(__filename);
  1872. let _nativeRequire;
  1873. const getNativeRequire = () => _nativeRequire || (_nativeRequire = node_module.createRequire(url));
  1874. function require(id) {
  1875. return getNativeRequire()(id);
  1876. }
  1877. require.resolve = (id, options) => getNativeRequire().resolve(id, options);
  1878. return {
  1879. __filename,
  1880. __dirname,
  1881. require
  1882. };
  1883. }
  1884. function interopDefault(sourceModule) {
  1885. if (!isObject(sourceModule) || !("default" in sourceModule)) {
  1886. return sourceModule;
  1887. }
  1888. const newModule = sourceModule.default;
  1889. for (const key in sourceModule) {
  1890. if (key === "default") {
  1891. try {
  1892. if (!(key in newModule)) {
  1893. Object.defineProperty(newModule, key, {
  1894. enumerable: false,
  1895. configurable: false,
  1896. get() {
  1897. return newModule;
  1898. }
  1899. });
  1900. }
  1901. } catch {
  1902. }
  1903. } else {
  1904. try {
  1905. if (!(key in newModule)) {
  1906. Object.defineProperty(newModule, key, {
  1907. enumerable: true,
  1908. configurable: true,
  1909. get() {
  1910. return sourceModule[key];
  1911. }
  1912. });
  1913. }
  1914. } catch {
  1915. }
  1916. }
  1917. }
  1918. return newModule;
  1919. }
  1920. const EVAL_ESM_IMPORT_RE = /(?<=import .* from ["'])([^"']+)(?=["'])|(?<=export .* from ["'])([^"']+)(?=["'])|(?<=import\s*["'])([^"']+)(?=["'])|(?<=import\s*\(["'])([^"']+)(?=["']\))/g;
  1921. async function loadModule(id, options = {}) {
  1922. const url = await resolve(id, options);
  1923. const code = await loadURL(url);
  1924. return evalModule(code, { ...options, url });
  1925. }
  1926. async function evalModule(code, options = {}) {
  1927. const transformed = await transformModule(code, options);
  1928. const dataURL = toDataURL(transformed);
  1929. return import(dataURL).catch((error) => {
  1930. error.stack = error.stack.replace(
  1931. new RegExp(dataURL, "g"),
  1932. options.url || "_mlly_eval_"
  1933. );
  1934. throw error;
  1935. });
  1936. }
  1937. function transformModule(code, options) {
  1938. if (options.url && options.url.endsWith(".json")) {
  1939. return Promise.resolve("export default " + code);
  1940. }
  1941. if (options.url) {
  1942. code = code.replace(/import\.meta\.url/g, `'${options.url}'`);
  1943. }
  1944. return Promise.resolve(code);
  1945. }
  1946. async function resolveImports(code, options) {
  1947. const imports = [...code.matchAll(EVAL_ESM_IMPORT_RE)].map((m) => m[0]);
  1948. if (imports.length === 0) {
  1949. return code;
  1950. }
  1951. const uniqueImports = [...new Set(imports)];
  1952. const resolved = /* @__PURE__ */ new Map();
  1953. await Promise.all(
  1954. uniqueImports.map(async (id) => {
  1955. let url = await resolve(id, options);
  1956. if (url.endsWith(".json")) {
  1957. const code2 = await loadURL(url);
  1958. url = toDataURL(await transformModule(code2, { url }));
  1959. }
  1960. resolved.set(id, url);
  1961. })
  1962. );
  1963. const re = new RegExp(
  1964. uniqueImports.map((index) => `(${index})`).join("|"),
  1965. "g"
  1966. );
  1967. return code.replace(re, (id) => resolved.get(id));
  1968. }
  1969. const ESM_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
  1970. const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
  1971. function hasESMSyntax(code) {
  1972. return ESM_RE.test(code);
  1973. }
  1974. const CJS_RE = /([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
  1975. function hasCJSSyntax(code) {
  1976. return CJS_RE.test(code);
  1977. }
  1978. function detectSyntax(code) {
  1979. const hasESM = hasESMSyntax(code);
  1980. const hasCJS = hasCJSSyntax(code);
  1981. return {
  1982. hasESM,
  1983. hasCJS,
  1984. isMixed: hasESM && hasCJS
  1985. };
  1986. }
  1987. const validNodeImportDefaults = {
  1988. allowedProtocols: ["node", "file", "data"]
  1989. };
  1990. async function isValidNodeImport(id, _options = {}) {
  1991. if (isNodeBuiltin(id)) {
  1992. return true;
  1993. }
  1994. const options = { ...validNodeImportDefaults, ..._options };
  1995. const proto = getProtocol(id);
  1996. if (proto && !options.allowedProtocols.includes(proto)) {
  1997. return false;
  1998. }
  1999. if (proto === "data") {
  2000. return true;
  2001. }
  2002. const resolvedPath = await resolvePath(id, options);
  2003. const extension = pathe.extname(resolvedPath);
  2004. if (BUILTIN_EXTENSIONS.has(extension)) {
  2005. return true;
  2006. }
  2007. if (extension !== ".js") {
  2008. return false;
  2009. }
  2010. const package_ = await pkgTypes.readPackageJSON(resolvedPath).catch(() => {
  2011. });
  2012. if (package_?.type === "module") {
  2013. return true;
  2014. }
  2015. if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(resolvedPath)) {
  2016. return false;
  2017. }
  2018. const code = options.code || await fs.promises.readFile(resolvedPath, "utf8").catch(() => {
  2019. }) || "";
  2020. return hasCJSSyntax(code) || !hasESMSyntax(code);
  2021. }
  2022. exports.DYNAMIC_IMPORT_RE = DYNAMIC_IMPORT_RE;
  2023. exports.ESM_STATIC_IMPORT_RE = ESM_STATIC_IMPORT_RE;
  2024. exports.EXPORT_DECAL_RE = EXPORT_DECAL_RE;
  2025. exports.EXPORT_DECAL_TYPE_RE = EXPORT_DECAL_TYPE_RE;
  2026. exports.createCommonJS = createCommonJS;
  2027. exports.createResolve = createResolve;
  2028. exports.detectSyntax = detectSyntax;
  2029. exports.evalModule = evalModule;
  2030. exports.fileURLToPath = fileURLToPath;
  2031. exports.findDynamicImports = findDynamicImports;
  2032. exports.findExportNames = findExportNames;
  2033. exports.findExports = findExports;
  2034. exports.findStaticImports = findStaticImports;
  2035. exports.findTypeExports = findTypeExports;
  2036. exports.getProtocol = getProtocol;
  2037. exports.hasCJSSyntax = hasCJSSyntax;
  2038. exports.hasESMSyntax = hasESMSyntax;
  2039. exports.interopDefault = interopDefault;
  2040. exports.isNodeBuiltin = isNodeBuiltin;
  2041. exports.isValidNodeImport = isValidNodeImport;
  2042. exports.loadModule = loadModule;
  2043. exports.loadURL = loadURL;
  2044. exports.normalizeid = normalizeid;
  2045. exports.parseStaticImport = parseStaticImport;
  2046. exports.resolve = resolve;
  2047. exports.resolveImports = resolveImports;
  2048. exports.resolveModuleExportNames = resolveModuleExportNames;
  2049. exports.resolvePath = resolvePath;
  2050. exports.resolvePathSync = resolvePathSync;
  2051. exports.resolveSync = resolveSync;
  2052. exports.sanitizeFilePath = sanitizeFilePath;
  2053. exports.sanitizeURIComponent = sanitizeURIComponent;
  2054. exports.toDataURL = toDataURL;
  2055. exports.transformModule = transformModule;