Resolver.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = require("tapable");
  7. const createInnerContext = require("./createInnerContext");
  8. const { parseIdentifier } = require("./util/identifier");
  9. const {
  10. PathType,
  11. createCachedBasename,
  12. createCachedDirname,
  13. createCachedJoin,
  14. getType,
  15. normalize,
  16. } = require("./util/path");
  17. /* eslint-disable jsdoc/check-alignment */
  18. // TODO in the next major release use only `Promise.withResolvers()`
  19. const _withResolvers =
  20. // eslint-disable-next-line n/no-unsupported-features/es-syntax
  21. Promise.withResolvers
  22. ? /**
  23. * @param {Resolver} self resolver
  24. * @param {Context} context context information object
  25. * @param {string} path context path
  26. * @param {string} request request string
  27. * @param {ResolveContext} resolveContext resolve context
  28. * @returns {Promise<string | false>} result
  29. */
  30. (self, context, path, request, resolveContext) => {
  31. // eslint-disable-next-line n/no-unsupported-features/es-syntax
  32. const { promise, resolve, reject } = Promise.withResolvers();
  33. self.resolve(context, path, request, resolveContext, (err, res) => {
  34. if (err) reject(err);
  35. else resolve(/** @type {string | false} */ (res));
  36. });
  37. return promise;
  38. }
  39. : /**
  40. * @param {Resolver} self resolver
  41. * @param {Context} context context information object
  42. * @param {string} path context path
  43. * @param {string} request request string
  44. * @param {ResolveContext} resolveContext resolve context
  45. * @returns {Promise<string | false>} result
  46. */
  47. (self, context, path, request, resolveContext) =>
  48. new Promise((resolve, reject) => {
  49. self.resolve(context, path, request, resolveContext, (err, res) => {
  50. if (err) reject(err);
  51. else resolve(/** @type {string | false} */ (res));
  52. });
  53. });
  54. /* eslint-enable jsdoc/check-alignment */
  55. /** @typedef {import("./AliasUtils").AliasOption} AliasOption */
  56. /** @typedef {import("./util/path").CachedJoin} CachedJoin */
  57. /** @typedef {import("./util/path").CachedDirname} CachedDirname */
  58. /** @typedef {import("./util/path").CachedBasename} CachedBasename */
  59. /**
  60. * @typedef {object} JoinCacheEntry
  61. * @property {CachedJoin["fn"]} fn cached join function
  62. * @property {CachedJoin["cache"]} cache the underlying cache map
  63. */
  64. /**
  65. * @typedef {object} DirnameCacheEntry
  66. * @property {CachedDirname["fn"]} fn cached dirname function
  67. * @property {CachedDirname["cache"]} cache the underlying cache map
  68. */
  69. /**
  70. * @typedef {object} BasenameCacheEntry
  71. * @property {CachedBasename["fn"]} fn cached dirname function
  72. * @property {CachedBasename["cache"]} cache the underlying cache map
  73. */
  74. /**
  75. * @typedef {object} PathCacheFunctions
  76. * @property {JoinCacheEntry} join cached join
  77. * @property {DirnameCacheEntry} dirname cached dirname
  78. * @property {BasenameCacheEntry} basename cached basename
  79. */
  80. /** @type {WeakMap<FileSystem, PathCacheFunctions>} */
  81. const _pathCacheByFs = new WeakMap();
  82. const HASH_ESCAPE_RE = /#/g;
  83. /** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */
  84. /**
  85. * @typedef {object} KnownContext
  86. * @property {string[]=} environments environments
  87. */
  88. // eslint-disable-next-line jsdoc/reject-any-type
  89. /** @typedef {KnownContext & Record<any, any>} Context */
  90. /** @typedef {Error & { details?: string }} ErrorWithDetail */
  91. /** @typedef {(err: ErrorWithDetail | null, res?: string | false, req?: ResolveRequest) => void} ResolveCallback */
  92. /**
  93. * @typedef {object} PossibleFileSystemError
  94. * @property {string=} code code
  95. * @property {number=} errno number
  96. * @property {string=} path path
  97. * @property {string=} syscall syscall
  98. */
  99. /**
  100. * @template T
  101. * @callback FileSystemCallback
  102. * @param {PossibleFileSystemError & Error | null} err
  103. * @param {T=} result
  104. */
  105. /**
  106. * @typedef {string | Buffer | URL} PathLike
  107. */
  108. /**
  109. * @typedef {PathLike | number} PathOrFileDescriptor
  110. */
  111. /**
  112. * @typedef {object} ObjectEncodingOptions
  113. * @property {BufferEncoding | null | undefined=} encoding encoding
  114. */
  115. /**
  116. * @typedef {ObjectEncodingOptions | BufferEncoding | undefined | null} EncodingOption
  117. */
  118. /** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */
  119. /** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer) => void} BufferCallback */
  120. /** @typedef {(err: NodeJS.ErrnoException | null, result?: (string | Buffer)) => void} StringOrBufferCallback */
  121. /** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats) => void} StatsCallback */
  122. /** @typedef {(err: NodeJS.ErrnoException | null, result?: IBigIntStats) => void} BigIntStatsCallback */
  123. /** @typedef {(err: NodeJS.ErrnoException | null, result?: (IStats | IBigIntStats)) => void} StatsOrBigIntStatsCallback */
  124. /** @typedef {(err: NodeJS.ErrnoException | Error | null, result?: JsonObject) => void} ReadJsonCallback */
  125. /**
  126. * @template T
  127. * @typedef {object} IStatsBase
  128. * @property {() => boolean} isFile is file
  129. * @property {() => boolean} isDirectory is directory
  130. * @property {() => boolean} isBlockDevice is block device
  131. * @property {() => boolean} isCharacterDevice is character device
  132. * @property {() => boolean} isSymbolicLink is symbolic link
  133. * @property {() => boolean} isFIFO is FIFO
  134. * @property {() => boolean} isSocket is socket
  135. * @property {T} dev dev
  136. * @property {T} ino ino
  137. * @property {T} mode mode
  138. * @property {T} nlink nlink
  139. * @property {T} uid uid
  140. * @property {T} gid gid
  141. * @property {T} rdev rdev
  142. * @property {T} size size
  143. * @property {T} blksize blksize
  144. * @property {T} blocks blocks
  145. * @property {T} atimeMs atime ms
  146. * @property {T} mtimeMs mtime ms
  147. * @property {T} ctimeMs ctime ms
  148. * @property {T} birthtimeMs birthtime ms
  149. * @property {Date} atime atime
  150. * @property {Date} mtime mtime
  151. * @property {Date} ctime ctime
  152. * @property {Date} birthtime birthtime
  153. */
  154. /**
  155. * @typedef {IStatsBase<number>} IStats
  156. */
  157. /**
  158. * @typedef {IStatsBase<bigint> & { atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint, birthtimeNs: bigint }} IBigIntStats
  159. */
  160. /**
  161. * @template {string | Buffer} [T=string]
  162. * @typedef {object} Dirent
  163. * @property {() => boolean} isFile true when is file, otherwise false
  164. * @property {() => boolean} isDirectory true when is directory, otherwise false
  165. * @property {() => boolean} isBlockDevice true when is block device, otherwise false
  166. * @property {() => boolean} isCharacterDevice true when is character device, otherwise false
  167. * @property {() => boolean} isSymbolicLink true when is symbolic link, otherwise false
  168. * @property {() => boolean} isFIFO true when is FIFO, otherwise false
  169. * @property {() => boolean} isSocket true when is socket, otherwise false
  170. * @property {T} name name
  171. * @property {string} parentPath path
  172. * @property {string=} path path
  173. */
  174. /**
  175. * @typedef {object} StatOptions
  176. * @property {(boolean | undefined)=} bigint need bigint values
  177. */
  178. /**
  179. * @typedef {object} StatSyncOptions
  180. * @property {(boolean | undefined)=} bigint need bigint values
  181. * @property {(boolean | undefined)=} throwIfNoEntry throw if no entry
  182. */
  183. /**
  184. * @typedef {{
  185. * (path: PathOrFileDescriptor, options: ({ encoding?: null | undefined, flag?: string | undefined } & import("events").Abortable) | undefined | null, callback: BufferCallback): void,
  186. * (path: PathOrFileDescriptor, options: ({ encoding: BufferEncoding, flag?: string | undefined } & import("events").Abortable) | BufferEncoding, callback: StringCallback): void,
  187. * (path: PathOrFileDescriptor, options: (ObjectEncodingOptions & { flag?: string | undefined } & import("events").Abortable) | BufferEncoding | undefined | null, callback: StringOrBufferCallback): void,
  188. * (path: PathOrFileDescriptor, callback: BufferCallback): void,
  189. * }} ReadFile
  190. */
  191. /**
  192. * @typedef {"buffer" | { encoding: "buffer" }} BufferEncodingOption
  193. */
  194. /**
  195. * @typedef {{
  196. * (path: PathOrFileDescriptor, options?: { encoding?: null | undefined, flag?: string | undefined } | null): Buffer,
  197. * (path: PathOrFileDescriptor, options: { encoding: BufferEncoding, flag?: string | undefined } | BufferEncoding): string,
  198. * (path: PathOrFileDescriptor, options?: (ObjectEncodingOptions & { flag?: string | undefined }) | BufferEncoding | null): string | Buffer,
  199. * }} ReadFileSync
  200. */
  201. /**
  202. * @typedef {{
  203. * (path: PathLike, options: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void,
  204. * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer", callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void): void,
  205. * (path: PathLike, options: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[] | Buffer[]) => void): void,
  206. * (path: PathLike, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void,
  207. * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files?: Dirent<string>[]) => void): void,
  208. * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files: Dirent<Buffer>[]) => void): void,
  209. * }} Readdir
  210. */
  211. /**
  212. * @typedef {{
  213. * (path: PathLike, options?: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | null): string[],
  214. * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer"): Buffer[],
  215. * (path: PathLike, options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | null): string[] | Buffer[],
  216. * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }): Dirent[],
  217. * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }): Dirent<Buffer>[],
  218. * }} ReaddirSync
  219. */
  220. /**
  221. * @typedef {(pathOrFileDescription: PathOrFileDescriptor, callback: ReadJsonCallback) => void} ReadJson
  222. */
  223. /**
  224. * @typedef {(pathOrFileDescription: PathOrFileDescriptor) => JsonObject} ReadJsonSync
  225. */
  226. /**
  227. * @typedef {{
  228. * (path: PathLike, options: EncodingOption, callback: StringCallback): void,
  229. * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void,
  230. * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void,
  231. * (path: PathLike, callback: StringCallback): void,
  232. * }} Readlink
  233. */
  234. /**
  235. * @typedef {{
  236. * (path: PathLike, options?: EncodingOption): string,
  237. * (path: PathLike, options: BufferEncodingOption): Buffer,
  238. * (path: PathLike, options?: EncodingOption): string | Buffer,
  239. * }} ReadlinkSync
  240. */
  241. /**
  242. * @typedef {{
  243. * (path: PathLike, callback: StatsCallback): void,
  244. * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void,
  245. * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void,
  246. * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void,
  247. * }} LStat
  248. */
  249. /**
  250. * @typedef {{
  251. * (path: PathLike, options?: undefined): IStats,
  252. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined,
  253. * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined,
  254. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats,
  255. * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats,
  256. * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats,
  257. * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined,
  258. * }} LStatSync
  259. */
  260. /**
  261. * @typedef {{
  262. * (path: PathLike, callback: StatsCallback): void,
  263. * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void,
  264. * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void,
  265. * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void,
  266. * }} Stat
  267. */
  268. /**
  269. * @typedef {{
  270. * (path: PathLike, options?: undefined): IStats,
  271. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined,
  272. * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined,
  273. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats,
  274. * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats,
  275. * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats,
  276. * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined,
  277. * }} StatSync
  278. */
  279. /**
  280. * @typedef {{
  281. * (path: PathLike, options: EncodingOption, callback: StringCallback): void,
  282. * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void,
  283. * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void,
  284. * (path: PathLike, callback: StringCallback): void,
  285. * }} RealPath
  286. */
  287. /**
  288. * @typedef {{
  289. * (path: PathLike, options?: EncodingOption): string,
  290. * (path: PathLike, options: BufferEncodingOption): Buffer,
  291. * (path: PathLike, options?: EncodingOption): string | Buffer,
  292. * }} RealPathSync
  293. */
  294. /**
  295. * @typedef {object} FileSystem
  296. * @property {ReadFile} readFile read file method
  297. * @property {Readdir} readdir readdir method
  298. * @property {ReadJson=} readJson read json method
  299. * @property {Readlink} readlink read link method
  300. * @property {LStat=} lstat lstat method
  301. * @property {Stat} stat stat method
  302. * @property {RealPath=} realpath realpath method
  303. */
  304. /**
  305. * @typedef {object} SyncFileSystem
  306. * @property {ReadFileSync} readFileSync read file sync method
  307. * @property {ReaddirSync} readdirSync read dir sync method
  308. * @property {ReadJsonSync=} readJsonSync read json sync method
  309. * @property {ReadlinkSync} readlinkSync read link sync method
  310. * @property {LStatSync=} lstatSync lstat sync method
  311. * @property {StatSync} statSync stat sync method
  312. * @property {RealPathSync=} realpathSync real path sync method
  313. */
  314. /**
  315. * @typedef {object} ParsedIdentifier
  316. * @property {string} request request
  317. * @property {string} query query
  318. * @property {string} fragment fragment
  319. * @property {boolean} directory is directory
  320. * @property {boolean} module is module
  321. * @property {boolean} file is file
  322. * @property {boolean} internal is internal
  323. */
  324. /** @typedef {string | number | boolean | null} JsonPrimitive */
  325. /** @typedef {JsonValue[]} JsonArray */
  326. /** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */
  327. /** @typedef {{ [Key in string]?: JsonValue | undefined }} JsonObject */
  328. /**
  329. * @typedef {object} TsconfigPathsMap
  330. * @property {TsconfigPathsData} main main tsconfig paths data
  331. * @property {string} mainContext main tsconfig base URL (absolute path)
  332. * @property {{ [baseUrl: string]: TsconfigPathsData }} refs referenced tsconfig paths data mapped by baseUrl
  333. * @property {{ [context: string]: TsconfigPathsData }} allContexts all contexts (main + refs) for quick lookup
  334. * @property {string[]} contextList precomputed `Object.keys(allContexts)` — read-only; used on the `_selectPathsDataForContext` hot path
  335. * @property {Set<string>} fileDependencies file dependencies
  336. */
  337. /**
  338. * @typedef {object} TsconfigPathsData
  339. * @property {import("./AliasUtils").CompiledAliasOption[]} alias tsconfig file data
  340. * @property {string[]} modules tsconfig file data
  341. */
  342. /**
  343. * @typedef {object} BaseResolveRequest
  344. * @property {string | false} path path
  345. * @property {Context=} context content
  346. * @property {string=} descriptionFilePath description file path
  347. * @property {string=} descriptionFileRoot description file root
  348. * @property {JsonObject=} descriptionFileData description file data
  349. * @property {TsconfigPathsMap | null | undefined=} tsconfigPathsMap tsconfig paths map
  350. * @property {string=} relativePath relative path
  351. * @property {boolean=} ignoreSymlinks true when need to ignore symlinks, otherwise false
  352. * @property {boolean=} fullySpecified true when full specified, otherwise false
  353. * @property {string=} __innerRequest inner request for internal usage
  354. * @property {string=} __innerRequest_request inner request for internal usage
  355. * @property {string=} __innerRequest_relativePath inner relative path for internal usage
  356. */
  357. /** @typedef {BaseResolveRequest & Partial<ParsedIdentifier>} ResolveRequest */
  358. /**
  359. * @template T
  360. * @typedef {{ add: (item: T) => void }} WriteOnlySet
  361. */
  362. /** @typedef {(request: ResolveRequest) => void} ResolveContextYield */
  363. /**
  364. * Singly-linked stack entry that also exposes a Set-like API
  365. * (`has`, `size`, iteration). Each `doResolve` call prepends a new
  366. * `StackEntry` that points at the previous tip via `.parent`, so pushing
  367. * is O(1) in time and memory. Recursion detection walks the linked list
  368. * (O(n)) but the stack is typically shallow, so this is cheaper overall
  369. * than cloning a `Set` per call.
  370. */
  371. class StackEntry {
  372. /**
  373. * @param {ResolveStepHook} hook hook
  374. * @param {ResolveRequest} request request
  375. * @param {StackEntry=} parent previous tip
  376. * @param {Set<string>=} preSeeded entries pre-seeded via the legacy `Set<string>` API
  377. */
  378. constructor(hook, request, parent, preSeeded) {
  379. this.name = hook.name;
  380. this.path = request.path;
  381. this.request = request.request || "";
  382. this.query = request.query || "";
  383. this.fragment = request.fragment || "";
  384. this.directory = Boolean(request.directory);
  385. this.module = Boolean(request.module);
  386. /** @type {StackEntry | undefined} */
  387. this.parent = parent;
  388. /**
  389. * Strings seeded by callers that still pass `stack: new Set([...])`.
  390. * Propagated through the chain so deeper `doResolve` calls still see
  391. * them during recursion checks. `undefined` in the common case so
  392. * there is no extra work on the hot path.
  393. * @type {Set<string> | undefined}
  394. */
  395. this.preSeeded = preSeeded;
  396. }
  397. /**
  398. * Walk the linked list looking for an entry with the same request shape.
  399. * Set-compatible: callers that used `stack.has(entry)` keep working.
  400. *
  401. * NOTE: kept monomorphic on purpose. An earlier draft accepted a string
  402. * query too (so pre-5.21 plugins keeping their own `Set<string>` of
  403. * seen entries could probe the live stack with the formatted form),
  404. * but adding the second shape regressed `doResolve`'s heap profile by
  405. * ~1 MiB / 200 resolves on stack-churn — V8 keeps a polymorphic
  406. * call-site state for `parent.has(stackEntry)` once `has` has two
  407. * argument shapes. Plugins that need string membership can reach for
  408. * `[...stack].find(e => e.includes(formattedString))` via the
  409. * `String`-method proxies on `StackEntry` instead.
  410. * @param {StackEntry} query entry to look for
  411. * @returns {boolean} whether the stack already contains an equivalent entry
  412. */
  413. has(query) {
  414. /** @type {StackEntry | undefined} */
  415. let node = this;
  416. while (node) {
  417. if (
  418. node.name === query.name &&
  419. node.path === query.path &&
  420. node.request === query.request &&
  421. node.query === query.query &&
  422. node.fragment === query.fragment &&
  423. node.directory === query.directory &&
  424. node.module === query.module
  425. ) {
  426. return true;
  427. }
  428. node = node.parent;
  429. }
  430. return this.preSeeded !== undefined && this.preSeeded.has(query.toString());
  431. }
  432. /**
  433. * Number of entries on the stack (oldest-to-newest length).
  434. * @returns {number} size
  435. */
  436. get size() {
  437. let count = this.preSeeded ? this.preSeeded.size : 0;
  438. /** @type {StackEntry | undefined} */
  439. let node = this;
  440. while (node) {
  441. count++;
  442. node = node.parent;
  443. }
  444. return count;
  445. }
  446. /**
  447. * Iterate entries from oldest (root) to newest (tip), matching how a
  448. * `Set` that was populated in insertion order would iterate. Pre-seeded
  449. * legacy `Set<string>` entries come first so error-message output stays
  450. * ordered oldest-to-newest.
  451. *
  452. * Yields each entry as its formatted `toString()` form. Plugins written
  453. * against the pre-5.21 `Set<string>` shape — e.g.
  454. * `[...resolveContext.stack].find(a => a.includes("module:"))` — keep
  455. * working unchanged because each yielded value is a plain string with
  456. * all of `String.prototype` available natively. Resolves that never
  457. * iterate the stack pay nothing; iteration costs one `toString()`
  458. * allocation per stack frame.
  459. * @returns {IterableIterator<string>} iterator
  460. */
  461. *[Symbol.iterator]() {
  462. if (this.preSeeded !== undefined) {
  463. for (const entry of this.preSeeded) yield entry;
  464. }
  465. /** @type {StackEntry[]} */
  466. const entries = [];
  467. /** @type {StackEntry | undefined} */
  468. let node = this;
  469. while (node) {
  470. entries.push(node);
  471. node = node.parent;
  472. }
  473. for (let i = entries.length - 1; i >= 0; i--) yield entries[i].toString();
  474. }
  475. /**
  476. * Human-readable form used in recursion error messages, logs, and the
  477. * iterator above. Not memoized: caching would require an extra slot on
  478. * every `StackEntry`, which costs heap even on resolves that never look
  479. * at the formatted form.
  480. * @returns {string} formatted entry
  481. */
  482. toString() {
  483. return `${this.name}: (${this.path}) ${this.request}${this.query}${
  484. this.fragment
  485. }${this.directory ? " directory" : ""}${this.module ? " module" : ""}`;
  486. }
  487. }
  488. /**
  489. * Resolve context
  490. * @typedef {object} ResolveContext
  491. * @property {WriteOnlySet<string>=} contextDependencies directories that was found on file system
  492. * @property {WriteOnlySet<string>=} fileDependencies files that was found on file system
  493. * @property {WriteOnlySet<string>=} missingDependencies dependencies that was not found on file system
  494. * @property {StackEntry | Set<string>=} stack tip of the resolver call stack (a singly-linked list with Set-like API). For instance, `resolve → parsedResolve → describedResolve`. Accepts a legacy `Set<string>` for back-compat with older callers; it is normalized internally without a hot-path branch.
  495. * @property {((str: string) => void)=} log log function
  496. * @property {ResolveContextYield=} yield yield result, if provided plugins can return several results
  497. */
  498. /** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */
  499. /**
  500. * @typedef {object} KnownHooks
  501. * @property {SyncHook<[ResolveStepHook, ResolveRequest], void>} resolveStep resolve step hook
  502. * @property {SyncHook<[ResolveRequest, Error]>} noResolve no resolve hook
  503. * @property {ResolveStepHook} resolve resolve hook
  504. * @property {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} result result hook
  505. */
  506. /**
  507. * @typedef {{ [key: string]: ResolveStepHook }} EnsuredHooks
  508. */
  509. /**
  510. * @param {string} str input string
  511. * @returns {string} in camel case
  512. */
  513. function toCamelCase(str) {
  514. return str.replace(/-([a-z])/g, (str) => str.slice(1).toUpperCase());
  515. }
  516. class Resolver {
  517. /**
  518. * @param {ResolveStepHook} hook hook
  519. * @param {ResolveRequest} request request
  520. * @param {StackEntry=} parent previous tip of the stack
  521. * @param {Set<string>=} preSeeded entries pre-seeded via the legacy `Set<string>` API
  522. * @returns {StackEntry} stack entry
  523. */
  524. static createStackEntry(hook, request, parent, preSeeded) {
  525. return new StackEntry(hook, request, parent, preSeeded);
  526. }
  527. /**
  528. * @param {FileSystem} fileSystem a filesystem
  529. * @param {ResolveOptions} options options
  530. */
  531. constructor(fileSystem, options) {
  532. /** @type {FileSystem} */
  533. this.fileSystem = fileSystem;
  534. /** @type {ResolveOptions} */
  535. this.options = options;
  536. let pathCache = _pathCacheByFs.get(fileSystem);
  537. if (!pathCache) {
  538. pathCache = {
  539. join: createCachedJoin(),
  540. dirname: createCachedDirname(),
  541. basename: createCachedBasename(),
  542. };
  543. _pathCacheByFs.set(fileSystem, pathCache);
  544. }
  545. /** @type {PathCacheFunctions} */
  546. this.pathCache = pathCache;
  547. /** @type {KnownHooks} */
  548. this.hooks = {
  549. resolveStep: new SyncHook(["hook", "request"], "resolveStep"),
  550. noResolve: new SyncHook(["request", "error"], "noResolve"),
  551. resolve: new AsyncSeriesBailHook(
  552. ["request", "resolveContext"],
  553. "resolve",
  554. ),
  555. result: new AsyncSeriesHook(["result", "resolveContext"], "result"),
  556. };
  557. }
  558. /**
  559. * @param {string | ResolveStepHook} name hook name or hook itself
  560. * @returns {ResolveStepHook} the hook
  561. */
  562. ensureHook(name) {
  563. if (typeof name !== "string") {
  564. return name;
  565. }
  566. name = toCamelCase(name);
  567. if (name.startsWith("before")) {
  568. return /** @type {ResolveStepHook} */ (
  569. this.ensureHook(name[6].toLowerCase() + name.slice(7)).withOptions({
  570. stage: -10,
  571. })
  572. );
  573. }
  574. if (name.startsWith("after")) {
  575. return /** @type {ResolveStepHook} */ (
  576. this.ensureHook(name[5].toLowerCase() + name.slice(6)).withOptions({
  577. stage: 10,
  578. })
  579. );
  580. }
  581. /** @type {ResolveStepHook} */
  582. const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name];
  583. if (!hook) {
  584. /** @type {KnownHooks & EnsuredHooks} */
  585. (this.hooks)[name] = new AsyncSeriesBailHook(
  586. ["request", "resolveContext"],
  587. name,
  588. );
  589. return /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name];
  590. }
  591. return hook;
  592. }
  593. /**
  594. * @param {string | ResolveStepHook} name hook name or hook itself
  595. * @returns {ResolveStepHook} the hook
  596. */
  597. getHook(name) {
  598. if (typeof name !== "string") {
  599. return name;
  600. }
  601. name = toCamelCase(name);
  602. if (name.startsWith("before")) {
  603. return /** @type {ResolveStepHook} */ (
  604. this.getHook(name[6].toLowerCase() + name.slice(7)).withOptions({
  605. stage: -10,
  606. })
  607. );
  608. }
  609. if (name.startsWith("after")) {
  610. return /** @type {ResolveStepHook} */ (
  611. this.getHook(name[5].toLowerCase() + name.slice(6)).withOptions({
  612. stage: 10,
  613. })
  614. );
  615. }
  616. /** @type {ResolveStepHook} */
  617. const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name];
  618. if (!hook) {
  619. throw new Error(`Hook ${name} doesn't exist`);
  620. }
  621. return hook;
  622. }
  623. /**
  624. * @overload
  625. * @param {string} path context path
  626. * @param {string} request request string
  627. * @param {ResolveContext=} resolveContext resolve context
  628. * @returns {string | false} result
  629. */
  630. /**
  631. * @overload
  632. * @param {Context} context context information object
  633. * @param {string} path context path
  634. * @param {string} request request string
  635. * @param {ResolveContext=} resolveContext resolve context
  636. * @returns {string | false} result
  637. */
  638. /**
  639. * @param {Context | string} context context information object or context path when no context is provided
  640. * @param {string | ResolveContext=} path context path or resolve context when no context is provided
  641. * @param {string | ResolveContext=} request request string or resolve context when no context is provided
  642. * @param {ResolveContext=} resolveContext resolve context
  643. * @returns {string | false} result
  644. */
  645. resolveSync(context, path, request, resolveContext) {
  646. /** @type {Error | null | undefined} */
  647. let err;
  648. /** @type {string | false | undefined} */
  649. let result;
  650. let sync = false;
  651. // `|| {}` so the underlying `resolve()` hits its 5-arg fast path
  652. // (skips the overload-shifting prologue) regardless of whether the
  653. // caller supplied a resolveContext.
  654. this.resolve(
  655. /** @type {Context} */ (context),
  656. /** @type {string} */ (path),
  657. /** @type {string} */ (request),
  658. /** @type {ResolveContext} */ (resolveContext) || {},
  659. (_err, r) => {
  660. err = _err;
  661. result = r;
  662. sync = true;
  663. },
  664. );
  665. if (!sync) {
  666. throw new Error(
  667. "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!",
  668. );
  669. }
  670. if (err) throw err;
  671. if (result === undefined) throw new Error("No result");
  672. return result;
  673. }
  674. /**
  675. * @overload
  676. * @param {string} path context path
  677. * @param {string} request request string
  678. * @param {ResolveContext=} resolveContext resolve context
  679. * @returns {Promise<string | false>} result
  680. */
  681. /**
  682. * @overload
  683. * @param {Context} context context information object
  684. * @param {string} path context path
  685. * @param {string} request request string
  686. * @param {ResolveContext=} resolveContext resolve context
  687. * @returns {Promise<string | false>} result
  688. */
  689. /**
  690. * @param {Context | string} context context information object or context path when no context is provided
  691. * @param {string | ResolveContext=} path context path or resolve context when no context is provided
  692. * @param {string | ResolveContext=} request request string or resolve context when no context is provided
  693. * @param {ResolveContext=} resolveContext resolve context
  694. * @returns {Promise<string | false>} result
  695. */
  696. resolvePromise(context, path, request, resolveContext) {
  697. // `|| {}` ensures the 5-arg fast path inside `resolve()` is reached
  698. // even when the caller doesn't pass a resolveContext.
  699. return _withResolvers(
  700. this,
  701. /** @type {Context} */ (context),
  702. /** @type {string} */ (path),
  703. /** @type {string} */ (request),
  704. /** @type {ResolveContext} */ (resolveContext) || {},
  705. );
  706. }
  707. /**
  708. * @overload
  709. * @param {string} path context path
  710. * @param {string} request request string
  711. * @param {ResolveCallback} callback callback function
  712. * @returns {void}
  713. */
  714. /**
  715. * @overload
  716. * @param {string} path context path
  717. * @param {string} request request string
  718. * @param {ResolveContext} resolveContext resolve context
  719. * @param {ResolveCallback} callback callback function
  720. * @returns {void}
  721. */
  722. /**
  723. * @overload
  724. * @param {Context} context context information object
  725. * @param {string} path context path
  726. * @param {string} request request string
  727. * @param {ResolveCallback} callback callback function
  728. * @returns {void}
  729. */
  730. /**
  731. * @overload
  732. * @param {Context} context context information object
  733. * @param {string} path context path
  734. * @param {string} request request string
  735. * @param {ResolveContext} resolveContext resolve context
  736. * @param {ResolveCallback} callback callback function
  737. * @returns {void}
  738. */
  739. /**
  740. * @param {Context | string} context context information object or context path when no context is provided
  741. * @param {string | ResolveContext | ResolveCallback=} path context path or (when no context) resolve context or callback
  742. * @param {string | ResolveContext | ResolveCallback=} request request string or (when no context) resolve context or callback
  743. * @param {ResolveContext | ResolveCallback=} resolveContext resolve context or callback when no resolve context is provided
  744. * @param {ResolveCallback=} callback callback function
  745. * @returns {void}
  746. */
  747. resolve(context, path, request, resolveContext, callback) {
  748. // Fast path for the common 5-arg call (`resolver.resolve(ctx, from,
  749. // req, resolveCtx, cb)`) — every call from `resolveSync` /
  750. // `resolvePromise` plus the vast majority of direct API callers.
  751. // PR #536 added runtime overload-shifting to support optional
  752. // `context` / `resolveContext`; that adds several `typeof` checks
  753. // per resolve which show up as a measurable instruction-count
  754. // regression on every benchmark that calls into this method. Skip
  755. // the shifting entirely when all 5 args are already well-typed.
  756. if (
  757. typeof callback === "function" &&
  758. typeof context === "object" &&
  759. context !== null &&
  760. typeof resolveContext === "object" &&
  761. resolveContext !== null
  762. ) {
  763. // proceed straight to per-arg validation below
  764. } else {
  765. // Slow path: shift positional args based on what was supplied.
  766. // Shift when context is omitted (first positional arg is the path string).
  767. if (typeof context === "string") {
  768. // Keep an already-supplied callback (resolveSync / resolvePromise
  769. // always pass one in the 5th position).
  770. if (typeof callback !== "function") {
  771. callback = /** @type {ResolveCallback | undefined} */ (
  772. resolveContext
  773. );
  774. }
  775. resolveContext =
  776. /** @type {ResolveContext | ResolveCallback | undefined} */ (request);
  777. request = /** @type {string} */ (path);
  778. path = context;
  779. context = {};
  780. }
  781. // 4-arg form: the resolveContext slot holds the callback.
  782. if (typeof resolveContext === "function") {
  783. callback = resolveContext;
  784. resolveContext = {};
  785. } else if (!resolveContext || typeof resolveContext !== "object") {
  786. resolveContext = {};
  787. }
  788. if (typeof callback !== "function") {
  789. throw new TypeError("callback argument is not a function");
  790. }
  791. if (!context || typeof context !== "object") {
  792. context = {};
  793. }
  794. }
  795. if (typeof path !== "string") {
  796. return callback(new Error("path argument is not a string"));
  797. }
  798. if (typeof request !== "string") {
  799. return callback(new Error("request argument is not a string"));
  800. }
  801. /** @type {ResolveRequest} */
  802. const obj = {
  803. context,
  804. path,
  805. request,
  806. };
  807. /** @type {ResolveContextYield | undefined} */
  808. let yield_;
  809. let yieldCalled = false;
  810. /** @type {ResolveContextYield | undefined} */
  811. let finishYield;
  812. if (typeof resolveContext.yield === "function") {
  813. const old = resolveContext.yield;
  814. /**
  815. * @param {ResolveRequest} obj object
  816. */
  817. yield_ = (obj) => {
  818. old(obj);
  819. yieldCalled = true;
  820. };
  821. /**
  822. * @param {ResolveRequest} result result
  823. * @returns {void}
  824. */
  825. finishYield = (result) => {
  826. if (result) {
  827. /** @type {ResolveContextYield} */ (yield_)(result);
  828. }
  829. callback(null);
  830. };
  831. }
  832. const message = `resolve '${request}' in '${path}'`;
  833. /**
  834. * @param {ResolveRequest} result result
  835. * @returns {void}
  836. */
  837. const finishResolved = (result) => {
  838. const resultPath = result.path;
  839. if (resultPath === false) return callback(null, false, result);
  840. const escapedPath = resultPath.includes("#")
  841. ? resultPath.replace(HASH_ESCAPE_RE, "\0#")
  842. : resultPath;
  843. const resultQuery = result.query;
  844. let escapedQuery;
  845. if (resultQuery) {
  846. escapedQuery = resultQuery.includes("#")
  847. ? resultQuery.replace(HASH_ESCAPE_RE, "\0#")
  848. : resultQuery;
  849. } else {
  850. escapedQuery = "";
  851. }
  852. return callback(
  853. null,
  854. `${escapedPath}${escapedQuery}${result.fragment || ""}`,
  855. result,
  856. );
  857. };
  858. /**
  859. * @param {string[]} log logs
  860. * @returns {void}
  861. */
  862. const finishWithoutResolve = (log) => {
  863. /**
  864. * @type {ErrorWithDetail}
  865. */
  866. const error = new Error(`Can't ${message}`);
  867. error.details = log.join("\n");
  868. this.hooks.noResolve.call(obj, error);
  869. return callback(error);
  870. };
  871. if (resolveContext.log) {
  872. // We need log anyway to capture it in case of an error
  873. const parentLog = resolveContext.log;
  874. /** @type {string[]} */
  875. const log = [];
  876. return this.doResolve(
  877. this.hooks.resolve,
  878. obj,
  879. message,
  880. {
  881. log: (msg) => {
  882. parentLog(msg);
  883. log.push(msg);
  884. },
  885. yield: yield_,
  886. fileDependencies: resolveContext.fileDependencies,
  887. contextDependencies: resolveContext.contextDependencies,
  888. missingDependencies: resolveContext.missingDependencies,
  889. stack: resolveContext.stack,
  890. },
  891. (err, result) => {
  892. if (err) return callback(err);
  893. if (yieldCalled || (result && yield_)) {
  894. return /** @type {ResolveContextYield} */ (finishYield)(
  895. /** @type {ResolveRequest} */ (result),
  896. );
  897. }
  898. if (result) return finishResolved(result);
  899. return finishWithoutResolve(log);
  900. },
  901. );
  902. }
  903. // Try to resolve assuming there is no error
  904. // We don't log stuff in this case
  905. return this.doResolve(
  906. this.hooks.resolve,
  907. obj,
  908. message,
  909. {
  910. log: undefined,
  911. yield: yield_,
  912. fileDependencies: resolveContext.fileDependencies,
  913. contextDependencies: resolveContext.contextDependencies,
  914. missingDependencies: resolveContext.missingDependencies,
  915. stack: resolveContext.stack,
  916. },
  917. (err, result) => {
  918. if (err) return callback(err);
  919. if (yieldCalled || (result && yield_)) {
  920. return /** @type {ResolveContextYield} */ (finishYield)(
  921. /** @type {ResolveRequest} */ (result),
  922. );
  923. }
  924. if (result) return finishResolved(result);
  925. // log is missing for the error details
  926. // so we redo the resolving for the log info
  927. // this is more expensive to the success case
  928. // is assumed by default
  929. /** @type {string[]} */
  930. const log = [];
  931. return this.doResolve(
  932. this.hooks.resolve,
  933. obj,
  934. message,
  935. {
  936. log: (msg) => log.push(msg),
  937. yield: yield_,
  938. stack: resolveContext.stack,
  939. },
  940. (err, result) => {
  941. if (err) return callback(err);
  942. // In a case that there is a race condition and yield will be called
  943. if (yieldCalled || (result && yield_)) {
  944. return /** @type {ResolveContextYield} */ (finishYield)(
  945. /** @type {ResolveRequest} */ (result),
  946. );
  947. }
  948. return finishWithoutResolve(log);
  949. },
  950. );
  951. },
  952. );
  953. }
  954. /**
  955. * @param {ResolveStepHook} hook hook
  956. * @param {ResolveRequest} request request
  957. * @param {null | string} message string
  958. * @param {ResolveContext} resolveContext resolver context
  959. * @param {(err?: null | Error, result?: ResolveRequest) => void} callback callback
  960. * @returns {void}
  961. */
  962. doResolve(hook, request, message, resolveContext, callback) {
  963. const rawStack = resolveContext.stack;
  964. /** @type {StackEntry | undefined} */
  965. let parent;
  966. /** @type {Set<string> | undefined} */
  967. let preSeeded;
  968. if (rawStack instanceof StackEntry) {
  969. parent = rawStack;
  970. preSeeded = rawStack.preSeeded;
  971. } else if (rawStack) {
  972. // TODO in the next major remove `Set<string>` support in favor of `StackEntry`
  973. // Legacy `stack: new Set<string>()` API: don't link the Set into
  974. // the parent chain (it would pollute iteration and field-compare
  975. // walks). Carry the strings on the StackEntry itself instead so
  976. // deeper `doResolve` calls keep seeing pre-seeded entries.
  977. preSeeded = /** @type {Set<string>} */ (rawStack);
  978. }
  979. // Prepend a new linked-list node. O(1) allocation, no Set clone.
  980. const stackEntry = Resolver.createStackEntry(
  981. hook,
  982. request,
  983. parent,
  984. preSeeded,
  985. );
  986. // When `parent` exists, its `has()` already consults `preSeeded`
  987. // (inherited from the same chain), so we only need the direct Set
  988. // lookup on the very first `doResolve` call (no parent yet).
  989. if (
  990. parent !== undefined
  991. ? parent.has(stackEntry)
  992. : preSeeded !== undefined && preSeeded.has(stackEntry.toString())
  993. ) {
  994. /**
  995. * Prevent recursion
  996. * @type {Error & { recursion?: boolean }}
  997. */
  998. const recursionError = new Error(
  999. `Recursion in resolving\nStack:\n ${[...stackEntry].join("\n ")}`,
  1000. );
  1001. recursionError.recursion = true;
  1002. if (resolveContext.log) {
  1003. resolveContext.log("abort resolving because of recursion");
  1004. }
  1005. return callback(recursionError);
  1006. }
  1007. this.hooks.resolveStep.call(hook, request);
  1008. if (hook.isUsed()) {
  1009. // Pass `resolveContext` and the override fields (stack, message)
  1010. // directly instead of constructing an intermediate options-object
  1011. // literal — `createInnerContext` reads from the parent and
  1012. // allocates exactly one inner context per step. See the comment
  1013. // on `createInnerContext` itself for the allocation rationale.
  1014. const innerContext = createInnerContext(
  1015. resolveContext,
  1016. stackEntry,
  1017. message,
  1018. );
  1019. return hook.callAsync(request, innerContext, (err, result) => {
  1020. if (err) return callback(err);
  1021. if (result) return callback(null, result);
  1022. callback();
  1023. });
  1024. }
  1025. callback();
  1026. }
  1027. /**
  1028. * @param {string} identifier identifier
  1029. * @returns {ParsedIdentifier} parsed identifier
  1030. */
  1031. parse(identifier) {
  1032. /** @type {ParsedIdentifier} */
  1033. const part = {
  1034. request: "",
  1035. query: "",
  1036. fragment: "",
  1037. module: false,
  1038. directory: false,
  1039. file: false,
  1040. internal: false,
  1041. };
  1042. const parsedIdentifier = parseIdentifier(identifier);
  1043. if (!parsedIdentifier) return part;
  1044. [part.request, part.query, part.fragment] = parsedIdentifier;
  1045. if (part.request.length > 0) {
  1046. // `getType` looks at the prefix of its input and the prefix is
  1047. // identical between `identifier` and `part.request` in every
  1048. // non-`\0`-escape case (slicing off `?query` / `#fragment` doesn't
  1049. // touch the head). `parseIdentifier`'s common fast path returns
  1050. // the same `identifier` reference as `parsedIdentifier[0]`, so a
  1051. // pointer-equality check detects the case where we can compute
  1052. // `getType` once and use it for both `module` and `internal`. The
  1053. // `\0#…` escape path produces a fresh `part.request` and falls
  1054. // through to the second `getType(identifier)` call to preserve
  1055. // the original `internal` flag.
  1056. const requestType = getType(part.request);
  1057. part.module = requestType === PathType.Normal;
  1058. part.internal =
  1059. identifier === part.request
  1060. ? requestType === PathType.Internal
  1061. : getType(identifier) === PathType.Internal;
  1062. // `isDirectory` is just `endsWith("/")` — inline so `parse()`
  1063. // doesn't pay for the extra method dispatch on every resolve.
  1064. part.directory = part.request.endsWith("/");
  1065. if (part.directory) {
  1066. part.request = part.request.slice(0, -1);
  1067. }
  1068. }
  1069. return part;
  1070. }
  1071. /**
  1072. * @param {string} path path
  1073. * @returns {boolean} true, if the path is a module
  1074. */
  1075. isModule(path) {
  1076. return getType(path) === PathType.Normal;
  1077. }
  1078. /**
  1079. * @param {string} path path
  1080. * @returns {boolean} true, if the path is private
  1081. */
  1082. isPrivate(path) {
  1083. return getType(path) === PathType.Internal;
  1084. }
  1085. /**
  1086. * @param {string} path a path
  1087. * @returns {boolean} true, if the path is a directory path
  1088. */
  1089. isDirectory(path) {
  1090. return path.endsWith("/");
  1091. }
  1092. /**
  1093. * @param {string} path path
  1094. * @returns {string} normalized path
  1095. */
  1096. normalize(path) {
  1097. return normalize(path);
  1098. }
  1099. /**
  1100. * @param {string} path path
  1101. * @param {string} request request
  1102. * @returns {string} joined path
  1103. */
  1104. join(path, request) {
  1105. return this.pathCache.join.fn(path, request);
  1106. }
  1107. /**
  1108. * @param {string} path path
  1109. * @returns {string} parent directory
  1110. */
  1111. dirname(path) {
  1112. return this.pathCache.dirname.fn(path);
  1113. }
  1114. /**
  1115. * @param {string} path the path to evaluate
  1116. * @param {string=} suffix an extension to remove from the result
  1117. * @returns {string} the last portion of a path
  1118. */
  1119. basename(path, suffix) {
  1120. return this.pathCache.basename.fn(path, suffix);
  1121. }
  1122. }
  1123. module.exports = Resolver;