1import { Command } from '@expo/commander';
2import chalk from 'chalk';
3import { PromisyClass, TaskQueue } from 'cwait';
4import fs from 'fs-extra';
5import os from 'os';
6import path from 'path';
7import recursiveOmitBy from 'recursive-omit-by';
8import { Application, TSConfigReader, TypeDocReader } from 'typedoc';
9
10import { EXPO_DIR, PACKAGES_DIR } from '../Constants';
11import logger from '../Logger';
12
13type ActionOptions = {
14  packageName?: string;
15  version?: string;
16};
17
18type EntryPoint = string | string[];
19
20type CommandAdditionalParams = [entryPoint: EntryPoint, packageName?: string];
21
22const MINIFY_JSON = true;
23
24const PACKAGES_MAPPING: Record<string, CommandAdditionalParams> = {
25  'expo-analytics-amplitude': ['Amplitude.ts'],
26  'expo-analytics-segment': ['Segment.ts'],
27  'expo-app-loading': ['index.ts'],
28  'expo-apple-authentication': ['index.ts'],
29  'expo-application': ['Application.ts'],
30  'expo-auth-session': ['AuthSession.ts'],
31  'expo-asset': [['Asset.ts', 'AssetHooks.ts']],
32  'expo-background-fetch': ['BackgroundFetch.ts'],
33  'expo-battery': ['Battery.ts'],
34  'expo-barcode-scanner': ['BarCodeScanner.tsx'],
35  'expo-blur': ['index.ts'],
36  'expo-brightness': ['Brightness.ts'],
37  'expo-calendar': ['Calendar.ts'],
38  'expo-camera': ['index.ts'],
39  'expo-cellular': ['Cellular.ts'],
40  'expo-checkbox': ['Checkbox.ts'],
41  'expo-clipboard': [['Clipboard.ts', 'Clipboard.types.ts']],
42  'expo-constants': [['Constants.ts', 'Constants.types.ts']],
43  'expo-crypto': ['Crypto.ts'],
44  'expo-document-picker': ['index.ts'],
45  'expo-error-recovery': ['ErrorRecovery.ts'],
46  'expo-face-detector': ['FaceDetector.ts'],
47  'expo-firebase-analytics': ['Analytics.ts'],
48  'expo-firebase-core': ['FirebaseCore.ts'],
49  'expo-facebook': [['Facebook.ts', 'Facebook.types.ts']],
50  'expo-font': ['index.ts'],
51  'expo-haptics': ['Haptics.ts'],
52  'expo-image-manipulator': ['ImageManipulator.ts'],
53  'expo-image-picker': ['ImagePicker.ts'],
54  'expo-in-app-purchases': ['InAppPurchases.ts'],
55  'expo-intent-launcher': ['IntentLauncher.ts'],
56  'expo-keep-awake': ['index.ts'],
57  'expo-linking': ['Linking.ts'],
58  'expo-linear-gradient': ['LinearGradient.tsx'],
59  'expo-local-authentication': ['LocalAuthentication.ts'],
60  'expo-localization': ['Localization.ts'],
61  'expo-location': ['Location.ts'],
62  'expo-mail-composer': ['MailComposer.ts'],
63  'expo-media-library': ['MediaLibrary.ts'],
64  'expo-navigation-bar': ['NavigationBar.ts'],
65  'expo-network': ['Network.ts'],
66  'expo-pedometer': ['Pedometer.ts', 'expo-sensors'],
67  'expo-print': ['Print.ts'],
68  'expo-random': ['Random.ts'],
69  'expo-screen-capture': ['ScreenCapture.ts'],
70  'expo-screen-orientation': ['ScreenOrientation.ts'],
71  'expo-secure-store': ['SecureStore.ts'],
72  'expo-sharing': ['Sharing.ts'],
73  'expo-sms': ['SMS.ts'],
74  'expo-speech': ['Speech/Speech.ts'],
75  'expo-splash-screen': ['SplashScreen.ts'],
76  'expo-sqlite': ['index.ts'],
77  'expo-status-bar': ['StatusBar.ts'],
78  'expo-store-review': ['StoreReview.ts'],
79  'expo-system-ui': ['SystemUI.ts'],
80  'expo-task-manager': ['TaskManager.ts'],
81  'expo-tracking-transparency': ['TrackingTransparency.ts'],
82  'expo-updates': ['index.ts'],
83  'expo-video': [['Video.tsx', 'Video.types.ts'], 'expo-av'],
84  'expo-video-thumbnails': ['VideoThumbnails.ts'],
85  'expo-web-browser': ['WebBrowser.ts'],
86};
87
88const executeCommand = async (
89  jsonFileName: string,
90  version: string,
91  entryPoint: EntryPoint = 'index.ts',
92  packageName: string = jsonFileName
93) => {
94  const app = new Application();
95
96  app.options.addReader(new TSConfigReader());
97  app.options.addReader(new TypeDocReader());
98
99  const dataPath = path.join(EXPO_DIR, 'docs', 'public', 'static', 'data', version);
100  const basePath = path.join(PACKAGES_DIR, packageName);
101  const entriesPath = path.join(basePath, 'src');
102  const tsConfigPath = path.join(basePath, 'tsconfig.json');
103  const jsonOutputPath = path.join(dataPath, `${jsonFileName}.json`);
104
105  const entryPoints = Array.isArray(entryPoint)
106    ? entryPoint.map((entry) => path.join(entriesPath, entry))
107    : [path.join(entriesPath, entryPoint)];
108
109  app.bootstrap({
110    entryPoints,
111    tsconfig: tsConfigPath,
112    disableSources: true,
113    hideGenerator: true,
114    excludePrivate: true,
115    excludeProtected: true,
116  });
117
118  const project = app.convert();
119
120  if (project) {
121    await app.generateJson(project, jsonOutputPath);
122    const output = await fs.readJson(jsonOutputPath);
123    output.name = jsonFileName;
124
125    if (Array.isArray(entryPoint)) {
126      const filterEntries = entryPoint.map((entry) => entry.substring(0, entry.lastIndexOf('.')));
127      output.children = output.children
128        .filter((entry) => filterEntries.includes(entry.name))
129        .map((entry) => entry.children)
130        .flat()
131        .sort((a, b) => a.name.localeCompare(b.name));
132    }
133
134    if (MINIFY_JSON) {
135      const minifiedJson = recursiveOmitBy(
136        output,
137        ({ key, node }) =>
138          ['id', 'groups', 'target'].includes(key) || (key === 'flags' && !Object.keys(node).length)
139      );
140      await fs.writeFile(jsonOutputPath, JSON.stringify(minifiedJson, null, 0));
141    } else {
142      await fs.writeFile(jsonOutputPath, JSON.stringify(output));
143    }
144  } else {
145    throw new Error(`�� Failed to extract API data from source code for '${packageName}' package.`);
146  }
147};
148
149async function action({ packageName, version = 'unversioned' }: ActionOptions) {
150  const taskQueue = new TaskQueue(Promise as PromisyClass, os.cpus().length);
151
152  try {
153    if (packageName) {
154      const packagesEntries = Object.entries(PACKAGES_MAPPING)
155        .filter(([key, value]) => key === packageName || value.includes(packageName))
156        .map(([key, value]) => taskQueue.add(() => executeCommand(key, version, ...value)));
157      if (packagesEntries.length) {
158        await Promise.all(packagesEntries);
159        logger.log(
160          chalk.green(`\n�� Successful extraction of docs API data for the selected package!`)
161        );
162      } else {
163        logger.warn(`�� Package '${packageName}' API data generation is not supported yet!`);
164      }
165    } else {
166      const packagesEntries = Object.entries(PACKAGES_MAPPING).map(([key, value]) =>
167        taskQueue.add(() => executeCommand(key, version, ...value))
168      );
169      await Promise.all(packagesEntries);
170      logger.log(
171        chalk.green(`\n�� Successful extraction of docs API data for all available packages!`)
172      );
173    }
174  } catch (error) {
175    logger.error(error);
176  }
177}
178
179export default (program: Command) => {
180  program
181    .command('generate-docs-api-data')
182    .alias('gdad')
183    .description(`Extract API data JSON files for docs using TypeDoc.`)
184    .option('-p, --packageName <packageName>', 'Extract API data only for the specific package.')
185    .option(
186      '-v, --version <version>',
187      'Set the data output path to the specific version.',
188      'unversioned'
189    )
190    .asyncAction(action);
191};
192