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