xref: /expo/packages/@expo/config/src/getConfig.ts (revision 082815dc)
1*082815dcSEvan Baconimport JsonFile from '@expo/json-file';
2*082815dcSEvan Baconimport { existsSync } from 'fs';
3*082815dcSEvan Bacon
4*082815dcSEvan Baconimport { AppJSONConfig, ConfigContext, ExpoConfig } from './Config.types';
5*082815dcSEvan Baconimport { ConfigError } from './Errors';
6*082815dcSEvan Baconimport { DynamicConfigResults, evalConfig } from './evalConfig';
7*082815dcSEvan Bacon
8*082815dcSEvan Bacon// We cannot use async config resolution right now because Next.js doesn't support async configs.
9*082815dcSEvan Bacon// If they don't add support for async Webpack configs then we may need to pull support for Next.js.
10*082815dcSEvan Baconfunction readConfigFile(configFile: string, context: ConfigContext): null | DynamicConfigResults {
11*082815dcSEvan Bacon  // If the file doesn't exist then we should skip it and continue searching.
12*082815dcSEvan Bacon  if (!existsSync(configFile)) {
13*082815dcSEvan Bacon    return null;
14*082815dcSEvan Bacon  }
15*082815dcSEvan Bacon  try {
16*082815dcSEvan Bacon    return evalConfig(configFile, context);
17*082815dcSEvan Bacon  } catch (error: any) {
18*082815dcSEvan Bacon    // @ts-ignore
19*082815dcSEvan Bacon    error.isConfigError = true;
20*082815dcSEvan Bacon    error.message = `Error reading Expo config at ${configFile}:\n\n${error.message}`;
21*082815dcSEvan Bacon    throw error;
22*082815dcSEvan Bacon  }
23*082815dcSEvan Bacon}
24*082815dcSEvan Bacon
25*082815dcSEvan Baconexport function getDynamicConfig(configPath: string, request: ConfigContext): DynamicConfigResults {
26*082815dcSEvan Bacon  const config = readConfigFile(configPath, request);
27*082815dcSEvan Bacon  if (config) {
28*082815dcSEvan Bacon    // The config must be serialized and evaluated ahead of time so the spawned process can send it over.
29*082815dcSEvan Bacon    return config;
30*082815dcSEvan Bacon  }
31*082815dcSEvan Bacon  // TODO: It seems this is only thrown if the file cannot be found (which may never happen).
32*082815dcSEvan Bacon  // If so we should throw a more helpful error.
33*082815dcSEvan Bacon  throw new ConfigError(`Failed to read config at: ${configPath}`, 'INVALID_CONFIG');
34*082815dcSEvan Bacon}
35*082815dcSEvan Bacon
36*082815dcSEvan Baconexport function getStaticConfig(configPath: string): AppJSONConfig | ExpoConfig {
37*082815dcSEvan Bacon  const config = JsonFile.read(configPath, { json5: true });
38*082815dcSEvan Bacon  if (config) {
39*082815dcSEvan Bacon    return config as any;
40*082815dcSEvan Bacon  }
41*082815dcSEvan Bacon  throw new ConfigError(`Failed to read config at: ${configPath}`, 'INVALID_CONFIG');
42*082815dcSEvan Bacon}
43