import 'dart:async'; import 'dart:io'; import 'package:flutter/services.dart' show rootBundle; /// Serves the bundled web build (assets/web) on http://localhost:[port]. /// /// Replaces flutter_inappwebview's InAppLocalhostServer, whose start() never /// completes when the port is taken (the app then stays on a dark screen): /// * binds with `shared: true`, so a second Flutter engine in the same /// process (Android can start a second activity instance) can serve too; /// * retries for a while, then throws, so the shell can show an error; /// * [healthy] / [ensureRunning] detect a socket the OS took away while the /// app was suspended (iOS) and bind again. /// /// The port is part of the page origin: localStorage and IndexedDB (the /// user's sites) belong to it. Never change it after release. class LocalServer { LocalServer({this.port = 47391, this.documentRoot = 'assets/web/'}); final int port; final String documentRoot; HttpServer? _server; String get origin => 'http://localhost:$port'; Future start({Duration timeout = const Duration(seconds: 8)}) async { if (_server != null) return; final deadline = DateTime.now().add(timeout); Object? lastError; while (true) { try { final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port, shared: true); _server = server; server.listen( _handle, onError: (Object _) {}, onDone: () { if (identical(_server, server)) _server = null; }, cancelOnError: false, ); return; } catch (e) { lastError = e; if (DateTime.now().isAfter(deadline)) break; await Future.delayed(const Duration(milliseconds: 400)); } } throw Exception('Local server could not use port $port: $lastError'); } Future stop() async { final s = _server; _server = null; try { await s?.close(force: true); } catch (_) {} } /// True when index.html can be fetched right now. Future healthy() async { if (_server == null) return false; final client = HttpClient()..connectionTimeout = const Duration(seconds: 1); try { final req = await client.getUrl(Uri.parse('$origin/index.html')).timeout(const Duration(seconds: 2)); final res = await req.close().timeout(const Duration(seconds: 2)); await res.drain(); return res.statusCode == 200; } catch (_) { return false; } finally { client.close(force: true); } } /// Binds again if the server is gone or not answering. Future ensureRunning() async { if (await healthy()) return; await stop(); await start(); } Future _handle(HttpRequest request) async { final res = request.response; try { var path = Uri.decodeFull(request.uri.path); if (path.startsWith('/')) path = path.substring(1); if (path.isEmpty || path.endsWith('/')) path += 'index.html'; if (path.split('/').contains('..')) { res.statusCode = HttpStatus.forbidden; return; } final data = await rootBundle.load('$documentRoot$path'); res.headers.contentType = _contentType(path); res.headers.set(HttpHeaders.cacheControlHeader, 'no-cache'); res.add(data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes)); } catch (_) { res.statusCode = HttpStatus.notFound; } finally { try { await res.close(); } catch (_) {} } } static ContentType _contentType(String path) { final ext = path.contains('.') ? path.substring(path.lastIndexOf('.') + 1).toLowerCase() : ''; switch (ext) { case 'html': return ContentType('text', 'html', charset: 'utf-8'); case 'js': case 'mjs': return ContentType('text', 'javascript', charset: 'utf-8'); case 'css': return ContentType('text', 'css', charset: 'utf-8'); case 'json': case 'webmanifest': return ContentType('application', 'json', charset: 'utf-8'); case 'wasm': return ContentType('application', 'wasm'); case 'svg': return ContentType('image', 'svg+xml'); case 'png': return ContentType('image', 'png'); case 'jpg': case 'jpeg': return ContentType('image', 'jpeg'); case 'ico': return ContentType('image', 'x-icon'); case 'woff': return ContentType('font', 'woff'); case 'woff2': return ContentType('font', 'woff2'); case 'txt': return ContentType('text', 'plain', charset: 'utf-8'); default: return ContentType('application', 'octet-stream'); } } }