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