index.cjs 73 KB

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