start static method

Future<FFXEmulator> start({
  1. required Directory projectDir,
  2. String host = '0.0.0.0',
  3. int port = 8790,
  4. Directory? runtimeStateDir,
  5. int? maxUploadBytes,
  6. int? maxUploadedBytes,
  7. String? advertisedHost,
  8. FunctionsHostConnection? functionsHost,
  9. DateTime clock()?,
  10. Duration? functionsResetTimeout,
  11. String? connectorsUrl,
  12. String? connectorsToken,
  13. ConnectorCatalog? connectorCatalog,
  14. String? connectorsSecret,
  15. Map<String, String>? environment,
  16. void log(
    1. String message
    )?,
})

Boots the emulator: binds HTTP, loads .ffx/, starts watching.

advertisedHost is what grant/download URLs embed (defaults to 127.0.0.1 when binding a wildcard address so minted URLs stay reachable from the same machine).

functionsHost attaches a local Functions host (26 ยง11): its socket directory must pass FunctionsHostConnection.checkConfinement (an ArgumentError otherwise), the emulator serves the host's internal API on the connection's emulator socket, and every Functions route is forwarded to the host's socket. Without it those routes answer functionsNotDeployed. clock times the retention of that API's superseded config generations, backend upload handles and test session leases. functionsResetTimeout bounds how long a reset waits for the host's answer to its reset signal (10 seconds; tests shorten it).

connectorsUrl is where connector calls are forwarded (defaults to FFX_CONNECTORS_URL), with connectorsToken (defaults to FFX_CONNECTORS_TOKEN) as the bearer; connectorCatalog (defaults to FFX_CONNECTORS_CATALOG) is the catalog's connectors and operations the call is held to; connectorsSecret (defaults to FFX_EMULATOR_CONNECTORS_SECRET) is what the preview's door sends as FFX-Connectors-Secret. Without all three, or with a malformed FFX_CONNECTORS_CATALOG, every connector call is refused. The defaults are read from environment, the process environment unless given.

Implementation

static Future<FFXEmulator> start({
  required Directory projectDir,
  String host = '0.0.0.0',
  int port = 8790,
  Directory? runtimeStateDir,
  int? maxUploadBytes,
  int? maxUploadedBytes,
  String? advertisedHost,
  FunctionsHostConnection? functionsHost,
  DateTime Function()? clock,
  Duration? functionsResetTimeout,
  String? connectorsUrl,
  String? connectorsToken,
  ConnectorCatalog? connectorCatalog,
  String? connectorsSecret,
  Map<String, String>? environment,
  void Function(String message)? log,
}) async {
  final emit = log ?? (message) => stdout.writeln('[ffx-emulator] $message');
  if (functionsHost != null) {
    try {
      functionsHost.checkConfinement();
    } on FormatException catch (error) {
      throw ArgumentError.value(
        functionsHost,
        'functionsHost',
        error.message,
      );
    }
  }
  final server = EmulatorServer(
    projectDir: projectDir,
    runtimeStateDir: runtimeStateDir,
    maxUploadBytes: maxUploadBytes,
    maxUploadedBytes: maxUploadedBytes,
    functionsHost: functionsHost,
    clock: clock,
    functionsResetTimeout:
        functionsResetTimeout ?? FunctionsHostContract.resetTimeout,
    log: emit,
    connectorsUrl: connectorsUrl,
    connectorsToken: connectorsToken,
    connectorCatalog: connectorCatalog,
    connectorsSecret: connectorsSecret,
    environment: environment,
  );
  HttpServer? internal;
  if (functionsHost != null) {
    try {
      internal = await _bindInternal(functionsHost.emulatorSocket);
    } on Object catch (cause) {
      // Replacing a leftover socket file can fail as well as the bind.
      await server.close();
      final reason = switch (cause) {
        SocketException(:final osError, :final message) =>
          osError?.message ?? message,
        FileSystemException(:final osError, :final message) =>
          osError?.message ?? message,
        _ => '$cause',
      };
      throw StateError(
        'Cannot listen on the private Functions socket ($reason).',
      );
    }
  }
  final HttpServer http;
  final EmulatorHttpIngress ingress;
  try {
    ingress = EmulatorHttpIngress(await ServerSocket.bind(host, port));
    http = HttpServer.listenOn(ingress);
  } on SocketException catch (cause) {
    await server.close();
    await _closeInternal(internal, functionsHost);
    throw StateError(
      'Cannot bind $host:$port (${cause.osError?.message ?? cause.message}). '
      'Is another emulator running? Pass a different --port.',
    );
  }
  final advertised =
      advertisedHost ??
      (host == '0.0.0.0' || host == '::' ? '127.0.0.1' : host);
  server.baseUrl = 'http://$advertised:${http.port}';
  server.startWatching();
  unawaited(
    http
        .forEach(
          (request) => server.handle(
            request,
            originalHead: ingress.takeHead(request),
            interim: (bytes) => ingress.writeInterim(request, bytes),
          ),
        )
        .catchError((Object error) {
          emit('http loop error: $error');
        }),
  );
  if (internal != null) {
    unawaited(
      internal.forEach(server.handleInternal).catchError((Object error) {
        emit('internal Functions loop error: $error');
      }),
    );
    emit('Functions routes forward to the attached local host.');
  }
  emit(
    'listening on http://$host:${http.port} '
    '(project: ${projectDir.path})',
  );
  return FFXEmulator._(server, http, ingress, internal, host, http.port);
}