From 8f30c9fed913a821260c7202ee21de7fcf9ad842 Mon Sep 17 00:00:00 2001 From: Rob Hogan Date: Mon, 16 Nov 2026 15:54:40 +0000 Subject: [PATCH 1/4] Fix matchFiles skipping symlinks when rooted above the project root Currently, `matchFiles` with a `rootDir` above the project root (eg `require.context` on a monorepo root) skips every symlink inside the project root, along with everything reached through them. To resolve a symlink, `matchFiles` joins the canonical path of `rootDir` with the symlink's path relative to it. From an ancestor, that gives eg `../project/link-to-foo` for `link-to-foo`, which isn't a normal path, so the lookup reports `../project` as missing and the symlink is skipped. This collapses those segments when joining, as `TreeFS` already does for other relative lookups. Changelog: ``` - **[Fix]**: `require.context` on a directory above the project root follows symlinks inside the project root ``` Test plan: New unit test, on posix and win32, which fails before this change. The existing "ancestor of project root includes project root" test was encoding the bug - it omitted `/project/root/project/bar.js` (through the `root -> ..` link), which the `/project`-rooted "recursive" test already expects. --- packages/metro-file-map/src/lib/TreeFS.js | 10 +++++--- .../src/lib/__tests__/TreeFS-test.js | 25 ++++++++++++++++++- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/packages/metro-file-map/src/lib/TreeFS.js b/packages/metro-file-map/src/lib/TreeFS.js index 8583e45403..56952e7878 100644 --- a/packages/metro-file-map/src/lib/TreeFS.js +++ b/packages/metro-file-map/src/lib/TreeFS.js @@ -1396,12 +1396,14 @@ export default class TreeFS implements MutableFileSystem { ? nodePath : nodePath.replaceAll(pathSep, path.sep); - // Although both paths are normal, the node path may begin '..' so we - // can't simply concatenate. - const normalPathOfSymlink = path.join( + // When iterating from an ancestor of the project root, the root's + // canonical path ends '..' and the node path may re-enter the + // project root (e.g. '..' and 'project/link'), so the join must + // collapse those segments to give a normal path ('link'). + const normalPathOfSymlink = this.#pathUtils.joinNormalToRelative( opts.canonicalPathOfRoot, nodePathWithSystemSeparators, - ); + ).normalPath; // We can't resolve the symlink directly here because we only have // its normal path, and we need a canonical path for resolution diff --git a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js index 7c69fdd5cd..03a29756a3 100644 --- a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js +++ b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js @@ -1003,7 +1003,30 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => { rootDir: p('/'), }), ), - ).toEqual([p('/project/bar.js')]); + ).toEqual([p('/project/bar.js'), p('/project/root/project/bar.js')]); + }); + + test('ancestor of project root follows symlinks within the project root', () => { + expect( + Array.from( + tfs.matchFiles({ + filter: new RegExp(/\/another\.js$/), + filterComparePosix: true, + follow: true, + recursive: true, + rootDir: p('/'), + }), + ), + ).toEqual([ + p('/project/foo/another.js'), + p('/project/foo/owndir/another.js'), + p('/project/link-to-foo/another.js'), + p('/project/link-to-foo/owndir/another.js'), + p('/project/root/project/foo/another.js'), + p('/project/root/project/foo/owndir/another.js'), + p('/project/root/project/link-to-foo/another.js'), + p('/project/root/project/link-to-foo/owndir/another.js'), + ]); }); test('recursive', () => { From 80af6a158f3fe43c43f037dffecc04ca2cb49cc8 Mon Sep 17 00:00:00 2001 From: Rob Hogan Date: Mon, 16 Nov 2026 16:39:54 +0000 Subject: [PATCH 2/4] Fix matchFiles from two or more levels above the project root An ancestor of the project root has no entry for the next ancestor down, so `matchFiles` yields that ancestor first, under its basename. Below the first level, it gave every child directory the same node and one less ancestor index, so from a `rootDir` two levels up (eg a monorepo root above `apps/mobile`), the next ancestor down was the wrong node and siblings of each ancestor gained a bogus copy of it. Only the next ancestor down is now treated as an ancestor, and each is looked up through the root's `..` links. Changelog: Internal Test plan: New unit test with the project root three levels deep, rooted at each ancestor, on posix and win32. It fails before this change for the two higher ancestors. --- packages/metro-file-map/src/lib/TreeFS.js | 99 ++++++++++++------- .../src/lib/__tests__/TreeFS-test.js | 54 ++++++++++ 2 files changed, 118 insertions(+), 35 deletions(-) diff --git a/packages/metro-file-map/src/lib/TreeFS.js b/packages/metro-file-map/src/lib/TreeFS.js index 56952e7878..b400c20b9e 100644 --- a/packages/metro-file-map/src/lib/TreeFS.js +++ b/packages/metro-file-map/src/lib/TreeFS.js @@ -507,7 +507,6 @@ export default class TreeFS implements MutableFileSystem { ancestorOfRootIdx, canonicalPath: rootRealPath, node: contextRoot, - parentNode: contextRootParent, } = contextRootResult; if (!isDirectory(contextRoot)) { return; @@ -526,7 +525,6 @@ export default class TreeFS implements MutableFileSystem { for (const relativePathForComparison of this.#pathIterator( contextRoot, - contextRootParent, ancestorOfRootIdx, { alwaysYieldPosix: filterComparePosix, @@ -1326,15 +1324,32 @@ export default class TreeFS implements MutableFileSystem { : this.#pathUtils.relativeToNormal(relativeOrAbsolutePath); } + // The nth ancestor of the root ('' is 0, '..' is 1, ...), reached through + // the '..' entries that link each ancestor to the next. + #getNthAncestorOfRoot(n: number): ?DirectoryNode { + let node: ?MixedNode = this.#rootNode; + for (let i = 0; i < n && isDirectory(node); i++) { + node = node.get('..'); + } + return isDirectory(node) ? node : null; + } + + // An ancestor of the root does not hold the next ancestor down (or the root + // itself) as an entry, so for the nth ancestor, the (n-1)th is yielded first, + // under its basename. *#directoryNodeIterator( node: DirectoryNode, - parent: ?DirectoryNode, ancestorOfRootIdx: ?number, + nextAncestorNode: ?DirectoryNode, ): IteratorObject<[string, MixedNode]> { - if (ancestorOfRootIdx != null && ancestorOfRootIdx > 0 && parent) { + if ( + ancestorOfRootIdx != null && + ancestorOfRootIdx > 0 && + nextAncestorNode != null + ) { yield [ this.#pathUtils.getBasenameOfNthAncestor(ancestorOfRootIdx - 1), - parent, + nextAncestorNode, ] as [string, MixedNode]; } yield* node.entries(); @@ -1346,7 +1361,6 @@ export default class TreeFS implements MutableFileSystem { */ *#pathIterator( iterationRootNode: DirectoryNode, - iterationRootParentNode: ?DirectoryNode, ancestorOfRootIdx: ?number, opts: Readonly<{ alwaysYieldPosix: boolean, @@ -1359,18 +1373,41 @@ export default class TreeFS implements MutableFileSystem { followedLinks: ReadonlySet = new Set(), ): Iterable { const pathSep = opts.alwaysYieldPosix ? '/' : path.sep; - const stack = [ - { + const makeFrame = ( + node: DirectoryNode, + nodeAncestorOfRootIdx: ?number, + prefixWithSep: string, + frameFollowedLinks: ReadonlySet, + ) => { + // Only the next ancestor down is itself an ancestor of the root. Every + // other entry of an ancestor is not. + const nextAncestorOfRootIdx = + nodeAncestorOfRootIdx != null && nodeAncestorOfRootIdx > 0 + ? nodeAncestorOfRootIdx - 1 + : null; + const nextAncestorNode = + nextAncestorOfRootIdx != null + ? this.#getNthAncestorOfRoot(nextAncestorOfRootIdx) + : null; + return { entries: this.#directoryNodeIterator( - iterationRootNode, - iterationRootParentNode, - ancestorOfRootIdx, + node, + nodeAncestorOfRootIdx, + nextAncestorNode, ), - parentNode: iterationRootParentNode, + nextAncestorNode, + nextAncestorOfRootIdx, + prefixWithSep, + followedLinks: frameFollowedLinks, + }; + }; + const stack = [ + makeFrame( + iterationRootNode, ancestorOfRootIdx, - prefixWithSep: pathPrefix === '' ? '' : pathPrefix + pathSep, + pathPrefix === '' ? '' : pathPrefix + pathSep, followedLinks, - }, + ), ]; while (stack.length > 0) { const frame = stack[stack.length - 1]; @@ -1430,35 +1467,27 @@ export default class TreeFS implements MutableFileSystem { ) { // Symlink points to a directory - iterate over its contents using // the path where we found the symlink as a prefix. - stack.push({ - entries: this.#directoryNodeIterator( + stack.push( + makeFrame( target, - resolved.parentNode, resolved.ancestorOfRootIdx, + nodePath + pathSep, + new Set([...frame.followedLinks, node]), ), - parentNode: resolved.parentNode, - ancestorOfRootIdx: resolved.ancestorOfRootIdx, - prefixWithSep: nodePath + pathSep, - followedLinks: new Set([...frame.followedLinks, node]), - }); + ); } } } else if (opts.recursive) { - const childAncestorOfRootIdx = - frame.ancestorOfRootIdx != null && frame.ancestorOfRootIdx > 0 - ? frame.ancestorOfRootIdx - 1 - : null; - stack.push({ - entries: this.#directoryNodeIterator( + stack.push( + makeFrame( node, - frame.parentNode, - childAncestorOfRootIdx, + node === frame.nextAncestorNode + ? frame.nextAncestorOfRootIdx + : null, + nodePath + pathSep, + frame.followedLinks, ), - parentNode: frame.parentNode, - ancestorOfRootIdx: childAncestorOfRootIdx, - prefixWithSep: nodePath + pathSep, - followedLinks: frame.followedLinks, - }); + ); } } } diff --git a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js index 03a29756a3..919e4e3521 100644 --- a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js +++ b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js @@ -1029,6 +1029,60 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => { ]); }); + test.each([ + [ + '/a/b', + [ + '/a/b/project/foo/x.js', + '/a/b/project/link-to-foo/x.js', + '/a/b/sib/y.js', + ], + ], + [ + '/a', + [ + '/a/b/project/foo/x.js', + '/a/b/project/link-to-foo/x.js', + '/a/b/sib/y.js', + '/a/c/z.js', + ], + ], + [ + '/', + [ + '/a/b/project/foo/x.js', + '/a/b/project/link-to-foo/x.js', + '/a/b/sib/y.js', + '/a/c/z.js', + ], + ], + ])( + 'ancestor %s of a deeper project root includes each level once', + (rootDir, expected) => { + const deepTfs = new TreeFS({ + rootDir: p('/a/b/project'), + files: new Map([ + [p('foo/x.js'), [0, 0, 0, null, 0, null]], + [p('link-to-foo'), [0, 0, 0, null, 'foo', null]], + [p('../sib/y.js'), [0, 0, 0, null, 0, null]], + [p('../../c/z.js'), [0, 0, 0, null, 0, null]], + ]), + processFile: () => { + throw new Error('Not implemented'); + }, + }); + expect( + Array.from( + deepTfs.matchFiles({ + follow: true, + recursive: true, + rootDir: p(rootDir), + }), + ), + ).toEqual(expected.map(p)); + }, + ); + test('recursive', () => { expect( Array.from( From 7028014b04f4d94e9c1dccba47dab967f382f822 Mon Sep 17 00:00:00 2001 From: Rob Hogan <2590098+robhogan@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:50:22 +0000 Subject: [PATCH 3/4] Fix matchFiles with no rootDir, and with ancestors missing from the map --- packages/metro-file-map/src/lib/TreeFS.js | 56 ++++---- .../src/lib/__tests__/TreeFS-test.js | 132 ++++++++++++++++++ 2 files changed, 162 insertions(+), 26 deletions(-) diff --git a/packages/metro-file-map/src/lib/TreeFS.js b/packages/metro-file-map/src/lib/TreeFS.js index b400c20b9e..1528abf443 100644 --- a/packages/metro-file-map/src/lib/TreeFS.js +++ b/packages/metro-file-map/src/lib/TreeFS.js @@ -1325,13 +1325,14 @@ export default class TreeFS implements MutableFileSystem { } // The nth ancestor of the root ('' is 0, '..' is 1, ...), reached through - // the '..' entries that link each ancestor to the next. - #getNthAncestorOfRoot(n: number): ?DirectoryNode { + // the '..' entries that link each ancestor to the next. An ancestor with + // nothing in the map has no entry, and is an empty directory, as in lookups. + #getNthAncestorOfRoot(n: number): DirectoryNode { let node: ?MixedNode = this.#rootNode; for (let i = 0; i < n && isDirectory(node); i++) { node = node.get('..'); } - return isDirectory(node) ? node : null; + return isDirectory(node) ? node : new Map(); } // An ancestor of the root does not hold the next ancestor down (or the root @@ -1373,8 +1374,12 @@ export default class TreeFS implements MutableFileSystem { followedLinks: ReadonlySet = new Set(), ): Iterable { const pathSep = opts.alwaysYieldPosix ? '/' : path.sep; + // Symlinks are resolved from the canonical path of their directory. The + // path where they were found differs when it passes through followed + // symlinks, or re-enters the root from an ancestor ('..' + 'project/link'). const makeFrame = ( node: DirectoryNode, + canonicalPath: string, nodeAncestorOfRootIdx: ?number, prefixWithSep: string, frameFollowedLinks: ReadonlySet, @@ -1390,6 +1395,7 @@ export default class TreeFS implements MutableFileSystem { ? this.#getNthAncestorOfRoot(nextAncestorOfRootIdx) : null; return { + canonicalPath, entries: this.#directoryNodeIterator( node, nodeAncestorOfRootIdx, @@ -1404,6 +1410,7 @@ export default class TreeFS implements MutableFileSystem { const stack = [ makeFrame( iterationRootNode, + opts.canonicalPathOfRoot, ancestorOfRootIdx, pathPrefix === '' ? '' : pathPrefix + pathSep, followedLinks, @@ -1417,7 +1424,11 @@ export default class TreeFS implements MutableFileSystem { continue; } const [name, node] = next.value; - if (opts.subtreeOnly && name === '..') { + // With no rootDir, '..' entries list files outside the project root. + // Inside a followed symlink they are skipped: those files are listed + // anyway, and a path through one (e.g. 'link-to-root/..') can't be + // joined lexically. + if (name === '..' && (opts.subtreeOnly || frame.followedLinks.size > 0)) { continue; } @@ -1427,29 +1438,11 @@ export default class TreeFS implements MutableFileSystem { // regular file yield nodePath; } else { - // symlink - const nodePathWithSystemSeparators = - pathSep === path.sep - ? nodePath - : nodePath.replaceAll(pathSep, path.sep); - - // When iterating from an ancestor of the project root, the root's - // canonical path ends '..' and the node path may re-enter the - // project root (e.g. '..' and 'project/link'), so the join must - // collapse those segments to give a normal path ('link'). - const normalPathOfSymlink = this.#pathUtils.joinNormalToRelative( - opts.canonicalPathOfRoot, - nodePathWithSystemSeparators, - ).normalPath; - - // We can't resolve the symlink directly here because we only have - // its normal path, and we need a canonical path for resolution - // (imagine our normal path contains a symlink 'bar' -> '.', and we - // are at /foo/bar/baz where baz -> '..' - that should resolve to - // /foo, not /foo/bar). We *can* use _lookupByNormalPath to walk to - // the canonical symlink, and then to its target. + // symlink - look it up by its canonical path to resolve its target, + // which may itself be a symlink. const resolved = this.#lookupByNormalPath( - normalPathOfSymlink, + this.#pathUtils.joinNormalToRelative(frame.canonicalPath, name) + .normalPath, LOOKUP_OPTIONS, ); if (!resolved.exists) { @@ -1470,6 +1463,7 @@ export default class TreeFS implements MutableFileSystem { stack.push( makeFrame( target, + resolved.canonicalPath, resolved.ancestorOfRootIdx, nodePath + pathSep, new Set([...frame.followedLinks, node]), @@ -1478,9 +1472,19 @@ export default class TreeFS implements MutableFileSystem { } } } else if (opts.recursive) { + // A '..' entry is always one level up, including past the top of a + // Windows drive, where it holds the other drives and a join would stop. + const canonicalPath = + name !== '..' + ? this.#pathUtils.joinNormalToRelative(frame.canonicalPath, name) + .normalPath + : frame.canonicalPath === '' + ? '..' + : frame.canonicalPath + path.sep + '..'; stack.push( makeFrame( node, + canonicalPath, node === frame.nextAncestorNode ? frame.nextAncestorOfRootIdx : null, diff --git a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js index 919e4e3521..e749a47811 100644 --- a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js +++ b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js @@ -1083,6 +1083,61 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => { }, ); + test('follows a symlink to two levels above the project root', () => { + const deepTfs = new TreeFS({ + rootDir: p('/a/b/project'), + files: new Map([ + [p('foo/x.js'), [0, 0, 0, null, 0, null]], + [p('up2'), [0, 0, 0, null, '../..', null]], + [p('../sib/y.js'), [0, 0, 0, null, 0, null]], + ]), + processFile: () => { + throw new Error('Not implemented'); + }, + }); + expect( + Array.from( + deepTfs.matchFiles({ + follow: true, + recursive: true, + rootDir: p('/a/b/project'), + }), + ), + ).toEqual([ + p('/a/b/project/foo/x.js'), + p('/a/b/project/up2/b/project/foo/x.js'), + p('/a/b/project/up2/b/sib/y.js'), + ]); + }); + + test.each([['/a/b/project'], ['/a'], ['/']])( + '%s lists the project root with nothing above it in the map', + rootDir => { + const deepTfs = new TreeFS({ + rootDir: p('/a/b/project'), + files: new Map([ + [p('foo/x.js'), [0, 0, 0, null, 0, null]], + [p('up2'), [0, 0, 0, null, '../..', null]], + ]), + processFile: () => { + throw new Error('Not implemented'); + }, + }); + expect( + Array.from( + deepTfs.matchFiles({ + follow: true, + recursive: true, + rootDir: p(rootDir), + }), + ), + ).toEqual([ + p('/a/b/project/foo/x.js'), + p('/a/b/project/up2/b/project/foo/x.js'), + ]); + }, + ); + test('recursive', () => { expect( Array.from( @@ -1186,6 +1241,58 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => { ).toEqual([p('/outside/external.js')]); }); + test('null rootDir follows a symlink outside the root to its ancestor', () => { + const deepTfs = new TreeFS({ + rootDir: p('/a/b/project'), + files: new Map([ + [p('foo/x.js'), [0, 0, 0, null, 0, null]], + [p('../sib/to-a'), [0, 0, 0, null, '../..', null]], + ]), + processFile: () => { + throw new Error('Not implemented'); + }, + }); + expect( + Array.from( + deepTfs.matchFiles({ + follow: true, + recursive: true, + rootDir: null, + }), + ), + ).toEqual([ + p('/a/b/project/foo/x.js'), + p('/a/b/sib/to-a/b/project/foo/x.js'), + ]); + }); + + test("null rootDir doesn't list outside the root through a symlink", () => { + const deepTfs = new TreeFS({ + rootDir: p('/a/b/project'), + files: new Map([ + [p('foo/x.js'), [0, 0, 0, null, 0, null]], + [p('link-to-root'), [0, 0, 0, null, '', null]], + [p('../sib/y.js'), [0, 0, 0, null, 0, null]], + ]), + processFile: () => { + throw new Error('Not implemented'); + }, + }); + expect( + Array.from( + deepTfs.matchFiles({ + follow: true, + recursive: true, + rootDir: null, + }), + ), + ).toEqual([ + p('/a/b/project/foo/x.js'), + p('/a/b/project/link-to-root/foo/x.js'), + p('/a/b/sib/y.js'), + ]); + }); + test('outside root, rootDir set to root has no matches', () => { expect( Array.from( @@ -1761,6 +1868,31 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => { realPath: 'D:\\external\\file.js', }); }); + + test('matchFiles() with no rootDir follows a symlink on another drive', () => { + const tfsLink = new TreeFS({ + rootDir: 'C:\\project', + files: new Map([ + ['..\\..\\D:\\external\\file.js', externalMeta], + [ + '..\\..\\D:\\external\\self', + [0, 0, 0, null, '../../D:/external', null], + ], + ]), + processFile: () => { + throw new Error('Not implemented'); + }, + }); + // Only the suffix is checked: paths on another drive are joined + // lexically to the project root (C:\D:\...). + expect( + Array.from( + tfsLink.matchFiles({follow: true, recursive: true, rootDir: null}), + ), + ).toContainEqual( + expect.stringMatching(/\\D:\\external\\self\\file\.js$/), + ); + }); }); } }); From 413284878f96230ff4d26feaf43f8542f182a8d4 Mon Sep 17 00:00:00 2001 From: Rob Hogan <2590098+robhogan@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:05:59 +0000 Subject: [PATCH 4/4] Test matchFiles through a symlink in a directory ending in a dot --- .../src/lib/__tests__/TreeFS-test.js | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js index e749a47811..7221270dab 100644 --- a/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js +++ b/packages/metro-file-map/src/lib/__tests__/TreeFS-test.js @@ -1029,6 +1029,28 @@ describe.each([['win32'], ['posix']])('TreeFS on %s', platform => { ]); }); + test('ancestor of project root follows a symlink in a directory ending in a dot', () => { + const dotTfs = new TreeFS({ + rootDir: p('/project'), + files: new Map([ + [p('foo./x.js'), [0, 0, 0, null, 0, null]], + [p('foo./link'), [0, 0, 0, null, 'foo.', null]], + ]), + processFile: () => { + throw new Error('Not implemented'); + }, + }); + expect( + Array.from( + dotTfs.matchFiles({ + follow: true, + recursive: true, + rootDir: p('/'), + }), + ), + ).toEqual([p('/project/foo./x.js'), p('/project/foo./link/x.js')]); + }); + test.each([ [ '/a/b',