Resolver.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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. cachedJoin: join,
  12. getType,
  13. normalize,
  14. } = require("./util/path");
  15. /** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */
  16. /** @typedef {Error & { details?: string }} ErrorWithDetail */
  17. /** @typedef {(err: ErrorWithDetail | null, res?: string | false, req?: ResolveRequest) => void} ResolveCallback */
  18. /**
  19. * @typedef {object} PossibleFileSystemError
  20. * @property {string=} code code
  21. * @property {number=} errno number
  22. * @property {string=} path path
  23. * @property {string=} syscall syscall
  24. */
  25. /**
  26. * @template T
  27. * @callback FileSystemCallback
  28. * @param {PossibleFileSystemError & Error | null} err
  29. * @param {T=} result
  30. */
  31. /**
  32. * @typedef {string | Buffer | URL} PathLike
  33. */
  34. /**
  35. * @typedef {PathLike | number} PathOrFileDescriptor
  36. */
  37. /**
  38. * @typedef {object} ObjectEncodingOptions
  39. * @property {BufferEncoding | null | undefined=} encoding encoding
  40. */
  41. /**
  42. * @typedef {ObjectEncodingOptions | BufferEncoding | undefined | null} EncodingOption
  43. */
  44. /** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */
  45. /** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer) => void} BufferCallback */
  46. /** @typedef {(err: NodeJS.ErrnoException | null, result?: (string | Buffer)) => void} StringOrBufferCallback */
  47. /** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats) => void} StatsCallback */
  48. /** @typedef {(err: NodeJS.ErrnoException | null, result?: IBigIntStats) => void} BigIntStatsCallback */
  49. /** @typedef {(err: NodeJS.ErrnoException | null, result?: (IStats | IBigIntStats)) => void} StatsOrBigIntStatsCallback */
  50. /** @typedef {(err: NodeJS.ErrnoException | Error | null, result?: JsonObject) => void} ReadJsonCallback */
  51. /**
  52. * @template T
  53. * @typedef {object} IStatsBase
  54. * @property {() => boolean} isFile is file
  55. * @property {() => boolean} isDirectory is directory
  56. * @property {() => boolean} isBlockDevice is block device
  57. * @property {() => boolean} isCharacterDevice is character device
  58. * @property {() => boolean} isSymbolicLink is symbolic link
  59. * @property {() => boolean} isFIFO is FIFO
  60. * @property {() => boolean} isSocket is socket
  61. * @property {T} dev dev
  62. * @property {T} ino ino
  63. * @property {T} mode mode
  64. * @property {T} nlink nlink
  65. * @property {T} uid uid
  66. * @property {T} gid gid
  67. * @property {T} rdev rdev
  68. * @property {T} size size
  69. * @property {T} blksize blksize
  70. * @property {T} blocks blocks
  71. * @property {T} atimeMs atime ms
  72. * @property {T} mtimeMs mtime ms
  73. * @property {T} ctimeMs ctime ms
  74. * @property {T} birthtimeMs birthtime ms
  75. * @property {Date} atime atime
  76. * @property {Date} mtime mtime
  77. * @property {Date} ctime ctime
  78. * @property {Date} birthtime birthtime
  79. */
  80. /**
  81. * @typedef {IStatsBase<number>} IStats
  82. */
  83. /**
  84. * @typedef {IStatsBase<bigint> & { atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint, birthtimeNs: bigint }} IBigIntStats
  85. */
  86. /**
  87. * @template {string | Buffer} [T=string]
  88. * @typedef {object} Dirent
  89. * @property {() => boolean} isFile true when is file, otherwise false
  90. * @property {() => boolean} isDirectory true when is directory, otherwise false
  91. * @property {() => boolean} isBlockDevice true when is block device, otherwise false
  92. * @property {() => boolean} isCharacterDevice true when is character device, otherwise false
  93. * @property {() => boolean} isSymbolicLink true when is symbolic link, otherwise false
  94. * @property {() => boolean} isFIFO true when is FIFO, otherwise false
  95. * @property {() => boolean} isSocket true when is socket, otherwise false
  96. * @property {T} name name
  97. * @property {string} parentPath path
  98. * @property {string=} path path
  99. */
  100. /**
  101. * @typedef {object} StatOptions
  102. * @property {(boolean | undefined)=} bigint need bigint values
  103. */
  104. /**
  105. * @typedef {object} StatSyncOptions
  106. * @property {(boolean | undefined)=} bigint need bigint values
  107. * @property {(boolean | undefined)=} throwIfNoEntry throw if no entry
  108. */
  109. /**
  110. * @typedef {{
  111. * (path: PathOrFileDescriptor, options: ({ encoding?: null | undefined, flag?: string | undefined } & import("events").Abortable) | undefined | null, callback: BufferCallback): void;
  112. * (path: PathOrFileDescriptor, options: ({ encoding: BufferEncoding, flag?: string | undefined } & import("events").Abortable) | BufferEncoding, callback: StringCallback): void;
  113. * (path: PathOrFileDescriptor, options: (ObjectEncodingOptions & { flag?: string | undefined } & import("events").Abortable) | BufferEncoding | undefined | null, callback: StringOrBufferCallback): void;
  114. * (path: PathOrFileDescriptor, callback: BufferCallback): void;
  115. * }} ReadFile
  116. */
  117. /**
  118. * @typedef {'buffer'| { encoding: 'buffer' }} BufferEncodingOption
  119. */
  120. /**
  121. * @typedef {{
  122. * (path: PathOrFileDescriptor, options?: { encoding?: null | undefined, flag?: string | undefined } | null): Buffer;
  123. * (path: PathOrFileDescriptor, options: { encoding: BufferEncoding, flag?: string | undefined } | BufferEncoding): string;
  124. * (path: PathOrFileDescriptor, options?: (ObjectEncodingOptions & { flag?: string | undefined }) | BufferEncoding | null): string | Buffer;
  125. * }} ReadFileSync
  126. */
  127. /**
  128. * @typedef {{
  129. * (path: PathLike, options: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void;
  130. * (path: PathLike, options: { encoding: 'buffer', withFileTypes?: false | undefined, recursive?: boolean | undefined } | 'buffer', callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void): void;
  131. * (path: PathLike, options: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[] | Buffer[]) => void): void;
  132. * (path: PathLike, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void;
  133. * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files?: Dirent<string>[]) => void): void;
  134. * (path: PathLike, options: { encoding: 'buffer', withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files: Dirent<Buffer>[]) => void): void;
  135. * }} Readdir
  136. */
  137. /**
  138. * @typedef {{
  139. * (path: PathLike, options?: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined; } | BufferEncoding | null): string[];
  140. * (path: PathLike, options: { encoding: 'buffer', withFileTypes?: false | undefined, recursive?: boolean | undefined } | 'buffer'): Buffer[];
  141. * (path: PathLike, options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | null): string[] | Buffer[];
  142. * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }): Dirent[];
  143. * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }): Dirent<Buffer>[];
  144. * }} ReaddirSync
  145. */
  146. /**
  147. * @typedef {(pathOrFileDescription: PathOrFileDescriptor, callback: ReadJsonCallback) => void} ReadJson
  148. */
  149. /**
  150. * @typedef {(pathOrFileDescription: PathOrFileDescriptor) => JsonObject} ReadJsonSync
  151. */
  152. /**
  153. * @typedef {{
  154. * (path: PathLike, options: EncodingOption, callback: StringCallback): void;
  155. * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void;
  156. * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void;
  157. * (path: PathLike, callback: StringCallback): void;
  158. * }} Readlink
  159. */
  160. /**
  161. * @typedef {{
  162. * (path: PathLike, options?: EncodingOption): string;
  163. * (path: PathLike, options: BufferEncodingOption): Buffer;
  164. * (path: PathLike, options?: EncodingOption): string | Buffer;
  165. * }} ReadlinkSync
  166. */
  167. /**
  168. * @typedef {{
  169. * (path: PathLike, callback: StatsCallback): void;
  170. * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void;
  171. * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void;
  172. * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void;
  173. * }} LStat
  174. */
  175. /**
  176. * @typedef {{
  177. * (path: PathLike, options?: undefined): IStats;
  178. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined;
  179. * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined;
  180. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats;
  181. * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats;
  182. * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats;
  183. * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined;
  184. * }} LStatSync
  185. */
  186. /**
  187. * @typedef {{
  188. * (path: PathLike, callback: StatsCallback): void;
  189. * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void;
  190. * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void;
  191. * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void;
  192. * }} Stat
  193. */
  194. /**
  195. * @typedef {{
  196. * (path: PathLike, options?: undefined): IStats;
  197. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined;
  198. * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined;
  199. * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats;
  200. * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats;
  201. * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats;
  202. * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined;
  203. * }} StatSync
  204. */
  205. /**
  206. * @typedef {{
  207. * (path: PathLike, options: EncodingOption, callback: StringCallback): void;
  208. * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void;
  209. * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void;
  210. * (path: PathLike, callback: StringCallback): void;
  211. * }} RealPath
  212. */
  213. /**
  214. * @typedef {{
  215. * (path: PathLike, options?: EncodingOption): string;
  216. * (path: PathLike, options: BufferEncodingOption): Buffer;
  217. * (path: PathLike, options?: EncodingOption): string | Buffer;
  218. * }} RealPathSync
  219. */
  220. /**
  221. * @typedef {object} FileSystem
  222. * @property {ReadFile} readFile read file method
  223. * @property {Readdir} readdir readdir method
  224. * @property {ReadJson=} readJson read json method
  225. * @property {Readlink} readlink read link method
  226. * @property {LStat=} lstat lstat method
  227. * @property {Stat} stat stat method
  228. * @property {RealPath=} realpath realpath method
  229. */
  230. /**
  231. * @typedef {object} SyncFileSystem
  232. * @property {ReadFileSync} readFileSync read file sync method
  233. * @property {ReaddirSync} readdirSync read dir sync method
  234. * @property {ReadJsonSync=} readJsonSync read json sync method
  235. * @property {ReadlinkSync} readlinkSync read link sync method
  236. * @property {LStatSync=} lstatSync lstat sync method
  237. * @property {StatSync} statSync stat sync method
  238. * @property {RealPathSync=} realpathSync real path sync method
  239. */
  240. /**
  241. * @typedef {object} ParsedIdentifier
  242. * @property {string} request request
  243. * @property {string} query query
  244. * @property {string} fragment fragment
  245. * @property {boolean} directory is directory
  246. * @property {boolean} module is module
  247. * @property {boolean} file is file
  248. * @property {boolean} internal is internal
  249. */
  250. /** @typedef {string | number | boolean | null} JsonPrimitive */
  251. /** @typedef {JsonValue[]} JsonArray */
  252. /** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */
  253. /** @typedef {{ [Key in string]?: JsonValue | undefined }} JsonObject */
  254. // eslint-disable-next-line jsdoc/require-property
  255. /** @typedef {object} Context */
  256. /**
  257. * @typedef {object} BaseResolveRequest
  258. * @property {string | false} path path
  259. * @property {Context=} context content
  260. * @property {string=} descriptionFilePath description file path
  261. * @property {string=} descriptionFileRoot description file root
  262. * @property {JsonObject=} descriptionFileData description file data
  263. * @property {string=} relativePath relative path
  264. * @property {boolean=} ignoreSymlinks true when need to ignore symlinks, otherwise false
  265. * @property {boolean=} fullySpecified true when full specified, otherwise false
  266. * @property {string=} __innerRequest inner request for internal usage
  267. * @property {string=} __innerRequest_request inner request for internal usage
  268. * @property {string=} __innerRequest_relativePath inner relative path for internal usage
  269. */
  270. /** @typedef {BaseResolveRequest & Partial<ParsedIdentifier>} ResolveRequest */
  271. /**
  272. * String with special formatting
  273. * @typedef {string} StackEntry
  274. */
  275. /**
  276. * @template T
  277. * @typedef {{ add: (item: T) => void }} WriteOnlySet
  278. */
  279. /** @typedef {(request: ResolveRequest) => void} ResolveContextYield */
  280. /**
  281. * Resolve context
  282. * @typedef {object} ResolveContext
  283. * @property {WriteOnlySet<string>=} contextDependencies directories that was found on file system
  284. * @property {WriteOnlySet<string>=} fileDependencies files that was found on file system
  285. * @property {WriteOnlySet<string>=} missingDependencies dependencies that was not found on file system
  286. * @property {Set<StackEntry>=} stack set of hooks' calls. For instance, `resolve → parsedResolve → describedResolve`,
  287. * @property {((str: string) => void)=} log log function
  288. * @property {ResolveContextYield=} yield yield result, if provided plugins can return several results
  289. */
  290. /** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */
  291. /**
  292. * @typedef {object} KnownHooks
  293. * @property {SyncHook<[ResolveStepHook, ResolveRequest], void>} resolveStep resolve step hook
  294. * @property {SyncHook<[ResolveRequest, Error]>} noResolve no resolve hook
  295. * @property {ResolveStepHook} resolve resolve hook
  296. * @property {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} result result hook
  297. */
  298. /**
  299. * @typedef {{[key: string]: ResolveStepHook}} EnsuredHooks
  300. */
  301. /**
  302. * @param {string} str input string
  303. * @returns {string} in camel case
  304. */
  305. function toCamelCase(str) {
  306. return str.replace(/-([a-z])/g, (str) => str.slice(1).toUpperCase());
  307. }
  308. class Resolver {
  309. /**
  310. * @param {ResolveStepHook} hook hook
  311. * @param {ResolveRequest} request request
  312. * @returns {StackEntry} stack entry
  313. */
  314. static createStackEntry(hook, request) {
  315. return `${hook.name}: (${request.path}) ${request.request || ""}${
  316. request.query || ""
  317. }${request.fragment || ""}${request.directory ? " directory" : ""}${
  318. request.module ? " module" : ""
  319. }`;
  320. }
  321. /**
  322. * @param {FileSystem} fileSystem a filesystem
  323. * @param {ResolveOptions} options options
  324. */
  325. constructor(fileSystem, options) {
  326. this.fileSystem = fileSystem;
  327. this.options = options;
  328. /** @type {KnownHooks} */
  329. this.hooks = {
  330. resolveStep: new SyncHook(["hook", "request"], "resolveStep"),
  331. noResolve: new SyncHook(["request", "error"], "noResolve"),
  332. resolve: new AsyncSeriesBailHook(
  333. ["request", "resolveContext"],
  334. "resolve",
  335. ),
  336. result: new AsyncSeriesHook(["result", "resolveContext"], "result"),
  337. };
  338. }
  339. /**
  340. * @param {string | ResolveStepHook} name hook name or hook itself
  341. * @returns {ResolveStepHook} the hook
  342. */
  343. ensureHook(name) {
  344. if (typeof name !== "string") {
  345. return name;
  346. }
  347. name = toCamelCase(name);
  348. if (name.startsWith("before")) {
  349. return /** @type {ResolveStepHook} */ (
  350. this.ensureHook(name[6].toLowerCase() + name.slice(7)).withOptions({
  351. stage: -10,
  352. })
  353. );
  354. }
  355. if (name.startsWith("after")) {
  356. return /** @type {ResolveStepHook} */ (
  357. this.ensureHook(name[5].toLowerCase() + name.slice(6)).withOptions({
  358. stage: 10,
  359. })
  360. );
  361. }
  362. /** @type {ResolveStepHook} */
  363. const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name];
  364. if (!hook) {
  365. /** @type {KnownHooks & EnsuredHooks} */
  366. (this.hooks)[name] = new AsyncSeriesBailHook(
  367. ["request", "resolveContext"],
  368. name,
  369. );
  370. return /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name];
  371. }
  372. return hook;
  373. }
  374. /**
  375. * @param {string | ResolveStepHook} name hook name or hook itself
  376. * @returns {ResolveStepHook} the hook
  377. */
  378. getHook(name) {
  379. if (typeof name !== "string") {
  380. return name;
  381. }
  382. name = toCamelCase(name);
  383. if (name.startsWith("before")) {
  384. return /** @type {ResolveStepHook} */ (
  385. this.getHook(name[6].toLowerCase() + name.slice(7)).withOptions({
  386. stage: -10,
  387. })
  388. );
  389. }
  390. if (name.startsWith("after")) {
  391. return /** @type {ResolveStepHook} */ (
  392. this.getHook(name[5].toLowerCase() + name.slice(6)).withOptions({
  393. stage: 10,
  394. })
  395. );
  396. }
  397. /** @type {ResolveStepHook} */
  398. const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name];
  399. if (!hook) {
  400. throw new Error(`Hook ${name} doesn't exist`);
  401. }
  402. return hook;
  403. }
  404. /**
  405. * @param {object} context context information object
  406. * @param {string} path context path
  407. * @param {string} request request string
  408. * @returns {string | false} result
  409. */
  410. resolveSync(context, path, request) {
  411. /** @type {Error | null | undefined} */
  412. let err;
  413. /** @type {string | false | undefined} */
  414. let result;
  415. let sync = false;
  416. this.resolve(context, path, request, {}, (_err, r) => {
  417. err = _err;
  418. result = r;
  419. sync = true;
  420. });
  421. if (!sync) {
  422. throw new Error(
  423. "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!",
  424. );
  425. }
  426. if (err) throw err;
  427. if (result === undefined) throw new Error("No result");
  428. return result;
  429. }
  430. /**
  431. * @param {object} context context information object
  432. * @param {string} path context path
  433. * @param {string} request request string
  434. * @param {ResolveContext} resolveContext resolve context
  435. * @param {ResolveCallback} callback callback function
  436. * @returns {void}
  437. */
  438. resolve(context, path, request, resolveContext, callback) {
  439. if (!context || typeof context !== "object") {
  440. return callback(new Error("context argument is not an object"));
  441. }
  442. if (typeof path !== "string") {
  443. return callback(new Error("path argument is not a string"));
  444. }
  445. if (typeof request !== "string") {
  446. return callback(new Error("request argument is not a string"));
  447. }
  448. if (!resolveContext) {
  449. return callback(new Error("resolveContext argument is not set"));
  450. }
  451. /** @type {ResolveRequest} */
  452. const obj = {
  453. context,
  454. path,
  455. request,
  456. };
  457. /** @type {ResolveContextYield | undefined} */
  458. let yield_;
  459. let yieldCalled = false;
  460. /** @type {ResolveContextYield | undefined} */
  461. let finishYield;
  462. if (typeof resolveContext.yield === "function") {
  463. const old = resolveContext.yield;
  464. /**
  465. * @param {ResolveRequest} obj object
  466. */
  467. yield_ = (obj) => {
  468. old(obj);
  469. yieldCalled = true;
  470. };
  471. /**
  472. * @param {ResolveRequest} result result
  473. * @returns {void}
  474. */
  475. finishYield = (result) => {
  476. if (result) {
  477. /** @type {ResolveContextYield} */ (yield_)(result);
  478. }
  479. callback(null);
  480. };
  481. }
  482. const message = `resolve '${request}' in '${path}'`;
  483. /**
  484. * @param {ResolveRequest} result result
  485. * @returns {void}
  486. */
  487. const finishResolved = (result) =>
  488. callback(
  489. null,
  490. result.path === false
  491. ? false
  492. : `${result.path.replace(/#/g, "\0#")}${
  493. result.query ? result.query.replace(/#/g, "\0#") : ""
  494. }${result.fragment || ""}`,
  495. result,
  496. );
  497. /**
  498. * @param {string[]} log logs
  499. * @returns {void}
  500. */
  501. const finishWithoutResolve = (log) => {
  502. /**
  503. * @type {ErrorWithDetail}
  504. */
  505. const error = new Error(`Can't ${message}`);
  506. error.details = log.join("\n");
  507. this.hooks.noResolve.call(obj, error);
  508. return callback(error);
  509. };
  510. if (resolveContext.log) {
  511. // We need log anyway to capture it in case of an error
  512. const parentLog = resolveContext.log;
  513. /** @type {string[]} */
  514. const log = [];
  515. return this.doResolve(
  516. this.hooks.resolve,
  517. obj,
  518. message,
  519. {
  520. log: (msg) => {
  521. parentLog(msg);
  522. log.push(msg);
  523. },
  524. yield: yield_,
  525. fileDependencies: resolveContext.fileDependencies,
  526. contextDependencies: resolveContext.contextDependencies,
  527. missingDependencies: resolveContext.missingDependencies,
  528. stack: resolveContext.stack,
  529. },
  530. (err, result) => {
  531. if (err) return callback(err);
  532. if (yieldCalled || (result && yield_)) {
  533. return /** @type {ResolveContextYield} */ (finishYield)(
  534. /** @type {ResolveRequest} */ (result),
  535. );
  536. }
  537. if (result) return finishResolved(result);
  538. return finishWithoutResolve(log);
  539. },
  540. );
  541. }
  542. // Try to resolve assuming there is no error
  543. // We don't log stuff in this case
  544. return this.doResolve(
  545. this.hooks.resolve,
  546. obj,
  547. message,
  548. {
  549. log: undefined,
  550. yield: yield_,
  551. fileDependencies: resolveContext.fileDependencies,
  552. contextDependencies: resolveContext.contextDependencies,
  553. missingDependencies: resolveContext.missingDependencies,
  554. stack: resolveContext.stack,
  555. },
  556. (err, result) => {
  557. if (err) return callback(err);
  558. if (yieldCalled || (result && yield_)) {
  559. return /** @type {ResolveContextYield} */ (finishYield)(
  560. /** @type {ResolveRequest} */ (result),
  561. );
  562. }
  563. if (result) return finishResolved(result);
  564. // log is missing for the error details
  565. // so we redo the resolving for the log info
  566. // this is more expensive to the success case
  567. // is assumed by default
  568. /** @type {string[]} */
  569. const log = [];
  570. return this.doResolve(
  571. this.hooks.resolve,
  572. obj,
  573. message,
  574. {
  575. log: (msg) => log.push(msg),
  576. yield: yield_,
  577. stack: resolveContext.stack,
  578. },
  579. (err, result) => {
  580. if (err) return callback(err);
  581. // In a case that there is a race condition and yield will be called
  582. if (yieldCalled || (result && yield_)) {
  583. return /** @type {ResolveContextYield} */ (finishYield)(
  584. /** @type {ResolveRequest} */ (result),
  585. );
  586. }
  587. return finishWithoutResolve(log);
  588. },
  589. );
  590. },
  591. );
  592. }
  593. /**
  594. * @param {ResolveStepHook} hook hook
  595. * @param {ResolveRequest} request request
  596. * @param {null|string} message string
  597. * @param {ResolveContext} resolveContext resolver context
  598. * @param {(err?: null|Error, result?: ResolveRequest) => void} callback callback
  599. * @returns {void}
  600. */
  601. doResolve(hook, request, message, resolveContext, callback) {
  602. const stackEntry = Resolver.createStackEntry(hook, request);
  603. /** @type {Set<string> | undefined} */
  604. let newStack;
  605. if (resolveContext.stack) {
  606. newStack = new Set(resolveContext.stack);
  607. if (resolveContext.stack.has(stackEntry)) {
  608. /**
  609. * Prevent recursion
  610. * @type {Error & {recursion?: boolean}}
  611. */
  612. const recursionError = new Error(
  613. `Recursion in resolving\nStack:\n ${[...newStack].join("\n ")}`,
  614. );
  615. recursionError.recursion = true;
  616. if (resolveContext.log) {
  617. resolveContext.log("abort resolving because of recursion");
  618. }
  619. return callback(recursionError);
  620. }
  621. newStack.add(stackEntry);
  622. } else {
  623. // creating a set with new Set([item])
  624. // allocates a new array that has to be garbage collected
  625. // this is an EXTREMELY hot path, so let's avoid it
  626. newStack = new Set();
  627. newStack.add(stackEntry);
  628. }
  629. this.hooks.resolveStep.call(hook, request);
  630. if (hook.isUsed()) {
  631. const innerContext = createInnerContext(
  632. {
  633. log: resolveContext.log,
  634. yield: resolveContext.yield,
  635. fileDependencies: resolveContext.fileDependencies,
  636. contextDependencies: resolveContext.contextDependencies,
  637. missingDependencies: resolveContext.missingDependencies,
  638. stack: newStack,
  639. },
  640. message,
  641. );
  642. return hook.callAsync(request, innerContext, (err, result) => {
  643. if (err) return callback(err);
  644. if (result) return callback(null, result);
  645. callback();
  646. });
  647. }
  648. callback();
  649. }
  650. /**
  651. * @param {string} identifier identifier
  652. * @returns {ParsedIdentifier} parsed identifier
  653. */
  654. parse(identifier) {
  655. const part = {
  656. request: "",
  657. query: "",
  658. fragment: "",
  659. module: false,
  660. directory: false,
  661. file: false,
  662. internal: false,
  663. };
  664. const parsedIdentifier = parseIdentifier(identifier);
  665. if (!parsedIdentifier) return part;
  666. [part.request, part.query, part.fragment] = parsedIdentifier;
  667. if (part.request.length > 0) {
  668. part.internal = this.isPrivate(identifier);
  669. part.module = this.isModule(part.request);
  670. part.directory = this.isDirectory(part.request);
  671. if (part.directory) {
  672. part.request = part.request.slice(0, -1);
  673. }
  674. }
  675. return part;
  676. }
  677. /**
  678. * @param {string} path path
  679. * @returns {boolean} true, if the path is a module
  680. */
  681. isModule(path) {
  682. return getType(path) === PathType.Normal;
  683. }
  684. /**
  685. * @param {string} path path
  686. * @returns {boolean} true, if the path is private
  687. */
  688. isPrivate(path) {
  689. return getType(path) === PathType.Internal;
  690. }
  691. /**
  692. * @param {string} path a path
  693. * @returns {boolean} true, if the path is a directory path
  694. */
  695. isDirectory(path) {
  696. return path.endsWith("/");
  697. }
  698. /**
  699. * @param {string} path path
  700. * @param {string} request request
  701. * @returns {string} joined path
  702. */
  703. join(path, request) {
  704. return join(path, request);
  705. }
  706. /**
  707. * @param {string} path path
  708. * @returns {string} normalized path
  709. */
  710. normalize(path) {
  711. return normalize(path);
  712. }
  713. }
  714. module.exports = Resolver;