diff --git a/packages/container/container/README.md b/packages/container/container/README.md index 1aa9a5e..2aaf571 100644 --- a/packages/container/container/README.md +++ b/packages/container/container/README.md @@ -38,7 +38,7 @@ A better IoC container for Protevus, ultimately allowing Protevus to be used wit app.container.registerSingleton(SalesController()); await app.mountController(); - var http = ProtevusHttp(app); + var http = PlatformHttp(app); var server = await http.startServer('localhost', 3000); print("Protevus server listening at ${http.uri}"); } diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index fcb0343..28c3e12 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -20,8 +20,8 @@ ## 8.2.0 -* Add `addResponseHeader` to `ProtevusHttp` to add headers to HTTP default response -* Add `removeResponseHeader` to `ProtevusHttp` to remove headers from HTTP default response +* Add `addResponseHeader` to `PlatformHttp` to add headers to HTTP default response +* Add `removeResponseHeader` to `PlatformHttp` to remove headers from HTTP default response ## 8.1.1 @@ -138,7 +138,7 @@ ## 2.1.1 -* `ProtevusHttp.uri` now returns an empty `Uri` if the server is not listening. +* `PlatformHttp.uri` now returns an empty `Uri` if the server is not listening. ## 2.1.0 @@ -150,7 +150,7 @@ therefore been bumped to `2.1.0`. ## 2.0.5-beta * Make `@Expose()` in `Controller` optional. -* Add `allowHttp1` to `ProtevusHttp2` constructors. +* Add `allowHttp1` to `PlatformHttp2` constructors. * Add `deserializeBody` and `decodeBody` to `RequestContext`. * Add `HostnameRouter`, which allows for routing based on hostname. * Default to using `ThrowingReflector`, instead of `EmptyReflector`. This will give a more descriptive @@ -199,7 +199,7 @@ handlers to run, even after the response was closed. ## 2.0.0-rc.10 -* Fix an error that prevented `ProtevusHttp2.custom` from working properly. +* Fix an error that prevented `PlatformHttp2.custom` from working properly. * Add `startSharedHttp2`. ## 2.0.0-rc.9 @@ -333,7 +333,7 @@ stable, there'll be a conversion, perhaps. ## 2.0.0-alpha.10 * All calls to `Service.parseId` are now affixed with the `` argument. -* Added `uri` getter to `ProtevusHttp`. +* Added `uri` getter to `PlatformHttp`. * The default for `parseQuery` now wraps query parameters in `Map.from`. This resolves a bug in `package:angel_validate`. @@ -418,7 +418,7 @@ stable, there'll be a conversion, perhaps. as well as `query`. * Removed `Protevus.injections` and `RequestContext.injections`. * Removed `Protevus.inject` and `RequestContext.inject`. -* Removed a dependency on `package:pool`, which also meant removing `ProtevusHttp.throttle`. +* Removed a dependency on `package:pool`, which also meant removing `PlatformHttp.throttle`. * Remove the `RequestMiddleware` typedef; from now on, one should use `ResponseContext.end` exclusively to close responses. * `waterfall` will now only accept `RequestHandler`. @@ -438,7 +438,7 @@ stable, there'll be a conversion, perhaps. * Removed `Protevus.defaultZoneCreator`. * Added all flags to the `Protevus` constructor, ex. `Protevus.eagerParseBodies`. * Fix a bug where synchronous errors in `handleRequest` would not be caught. -* `ProtevusHttp.useZone` now defaults to `false`. +* `PlatformHttp.useZone` now defaults to `false`. * `ResponseContext` now starts in streaming mode by default; the response buffer is opt-in, as in many cases it is unnecessary and slows down response time. * `ResponseContext.streaming` was replaced by `ResponseContext.isBuffered`. diff --git a/packages/core/example/controller.dart b/packages/core/example/controller.dart index f0b136c..583bece 100644 --- a/packages/core/example/controller.dart +++ b/packages/core/example/controller.dart @@ -8,14 +8,15 @@ void main() async { Logger.root.onRecord.listen(print); // Create our server. - var app = Protevus(logger: Logger('protevus'), reflector: MirrorsReflector()); - var http = ProtevusHttp(app); + var app = + Application(logger: Logger('protevus'), reflector: MirrorsReflector()); + var http = PlatformHttp(app); await app.mountController(); // Simple fallback to throw a 404 on unknown paths. app.fallback((req, res) { - throw HttpException.notFound( + throw PlatformHttpException.notFound( message: 'Unknown path: "${req.uri!.path}"', ); }); diff --git a/packages/core/example/handle_error.dart b/packages/core/example/handle_error.dart index 7c721c1..05a9e36 100644 --- a/packages/core/example/handle_error.dart +++ b/packages/core/example/handle_error.dart @@ -6,7 +6,7 @@ import 'package:platform_core/http.dart'; import 'package:logging/logging.dart'; void main() async { - var app = Protevus(reflector: MirrorsReflector()) + var app = Application(reflector: MirrorsReflector()) ..logger = (Logger('protevus') ..onRecord.listen((rec) { print(rec); @@ -18,7 +18,7 @@ void main() async { app.fallback( (req, res) => Future.error('Throwing just because I feel like!')); - var http = ProtevusHttp(app); + var http = PlatformHttp(app); HttpServer? server = await http.startServer('127.0.0.1', 3000); var url = 'http://${server.address.address}:${server.port}'; print('Listening at $url'); diff --git a/packages/core/example/hostname.dart b/packages/core/example/hostname.dart index 18536da..d485725 100644 --- a/packages/core/example/hostname.dart +++ b/packages/core/example/hostname.dart @@ -3,14 +3,14 @@ import 'package:platform_core/core.dart'; import 'package:platform_core/http.dart'; import 'package:logging/logging.dart'; -Future apiConfigurer(Protevus app) async { +Future apiConfigurer(Application app) async { app.get('/', (req, res) => 'Hello, API!'); app.fallback((req, res) { return 'fallback on ${req.uri} (within the API)'; }); } -Future frontendConfigurer(Protevus app) async { +Future frontendConfigurer(Application app) async { app.fallback((req, res) => '(usually an index page would be shown here.)'); } @@ -19,8 +19,8 @@ void main() async { hierarchicalLoggingEnabled = true; //Logger.root.onRecord.listen(prettyLog); - var app = Protevus(logger: Logger('protevus')); - var http = ProtevusHttp(app); + var app = Application(logger: Logger('protevus')); + var http = PlatformHttp(app); var multiHost = HostnameRouter.configure({ 'api.localhost:3000': apiConfigurer, 'localhost:3000': frontendConfigurer, diff --git a/packages/core/example/http2/body_parsing.dart b/packages/core/example/http2/body_parsing.dart index 0cf6c3b..1592b5e 100644 --- a/packages/core/example/http2/body_parsing.dart +++ b/packages/core/example/http2/body_parsing.dart @@ -6,7 +6,7 @@ import 'package:file/local.dart'; import 'package:logging/logging.dart'; void main() async { - var app = Protevus(); + var app = Application(); app.logger = Logger('protevus') ..onRecord.listen((rec) { print(rec); @@ -35,10 +35,10 @@ void main() async { st); } - var http1 = ProtevusHttp(app); - var http2 = ProtevusHttp2(app, ctx); + var http1 = PlatformHttp(app); + var http2 = PlatformHttp2(app, ctx); - // HTTP/1.x requests will fallback to `ProtevusHttp` + // HTTP/1.x requests will fallback to `PlatformHttp` http2.onHttp1.listen(http1.handleRequest); var server = await http2.startServer('127.0.0.1', 3000); diff --git a/packages/core/example/http2/main.dart b/packages/core/example/http2/main.dart index 5956f2d..395ac38 100644 --- a/packages/core/example/http2/main.dart +++ b/packages/core/example/http2/main.dart @@ -6,7 +6,7 @@ import 'package:logging/logging.dart'; import 'common.dart'; void main() async { - var app = Protevus() + var app = Application() ..encoders.addAll({ 'gzip': gzip.encoder, 'deflate': zlib.encoder, @@ -15,8 +15,8 @@ void main() async { app.get('/', (req, res) => 'Hello HTTP/2!!!'); - app.fallback((req, res) => - throw HttpException.notFound(message: 'No file exists at ${req.uri}')); + app.fallback((req, res) => throw PlatformHttpException.notFound( + message: 'No file exists at ${req.uri}')); var ctx = SecurityContext() ..useCertificateChain('dev.pem') @@ -32,10 +32,10 @@ void main() async { ); } - var http1 = ProtevusHttp(app); - var http2 = ProtevusHttp2(app, ctx); + var http1 = PlatformHttp(app); + var http2 = PlatformHttp2(app, ctx); - // HTTP/1.x requests will fallback to `ProtevusHttp` + // HTTP/1.x requests will fallback to `PlatformHttp` http2.onHttp1.listen(http1.handleRequest); await http2.startServer('127.0.0.1', 3000); diff --git a/packages/core/example/http2/server_push.dart b/packages/core/example/http2/server_push.dart index b142863..f3d16c6 100644 --- a/packages/core/example/http2/server_push.dart +++ b/packages/core/example/http2/server_push.dart @@ -6,7 +6,7 @@ import 'package:file/local.dart'; import 'package:logging/logging.dart'; void main() async { - var app = Protevus(); + var app = Application(); app.logger = Logger('protevus') ..onRecord.listen((rec) { print(rec); @@ -51,10 +51,10 @@ void main() async { st); } - var http1 = ProtevusHttp(app); - var http2 = ProtevusHttp2(app, ctx); + var http1 = PlatformHttp(app); + var http2 = PlatformHttp2(app, ctx); - // HTTP/1.x requests will fallback to `ProtevusHttp` + // HTTP/1.x requests will fallback to `PlatformHttp` http2.onHttp1.listen(http1.handleRequest); var server = await http2.startServer('127.0.0.1', 3000); diff --git a/packages/core/example/json.dart b/packages/core/example/json.dart index 5e1b97b..679c057 100644 --- a/packages/core/example/json.dart +++ b/packages/core/example/json.dart @@ -31,9 +31,9 @@ void main() async { } void serverMain(_) async { - var app = Protevus(); + var app = Application(); var http = - ProtevusHttp.custom(app, startShared, useZone: false); // Run a cluster + PlatformHttp.custom(app, startShared, useZone: false); // Run a cluster app.get('/', (req, res) { return res.serialize({ diff --git a/packages/core/example/main.dart b/packages/core/example/main.dart index 35e5515..e8cf5a3 100644 --- a/packages/core/example/main.dart +++ b/packages/core/example/main.dart @@ -8,7 +8,7 @@ void main() async { //Logger.root.onRecord.listen(prettyLog); // Create our server. - var app = Protevus( + var app = Application( logger: Logger('protevus'), reflector: MirrorsReflector(), ); @@ -41,12 +41,12 @@ void main() async { // Simple fallback to throw a 404 on unknown paths. app.fallback((req, res) { - throw HttpException.notFound( + throw PlatformHttpException.notFound( message: 'Unknown path: "${req.uri!.path}"', ); }); - var http = ProtevusHttp(app); + var http = PlatformHttp(app); var server = await http.startServer('127.0.0.1', 3000); var url = 'http://${server.address.address}:${server.port}'; print('Listening at $url'); diff --git a/packages/core/example/map_service.dart b/packages/core/example/map_service.dart index 548ab1d..f9aa9b1 100644 --- a/packages/core/example/map_service.dart +++ b/packages/core/example/map_service.dart @@ -8,7 +8,7 @@ void main() async { Logger.root.onRecord.listen(print); // Create our server. - var app = Protevus( + var app = Application( logger: Logger('protevus'), reflector: MirrorsReflector(), ); @@ -16,7 +16,7 @@ void main() async { // Create a RESTful service that manages an in-memory collection. app.use('/api/todos', MapService()); - var http = ProtevusHttp(app); + var http = PlatformHttp(app); await http.startServer('127.0.0.1', 0); print('Listening at ${http.uri}'); } diff --git a/packages/core/example/status.dart b/packages/core/example/status.dart index 6435f46..3f8ac38 100644 --- a/packages/core/example/status.dart +++ b/packages/core/example/status.dart @@ -2,8 +2,8 @@ import 'package:platform_core/core.dart'; import 'package:platform_core/http.dart'; void main() async { - var app = Protevus(); - var http = ProtevusHttp(app); + var app = Application(); + var http = PlatformHttp(app); app.fallback((req, res) { res.statusCode = 304; diff --git a/packages/core/example/view.dart b/packages/core/example/view.dart index 0134824..4893053 100644 --- a/packages/core/example/view.dart +++ b/packages/core/example/view.dart @@ -3,7 +3,7 @@ import 'package:platform_core/core.dart'; import 'package:platform_core/http.dart'; void main() async { - var app = Protevus(reflector: MirrorsReflector()); + var app = Application(reflector: MirrorsReflector()); app.viewGenerator = (name, [data]) async => 'View generator invoked with name $name and data: $data'; @@ -11,7 +11,7 @@ void main() async { // Index route. Returns JSON. app.get('/', (req, res) => res.render('index', {'foo': 'bar'})); - var http = ProtevusHttp(app); + var http = PlatformHttp(app); var server = await http.startServer('127.0.0.1', 3000); var url = 'http://${server.address.address}:${server.port}'; print('Listening at $url'); diff --git a/packages/core/lib/src/core/controller.dart b/packages/core/lib/src/core/controller.dart index 68d2d2b..3625164 100644 --- a/packages/core/lib/src/core/controller.dart +++ b/packages/core/lib/src/core/controller.dart @@ -9,10 +9,10 @@ import '../core/core.dart'; /// Supports grouping routes with shared functionality. class Controller { - Protevus? _app; + Application? _app; - /// The [Protevus] application powering this controller. - Protevus get app { + /// The [Application] application powering this controller. + Application get app { if (_app == null) { throw ArgumentError("Protevus is not instantiated."); } @@ -38,7 +38,7 @@ class Controller { /// Applies routes, DI, and other configuration to an [app]. @mustCallSuper - Future configureServer(Protevus app) async { + Future configureServer(Application app) async { _app = app; if (injectSingleton != false) { diff --git a/packages/core/lib/src/core/driver.dart b/packages/core/lib/src/core/driver.dart index 414e14b..3e17d55 100644 --- a/packages/core/lib/src/core/driver.dart +++ b/packages/core/lib/src/core/driver.dart @@ -10,14 +10,14 @@ import 'core.dart'; /// Base driver class for Protevus implementations. /// -/// Powers both ProtevusHttp and ProtevusHttp2. +/// Powers both PlatformHttp and PlatformHttp2. abstract class Driver< Request, Response, Server extends Stream, RequestContextType extends RequestContext, ResponseContextType extends ResponseContext> { - final Protevus app; + final Application app; final bool useZone; bool _closed = false; @@ -170,22 +170,23 @@ abstract class Driver< return f.catchError((e, StackTrace st) { if (e is FormatException) { - throw HttpException.badRequest(message: e.message) + throw PlatformHttpException.badRequest(message: e.message) ..stackTrace = st; } - throw HttpException( + throw PlatformHttpException( stackTrace: st, - statusCode: (e is HttpException) ? e.statusCode : 500, + statusCode: (e is PlatformHttpException) ? e.statusCode : 500, message: e?.toString() ?? '500 Internal Server Error'); - }, test: (e) => e is HttpException).catchError((ee, StackTrace st) { + }, test: (e) => e is PlatformHttpException).catchError( + (ee, StackTrace st) { //print(">>>> Framework error: $ee"); //var t = (st).runtimeType; //print(">>>> StackTrace: $t"); - HttpException e; - if (ee is HttpException) { + PlatformHttpException e; + if (ee is PlatformHttpException) { e = ee; } else { - e = HttpException( + e = PlatformHttpException( stackTrace: st, statusCode: 500, message: ee?.toString() ?? '500 Internal Server Error'); @@ -207,14 +208,14 @@ abstract class Driver< // TODO: To be revisited Future(() { - HttpException e; + PlatformHttpException e; if (error is FormatException) { - e = HttpException.badRequest(message: error.message); - } else if (error is HttpException) { + e = PlatformHttpException.badRequest(message: error.message); + } else if (error is PlatformHttpException) { e = error; } else { - e = HttpException( + e = PlatformHttpException( stackTrace: stackTrace, message: error.toString()); } @@ -251,9 +252,9 @@ abstract class Driver< }); } - /// Handles an [HttpException]. + /// Handles an [PlatformHttpException]. Future handleHttpException( - HttpException e, + PlatformHttpException e, StackTrace st, RequestContext? req, ResponseContext? res, @@ -383,7 +384,7 @@ abstract class Driver< MiddlewarePipelineIterator it, RequestContextType req, ResponseContextType res, - Protevus app) async { + Application app) async { var broken = false; while (it.moveNext()) { var current = it.current.handlers.iterator; diff --git a/packages/core/lib/src/core/hooked_service.dart b/packages/core/lib/src/core/hooked_service.dart index dd79e7e..0cf31f3 100644 --- a/packages/core/lib/src/core/hooked_service.dart +++ b/packages/core/lib/src/core/hooked_service.dart @@ -98,7 +98,7 @@ class HookedService> } /// Adds hooks to this instance. - void addHooks(Protevus app) { + void addHooks(Application app) { var hooks = getAnnotation(inner, app.container.reflector); var before = >[]; var after = >[]; diff --git a/packages/core/lib/src/core/hostname_router.dart b/packages/core/lib/src/core/hostname_router.dart index b336808..9b7e121 100644 --- a/packages/core/lib/src/core/hostname_router.dart +++ b/packages/core/lib/src/core/hostname_router.dart @@ -24,13 +24,13 @@ import 'server.dart'; /// * `example.*` -> `/example\./[^$]*` /// * `example.+` -> `/example\./[^$]+` class HostnameRouter { - final Map _apps = {}; - final Map Function()> _creators = {}; + final Map _apps = {}; + final Map Function()> _creators = {}; final List _patterns = []; HostnameRouter( - {Map apps = const {}, - Map Function()> creators = const {}}) { + {Map apps = const {}, + Map Function()> creators = const {}}) { Map parseMap(Map map) { return map.map((p, c) { Pattern pp; @@ -55,7 +55,7 @@ class HostnameRouter { } factory HostnameRouter.configure( - Map Function(Protevus)> configurers, + Map Function(Application)> configurers, {Reflector reflector = const EmptyReflector(), ProtevusEnvironment environment = protevusEnv, Logger? logger, @@ -64,7 +64,7 @@ class HostnameRouter { ViewGenerator? viewGenerator}) { var creators = configurers.map((p, c) { return MapEntry(p, () async { - var app = Protevus( + var app = Application( reflector: reflector, environment: environment, logger: logger, diff --git a/packages/core/lib/src/core/map_service.dart b/packages/core/lib/src/core/map_service.dart index fbb4b32..417af78 100644 --- a/packages/core/lib/src/core/map_service.dart +++ b/packages/core/lib/src/core/map_service.dart @@ -72,7 +72,7 @@ class MapService extends Service> { Future> read(String? id, [Map? params]) { return Future.value(items.firstWhere(_matchesId(id), - orElse: (() => throw HttpException.notFound( + orElse: (() => throw PlatformHttpException.notFound( message: 'No record found for ID $id')))); } @@ -127,7 +127,8 @@ class MapService extends Service> { return read(id).then((old) { if (!items.remove(old)) { - throw HttpException.notFound(message: 'No record found for ID $id'); + throw PlatformHttpException.notFound( + message: 'No record found for ID $id'); } var result = Map.from(data); @@ -151,7 +152,7 @@ class MapService extends Service> { // Remove everything... if (!(allowRemoveAll == true || params?.containsKey('provider') != true)) { - throw HttpException.forbidden( + throw PlatformHttpException.forbidden( message: 'Clients are not allowed to delete all items.'); } else { items.clear(); @@ -163,7 +164,8 @@ class MapService extends Service> { if (items.remove(result)) { return result; } else { - throw HttpException.notFound(message: 'No record found for ID $id'); + throw PlatformHttpException.notFound( + message: 'No record found for ID $id'); } }); } diff --git a/packages/core/lib/src/core/metadata.dart b/packages/core/lib/src/core/metadata.dart index e04a044..90fd360 100644 --- a/packages/core/lib/src/core/metadata.dart +++ b/packages/core/lib/src/core/metadata.dart @@ -103,15 +103,15 @@ class Parameter { /// Returns an error that can be thrown when the parameter is not present. Object? get error { if (cookie?.isNotEmpty == true) { - return HttpException.badRequest( + return PlatformHttpException.badRequest( message: 'Missing required cookie "$cookie".'); } if (header?.isNotEmpty == true) { - return HttpException.badRequest( + return PlatformHttpException.badRequest( message: 'Missing required header "$header".'); } if (query?.isNotEmpty == true) { - return HttpException.badRequest( + return PlatformHttpException.badRequest( message: 'Missing required query parameter "$query".'); } if (session?.isNotEmpty == true) { diff --git a/packages/core/lib/src/core/request_context.dart b/packages/core/lib/src/core/request_context.dart index 4bd0fa3..5bc3603 100644 --- a/packages/core/lib/src/core/request_context.dart +++ b/packages/core/lib/src/core/request_context.dart @@ -18,13 +18,13 @@ import 'package:logging/logging.dart'; import 'metadata.dart'; import 'response_context.dart'; import 'routable.dart'; -import 'server.dart' show Protevus; +import 'server.dart' show Application; part 'injection.dart'; /// A convenience wrapper around an incoming [RawRequest]. abstract class RequestContext { - /// Similar to [Protevus.shutdownHooks], allows for logic to be executed + /// Similar to [Application.shutdownHooks], allows for logic to be executed /// when a [RequestContext] is done being processed. final _log = Logger('RequestContext'); @@ -46,8 +46,8 @@ abstract class RequestContext { /// Additional params to be passed to services. final Map serviceParams = {}; - /// The [Protevus] instance that is responding to this request. - Protevus? app; + /// The [Application] instance that is responding to this request. + Application? app; /// Any cookies sent with this request. List get cookies => []; diff --git a/packages/core/lib/src/core/response_context.dart b/packages/core/lib/src/core/response_context.dart index e1e096a..0ab77b6 100644 --- a/packages/core/lib/src/core/response_context.dart +++ b/packages/core/lib/src/core/response_context.dart @@ -13,7 +13,7 @@ import 'package:mime/mime.dart'; import 'controller.dart'; import 'request_context.dart'; -import 'server.dart' show Protevus; +import 'server.dart' show Application; final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)'); @@ -29,8 +29,8 @@ abstract class ResponseContext Completer? _done; int _statusCode = 200; - /// The [Protevus] instance that is sending a response. - Protevus? app; + /// The [Application] instance that is sending a response. + Application? app; /// Is `Transfer-Encoding` chunked? bool? chunked; diff --git a/packages/core/lib/src/core/server.dart b/packages/core/lib/src/core/server.dart index 32dba66..27b0c0d 100644 --- a/packages/core/lib/src/core/server.dart +++ b/packages/core/lib/src/core/server.dart @@ -21,8 +21,8 @@ import 'service.dart'; //final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)'); -/// A function that configures an [Protevus] server. -typedef Configurer = FutureOr Function(Protevus app); +/// A function that configures an [Application] server. +typedef PlatformConfigurer = FutureOr Function(Application app); /// A function that asynchronously generates a view from the given path and data. typedef ViewGenerator = FutureOr Function(String path, @@ -30,11 +30,11 @@ typedef ViewGenerator = FutureOr Function(String path, /// A function that handles error typedef PlatformErrorHandler = dynamic Function( - HttpException e, RequestContext req, ResponseContext res); + PlatformHttpException e, RequestContext req, ResponseContext res); -/// The default error handler for [Protevus] server +/// The default error handler for [Application] server Future _defaultErrorHandler( - HttpException e, RequestContext req, ResponseContext res) async { + PlatformHttpException e, RequestContext req, ResponseContext res) async { if (!req.accepts('text/html', strict: true) && (req.accepts('application/json') || req.accepts('application/javascript'))) { @@ -65,7 +65,7 @@ Logger _defaultLogger() { if (rec.error != null) { var err = rec.error; - if (err is HttpException && err.statusCode != 500) return; + if (err is PlatformHttpException && err.statusCode != 500) return; print('${rec.message} \n'); print(rec.error); if (rec.stackTrace != null) { @@ -78,18 +78,18 @@ Logger _defaultLogger() { } /// A powerful real-time/REST/MVC server class. -class Protevus extends Routable { +class Application extends Routable { static Future _noViewEngineConfigured(String view, [Map? data]) => Future.value('No view engine has been configured yet.'); - final List _children = []; + final List _children = []; final Map< String, Tuple4, ParseResult, MiddlewarePipeline>> handlerCache = HashMap(); Router? _flattened; - Protevus? _parent; + Application? _parent; /// A global Map of converters that can transform responses bodies. final Map, List>> encoders = {}; @@ -114,7 +114,7 @@ class Protevus extends Routable { bool allowMethodOverrides = true; /// All child application mounted on this instance. - List get children => List.unmodifiable(_children); + List get children => List.unmodifiable(_children); final Map _controllers = {}; @@ -127,7 +127,7 @@ class Protevus extends Routable { final ProtevusEnvironment environment; /// Returns the parent instance of this application, if any. - Protevus? get parent => _parent; + Application? get parent => _parent; /// Outputs diagnostics and debug messages. Logger _logger = _defaultLogger(); @@ -145,12 +145,12 @@ class Protevus extends Routable { /// Plug-ins to be called right before server startup. /// /// If the server is never started, they will never be called. - final List startupHooks = []; + final List startupHooks = []; /// Plug-ins to be called right before server shutdown. /// /// If the server is never [close]d, they will never be called. - final List shutdownHooks = []; + final List shutdownHooks = []; /// Always run before responses are sent. /// @@ -162,7 +162,7 @@ class Protevus extends Routable { /// Called by [ResponseContext]@`render`. ViewGenerator? viewGenerator = _noViewEngineConfigured; - /// The handler currently configured to run on [HttpException]s. + /// The handler currently configured to run on [PlatformHttpException]s. PlatformErrorHandler errorHandler = _defaultErrorHandler; @override @@ -189,7 +189,7 @@ class Protevus extends Routable { 'This route will be ignored, and no requests will ever reach it.'); } - if (router is Protevus) { + if (router is Application) { router._parent = this; _children.add(router); } @@ -199,11 +199,11 @@ class Protevus extends Routable { /// Loads some base dependencies into the service container. void bootstrapContainer() { - if (runtimeType != Protevus) { + if (runtimeType != Application) { container.registerSingleton(this); } - container.registerSingleton(this); + container.registerSingleton(this); container.registerSingleton(this); container.registerSingleton(this); } @@ -358,8 +358,8 @@ class Protevus extends Routable { // return closureMirror.apply(args).reflectee; } - /// Applies an [Configurer] to this instance. - Future configure(Configurer configurer) { + /// Applies an [PlatformConfigurer] to this instance. + Future configure(PlatformConfigurer configurer) { return Future.sync(() => configurer(this)); } @@ -396,7 +396,7 @@ class Protevus extends Routable { 'For more, see the documentation:\n' 'https://docs.angel-dart.dev/guides/dependency-injection#enabling-dart-mirrors-or-other-reflection'; - Protevus( + Application( {Reflector reflector = const ThrowingReflector(errorMessage: _reflectionErrorMessage), this.environment = protevusEnv, diff --git a/packages/core/lib/src/core/service.dart b/packages/core/lib/src/core/service.dart index 35512bf..5259a40 100644 --- a/packages/core/lib/src/core/service.dart +++ b/packages/core/lib/src/core/service.dart @@ -67,17 +67,17 @@ class Service extends Routable { /// Handlers that must run to ensure this service's functionality. List get bootstrappers => []; - /// The [Protevus] app powering this service. - Protevus? _app; + /// The [Application] app powering this service. + Application? _app; - Protevus get app { + Application get app { if (_app == null) { throw ArgumentError("Protevus is not initialized"); } return _app!; } - set app(Protevus protevus) { + set app(Application protevus) { _app = protevus; } @@ -94,7 +94,7 @@ class Service extends Routable { _readData ??= (req, res) { if (req.bodyAsObject is! Data) { - throw HttpException.badRequest( + throw PlatformHttpException.badRequest( message: 'Invalid request body. Expected $Data; found ${req.bodyAsObject} instead.'); } else { @@ -123,7 +123,7 @@ class Service extends Routable { String errorMessage = 'No record was found matching the given query.']) { return index(params).then((result) { if (result.isEmpty) { - throw HttpException.notFound(message: errorMessage); + throw PlatformHttpException.notFound(message: errorMessage); } else { return result.first; } @@ -132,12 +132,12 @@ class Service extends Routable { /// Retrieves all resources. Future> index([Map? params]) { - throw HttpException.methodNotAllowed(); + throw PlatformHttpException.methodNotAllowed(); } /// Retrieves the desired resource. Future read(Id id, [Map? params]) { - throw HttpException.methodNotAllowed(); + throw PlatformHttpException.methodNotAllowed(); } /// Reads multiple resources at once. @@ -150,22 +150,22 @@ class Service extends Routable { /// Creates a resource. Future create(Data data, [Map? params]) { - throw HttpException.methodNotAllowed(); + throw PlatformHttpException.methodNotAllowed(); } /// Modifies a resource. Future modify(Id id, Data data, [Map? params]) { - throw HttpException.methodNotAllowed(); + throw PlatformHttpException.methodNotAllowed(); } /// Overwrites a resource. Future update(Id id, Data data, [Map? params]) { - throw HttpException.methodNotAllowed(); + throw PlatformHttpException.methodNotAllowed(); } /// Removes the given resource. Future remove(Id id, [Map? params]) { - throw HttpException.methodNotAllowed(); + throw PlatformHttpException.methodNotAllowed(); } /// Creates an [AnonymousService] that wraps over this one, and maps input and output @@ -371,8 +371,8 @@ class Service extends Routable { ]); // REST compliance - put('/', (req, res) => throw HttpException.notFound()); - patch('/', (req, res) => throw HttpException.notFound()); + put('/', (req, res) => throw PlatformHttpException.notFound()); + patch('/', (req, res) => throw PlatformHttpException.notFound()); } /// Invoked when this service is wrapped within a [HookedService]. diff --git a/packages/core/lib/src/http/http.dart b/packages/core/lib/src/http/http.dart index a764146..27e7f73 100644 --- a/packages/core/lib/src/http/http.dart +++ b/packages/core/lib/src/http/http.dart @@ -1,5 +1,5 @@ /// Various libraries useful for creating highly-extensible servers. -library angel_framework.http; +library platform_core.http; import 'dart:async'; import 'dart:io'; diff --git a/packages/core/lib/src/http/http_request_context.dart b/packages/core/lib/src/http/http_request_context.dart index 855318c..bbc0cb5 100644 --- a/packages/core/lib/src/http/http_request_context.dart +++ b/packages/core/lib/src/http/http_request_context.dart @@ -77,7 +77,7 @@ class HttpRequestContext extends RequestContext { /// Magically transforms an [HttpRequest] into a [RequestContext]. static Future from( - HttpRequest request, Protevus app, String path) { + HttpRequest request, Application app, String path) { var ctx = HttpRequestContext().._container = app.container.createChild(); var override = request.method; diff --git a/packages/core/lib/src/http/http_response_context.dart b/packages/core/lib/src/http/http_response_context.dart index c15bda5..ed3d06b 100644 --- a/packages/core/lib/src/http/http_response_context.dart +++ b/packages/core/lib/src/http/http_response_context.dart @@ -18,7 +18,7 @@ class HttpResponseContext extends ResponseContext { final HttpRequestContext? _correspondingRequest; bool _isDetached = false, _isClosed = false, _streamInitialized = false; - HttpResponseContext(this.rawResponse, Protevus? app, + HttpResponseContext(this.rawResponse, Application? app, [this._correspondingRequest]) { this.app = app; } diff --git a/packages/core/lib/src/http/protevus_http.dart b/packages/core/lib/src/http/protevus_http.dart index 81d67e2..bcc9bc5 100644 --- a/packages/core/lib/src/http/protevus_http.dart +++ b/packages/core/lib/src/http/protevus_http.dart @@ -17,7 +17,7 @@ final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)'); typedef ServerGeneratorType = Future Function(dynamic, int); /// Adapts `dart:io`'s [HttpServer] to serve Protevus. -class ProtevusHttp extends Driver { @override Uri get uri { @@ -25,23 +25,24 @@ class ProtevusHttp extends Driver headers = const {}}) { - return ProtevusHttp._(app, serverGenerator, useZone); + return PlatformHttp._(app, serverGenerator, useZone); } - factory ProtevusHttp.fromSecurityContext( - Protevus app, SecurityContext context, + factory PlatformHttp.fromSecurityContext( + Application app, SecurityContext context, {bool useZone = true}) { - return ProtevusHttp._(app, (address, int port) { + return PlatformHttp._(app, (address, int port) { return HttpServer.bindSecure(address, port, context); }, useZone); } @@ -51,8 +52,8 @@ class ProtevusHttp extends Driver { static Future from( ServerTransportStream stream, Socket socket, - Protevus app, + Application app, Map sessions, Uuid uuid) { var c = Completer(); diff --git a/packages/core/lib/src/http2/http2_response_context.dart b/packages/core/lib/src/http2/http2_response_context.dart index 569f10a..7e164c6 100644 --- a/packages/core/lib/src/http2/http2_response_context.dart +++ b/packages/core/lib/src/http2/http2_response_context.dart @@ -23,7 +23,7 @@ class Http2ResponseContext extends ResponseContext { Uri? _targetUri; - Http2ResponseContext(Protevus? app, this.stream, this._req) { + Http2ResponseContext(Application? app, this.stream, this._req) { this.app = app; _targetUri = _req?.uri; } diff --git a/packages/core/lib/src/http2/protevus_http2.dart b/packages/core/lib/src/http2/protevus_http2.dart index 917a89d..7f1a1b7 100644 --- a/packages/core/lib/src/http2/protevus_http2.dart +++ b/packages/core/lib/src/http2/protevus_http2.dart @@ -16,10 +16,10 @@ Future startSharedHttp2( } /// Adapts `package:http2`'s [ServerTransportConnection] to serve Protevus. -class ProtevusHttp2 extends Driver { final ServerSettings? settings; - late ProtevusHttp _http; + late PlatformHttp _http; final StreamController _onHttp1 = StreamController(); final Map _sessions = {}; final Uuid _uuid = Uuid(); @@ -27,8 +27,8 @@ class ProtevusHttp2 extends Driver _artificial; - ProtevusHttp2._( - Protevus app, + PlatformHttp2._( + Application app, Future Function(dynamic, int) serverGenerator, bool useZone, bool allowHttp1, @@ -39,21 +39,21 @@ class ProtevusHttp2 extends Driver Function( InternetAddress? address, int port, SecurityContext ctx) @@ -61,7 +61,7 @@ class ProtevusHttp2 extends Driver implements ServerSocket { class _ProtevusHttp2ServerSocket extends Stream implements SecureServerSocket { final SecureServerSocket socket; - final ProtevusHttp2 driver; + final PlatformHttp2 driver; final _ctrl = StreamController(); late _FakeServerSocket _fake; StreamSubscription? _sub; @@ -206,7 +206,7 @@ class _ProtevusHttp2ServerSocket extends Stream } else { socket.destroy(); throw Exception( - 'ProtevusHttp2 does not support ${socket.selectedProtocol} as an ALPN protocol.'); + 'PlatformHttp2 does not support ${socket.selectedProtocol} as an ALPN protocol.'); } }, onDone: _ctrl.close, diff --git a/packages/core/performance/hello/main.dart b/packages/core/performance/hello/main.dart index be581b1..d8d83ef 100644 --- a/packages/core/performance/hello/main.dart +++ b/packages/core/performance/hello/main.dart @@ -5,8 +5,8 @@ import 'package:platform_core/core.dart'; import 'package:platform_core/http.dart'; void main() async { - var app = Protevus(); - var http = ProtevusHttp.custom(app, startShared, useZone: false); + var app = Application(); + var http = PlatformHttp.custom(app, startShared, useZone: false); app.get('/', (req, res) => res.write('Hello, world!')); app.optimizeForProduction(force: true); diff --git a/packages/core/test/accepts_test.dart b/packages/core/test/accepts_test.dart index 6558ab1..40bb45a 100644 --- a/packages/core/test/accepts_test.dart +++ b/packages/core/test/accepts_test.dart @@ -64,7 +64,7 @@ Future acceptContentTypes( var rq = MockHttpRequest('GET', endpoint, persistentConnection: false); rq.headers.set('accept', headerString); rq.close(); - var app = Protevus(reflector: MirrorsReflector()); - var http = ProtevusHttp(app); + var app = Application(reflector: MirrorsReflector()); + var http = PlatformHttp(app); return http.createRequestContext(rq, rq.response); } diff --git a/packages/core/test/anonymous_service_test.dart b/packages/core/test/anonymous_service_test.dart index f0ebdc2..9785c1a 100644 --- a/packages/core/test/anonymous_service_test.dart +++ b/packages/core/test/anonymous_service_test.dart @@ -23,21 +23,21 @@ void main() { var svc = AnonymousService(); await svc.read(1); throw 'Should have thrown 405!'; - } on HttpException { + } on PlatformHttpException { // print('Ok!'); } try { var svc = AnonymousService(); await svc.modify(2, null); throw 'Should have thrown 405!'; - } on HttpException { + } on PlatformHttpException { // print('Ok!'); } try { var svc = AnonymousService(); await svc.update(3, null); throw 'Should have thrown 405!'; - } on HttpException { + } on PlatformHttpException { // print('Ok!'); } }); diff --git a/packages/core/test/body_test.dart b/packages/core/test/body_test.dart index 8847dc6..386dc5e 100644 --- a/packages/core/test/body_test.dart +++ b/packages/core/test/body_test.dart @@ -7,8 +7,8 @@ import 'package:platform_mocking/mocking.dart'; import 'package:test/test.dart'; void main() { - var app = Protevus(); - var http = ProtevusHttp(app); + var app = Application(); + var http = PlatformHttp(app); Future request( {bool asJson = true, diff --git a/packages/core/test/controller_test.dart b/packages/core/test/controller_test.dart index eb1ab2c..7f2dcc7 100644 --- a/packages/core/test/controller_test.dart +++ b/packages/core/test/controller_test.dart @@ -70,7 +70,7 @@ bool bar(RequestContext req, ResponseContext res) { } void main() { - late Protevus app; + late Application app; late TodoController todoController; late NoExposeController noExposeCtrl; late HttpServer server; @@ -78,7 +78,7 @@ void main() { String? url; setUp(() async { - app = Protevus(reflector: MirrorsReflector()); + app = Application(reflector: MirrorsReflector()); app.get( '/redirect', (req, res) async => @@ -104,7 +104,7 @@ void main() { print(app.controllers); app.dumpTree(); - server = await ProtevusHttp(app).startServer(); + server = await PlatformHttp(app).startServer(); url = 'http://${server.address.address}:${server.port}'; }); @@ -118,20 +118,20 @@ void main() { }); test('create dynamic handler', () async { - var app = Protevus(reflector: MirrorsReflector()); + var app = Application(reflector: MirrorsReflector()); app.get( '/foo', ioc(({String? bar}) { return 2; }, optional: ['bar'])); var rq = MockHttpRequest('GET', Uri(path: 'foo')); - await ProtevusHttp(app).handleRequest(rq); + await PlatformHttp(app).handleRequest(rq); var body = await utf8.decoder.bind(rq.response).join(); expect(json.decode(body), 2); }); test('optional name', () async { - var app = Protevus(reflector: MirrorsReflector()); + var app = Application(reflector: MirrorsReflector()); await app.configure(NamedController().configureServer); expect(app.controllers['foo'], const IsInstanceOf()); }); diff --git a/packages/core/test/detach_test.dart b/packages/core/test/detach_test.dart index f042c44..af315b4 100644 --- a/packages/core/test/detach_test.dart +++ b/packages/core/test/detach_test.dart @@ -5,11 +5,11 @@ import 'package:platform_mocking/mocking.dart'; import 'package:test/test.dart'; void main() { - late ProtevusHttp http; + late PlatformHttp http; setUp(() async { - var app = Protevus(); - http = ProtevusHttp(app); + var app = Application(); + http = PlatformHttp(app); app.get('/detach', (req, res) async { if (res is HttpResponseContext) { diff --git a/packages/core/test/di_test.dart b/packages/core/test/di_test.dart index 3390e93..0695434 100644 --- a/packages/core/test/di_test.dart +++ b/packages/core/test/di_test.dart @@ -15,13 +15,13 @@ final String sampleText = 'make your bed'; final String sampleOver = 'never'; void main() { - late Protevus app; + late Application app; late http.Client client; late HttpServer server; String? url; setUp(() async { - app = Protevus(reflector: MirrorsReflector()); + app = Application(reflector: MirrorsReflector()); client = http.Client(); // Inject some todos @@ -41,7 +41,7 @@ void main() { await app.configure(SingletonController().configureServer); await app.configure(ErrandController().configureServer); - server = await ProtevusHttp(app).startServer(); + server = await PlatformHttp(app).startServer(); url = 'http://${server.address.host}:${server.port}'; }); @@ -52,7 +52,7 @@ void main() { }); test('runContained with custom container', () async { - var app = Protevus(); + var app = Application(); var c = Container(const MirrorsReflector()); c.registerSingleton(Todo(text: 'Hey!')); @@ -63,7 +63,7 @@ void main() { var rq = MockHttpRequest('GET', Uri(path: '/')); await rq.close(); var rs = rq.response; - await ProtevusHttp(app).handleRequest(rq); + await PlatformHttp(app).handleRequest(rq); var text = await rs.transform(utf8.decoder).join(); expect(text, json.encode('Hey!')); }); diff --git a/packages/core/test/encoders_buffer_test.dart b/packages/core/test/encoders_buffer_test.dart index 9a04d2c..14afaa8 100644 --- a/packages/core/test/encoders_buffer_test.dart +++ b/packages/core/test/encoders_buffer_test.dart @@ -17,10 +17,10 @@ Future> getBody(MockHttpResponse rs) async { } void main() { - late Protevus app; + late Application app; setUp(() { - app = Protevus(reflector: MirrorsReflector()); + app = Application(reflector: MirrorsReflector()); app.encoders.addAll( { 'deflate': zlib.encoder, @@ -40,14 +40,14 @@ void main() { encodingTests(() => app); } -void encodingTests(Protevus Function() getApp) { +void encodingTests(Application Function() getApp) { group('encoding', () { - Protevus app; - late ProtevusHttp http; + Application app; + late PlatformHttp http; setUp(() { app = getApp(); - http = ProtevusHttp(app); + http = PlatformHttp(app); }); test('sends plaintext if no accept-encoding', () async { diff --git a/packages/core/test/exception_test.dart b/packages/core/test/exception_test.dart index eed34d4..908541e 100644 --- a/packages/core/test/exception_test.dart +++ b/packages/core/test/exception_test.dart @@ -4,41 +4,46 @@ import 'package:test/test.dart'; void main() { test('named constructors', () { - expect(HttpException.badRequest(), isException(400, '400 Bad Request')); - expect(HttpException.notAuthenticated(), + expect(PlatformHttpException.badRequest(), + isException(400, '400 Bad Request')); + expect(PlatformHttpException.notAuthenticated(), isException(401, '401 Not Authenticated')); - expect(HttpException.paymentRequired(), + expect(PlatformHttpException.paymentRequired(), isException(402, '402 Payment Required')); - expect(HttpException.forbidden(), isException(403, '403 Forbidden')); - expect(HttpException.notFound(), isException(404, '404 Not Found')); - expect(HttpException.methodNotAllowed(), - isException(405, '405 Method Not Allowed')); expect( - HttpException.notAcceptable(), isException(406, '406 Not Acceptable')); - expect(HttpException.methodTimeout(), isException(408, '408 Timeout')); - expect(HttpException.conflict(), isException(409, '409 Conflict')); - expect(HttpException.notProcessable(), + PlatformHttpException.forbidden(), isException(403, '403 Forbidden')); + expect(PlatformHttpException.notFound(), isException(404, '404 Not Found')); + expect(PlatformHttpException.methodNotAllowed(), + isException(405, '405 Method Not Allowed')); + expect(PlatformHttpException.notAcceptable(), + isException(406, '406 Not Acceptable')); + expect( + PlatformHttpException.methodTimeout(), isException(408, '408 Timeout')); + expect(PlatformHttpException.conflict(), isException(409, '409 Conflict')); + expect(PlatformHttpException.notProcessable(), isException(422, '422 Not Processable')); - expect(HttpException.notImplemented(), + expect(PlatformHttpException.notImplemented(), isException(501, '501 Not Implemented')); - expect(HttpException.unavailable(), isException(503, '503 Unavailable')); + expect(PlatformHttpException.unavailable(), + isException(503, '503 Unavailable')); }); test('fromMap', () { - expect(HttpException.fromMap({'status_code': -1, 'message': 'ok'}), + expect(PlatformHttpException.fromMap({'status_code': -1, 'message': 'ok'}), isException(-1, 'ok')); }); test('toMap = toJson', () { - var exc = HttpException.badRequest(); + var exc = PlatformHttpException.badRequest(); expect(exc.toMap(), exc.toJson()); var json_ = json.encode(exc.toJson()); - var exc2 = HttpException.fromJson(json_); + var exc2 = PlatformHttpException.fromJson(json_); expect(exc2.toJson(), exc.toJson()); }); test('toString', () { - expect(HttpException(statusCode: 420, message: 'Blaze It').toString(), + expect( + PlatformHttpException(statusCode: 420, message: 'Blaze It').toString(), '420: Blaze It'); }); } @@ -58,7 +63,7 @@ class _IsException extends Matcher { @override bool matches(item, Map matchState) { - return item is HttpException && + return item is PlatformHttpException && item.statusCode == statusCode && item.message == message; } diff --git a/packages/core/test/extension_test.dart b/packages/core/test/extension_test.dart index d801341..d139766 100644 --- a/packages/core/test/extension_test.dart +++ b/packages/core/test/extension_test.dart @@ -26,7 +26,7 @@ void main() { Future makeRequest(String path) { var rq = MockHttpRequest('GET', endpoint.replace(path: path))..close(); - var app = Protevus(reflector: MirrorsReflector()); - var http = ProtevusHttp(app); + var app = Application(reflector: MirrorsReflector()); + var http = PlatformHttp(app); return http.createRequestContext(rq, rq.response); } diff --git a/packages/core/test/find_one_test.dart b/packages/core/test/find_one_test.dart index 9e6df4b..645660c 100644 --- a/packages/core/test/find_one_test.dart +++ b/packages/core/test/find_one_test.dart @@ -3,7 +3,8 @@ import 'package:test/test.dart'; import 'common.dart'; void main() { - var throwsAnHttpException = throwsA(const IsInstanceOf()); + var throwsAnHttpException = + throwsA(const IsInstanceOf()); /* test('throw 404 on null', () { diff --git a/packages/core/test/general_test.dart b/packages/core/test/general_test.dart index 4eeae1d..20b7fe9 100644 --- a/packages/core/test/general_test.dart +++ b/packages/core/test/general_test.dart @@ -7,18 +7,18 @@ import 'package:http/http.dart' as http; import 'package:test/test.dart'; void main() { - late Protevus app; + late Application app; late http.Client client; late HttpServer server; late String url; setUp(() async { - app = Protevus(reflector: MirrorsReflector()) + app = Application(reflector: MirrorsReflector()) ..post('/foo', (req, res) => res.serialize({'hello': 'world'})) - ..all('*', (req, res) => throw HttpException.notFound()); + ..all('*', (req, res) => throw PlatformHttpException.notFound()); client = http.Client(); - server = await ProtevusHttp(app).startServer(); + server = await PlatformHttp(app).startServer(); url = 'http://${server.address.host}:${server.port}'; }); diff --git a/packages/core/test/hooked_test.dart b/packages/core/test/hooked_test.dart index 8d6b65d..daa5030 100644 --- a/packages/core/test/hooked_test.dart +++ b/packages/core/test/hooked_test.dart @@ -13,14 +13,14 @@ void main() { 'Content-Type': 'application/json' }; - late Protevus app; + late Application app; late HttpServer server; late String url; late http.Client client; late HookedService todoService; setUp(() async { - app = Protevus(reflector: MirrorsReflector()); + app = Application(reflector: MirrorsReflector()); client = http.Client(); app.use('/todos', MapService()); app.use('/books', BookService()); @@ -36,7 +36,7 @@ void main() { throw e.error as Object; }; - server = await ProtevusHttp(app).startServer(); + server = await PlatformHttp(app).startServer(); url = 'http://${server.address.host}:${server.port}'; }); diff --git a/packages/core/test/http2/adapter_test.dart b/packages/core/test/http2/adapter_test.dart index aaa859b..ad26840 100644 --- a/packages/core/test/http2/adapter_test.dart +++ b/packages/core/test/http2/adapter_test.dart @@ -25,12 +25,12 @@ Stream> jfkStream() { void main() { var client = Http2Client(); late IOClient h1c; - Protevus app; - late ProtevusHttp2 http2; + Application app; + late PlatformHttp2 http2; late Uri serverRoot; setUp(() async { - app = Protevus(reflector: MirrorsReflector()) + app = Application(reflector: MirrorsReflector()) ..encoders['gzip'] = gzip.encoder; hierarchicalLoggingEnabled = true; app.logger = Logger.detached('protevus.http2') @@ -106,7 +106,7 @@ void main() { // Create an HTTP client that trusts our server. h1c = IOClient(HttpClient()..badCertificateCallback = (_, __, ___) => true); - http2 = ProtevusHttp2(app, ctx, allowHttp1: true); + http2 = PlatformHttp2(app, ctx, allowHttp1: true); var server = await http2.startServer(); serverRoot = Uri.parse('https://127.0.0.1:${server.port}'); diff --git a/packages/core/test/http_404_hole_test.dart b/packages/core/test/http_404_hole_test.dart index 9d45cf7..433fae6 100644 --- a/packages/core/test/http_404_hole_test.dart +++ b/packages/core/test/http_404_hole_test.dart @@ -9,7 +9,7 @@ import 'pretty_log.dart'; void main() { late http.IOClient client; - late ProtevusHttp driver; + late PlatformHttp driver; late Logger logger; setUp(() async { @@ -20,7 +20,7 @@ void main() { ..level = Level.ALL ..onRecord.listen(prettyLog); - var app = Protevus(logger: logger); + var app = Application(logger: logger); app.fallback(hello); app.fallback(throw404); @@ -40,7 +40,7 @@ void main() { } }; - driver = ProtevusHttp(app); + driver = PlatformHttp(app); await driver.startServer(); }); @@ -76,5 +76,5 @@ Future hello(RequestContext req, ResponseContext res) { void throw404(RequestContext req, ResponseContext res) { Zone.current .handleUncaughtError('This 404 should not occur.', StackTrace.current); - throw HttpException.notFound(); + throw PlatformHttpException.notFound(); } diff --git a/packages/core/test/jsonp_test.dart b/packages/core/test/jsonp_test.dart index f535268..47ac418 100644 --- a/packages/core/test/jsonp_test.dart +++ b/packages/core/test/jsonp_test.dart @@ -7,8 +7,8 @@ import 'package:platform_mocking/mocking.dart'; import 'package:test/test.dart'; void main() { - var app = Protevus(); - var http = ProtevusHttp(app); + var app = Application(); + var http = PlatformHttp(app); app.get('/default', (req, res) => res.jsonp({'foo': 'bar'})); diff --git a/packages/core/test/parameter_meta_test.dart b/packages/core/test/parameter_meta_test.dart index 134a064..dd50d2f 100644 --- a/packages/core/test/parameter_meta_test.dart +++ b/packages/core/test/parameter_meta_test.dart @@ -24,12 +24,12 @@ void main() { } void parameterMetaTests() { - Protevus app; - late ProtevusHttp http; + Application app; + late PlatformHttp http; setUp(() { - app = Protevus(reflector: MirrorsReflector()); - http = ProtevusHttp(app); + app = Application(reflector: MirrorsReflector()); + http = PlatformHttp(app); app.get('/cookie', ioc((@CookieValue('token') String jwt) { return jwt; diff --git a/packages/core/test/precontained_test.dart b/packages/core/test/precontained_test.dart index 01a1a3c..92eadad 100644 --- a/packages/core/test/precontained_test.dart +++ b/packages/core/test/precontained_test.dart @@ -9,7 +9,7 @@ import 'package:test/test.dart'; void main() { test('preinjects functions', () async { - var app = Protevus(reflector: MirrorsReflector()) + var app = Application(reflector: MirrorsReflector()) ..configuration['foo'] = 'bar' ..get('/foo', ioc(echoAppFoo)); app.optimizeForProduction(force: true); @@ -18,7 +18,7 @@ void main() { var rq = MockHttpRequest('GET', Uri(path: '/foo')); await rq.close(); - await ProtevusHttp(app).handleRequest(rq); + await PlatformHttp(app).handleRequest(rq); var rs = rq.response; var body = await rs.transform(utf8.decoder).join(); expect(body, json.encode('bar')); diff --git a/packages/core/test/primitives_test.dart b/packages/core/test/primitives_test.dart index 4c670d3..7968c28 100644 --- a/packages/core/test/primitives_test.dart +++ b/packages/core/test/primitives_test.dart @@ -9,13 +9,13 @@ import 'package:platform_mocking/mocking.dart'; import 'package:test/test.dart'; void main() { - late Protevus app; - late ProtevusHttp http; + late Application app; + late PlatformHttp http; setUp(() { - app = Protevus(reflector: MirrorsReflector()) + app = Application(reflector: MirrorsReflector()) ..configuration['global'] = 305; // Pitbull! - http = ProtevusHttp(app); + http = PlatformHttp(app); app.get('/string/:string', ioc((String string) => string)); diff --git a/packages/core/test/repeat_request_test.dart b/packages/core/test/repeat_request_test.dart index 886f0e1..ab0d994 100644 --- a/packages/core/test/repeat_request_test.dart +++ b/packages/core/test/repeat_request_test.dart @@ -13,10 +13,10 @@ void main() { } test('can request the same url twice', () async { - var app = Protevus(reflector: MirrorsReflector()) + var app = Application(reflector: MirrorsReflector()) ..get('/test/:id', ioc((id) => 'Hello $id')); var rq1 = mk(1), rq2 = mk(2), rq3 = mk(1); - await Future.wait([rq1, rq2, rq3].map(ProtevusHttp(app).handleRequest)); + await Future.wait([rq1, rq2, rq3].map(PlatformHttp(app).handleRequest)); var body1 = await rq1.response.transform(utf8.decoder).join(), body2 = await rq2.response.transform(utf8.decoder).join(), body3 = await rq3.response.transform(utf8.decoder).join(); diff --git a/packages/core/test/req_shutdown_test.dart b/packages/core/test/req_shutdown_test.dart index 3a26613..778e654 100644 --- a/packages/core/test/req_shutdown_test.dart +++ b/packages/core/test/req_shutdown_test.dart @@ -8,7 +8,7 @@ import 'pretty_log.dart'; void main() { late http.IOClient client; - late ProtevusHttp driver; + late PlatformHttp driver; late Logger logger; late StringBuffer buf; @@ -21,14 +21,14 @@ void main() { ..level = Level.ALL ..onRecord.listen(prettyLog); - var app = Protevus(logger: logger); + var app = Application(logger: logger); app.fallback((req, res) { req.shutdownHooks.add(() => buf.write('Hello, ')); req.shutdownHooks.add(() => buf.write('world!')); }); - driver = ProtevusHttp(app); + driver = PlatformHttp(app); await driver.startServer(); }); diff --git a/packages/core/test/response_header_test.dart b/packages/core/test/response_header_test.dart index 63c0b13..151b374 100644 --- a/packages/core/test/response_header_test.dart +++ b/packages/core/test/response_header_test.dart @@ -6,13 +6,13 @@ import 'package:platform_core/src/http/protevus_http.dart'; import 'package:test/test.dart'; void main() { - late Protevus app; - late ProtevusHttp http; + late Application app; + late PlatformHttp http; late HttpClient client; setUp(() async { - app = Protevus(reflector: MirrorsReflector()); - http = ProtevusHttp(app); + app = Application(reflector: MirrorsReflector()); + http = PlatformHttp(app); await http.startServer(); diff --git a/packages/core/test/routing_test.dart b/packages/core/test/routing_test.dart index e749d5e..dce777e 100644 --- a/packages/core/test/routing_test.dart +++ b/packages/core/test/routing_test.dart @@ -36,16 +36,16 @@ bool interceptService(RequestContext req, ResponseContext res) { } void main() { - late Protevus app; - late Protevus nested; - late Protevus todos; + late Application app; + late Application nested; + late Application todos; late String url; late http.Client client; setUp(() async { - app = Protevus(reflector: MirrorsReflector()); - nested = Protevus(reflector: MirrorsReflector()); - todos = Protevus(reflector: MirrorsReflector()); + app = Application(reflector: MirrorsReflector()); + nested = Application(reflector: MirrorsReflector()); + todos = Application(reflector: MirrorsReflector()); for (var app in [app, nested, todos]) { app.logger = Logger('routing_test') @@ -113,7 +113,7 @@ void main() { //app.dumpTree(header: "DUMPING ROUTES:", showMatchers: true); client = http.Client(); - var server = await ProtevusHttp(app).startServer('127.0.0.1', 0); + var server = await PlatformHttp(app).startServer('127.0.0.1', 0); url = 'http://${server.address.host}:${server.port}'; }); diff --git a/packages/core/test/serialize_test.dart b/packages/core/test/serialize_test.dart index 48a1f94..23a8e54 100644 --- a/packages/core/test/serialize_test.dart +++ b/packages/core/test/serialize_test.dart @@ -8,13 +8,13 @@ import 'package:http_parser/http_parser.dart'; import 'package:test/test.dart'; void main() { - late Protevus app; + late Application app; late http.Client client; late HttpServer server; late String url; setUp(() async { - app = Protevus(reflector: MirrorsReflector()) + app = Application(reflector: MirrorsReflector()) ..get('/foo', ioc(() => {'hello': 'world'})) ..get('/bar', (req, res) async { await res.serialize({'hello': 'world'}, @@ -22,7 +22,7 @@ void main() { }); client = http.Client(); - server = await ProtevusHttp(app).startServer(); + server = await PlatformHttp(app).startServer(); url = 'http://${server.address.host}:${server.port}'; }); diff --git a/packages/core/test/server_test.dart b/packages/core/test/server_test.dart index 69206b5..b01090b 100644 --- a/packages/core/test/server_test.dart +++ b/packages/core/test/server_test.dart @@ -14,9 +14,9 @@ final Uri $foo = Uri.parse('http://localhost:3000/foo'); /// Additional tests to improve coverage of server.dart void main() { group('scoping', () { - var parent = Protevus(reflector: MirrorsReflector()) + var parent = Application(reflector: MirrorsReflector()) ..configuration['two'] = 2; - var child = Protevus(reflector: MirrorsReflector()); + var child = Application(reflector: MirrorsReflector()); parent.mount('/child', child); test('sets children', () { @@ -33,20 +33,20 @@ void main() { }); test('custom server generator', () { - var app = Protevus(reflector: MirrorsReflector()); - var http = ProtevusHttp.custom(app, HttpServer.bind); + var app = Application(reflector: MirrorsReflector()); + var http = PlatformHttp.custom(app, HttpServer.bind); expect(http.serverGenerator, HttpServer.bind); }); test('default error handler', () async { - var app = Protevus(reflector: MirrorsReflector()); - var http = ProtevusHttp(app); + var app = Application(reflector: MirrorsReflector()); + var http = PlatformHttp(app); var rq = MockHttpRequest('GET', $foo); await (rq.close()); var rs = rq.response; var req = await http.createRequestContext(rq, rs); var res = await http.createResponseContext(rq, rs); - var e = HttpException( + var e = PlatformHttpException( statusCode: 321, message: 'Hello', errors: ['foo', 'bar']); await app.errorHandler(e, req, res); await http.sendResponse(rq, rs, req, res); @@ -62,10 +62,10 @@ void main() { }); test('plug-ins run on startup', () async { - var app = Protevus(reflector: MirrorsReflector()); + var app = Application(reflector: MirrorsReflector()); app.startupHooks.add((app) => app.configuration['two'] = 2); - var http = ProtevusHttp(app); + var http = PlatformHttp(app); await http.startServer(); expect(app.configuration['two'], 2); await app.close(); @@ -73,7 +73,7 @@ void main() { }); test('warning when adding routes to flattened router', () { - var app = Protevus(reflector: MirrorsReflector()) + var app = Application(reflector: MirrorsReflector()) ..optimizeForProduction(force: true); app.dumpTree(); app.get('/', (req, res) => 2); @@ -81,7 +81,7 @@ void main() { }); test('services close on close call', () async { - var app = Protevus(reflector: MirrorsReflector()); + var app = Application(reflector: MirrorsReflector()); var svc = CustomCloseService(); expect(svc.value, 2); app.use('/', svc); @@ -90,8 +90,9 @@ void main() { }); test('global injection added to injection map', () async { - var app = Protevus(reflector: MirrorsReflector())..configuration['a'] = 'b'; - var http = ProtevusHttp(app); + var app = Application(reflector: MirrorsReflector()) + ..configuration['a'] = 'b'; + var http = PlatformHttp(app); app.get('/', ioc((String a) => a)); var rq = MockHttpRequest('GET', Uri.parse('/')); await (rq.close()); @@ -101,8 +102,9 @@ void main() { }); test('global injected serializer', () async { - var app = Protevus(reflector: MirrorsReflector())..serializer = (_) => 'x'; - var http = ProtevusHttp(app); + var app = Application(reflector: MirrorsReflector()) + ..serializer = (_) => 'x'; + var http = PlatformHttp(app); app.get($foo.path, (req, ResponseContext res) => res.serialize(null)); var rq = MockHttpRequest('GET', $foo); await (rq.close()); @@ -112,9 +114,10 @@ void main() { }); group('handler results', () { - var app = Protevus(reflector: MirrorsReflector()); - var http = ProtevusHttp(app); - app.responseFinalizers.add((req, res) => throw HttpException.forbidden()); + var app = Application(reflector: MirrorsReflector()); + var http = PlatformHttp(app); + app.responseFinalizers + .add((req, res) => throw PlatformHttpException.forbidden()); late RequestContext req; late ResponseContext res; @@ -154,14 +157,14 @@ void main() { }); group('handleHttpException', () { - late Protevus app; - late ProtevusHttp http; + late Application app; + late PlatformHttp http; setUp(() async { - app = Protevus(reflector: MirrorsReflector()); - app.get('/wtf', (req, res) => throw HttpException.forbidden()); - app.get('/wtf2', (req, res) => throw HttpException.forbidden()); - http = ProtevusHttp(app); + app = Application(reflector: MirrorsReflector()); + app.get('/wtf', (req, res) => throw PlatformHttpException.forbidden()); + app.get('/wtf2', (req, res) => throw PlatformHttpException.forbidden()); + http = PlatformHttp(app); await http.startServer('127.0.0.1', 0); var oldHandler = app.errorHandler; diff --git a/packages/core/test/services_test.dart b/packages/core/test/services_test.dart index 64b0131..9fb276b 100644 --- a/packages/core/test/services_test.dart +++ b/packages/core/test/services_test.dart @@ -16,20 +16,20 @@ void main() { 'Accept': 'application/json', 'Content-Type': 'application/json' }; - late Protevus app; + late Application app; late MapService service; late String url; late http.Client client; setUp(() async { - app = Protevus(reflector: MirrorsReflector()) + app = Application(reflector: MirrorsReflector()) ..use('/todos', service = MapService()) ..errorHandler = (e, req, res) { if (e.error != null) print('Whoops: ${e.error}'); if (e.stackTrace != null) print(Chain.forTrace(e.stackTrace!).terse); }; - var server = await ProtevusHttp(app).startServer(); + var server = await PlatformHttp(app).startServer(); client = http.Client(); url = 'http://${server.address.host}:${server.port}'; }); diff --git a/packages/core/test/streaming_test.dart b/packages/core/test/streaming_test.dart index 808fb38..6d25457 100644 --- a/packages/core/test/streaming_test.dart +++ b/packages/core/test/streaming_test.dart @@ -13,12 +13,12 @@ import 'package:test/test.dart'; import 'encoders_buffer_test.dart' show encodingTests; void main() { - late Protevus app; - late ProtevusHttp http; + late Application app; + late PlatformHttp http; setUp(() { - app = Protevus(reflector: MirrorsReflector()); - http = ProtevusHttp(app, useZone: true); + app = Application(reflector: MirrorsReflector()); + http = PlatformHttp(app, useZone: true); app.logger = Logger('streaming_test') ..onRecord.listen((rec) { diff --git a/packages/core/test/view_generator_test.dart b/packages/core/test/view_generator_test.dart index e3db648..7d39711 100644 --- a/packages/core/test/view_generator_test.dart +++ b/packages/core/test/view_generator_test.dart @@ -3,7 +3,7 @@ import 'package:test/test.dart'; void main() { test('default view generator', () async { - var app = Protevus(); + var app = Application(); var view = await app.viewGenerator!('foo', {'bar': 'baz'}); expect(view, contains('No view engine')); }); diff --git a/packages/exceptions/example/main.dart b/packages/exceptions/example/main.dart index ef7afe0..e7171c5 100644 --- a/packages/exceptions/example/main.dart +++ b/packages/exceptions/example/main.dart @@ -1,3 +1,4 @@ import 'package:platform_exceptions/http_exception.dart'; -void main() => throw HttpException.notFound(message: "Can't find that page!"); +void main() => + throw PlatformHttpException.notFound(message: "Can't find that page!"); diff --git a/packages/exceptions/lib/http_exception.dart b/packages/exceptions/lib/http_exception.dart index 77ed1ae..07e5a38 100644 --- a/packages/exceptions/lib/http_exception.dart +++ b/packages/exceptions/lib/http_exception.dart @@ -1,4 +1,4 @@ -library http_exception; +library platform_http_exception; //import 'package:dart2_constant/convert.dart'; import 'dart:convert'; @@ -8,7 +8,7 @@ import 'dart:convert'; /// /// Originally inspired by /// [feathers-errors](https://github.com/feathersjs/feathers-errors). -class HttpException implements Exception { +class PlatformHttpException implements Exception { /// A list of errors that occurred when this exception was thrown. final List errors = []; @@ -24,7 +24,7 @@ class HttpException implements Exception { /// An HTTP status code this exception will throw. int statusCode; - HttpException( + PlatformHttpException( {this.message = '500 Internal Server Error', this.stackTrace, this.statusCode = 500, @@ -49,8 +49,8 @@ class HttpException implements Exception { return '$statusCode: $message'; } - factory HttpException.fromMap(Map data) { - return HttpException( + factory PlatformHttpException.fromMap(Map data) { + return PlatformHttpException( statusCode: (data['status_code'] ?? data['statusCode'] ?? 500) as int, message: data['message']?.toString() ?? 'Internal Server Error', errors: data['errors'] is Iterable @@ -59,63 +59,65 @@ class HttpException implements Exception { ); } - factory HttpException.fromJson(String str) => - HttpException.fromMap(json.decode(str) as Map); + factory PlatformHttpException.fromJson(String str) => + PlatformHttpException.fromMap(json.decode(str) as Map); /// Throws a 400 Bad Request error, including an optional arrray of (validation?) /// errors you specify. - factory HttpException.badRequest( + factory PlatformHttpException.badRequest( {String message = '400 Bad Request', List errors = const []}) => - HttpException(message: message, errors: errors, statusCode: 400); + PlatformHttpException(message: message, errors: errors, statusCode: 400); /// Throws a 401 Not Authenticated error. - factory HttpException.notAuthenticated( + factory PlatformHttpException.notAuthenticated( {String message = '401 Not Authenticated'}) => - HttpException(message: message, statusCode: 401); + PlatformHttpException(message: message, statusCode: 401); /// Throws a 402 Payment Required error. - factory HttpException.paymentRequired( + factory PlatformHttpException.paymentRequired( {String message = '402 Payment Required'}) => - HttpException(message: message, statusCode: 402); + PlatformHttpException(message: message, statusCode: 402); /// Throws a 403 Forbidden error. - factory HttpException.forbidden({String message = '403 Forbidden'}) => - HttpException(message: message, statusCode: 403); + factory PlatformHttpException.forbidden({String message = '403 Forbidden'}) => + PlatformHttpException(message: message, statusCode: 403); /// Throws a 404 Not Found error. - factory HttpException.notFound({String message = '404 Not Found'}) => - HttpException(message: message, statusCode: 404); + factory PlatformHttpException.notFound({String message = '404 Not Found'}) => + PlatformHttpException(message: message, statusCode: 404); /// Throws a 405 Method Not Allowed error. - factory HttpException.methodNotAllowed( + factory PlatformHttpException.methodNotAllowed( {String message = '405 Method Not Allowed'}) => - HttpException(message: message, statusCode: 405); + PlatformHttpException(message: message, statusCode: 405); /// Throws a 406 Not Acceptable error. - factory HttpException.notAcceptable( + factory PlatformHttpException.notAcceptable( {String message = '406 Not Acceptable'}) => - HttpException(message: message, statusCode: 406); + PlatformHttpException(message: message, statusCode: 406); /// Throws a 408 Timeout error. - factory HttpException.methodTimeout({String message = '408 Timeout'}) => - HttpException(message: message, statusCode: 408); + factory PlatformHttpException.methodTimeout( + {String message = '408 Timeout'}) => + PlatformHttpException(message: message, statusCode: 408); /// Throws a 409 Conflict error. - factory HttpException.conflict({String message = '409 Conflict'}) => - HttpException(message: message, statusCode: 409); + factory PlatformHttpException.conflict({String message = '409 Conflict'}) => + PlatformHttpException(message: message, statusCode: 409); /// Throws a 422 Not Processable error. - factory HttpException.notProcessable( + factory PlatformHttpException.notProcessable( {String message = '422 Not Processable'}) => - HttpException(message: message, statusCode: 422); + PlatformHttpException(message: message, statusCode: 422); /// Throws a 501 Not Implemented error. - factory HttpException.notImplemented( + factory PlatformHttpException.notImplemented( {String message = '501 Not Implemented'}) => - HttpException(message: message, statusCode: 501); + PlatformHttpException(message: message, statusCode: 501); /// Throws a 503 Unavailable error. - factory HttpException.unavailable({String message = '503 Unavailable'}) => - HttpException(message: message, statusCode: 503); + factory PlatformHttpException.unavailable( + {String message = '503 Unavailable'}) => + PlatformHttpException(message: message, statusCode: 503); } diff --git a/packages/mocking/test/all_test.dart b/packages/mocking/test/all_test.dart index d892053..a0244a1 100644 --- a/packages/mocking/test/all_test.dart +++ b/packages/mocking/test/all_test.dart @@ -20,7 +20,7 @@ void main() { return res.serialize(req.ip == InternetAddress.loopbackIPv4.address); }); - var http = ProtevusHttp(app); + var http = PlatformHttp(app); test('receive a response', () async { var rq = MockHttpRequest('GET', uri.resolve('/foo'));