1import { MessageSocket } from '@expo/dev-server';
2import assert from 'assert';
3import openBrowserAsync from 'better-opn';
4import resolveFrom from 'resolve-from';
5
6import { APISettings } from '../../api/settings';
7import * as Log from '../../log';
8import { FileNotifier } from '../../utils/FileNotifier';
9import { env } from '../../utils/env';
10import { CommandError } from '../../utils/errors';
11import { BaseResolveDeviceProps, PlatformManager } from '../platforms/PlatformManager';
12import { AsyncNgrok } from './AsyncNgrok';
13import { DevelopmentSession } from './DevelopmentSession';
14import { CreateURLOptions, UrlCreator } from './UrlCreator';
15
16export type ServerLike = {
17  close(callback?: (err?: Error) => void): void;
18};
19
20export type DevServerInstance = {
21  /** Bundler dev server instance. */
22  server: ServerLike;
23  /** Dev server URL location properties. */
24  location: {
25    url: string;
26    port: number;
27    protocol: 'http' | 'https';
28    host?: string;
29  };
30  /** Additional middleware that's attached to the `server`. */
31  middleware: any;
32  /** Message socket for communicating with the runtime. */
33  messageSocket: MessageSocket;
34};
35
36export interface BundlerStartOptions {
37  /** Should the dev server use `https` protocol. */
38  https?: boolean;
39  /** Should start the dev servers in development mode (minify). */
40  mode?: 'development' | 'production';
41  /** Is dev client enabled. */
42  devClient?: boolean;
43  /** Should run dev servers with clean caches. */
44  resetDevServer?: boolean;
45  /** Which manifest type to serve. */
46  forceManifestType?: 'expo-updates' | 'classic';
47
48  /** Max amount of workers (threads) to use with Metro bundler, defaults to undefined for max workers. */
49  maxWorkers?: number;
50  /** Port to start the dev server on. */
51  port?: number;
52
53  /** Should instruct the bundler to create minified bundles. */
54  minify?: boolean;
55
56  // Webpack options
57  /** Should modify and create PWA icons. */
58  isImageEditingEnabled?: boolean;
59
60  location: CreateURLOptions;
61}
62
63const PLATFORM_MANAGERS = {
64  simulator: () =>
65    require('../platforms/ios/ApplePlatformManager')
66      .ApplePlatformManager as typeof import('../platforms/ios/ApplePlatformManager').ApplePlatformManager,
67  emulator: () =>
68    require('../platforms/android/AndroidPlatformManager')
69      .AndroidPlatformManager as typeof import('../platforms/android/AndroidPlatformManager').AndroidPlatformManager,
70};
71
72const MIDDLEWARES = {
73  classic: () =>
74    require('./middleware/ClassicManifestMiddleware')
75      .ClassicManifestMiddleware as typeof import('./middleware/ClassicManifestMiddleware').ClassicManifestMiddleware,
76  'expo-updates': () =>
77    require('./middleware/ExpoGoManifestHandlerMiddleware')
78      .ExpoGoManifestHandlerMiddleware as typeof import('./middleware/ExpoGoManifestHandlerMiddleware').ExpoGoManifestHandlerMiddleware,
79};
80
81export abstract class BundlerDevServer {
82  /** Name of the bundler. */
83  abstract get name(): string;
84
85  /** Ngrok instance for managing tunnel connections. */
86  protected ngrok: AsyncNgrok | null = null;
87  /** Interfaces with the Expo 'Development Session' API. */
88  protected devSession: DevelopmentSession | null = null;
89  /** Http server and related info. */
90  protected instance: DevServerInstance | null = null;
91  /** Native platform interfaces for opening projects.  */
92  private platformManagers: Record<string, PlatformManager<any>> = {};
93  /** Manages the creation of dev server URLs. */
94  protected urlCreator?: UrlCreator | null = null;
95
96  constructor(
97    /** Project root folder. */
98    public projectRoot: string,
99    // TODO: Replace with custom scheme maybe...
100    public isDevClient?: boolean
101  ) {}
102
103  protected setInstance(instance: DevServerInstance) {
104    this.instance = instance;
105  }
106
107  /** Get the manifest middleware function. */
108  protected async getManifestMiddlewareAsync(
109    options: Pick<BundlerStartOptions, 'minify' | 'mode' | 'forceManifestType'> = {}
110  ) {
111    const manifestType = options.forceManifestType || 'classic';
112    assert(manifestType in MIDDLEWARES, `Manifest middleware for type '${manifestType}' not found`);
113    const Middleware = MIDDLEWARES[manifestType]();
114
115    const urlCreator = this.getUrlCreator();
116    const middleware = new Middleware(this.projectRoot, {
117      constructUrl: urlCreator.constructUrl.bind(urlCreator),
118      mode: options.mode,
119      minify: options.minify,
120      isNativeWebpack: this.name === 'webpack' && this.isTargetingNative(),
121    });
122    return middleware.getHandler();
123  }
124
125  /** Start the dev server using settings defined in the start command. */
126  public abstract startAsync(options: BundlerStartOptions): Promise<DevServerInstance>;
127
128  protected async postStartAsync(options: BundlerStartOptions) {
129    if (options.location.hostType === 'tunnel' && !APISettings.isOffline) {
130      await this._startTunnelAsync();
131    }
132    await this.startDevSessionAsync();
133
134    this.watchConfig();
135  }
136
137  protected abstract getConfigModuleIds(): string[];
138
139  protected watchConfig() {
140    const notifier = new FileNotifier(this.projectRoot, this.getConfigModuleIds());
141    notifier.startObserving();
142  }
143
144  /** Create ngrok instance and start the tunnel server. Exposed for testing. */
145  public async _startTunnelAsync(): Promise<AsyncNgrok | null> {
146    const port = this.getInstance()?.location.port;
147    if (!port) return null;
148    Log.debug('[ngrok] connect to port: ' + port);
149    this.ngrok = new AsyncNgrok(this.projectRoot, port);
150    await this.ngrok.startAsync();
151    return this.ngrok;
152  }
153
154  protected async startDevSessionAsync() {
155    // This is used to make Expo Go open the project in either Expo Go, or the web browser.
156    // Must come after ngrok (`startTunnelAsync`) setup.
157
158    if (this.devSession) {
159      this.devSession.stop();
160    }
161
162    this.devSession = new DevelopmentSession(
163      this.projectRoot,
164      // This URL will be used on external devices so the computer IP won't be relevant.
165      this.isTargetingNative()
166        ? this.getNativeRuntimeUrl()
167        : this.getDevServerUrl({ hostType: 'localhost' })
168    );
169
170    await this.devSession.startAsync({
171      runtime: this.isTargetingNative() ? 'native' : 'web',
172    });
173  }
174
175  public isTargetingNative() {
176    // Temporary hack while we implement multi-bundler dev server proxy.
177    return true;
178  }
179
180  public isTargetingWeb() {
181    return false;
182  }
183
184  /**
185   * Sends a message over web sockets to any connected device,
186   * does nothing when the dev server is not running.
187   *
188   * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.
189   * @param params
190   */
191  public broadcastMessage(
192    method: 'reload' | 'devMenu' | 'sendDevCommand',
193    params?: Record<string, any>
194  ) {
195    this.getInstance()?.messageSocket.broadcast(method, params);
196  }
197
198  /** Get the running dev server instance. */
199  public getInstance() {
200    return this.instance;
201  }
202
203  /** Stop the running dev server instance. */
204  async stopAsync() {
205    // Stop the dev session timer.
206    this.devSession?.stop();
207
208    // Stop ngrok if running.
209    await this.ngrok?.stopAsync().catch((e) => {
210      Log.error(`Error stopping ngrok:`);
211      Log.exception(e);
212    });
213
214    return new Promise<void>((resolve, reject) => {
215      // Close the server.
216      if (this.instance?.server) {
217        this.instance.server.close((error) => {
218          this.instance = null;
219          if (error) {
220            reject(error);
221          } else {
222            resolve();
223          }
224        });
225      } else {
226        this.instance = null;
227        resolve();
228      }
229    });
230  }
231
232  private getUrlCreator() {
233    assert(this.urlCreator, 'Dev server is not running.');
234    return this.urlCreator;
235  }
236
237  public getNativeRuntimeUrl(opts: Partial<CreateURLOptions> = {}) {
238    return this.isDevClient
239      ? this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl()
240      : this.getUrlCreator().constructUrl({ ...opts, scheme: 'exp' });
241  }
242
243  /** Get the URL for the running instance of the dev server. */
244  public getDevServerUrl(options: { hostType?: 'localhost' } = {}): string | null {
245    const instance = this.getInstance();
246    if (!instance?.location) {
247      return null;
248    }
249    const { location } = instance;
250    if (options.hostType === 'localhost') {
251      return `${location.protocol}://localhost:${location.port}`;
252    }
253    return location.url ?? null;
254  }
255
256  /** Get the tunnel URL from ngrok. */
257  public getTunnelUrl(): string | null {
258    return this.ngrok?.getActiveUrl() ?? null;
259  }
260
261  /** Open the dev server in a runtime. */
262  public async openPlatformAsync(
263    launchTarget: keyof typeof PLATFORM_MANAGERS | 'desktop',
264    resolver: BaseResolveDeviceProps<any> = {}
265  ) {
266    if (launchTarget === 'desktop') {
267      const url = this.getDevServerUrl({ hostType: 'localhost' });
268      await openBrowserAsync(url!);
269      return { url };
270    }
271
272    const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';
273    const manager = await this.getPlatformManagerAsync(launchTarget);
274    return manager.openAsync({ runtime }, resolver);
275  }
276
277  /** Should use the interstitial page for selecting which runtime to use. */
278  protected shouldUseInterstitialPage(): boolean {
279    return (
280      env.EXPO_ENABLE_INTERSTITIAL_PAGE &&
281      // Checks if dev client is installed.
282      !!resolveFrom.silent(this.projectRoot, 'expo-dev-launcher')
283    );
284  }
285
286  /** Get the URL for opening in Expo Go. */
287  protected getExpoGoUrl(platform: keyof typeof PLATFORM_MANAGERS): string | null {
288    if (this.shouldUseInterstitialPage()) {
289      const loadingUrl =
290        platform === 'emulator'
291          ? this.urlCreator?.constructLoadingUrl({}, 'android')
292          : this.urlCreator?.constructLoadingUrl({ hostType: 'localhost' }, 'ios');
293      return loadingUrl ?? null;
294    }
295
296    return this.urlCreator?.constructUrl({ scheme: 'exp' }) ?? null;
297  }
298
299  protected async getPlatformManagerAsync(platform: keyof typeof PLATFORM_MANAGERS) {
300    if (!this.platformManagers[platform]) {
301      const Manager = PLATFORM_MANAGERS[platform]();
302      const port = this.getInstance()?.location.port;
303      if (!port || !this.urlCreator) {
304        throw new CommandError(
305          'DEV_SERVER',
306          'Cannot interact with native platforms until dev server has started'
307        );
308      }
309      this.platformManagers[platform] = new Manager(this.projectRoot, port, {
310        getCustomRuntimeUrl: this.urlCreator.constructDevClientUrl.bind(this.urlCreator),
311        getExpoGoUrl: this.getExpoGoUrl.bind(this, platform),
312        getDevServerUrl: this.getDevServerUrl.bind(this, { hostType: 'localhost' }),
313      });
314    }
315    return this.platformManagers[platform];
316  }
317}
318