Skip to content

Commit 03016f9

Browse files
feat: accept URLs in options
1 parent 795fab9 commit 03016f9

5 files changed

Lines changed: 359 additions & 46 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"enhanced-resolve": minor
3+
---
4+
5+
Allow the path-like resolve options `roots`, `modules`, `alias`/`fallback` targets, `restrictions`, and `tsconfig` (the config file, `configFile`, `baseUrl`, and `references`) to accept file `URL` instances (such as `new URL("./dir/", import.meta.url)`), converting them to filesystem paths. Plain strings are still treated as literal paths, matching Node's `fs`.

‎lib/ResolverFactory.js‎

Lines changed: 85 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ const TryNextPlugin = require("./TryNextPlugin");
3737
const TsconfigPathsPlugin = require("./TsconfigPathsPlugin");
3838
const UnsafeCachePlugin = require("./UnsafeCachePlugin");
3939
const UseFilePlugin = require("./UseFilePlugin");
40-
const { PathType, getType } = require("./util/path");
40+
const { PathType, getType, toPath } = require("./util/path");
4141

4242
/** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */
4343
/** @typedef {import("./ExtensionAliasPlugin").ExtensionAliasOption} ExtensionAliasOption */
@@ -51,6 +51,9 @@ const { PathType, getType } = require("./util/path");
5151

5252
/** @typedef {string | string[] | false} AliasOptionNewRequest */
5353
/** @typedef {{ [k: string]: AliasOptionNewRequest }} AliasOptions */
54+
/** @typedef {string | URL | (string | URL)[] | false} UserAliasOptionNewRequest */
55+
/** @typedef {{ [k: string]: UserAliasOptionNewRequest }} UserAliasOptions */
56+
/** @typedef {{ alias: UserAliasOptionNewRequest, name: string, onlyModule?: boolean }} UserAliasOptionEntry */
5457
/** @typedef {{ [k: string]: string | string[] }} ExtensionAliasOptions */
5558
/** @typedef {false | 0 | "" | null | undefined} Falsy */
5659
/** @typedef {{ apply: (resolver: Resolver) => void } | ((this: Resolver, resolver: Resolver) => void) | Falsy} Plugin */
@@ -62,10 +65,17 @@ const { PathType, getType } = require("./util/path");
6265
* @property {string=} baseUrl Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file
6366
*/
6467

68+
/**
69+
* @typedef {object} UserTsconfigOptions
70+
* @property {(string | URL)=} configFile A path, or `file:` `URL` instance, pointing at the tsconfig file
71+
* @property {((string | URL)[] | "auto")=} references References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths or `file:` `URL` instances
72+
* @property {(string | URL)=} baseUrl Override baseUrl from tsconfig.json with a path or `file:` `URL` instance
73+
*/
74+
6575
/**
6676
* @typedef {object} UserResolveOptions
67-
* @property {(AliasOptions | AliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value
68-
* @property {(AliasOptions | AliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option
77+
* @property {(UserAliasOptions | UserAliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value
78+
* @property {(UserAliasOptions | UserAliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option
6979
* @property {ExtensionAliasOptions=} extensionAlias An object which maps extension to extension aliases
7080
* @property {boolean=} extensionAliasForExports Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned); when enabled, matches TypeScript's behavior for packages that ship TS sources alongside compiled JS.
7181
* @property {(string | string[])[]=} aliasFields A list of alias fields in description files
@@ -81,19 +91,19 @@ const { PathType, getType } = require("./util/path");
8191
* @property {(Cache | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests
8292
* @property {boolean=} symlinks Resolve symlinks to their symlinked location
8393
* @property {Resolver=} resolver A prepared Resolver to which the plugins are attached
84-
* @property {string[] | string=} modules A list of directories to resolve modules from, can be absolute path or folder name
94+
* @property {(string | URL)[] | string | URL=} modules A list of directories to resolve modules from, can be absolute path, folder name, or a `file:` `URL` instance
8595
* @property {(string | string[] | { name: string | string[], forceRelative: boolean })[]=} mainFields A list of main fields in description files
8696
* @property {string[]=} mainFiles A list of main files in directories
8797
* @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied
8898
* @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto"
89-
* @property {string[]=} roots A list of root paths
99+
* @property {(string | URL)[]=} roots A list of root paths, each an absolute path or a `file:` `URL` instance
90100
* @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it
91101
* @property {boolean=} resolveToContext Resolve to a context instead of a file
92-
* @property {(string | RegExp)[]=} restrictions A list of resolve restrictions
102+
* @property {(string | URL | RegExp)[]=} restrictions A list of resolve restrictions, each an absolute path, a `file:` `URL` instance, or a RegExp
93103
* @property {boolean=} useSyncFileSystemCalls Use only the sync constraints of the file system calls
94104
* @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules
95105
* @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots
96-
* @property {string | boolean | TsconfigOptions=} tsconfig TypeScript config file path or config object with configFile and references
106+
* @property {string | URL | boolean | UserTsconfigOptions=} tsconfig TypeScript config file path (or `file:` `URL` instance) or config object with configFile and references
97107
*/
98108

99109
/**
@@ -165,23 +175,69 @@ function processPnpApiOption(option) {
165175
}
166176

167177
/**
168-
* @param {AliasOptions | AliasOptionEntry[] | undefined} alias alias
178+
* @param {UserAliasOptionNewRequest} alias alias target(s)
179+
* @returns {AliasOptionNewRequest} target(s) with file `URL` instances converted to paths
180+
*/
181+
function toPathAlias(alias) {
182+
if (alias === false) return false;
183+
return Array.isArray(alias) ? alias.map(toPath) : toPath(alias);
184+
}
185+
186+
/**
187+
* @param {UserAliasOptions | UserAliasOptionEntry[] | undefined} alias alias
169188
* @returns {AliasOptionEntry[]} normalized aliases
170189
*/
171190
function normalizeAlias(alias) {
172-
return typeof alias === "object" && !Array.isArray(alias) && alias !== null
173-
? Object.keys(alias).map((key) => {
174-
/** @type {AliasOptionEntry} */
175-
const obj = { name: key, onlyModule: false, alias: alias[key] };
176-
177-
if (/\$$/.test(key)) {
178-
obj.onlyModule = true;
179-
obj.name = key.slice(0, -1);
180-
}
181-
182-
return obj;
183-
})
184-
: /** @type {AliasOptionEntry[]} */ (alias) || [];
191+
if (typeof alias === "object" && !Array.isArray(alias) && alias !== null) {
192+
return Object.keys(alias).map((key) => {
193+
/** @type {AliasOptionEntry} */
194+
const obj = {
195+
name: key,
196+
onlyModule: false,
197+
alias: toPathAlias(alias[key]),
198+
};
199+
200+
if (/\$$/.test(key)) {
201+
obj.onlyModule = true;
202+
obj.name = key.slice(0, -1);
203+
}
204+
205+
return obj;
206+
});
207+
}
208+
209+
return alias
210+
? alias.map((item) => ({ ...item, alias: toPathAlias(item.alias) }))
211+
: [];
212+
}
213+
214+
/**
215+
* @param {string | URL | boolean | UserTsconfigOptions | undefined} tsconfig tsconfig option
216+
* @returns {string | boolean | TsconfigOptions} normalized tsconfig with file `URL` instances converted to paths
217+
*/
218+
function normalizeTsconfig(tsconfig) {
219+
if (tsconfig === undefined) return false;
220+
if (typeof tsconfig === "boolean") return tsconfig;
221+
if (typeof tsconfig === "string" || tsconfig instanceof URL) {
222+
return toPath(tsconfig);
223+
}
224+
225+
/** @type {TsconfigOptions} */
226+
const result = {};
227+
228+
if (tsconfig.configFile !== undefined) {
229+
result.configFile = toPath(tsconfig.configFile);
230+
}
231+
if (tsconfig.baseUrl !== undefined) {
232+
result.baseUrl = toPath(tsconfig.baseUrl);
233+
}
234+
if (tsconfig.references !== undefined) {
235+
result.references = Array.isArray(tsconfig.references)
236+
? tsconfig.references.map(toPath)
237+
: tsconfig.references;
238+
}
239+
240+
return result;
185241
}
186242

187243
/**
@@ -288,9 +344,9 @@ function createOptions(options) {
288344
resolver: options.resolver,
289345
modules: mergeFilteredToArray(
290346
Array.isArray(options.modules)
291-
? options.modules
347+
? options.modules.map(toPath)
292348
: options.modules
293-
? [options.modules]
349+
? [toPath(options.modules)]
294350
: ["node_modules"],
295351
(item) => {
296352
const type = getType(item);
@@ -301,14 +357,16 @@ function createOptions(options) {
301357
mainFiles: new Set(options.mainFiles || ["index"]),
302358
plugins: options.plugins || [],
303359
pnpApi: processPnpApiOption(options.pnpApi),
304-
roots: new Set(options.roots || undefined),
360+
roots: new Set(options.roots ? options.roots.map(toPath) : undefined),
305361
fullySpecified: options.fullySpecified || false,
306362
resolveToContext: options.resolveToContext || false,
307363
preferRelative: options.preferRelative || false,
308364
preferAbsolute: options.preferAbsolute || false,
309-
restrictions: new Set(options.restrictions),
310-
tsconfig:
311-
typeof options.tsconfig === "undefined" ? false : options.tsconfig,
365+
restrictions: new Set(
366+
options.restrictions &&
367+
options.restrictions.map((r) => (r instanceof RegExp ? r : toPath(r))),
368+
),
369+
tsconfig: normalizeTsconfig(options.tsconfig),
312370
};
313371
}
314372

‎lib/util/path.js‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
"use strict";
77

88
const path = require("path");
9+
const memoize = require("./memoize");
10+
11+
const getUrl = memoize(() => require("url"));
912

1013
const CHAR_HASH = "#".charCodeAt(0);
1114
const CHAR_SLASH = "/".charCodeAt(0);
@@ -330,6 +333,18 @@ const isSubPath = (parentPath, childPath) => {
330333
return nextChar === CHAR_SLASH || nextChar === CHAR_BACKSLASH;
331334
};
332335

336+
/**
337+
* Convert a `file:` `URL` instance to a filesystem path; any other input
338+
* (including plain strings) is returned unchanged. Mirrors Node's `fs`, which
339+
* treats strings as literal paths and only `URL` objects as URLs (see
340+
* nodejs/node#17658) — so a directory literally named `file:` is never
341+
* mistaken for a URL.
342+
* @param {string | URL} maybeURL a path string or a `file:` `URL` instance
343+
* @returns {string} a filesystem path
344+
*/
345+
const toPath = (maybeURL) =>
346+
maybeURL instanceof URL ? getUrl().fileURLToPath(maybeURL) : maybeURL;
347+
333348
module.exports.PathType = PathType;
334349
module.exports.createCachedBasename = createCachedBasename;
335350
module.exports.createCachedDirname = createCachedDirname;
@@ -342,3 +357,4 @@ module.exports.isRelativeRequest = isRelativeRequest;
342357
module.exports.isSubPath = isSubPath;
343358
module.exports.join = join;
344359
module.exports.normalize = normalize;
360+
module.exports.toPath = toPath;

0 commit comments

Comments
 (0)