Skip to content

Commit 06f1de1

Browse files
robhoganmeta-codesync[bot]
authored andcommitted
Resolver: Implement PACKAGE_SELF_RESOLVE for self-referencing imports (#1721)
Summary: Pull Request resolved: #1721 Add support to Metro's resolver for [self-referencing](https://nodejs.org/api/packages.html#self-referencing-a-package-using-its-name). A package can import itself by name, resolving via its own `exports` field. Per the [Node ESM resolution algorithm](https://nodejs.org/api/esm.html#resolution-algorithm-specification) (6.5 `PACKAGE_SELF_RESOLVE`), if the origin module lives in a package whose `name` matches the bare specifier and which declares `exports`, the request is routed through `PACKAGE_EXPORTS_RESOLVE` against that package, in preference to hierarchical `node_modules` lookup. (In particular, this allows `react-native`'s own source to `import {Platform} from 'react-native'`, which *may* be the approach we take to fix broken platform inlining) Gated behind the existing `unstable_enablePackageExports` flag (enabled by default). When on, the resolver attempts self-resolve before hierarchical lookup; on `PackagePathNotExportedError` it follows Metro's existing nonstrict policy of warning and falling through to legacy resolution, consistent with how non-self bare specifiers behave today. This nonstrict fallback will be removed in future. Matches webpack's `SelfReferencePlugin` and Node's own behaviour. ``` - **[Feature]**: Resolver: support self-referencing packages ([`PACKAGE_SELF_RESOLVE`](https://nodejs.org/api/esm.html#resolution-algorithm-specification)) ``` Reviewed By: huntie, motiz88 Differential Revision: D105485943 fbshipit-source-id: 257090425208ef418d9b8c9cc3968d9d1df839cf
1 parent 385a946 commit 06f1de1

3 files changed

Lines changed: 162 additions & 4 deletions

File tree

‎docs/Resolution.md‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,18 +75,21 @@ Parameters: (*context*, *moduleName*, *platform*)
7575
2. If resolved as a Haste package path, then
7676
1. Perform the algorithm for resolving a path (step 2 above). Throw an error if this resolution fails.
7777
For example, if the Haste package path for `'a/b'` is `foo/package.json`, perform step 2 as if _moduleName_ was `foo/c`.
78-
6. If [`context.disableHierarchicalLookup`](#disableHierarchicalLookup-boolean) is not `true`, then
78+
6. If [`context.enablePackageExports`](#enablepackageexports-boolean) is enabled, then
79+
1. Get the result of [**PACKAGE_SELF_RESOLVE**](#package_self_resolve)(*context*, *moduleName*, *platform*).
80+
2. If resolved, return result.
81+
7. If [`context.disableHierarchicalLookup`](#disableHierarchicalLookup-boolean) is not `true`, then
7982
1. Try resolving _moduleName_ under `node_modules` from the current directory (i.e. parent of [`context.originModulePath`](#originmodulepath-string)) up to the root directory.
8083
2. Perform [**RESOLVE_PACKAGE**](#resolve_package)(*context*, *modulePath*, *platform*) for each candidate path.
81-
7. For each element _nodeModulesPath_ of [`context.nodeModulesPaths`](#nodemodulespaths-readonlyarraystring):
84+
8. For each element _nodeModulesPath_ of [`context.nodeModulesPaths`](#nodemodulespaths-readonlyarraystring):
8285
1. Try resolving _moduleName_ under _nodeModulesPath_ as if the latter was another `node_modules` directory (similar to step 5 above).
8386
2. Perform [**RESOLVE_PACKAGE**](#resolve_package)(*context*, *modulePath*, *platform*) for each candidate path.
84-
8. If [`context.extraNodeModules`](#extranodemodules-string-string) is set:
87+
9. If [`context.extraNodeModules`](#extranodemodules-string-string) is set:
8588
1. Split _moduleName_ into a package name (including an optional [scope](https://docs.npmjs.com/cli/v8/using-npm/scope)) and relative path.
8689
2. Look up the package name in [`context.extraNodeModules`](#extranodemodules-string-string). If found, then
8790
1. Construct a path _modulePath_ by replacing the package name part of _moduleName_ with the value found in [`context.extraNodeModules`](#extranodemodules-string-string)
8891
2. Return the result of [**RESOLVE_PACKAGE**](#resolve_package)(*context*, *modulePath*, *platform*).
89-
9. If no valid resolution has been found, throw a resolution failure error.
92+
10. If no valid resolution has been found, throw a resolution failure error.
9093

9194
#### RESOLVE_MODULE
9295

@@ -110,6 +113,18 @@ Parameters: (*context*, *moduleName*, *platform*)
110113
2. Else, log either a package configuration or package encapsulation warning.
111114
2. Return the result of [**RESOLVE_MODULE**](#resolve_module)(*context*, *filePath*, *platform*).
112115

116+
#### PACKAGE_SELF_RESOLVE
117+
118+
Parameters: (*context*, *moduleName*, *platform*)
119+
120+
1. Find the closest package to [`context.originModulePath`](#originmodulepath-string). If no package is found, return no resolution.
121+
2. If the package does not declare both a `"name"` field and an `"exports"` field, return no resolution.
122+
3. Split _moduleName_ into a package name (including an optional [scope](https://docs.npmjs.com/cli/v8/using-npm/scope)) and relative path.
123+
4. If the package name does not match the current package's `"name"` field, return no resolution.
124+
5. Get the result of [**RESOLVE_PACKAGE_EXPORTS**](#resolve_package-exports)(*context*, *packagePath*, *filePath*, *exportsField*, *platform*) against the current package's `"exports"` field.
125+
1. If resolved path exists, return result.
126+
2. Else, log either a package configuration or package encapsulation warning, then continue with normal resolution.
127+
113128
#### RESOLVE_PACKAGE_EXPORTS
114129

115130
Parameters: (*context*, *packagePath*, *filePath*, *exportsField*, *platform*)

‎packages/metro-resolver/src/__tests__/package-exports-test.js‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1210,4 +1210,97 @@ describe('with package exports resolution enabled', () => {
12101210
});
12111211
});
12121212
});
1213+
1214+
describe('self-referencing imports (PACKAGE_SELF_RESOLVE)', () => {
1215+
const packageJson = {
1216+
name: 'self-pkg',
1217+
main: 'index-main.js',
1218+
exports: {
1219+
'.': './index.js',
1220+
'./sub': './lib/sub.js',
1221+
},
1222+
};
1223+
const baseContext = {
1224+
...createResolutionContext({
1225+
'/root/node_modules/self-pkg/package.json': JSON.stringify(packageJson),
1226+
'/root/node_modules/self-pkg/index.js': '',
1227+
'/root/node_modules/self-pkg/index-main.js': '',
1228+
'/root/node_modules/self-pkg/lib/sub.js': '',
1229+
'/root/node_modules/self-pkg/lib/internal.js': '',
1230+
}),
1231+
originModulePath: '/root/node_modules/self-pkg/index.js',
1232+
unstable_enablePackageExports: true,
1233+
};
1234+
1235+
test('should resolve own package name via its own "exports" field', () => {
1236+
expect(Resolver.resolve(baseContext, 'self-pkg', null)).toEqual({
1237+
type: 'sourceFile',
1238+
filePath: '/root/node_modules/self-pkg/index.js',
1239+
});
1240+
});
1241+
1242+
test('should resolve a subpath of the own package via "exports"', () => {
1243+
expect(Resolver.resolve(baseContext, 'self-pkg/sub', null)).toEqual({
1244+
type: 'sourceFile',
1245+
filePath: '/root/node_modules/self-pkg/lib/sub.js',
1246+
});
1247+
});
1248+
1249+
test('[nonstrict] should warn and fall back when self subpath is not in "exports"', () => {
1250+
const logWarning = jest.fn();
1251+
// `./lib/internal.js` is not exported, but exists on disk. We log the
1252+
// out-of-exports access and fall through to the regular hierarchical
1253+
// lookup, which finds the file inside `node_modules/self-pkg/`.
1254+
expect(
1255+
Resolver.resolve(
1256+
{...baseContext, unstable_logWarning: logWarning},
1257+
'self-pkg/lib/internal',
1258+
null,
1259+
),
1260+
).toEqual({
1261+
type: 'sourceFile',
1262+
filePath: '/root/node_modules/self-pkg/lib/internal.js',
1263+
});
1264+
expect(logWarning).toHaveBeenCalled();
1265+
expect(logWarning.mock.calls[0][0]).toMatch(
1266+
/which is not listed in the "exports"/,
1267+
);
1268+
});
1269+
1270+
test('should not self-resolve when origin package has no name', () => {
1271+
const noNameContext = {
1272+
...baseContext,
1273+
...createPackageAccessors({
1274+
'/root/node_modules/self-pkg/package.json': {
1275+
main: 'index-main.js',
1276+
exports: {'.': './index.js'},
1277+
},
1278+
}),
1279+
};
1280+
// With no `name`, falls through to hierarchical lookup (and finds the
1281+
// package in node_modules, going through "exports" as a normal import).
1282+
expect(Resolver.resolve(noNameContext, 'self-pkg', null)).toEqual({
1283+
type: 'sourceFile',
1284+
filePath: '/root/node_modules/self-pkg/index.js',
1285+
});
1286+
});
1287+
1288+
test('should not self-resolve when the package has no "exports" field', () => {
1289+
const noExportsContext = {
1290+
...baseContext,
1291+
...createPackageAccessors({
1292+
'/root/node_modules/self-pkg/package.json': {
1293+
name: 'self-pkg',
1294+
main: 'index-main.js',
1295+
},
1296+
}),
1297+
};
1298+
// Without `exports`, self-resolve does not apply. Falls back to
1299+
// node_modules lookup, which resolves via "main".
1300+
expect(Resolver.resolve(noExportsContext, 'self-pkg', null)).toEqual({
1301+
type: 'sourceFile',
1302+
filePath: '/root/node_modules/self-pkg/index-main.js',
1303+
});
1304+
});
1305+
});
12131306
});

‎packages/metro-resolver/src/resolve.js‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,56 @@ export default function resolve(
193193

194194
// parsedSpecifier is now a non-Haste bare specifier.
195195

196+
// PACKAGE_SELF_RESOLVE: if the origin lives inside a package whose `name`
197+
// matches the bare specifier and which declares an `exports` field, resolve
198+
// the request via that package's `exports`. Per Node.js ESM spec section 6.5
199+
// (https://nodejs.org/api/esm.html#resolution-algorithm-specification).
200+
if (
201+
context.unstable_enablePackageExports &&
202+
closestPackageToOrigin != null &&
203+
closestPackageToOrigin.packageJson.exports != null &&
204+
closestPackageToOrigin.packageJson.name === parsedSpecifier.packageName
205+
) {
206+
try {
207+
const exportsField = closestPackageToOrigin.packageJson.exports;
208+
const packageExportsResult = resolvePackageTargetFromExports(
209+
context,
210+
closestPackageToOrigin.rootPath,
211+
path.join(
212+
closestPackageToOrigin.rootPath,
213+
parsedSpecifier.posixSubpath,
214+
),
215+
// packageRelativePath for the requested subpath, stripping the leading
216+
// './' so the empty string represents the package root (matching how
217+
// `getPackageForModule` reports `packageRelativePath`).
218+
parsedSpecifier.posixSubpath === '.'
219+
? ''
220+
: parsedSpecifier.posixSubpath.slice(2),
221+
exportsField,
222+
platform,
223+
);
224+
if (packageExportsResult != null) {
225+
return packageExportsResult;
226+
}
227+
} catch (e) {
228+
// NB: Falling back is a departure from the spec, but retained for
229+
// backwards compatibility. Remove this in a breaking change.
230+
if (e instanceof PackagePathNotExportedError) {
231+
context.unstable_logWarning(
232+
e.message +
233+
' Falling back to hierarchical resolution for backwards compatibility.',
234+
);
235+
} else if (e instanceof InvalidPackageConfigurationError) {
236+
context.unstable_logWarning(
237+
e.message +
238+
' Falling back to hierarchical resolution for backwards compatibility.',
239+
);
240+
} else {
241+
throw e;
242+
}
243+
}
244+
}
245+
196246
const {disableHierarchicalLookup} = context;
197247

198248
if (!disableHierarchicalLookup) {

0 commit comments

Comments
 (0)