1import fs from 'fs-extra'; 2import glob from 'glob-promise'; 3import path from 'path'; 4 5import { Podspec, readPodspecAsync } from './CocoaPods'; 6import * as Directories from './Directories'; 7import * as Npm from './Npm'; 8import AndroidUnversionablePackages from './versioning/android/unversionablePackages.json'; 9import IosUnversionablePackages from './versioning/ios/unversionablePackages.json'; 10 11const ANDROID_DIR = Directories.getAndroidDir(); 12const IOS_DIR = Directories.getIosDir(); 13const PACKAGES_DIR = Directories.getPackagesDir(); 14 15/** 16 * Cached list of packages or `null` if they haven't been loaded yet. See `getListOfPackagesAsync`. 17 */ 18let cachedPackages: Package[] | null = null; 19 20export interface CodegenConfigLibrary { 21 name: string; 22 type: 'modules' | 'components'; 23 jsSrcsDir: string; 24} 25 26export enum DependencyKind { 27 Normal = 'dependencies', 28 Dev = 'devDependencies', 29 Peer = 'peerDependencies', 30 Optional = 'optionalDependencies', 31} 32 33export const DefaultDependencyKind = [DependencyKind.Normal, DependencyKind.Dev]; 34 35/** 36 * An object representing `package.json` structure. 37 */ 38export type PackageJson = { 39 name: string; 40 version: string; 41 scripts: Record<string, string>; 42 gitHead?: string; 43 codegenConfig?: { 44 libraries: CodegenConfigLibrary[]; 45 }; 46 dependencies?: Record<string, string>; 47 devDependencies?: Record<string, string>; 48 peerDependencies?: Record<string, string>; 49 optionalDependencies?: Record<string, string>; 50 [key: string]: unknown; 51}; 52 53/** 54 * Type of package's dependency returned by `getDependencies`. 55 */ 56export type PackageDependency = { 57 name: string; 58 kind: DependencyKind; 59 versionRange: string; 60}; 61 62/** 63 * Union with possible platform names. 64 */ 65type Platform = 'ios' | 'android' | 'web'; 66 67/** 68 * Type representing `expo-modules.config.json` structure. 69 */ 70export type ExpoModuleConfig = { 71 name: string; 72 platforms: Platform[]; 73 ios?: { 74 subdirectory?: string; 75 podName?: string; 76 podspecPath?: string; 77 }; 78 android?: { 79 subdirectory?: string; 80 }; 81}; 82 83/** 84 * Represents a package in the monorepo. 85 */ 86export class Package { 87 path: string; 88 packageJson: PackageJson; 89 expoModuleConfig: ExpoModuleConfig; 90 packageView?: Npm.PackageViewType | null; 91 92 constructor(rootPath: string, packageJson?: PackageJson) { 93 this.path = rootPath; 94 this.packageJson = packageJson || require(path.join(rootPath, 'package.json')); 95 this.expoModuleConfig = readExpoModuleConfigJson(rootPath); 96 } 97 98 get hasPlugin(): boolean { 99 return fs.pathExistsSync(path.join(this.path, 'plugin')); 100 } 101 102 get packageName(): string { 103 return this.packageJson.name; 104 } 105 106 get packageVersion(): string { 107 return this.packageJson.version; 108 } 109 110 get packageSlug(): string { 111 return (this.expoModuleConfig && this.expoModuleConfig.name) || this.packageName; 112 } 113 114 get scripts(): { [key: string]: string } { 115 return this.packageJson.scripts || {}; 116 } 117 118 get podspecPath(): string | null { 119 if (this.expoModuleConfig?.ios?.podspecPath) { 120 return this.expoModuleConfig.ios.podspecPath; 121 } 122 123 // Obtain podspecName by looking for podspecs in both package's root directory and ios subdirectory. 124 const [podspecPath] = glob.sync(`{*,${this.iosSubdirectory}/*}.podspec`, { 125 cwd: this.path, 126 }); 127 128 return podspecPath || null; 129 } 130 131 get podspecName(): string | null { 132 const iosConfig = { 133 subdirectory: 'ios', 134 ...(this.expoModuleConfig?.ios ?? {}), 135 }; 136 137 // 'ios.podName' is actually not used anywhere in our modules, but let's have the same logic as react-native-unimodules script. 138 if ('podName' in iosConfig) { 139 return iosConfig.podName as string; 140 } 141 142 const podspecPath = this.podspecPath; 143 if (!podspecPath) { 144 return null; 145 } 146 return path.basename(podspecPath, '.podspec'); 147 } 148 149 get iosSubdirectory(): string { 150 return this.expoModuleConfig?.ios?.subdirectory ?? 'ios'; 151 } 152 153 get androidSubdirectory(): string { 154 return this.expoModuleConfig?.android?.subdirectory ?? 'android'; 155 } 156 157 get androidPackageName(): string | null { 158 if (!this.isSupportedOnPlatform('android')) { 159 return null; 160 } 161 const buildGradle = fs.readFileSync( 162 path.join(this.path, this.androidSubdirectory, 'build.gradle'), 163 'utf8' 164 ); 165 const match = buildGradle.match(/^group ?= ?'([\w.]+)'\n/m); 166 return match?.[1] ?? null; 167 } 168 169 get changelogPath(): string { 170 return path.join(this.path, 'CHANGELOG.md'); 171 } 172 173 isExpoModule() { 174 return !!this.expoModuleConfig; 175 } 176 177 containsPodspecFile() { 178 return [ 179 ...fs.readdirSync(this.path), 180 ...fs.readdirSync(path.join(this.path, this.iosSubdirectory)), 181 ].some((path) => path.endsWith('.podspec')); 182 } 183 184 isSupportedOnPlatform(platform: 'ios' | 'android'): boolean { 185 if (this.expoModuleConfig && !fs.existsSync(path.join(this.path, 'react-native.config.js'))) { 186 // check platform support from expo autolinking but not rn-cli linking which is not platform aware 187 return this.expoModuleConfig.platforms?.includes(platform) ?? false; 188 } else if (platform === 'android') { 189 return fs.existsSync(path.join(this.path, this.androidSubdirectory, 'build.gradle')); 190 } else if (platform === 'ios') { 191 return ( 192 fs.existsSync(path.join(this.path, this.iosSubdirectory)) && this.containsPodspecFile() 193 ); 194 } 195 return false; 196 } 197 198 isIncludedInExpoClientOnPlatform(platform: 'ios' | 'android'): boolean { 199 if (platform === 'ios') { 200 // On iOS we can easily check whether the package is included in Expo client by checking if it is installed by Cocoapods. 201 const { podspecName } = this; 202 return ( 203 podspecName != null && 204 fs.pathExistsSync(path.join(IOS_DIR, 'Pods', 'Headers', 'Public', podspecName)) 205 ); 206 } else if (platform === 'android') { 207 // On Android we need to read settings.gradle file 208 const settingsGradle = fs.readFileSync(path.join(ANDROID_DIR, 'settings.gradle'), 'utf8'); 209 const match = settingsGradle.search( 210 new RegExp( 211 `useExpoModules\\([^\\)]+exclude\\s*:\\s*\\[[^\\]]*'${this.packageName}'[^\\]]*\\][^\\)]+\\)` 212 ) 213 ); 214 // this is somewhat brittle so we do a quick-and-dirty sanity check: 215 // 'expo-in-app-purchases' should never be included so if we don't find a match 216 // for that package, something is wrong. 217 if (this.packageName === 'expo-in-app-purchases' && match === -1) { 218 throw new Error( 219 "'isIncludedInExpoClientOnPlatform' is not behaving correctly, please check android/settings.gradle format" 220 ); 221 } 222 return match === -1; 223 } 224 throw new Error( 225 `'isIncludedInExpoClientOnPlatform' is not supported on '${platform}' platform yet.` 226 ); 227 } 228 229 isVersionableOnPlatform(platform: 'ios' | 'android'): boolean { 230 if (platform === 'ios') { 231 return this.podspecName != null && !IosUnversionablePackages.includes(this.packageName); 232 } else if (platform === 'android') { 233 return !AndroidUnversionablePackages.includes(this.packageName); 234 } 235 throw new Error(`'isVersionableOnPlatform' is not supported on '${platform}' platform yet.`); 236 } 237 238 async getPackageViewAsync(): Promise<Npm.PackageViewType | null> { 239 if (this.packageView !== undefined) { 240 return this.packageView; 241 } 242 return await Npm.getPackageViewAsync(this.packageName, this.packageVersion); 243 } 244 245 getDependencies(kinds: DependencyKind[] = [DependencyKind.Normal]): PackageDependency[] { 246 const dependencies = kinds.map((kind) => { 247 const deps = this.packageJson[kind]; 248 249 return !deps 250 ? [] 251 : Object.entries(deps).map(([name, versionRange]) => { 252 return { 253 name, 254 kind, 255 versionRange, 256 }; 257 }); 258 }); 259 return ([] as PackageDependency[]).concat(...dependencies); 260 } 261 262 dependsOn(packageName: string): boolean { 263 return this.getDependencies().some((dep) => dep.name === packageName); 264 } 265 266 /** 267 * Iterates through dist tags returned by npm to determine an array of tags to which given version is bound. 268 */ 269 async getDistTagsAsync(version: string = this.packageVersion): Promise<string[]> { 270 const pkgView = await this.getPackageViewAsync(); 271 const distTags = pkgView?.['dist-tags'] ?? {}; 272 return Object.keys(distTags).filter((tag) => distTags[tag] === version); 273 } 274 275 /** 276 * Checks whether the package depends on a local pod with given name. 277 */ 278 async hasLocalPodDependencyAsync(podName?: string | null): Promise<boolean> { 279 if (!podName) { 280 return false; 281 } 282 const podspecPath = path.join(this.path, 'ios/Pods/Local Podspecs', `${podName}.podspec.json`); 283 return await fs.pathExists(podspecPath); 284 } 285 286 /** 287 * Checks whether package has its own changelog file. 288 */ 289 async hasChangelogAsync(): Promise<boolean> { 290 return fs.pathExists(this.changelogPath); 291 } 292 293 /** 294 * Checks whether package has any native code (iOS, Android, C++). 295 */ 296 async isNativeModuleAsync(): Promise<boolean> { 297 const dirs = ['ios', 'android', 'cpp'].map((dir) => path.join(this.path, dir)); 298 for (const dir of dirs) { 299 if (await fs.pathExists(dir)) { 300 return true; 301 } 302 } 303 return false; 304 } 305 306 /** 307 * Checks whether the package contains native unit tests on the given platform. 308 */ 309 async hasNativeTestsAsync(platform: Platform): Promise<boolean> { 310 if (platform === 'android') { 311 return ( 312 fs.pathExists(path.join(this.path, this.androidSubdirectory, 'src/test')) || 313 fs.pathExists(path.join(this.path, this.androidSubdirectory, 'src/androidTest')) 314 ); 315 } 316 if (platform === 'ios') { 317 return ( 318 this.isSupportedOnPlatform(platform) && 319 !!this.podspecPath && 320 fs.readFileSync(path.join(this.path, this.podspecPath), 'utf8').includes('test_spec') 321 ); 322 } 323 // TODO(tsapeta): Support web. 324 throw new Error(`"hasNativeTestsAsync" for platform "${platform}" is not implemented yet.`); 325 } 326 327 /** 328 * Checks whether package contains native instrumentation tests for Android. 329 */ 330 async hasNativeInstrumentationTestsAsync(platform: Platform): Promise<boolean> { 331 if (platform === 'android') { 332 return fs.pathExists(path.join(this.path, this.androidSubdirectory, 'src/androidTest')); 333 } 334 return false; 335 } 336 337 /** 338 * Reads the podspec and returns it in JSON format 339 * or `null` if the package doesn't have a podspec. 340 */ 341 async getPodspecAsync(): Promise<Podspec | null> { 342 if (!this.podspecPath) { 343 return null; 344 } 345 const podspecPath = path.join(this.path, this.podspecPath); 346 return await readPodspecAsync(podspecPath); 347 } 348} 349 350/** 351 * Resolves to a Package instance if the package with given name exists in the repository. 352 */ 353export function getPackageByName(packageName: string): Package | null { 354 const packageJsonPath = pathToLocalPackageJson(packageName); 355 try { 356 const packageJson = require(packageJsonPath); 357 return new Package(path.dirname(packageJsonPath), packageJson); 358 } catch { 359 return null; 360 } 361} 362 363/** 364 * Resolves to an array of Package instances that represent Expo packages inside given directory. 365 */ 366export async function getListOfPackagesAsync(): Promise<Package[]> { 367 if (!cachedPackages) { 368 const paths = await glob('**/package.json', { 369 cwd: PACKAGES_DIR, 370 ignore: ['**/example/**', '**/node_modules/**', '**/__tests__/**', '**/__mocks__/**'], 371 }); 372 cachedPackages = paths 373 .map((packageJsonPath) => { 374 const fullPackageJsonPath = path.join(PACKAGES_DIR, packageJsonPath); 375 const packagePath = path.dirname(fullPackageJsonPath); 376 const packageJson = require(fullPackageJsonPath); 377 378 return new Package(packagePath, packageJson); 379 }) 380 .filter((pkg) => !!pkg.packageName); 381 } 382 return cachedPackages; 383} 384 385function readExpoModuleConfigJson(dir: string) { 386 const expoModuleConfigJsonPath = path.join(dir, 'expo-module.config.json'); 387 const expoModuleConfigJsonExists = fs.existsSync(expoModuleConfigJsonPath); 388 const unimoduleJsonPath = path.join(dir, 'unimodule.json'); 389 try { 390 return require(expoModuleConfigJsonExists ? expoModuleConfigJsonPath : unimoduleJsonPath); 391 } catch { 392 return null; 393 } 394} 395 396function pathToLocalPackageJson(packageName: string): string { 397 return path.join(PACKAGES_DIR, packageName, 'package.json'); 398} 399