11const fs = require ( 'fs' ) ;
2+ const path = require ( 'path' ) ;
23const moduleRequire = require ( 'module' ) . createRequire ( __dirname ) ;
34
45const PACKAGES_TO_DEDUPE = [
@@ -41,19 +42,45 @@ function normalizeSubpath(pkgName, subpath) {
4142 return `${ pkgName } /${ subpath . replace ( / ^ \. \/ / , '' ) } ` ;
4243}
4344
44- function buildAliasesForPackage ( pkgName ) {
45- let pkgJsonPath ;
45+ function resolvePackageMetadata ( pkgName ) {
46+ let entryPoint ;
4647 try {
47- pkgJsonPath = moduleRequire . resolve ( ` ${ pkgName } /package.json` ) ;
48+ entryPoint = moduleRequire . resolve ( pkgName ) ;
4849 } catch ( error ) {
4950 console . warn (
50- `docusaurus-dedupe-aliases: unable to resolve ${ pkgName } ` ,
51+ `docusaurus-dedupe-aliases: unable to resolve entry for ${ pkgName } ` ,
5152 error
5253 ) ;
54+ return null ;
55+ }
56+
57+ let currentDir = path . dirname ( entryPoint ) ;
58+ const fsRoot = path . parse ( currentDir ) . root ;
59+
60+ while ( currentDir && currentDir !== fsRoot ) {
61+ const candidate = path . join ( currentDir , 'package.json' ) ;
62+ if ( fs . existsSync ( candidate ) ) {
63+ const pkgJson = JSON . parse ( fs . readFileSync ( candidate , 'utf8' ) ) ;
64+ if ( pkgJson ?. name === pkgName ) {
65+ return { pkgJson, pkgRoot : currentDir } ;
66+ }
67+ }
68+ currentDir = path . dirname ( currentDir ) ;
69+ }
70+
71+ console . warn (
72+ `docusaurus-dedupe-aliases: could not locate package.json for ${ pkgName } `
73+ ) ;
74+ return null ;
75+ }
76+
77+ function buildAliasesForPackage ( pkgName ) {
78+ const metadata = resolvePackageMetadata ( pkgName ) ;
79+ if ( ! metadata ) {
5380 return [ ] ;
5481 }
5582
56- const pkgJson = JSON . parse ( fs . readFileSync ( pkgJsonPath , 'utf8' ) ) ;
83+ const { pkgJson, pkgRoot } = metadata ;
5784 const exportKeys = getExportKeys ( pkgJson . exports ) ;
5885
5986 return exportKeys . flatMap ( ( subpath ) => {
@@ -64,6 +91,21 @@ function buildAliasesForPackage(pkgName) {
6491 subpath === '.' ? `${ pkgName } $` : specifier . replace ( / \\ / g, '/' ) ;
6592 return [ [ aliasKey , target ] ] ;
6693 } catch ( error ) {
94+ const aliasKey =
95+ subpath === '.' ? `${ pkgName } $` : specifier . replace ( / \\ / g, '/' ) ;
96+ const fallbackTarget =
97+ subpath === '.'
98+ ? path . join ( pkgRoot , pkgJson . main ?? 'index.js' )
99+ : path . join ( pkgRoot , subpath . replace ( / ^ \. \/ / , '' ) ) ;
100+
101+ if ( fs . existsSync ( fallbackTarget ) ) {
102+ console . warn (
103+ `docusaurus-dedupe-aliases: resolved ${ specifier } via fallback path ${ fallbackTarget } due to` ,
104+ error . message
105+ ) ;
106+ return [ [ aliasKey , fallbackTarget ] ] ;
107+ }
108+
67109 console . warn (
68110 `docusaurus-dedupe-aliases: unable to resolve specifier ${ specifier } ` ,
69111 error
0 commit comments