update(angel3): rebranding angel3

This commit is contained in:
Patrick Stewart 2024-09-28 16:14:48 -07:00
parent 92f78894fb
commit 1a5489a993
61 changed files with 325 additions and 308 deletions

View file

@ -38,7 +38,7 @@ A better IoC container for Protevus, ultimately allowing Protevus to be used wit
app.container.registerSingleton<SalesController>(SalesController()); app.container.registerSingleton<SalesController>(SalesController());
await app.mountController<SalesController>(); await app.mountController<SalesController>();
var http = ProtevusHttp(app); var http = PlatformHttp(app);
var server = await http.startServer('localhost', 3000); var server = await http.startServer('localhost', 3000);
print("Protevus server listening at ${http.uri}"); print("Protevus server listening at ${http.uri}");
} }

View file

@ -20,8 +20,8 @@
## 8.2.0 ## 8.2.0
* Add `addResponseHeader` to `ProtevusHttp` to add headers to HTTP default response * Add `addResponseHeader` to `PlatformHttp` to add headers to HTTP default response
* Add `removeResponseHeader` to `ProtevusHttp` to remove headers from HTTP default response * Add `removeResponseHeader` to `PlatformHttp` to remove headers from HTTP default response
## 8.1.1 ## 8.1.1
@ -138,7 +138,7 @@
## 2.1.1 ## 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 ## 2.1.0
@ -150,7 +150,7 @@ therefore been bumped to `2.1.0`.
## 2.0.5-beta ## 2.0.5-beta
* Make `@Expose()` in `Controller` optional. <https://github.com/angel-dart/angel/issues/107> * Make `@Expose()` in `Controller` optional. <https://github.com/angel-dart/angel/issues/107>
* Add `allowHttp1` to `ProtevusHttp2` constructors. <https://github.com/angel-dart/angel/issues/108> * Add `allowHttp1` to `PlatformHttp2` constructors. <https://github.com/angel-dart/angel/issues/108>
* Add `deserializeBody` and `decodeBody` to `RequestContext`. <https://github.com/angel-dart/angel/issues/109> * Add `deserializeBody` and `decodeBody` to `RequestContext`. <https://github.com/angel-dart/angel/issues/109>
* Add `HostnameRouter`, which allows for routing based on hostname. <https://github.com/angel-dart/angel/issues/110> * Add `HostnameRouter`, which allows for routing based on hostname. <https://github.com/angel-dart/angel/issues/110>
* Default to using `ThrowingReflector`, instead of `EmptyReflector`. This will give a more descriptive * 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 ## 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`. * Add `startSharedHttp2`.
## 2.0.0-rc.9 ## 2.0.0-rc.9
@ -333,7 +333,7 @@ stable, there'll be a conversion, perhaps.
## 2.0.0-alpha.10 ## 2.0.0-alpha.10
* All calls to `Service.parseId` are now affixed with the `<Id>` argument. * All calls to `Service.parseId` are now affixed with the `<Id>` argument.
* Added `uri` getter to `ProtevusHttp`. * Added `uri` getter to `PlatformHttp`.
* The default for `parseQuery` now wraps query parameters in `Map<String, dynamic>.from`. * The default for `parseQuery` now wraps query parameters in `Map<String, dynamic>.from`.
This resolves a bug in `package:angel_validate`. This resolves a bug in `package:angel_validate`.
@ -418,7 +418,7 @@ stable, there'll be a conversion, perhaps.
as well as `query`. as well as `query`.
* Removed `Protevus.injections` and `RequestContext.injections`. * Removed `Protevus.injections` and `RequestContext.injections`.
* Removed `Protevus.inject` and `RequestContext.inject`. * 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` * Remove the `RequestMiddleware` typedef; from now on, one should use `ResponseContext.end`
exclusively to close responses. exclusively to close responses.
* `waterfall` will now only accept `RequestHandler`. * `waterfall` will now only accept `RequestHandler`.
@ -438,7 +438,7 @@ stable, there'll be a conversion, perhaps.
* Removed `Protevus.defaultZoneCreator`. * Removed `Protevus.defaultZoneCreator`.
* Added all flags to the `Protevus` constructor, ex. `Protevus.eagerParseBodies`. * Added all flags to the `Protevus` constructor, ex. `Protevus.eagerParseBodies`.
* Fix a bug where synchronous errors in `handleRequest` would not be caught. * 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, * `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. as in many cases it is unnecessary and slows down response time.
* `ResponseContext.streaming` was replaced by `ResponseContext.isBuffered`. * `ResponseContext.streaming` was replaced by `ResponseContext.isBuffered`.

View file

@ -8,14 +8,15 @@ void main() async {
Logger.root.onRecord.listen(print); Logger.root.onRecord.listen(print);
// Create our server. // Create our server.
var app = Protevus(logger: Logger('protevus'), reflector: MirrorsReflector()); var app =
var http = ProtevusHttp(app); Application(logger: Logger('protevus'), reflector: MirrorsReflector());
var http = PlatformHttp(app);
await app.mountController<ArtistsController>(); await app.mountController<ArtistsController>();
// Simple fallback to throw a 404 on unknown paths. // Simple fallback to throw a 404 on unknown paths.
app.fallback((req, res) { app.fallback((req, res) {
throw HttpException.notFound( throw PlatformHttpException.notFound(
message: 'Unknown path: "${req.uri!.path}"', message: 'Unknown path: "${req.uri!.path}"',
); );
}); });

View file

@ -6,7 +6,7 @@ import 'package:platform_core/http.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
void main() async { void main() async {
var app = Protevus(reflector: MirrorsReflector()) var app = Application(reflector: MirrorsReflector())
..logger = (Logger('protevus') ..logger = (Logger('protevus')
..onRecord.listen((rec) { ..onRecord.listen((rec) {
print(rec); print(rec);
@ -18,7 +18,7 @@ void main() async {
app.fallback( app.fallback(
(req, res) => Future.error('Throwing just because I feel like!')); (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); HttpServer? server = await http.startServer('127.0.0.1', 3000);
var url = 'http://${server.address.address}:${server.port}'; var url = 'http://${server.address.address}:${server.port}';
print('Listening at $url'); print('Listening at $url');

View file

@ -3,14 +3,14 @@ import 'package:platform_core/core.dart';
import 'package:platform_core/http.dart'; import 'package:platform_core/http.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
Future<void> apiConfigurer(Protevus app) async { Future<void> apiConfigurer(Application app) async {
app.get('/', (req, res) => 'Hello, API!'); app.get('/', (req, res) => 'Hello, API!');
app.fallback((req, res) { app.fallback((req, res) {
return 'fallback on ${req.uri} (within the API)'; return 'fallback on ${req.uri} (within the API)';
}); });
} }
Future<void> frontendConfigurer(Protevus app) async { Future<void> frontendConfigurer(Application app) async {
app.fallback((req, res) => '(usually an index page would be shown here.)'); app.fallback((req, res) => '(usually an index page would be shown here.)');
} }
@ -19,8 +19,8 @@ void main() async {
hierarchicalLoggingEnabled = true; hierarchicalLoggingEnabled = true;
//Logger.root.onRecord.listen(prettyLog); //Logger.root.onRecord.listen(prettyLog);
var app = Protevus(logger: Logger('protevus')); var app = Application(logger: Logger('protevus'));
var http = ProtevusHttp(app); var http = PlatformHttp(app);
var multiHost = HostnameRouter.configure({ var multiHost = HostnameRouter.configure({
'api.localhost:3000': apiConfigurer, 'api.localhost:3000': apiConfigurer,
'localhost:3000': frontendConfigurer, 'localhost:3000': frontendConfigurer,

View file

@ -6,7 +6,7 @@ import 'package:file/local.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
void main() async { void main() async {
var app = Protevus(); var app = Application();
app.logger = Logger('protevus') app.logger = Logger('protevus')
..onRecord.listen((rec) { ..onRecord.listen((rec) {
print(rec); print(rec);
@ -35,10 +35,10 @@ void main() async {
st); st);
} }
var http1 = ProtevusHttp(app); var http1 = PlatformHttp(app);
var http2 = ProtevusHttp2(app, ctx); 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); http2.onHttp1.listen(http1.handleRequest);
var server = await http2.startServer('127.0.0.1', 3000); var server = await http2.startServer('127.0.0.1', 3000);

View file

@ -6,7 +6,7 @@ import 'package:logging/logging.dart';
import 'common.dart'; import 'common.dart';
void main() async { void main() async {
var app = Protevus() var app = Application()
..encoders.addAll({ ..encoders.addAll({
'gzip': gzip.encoder, 'gzip': gzip.encoder,
'deflate': zlib.encoder, 'deflate': zlib.encoder,
@ -15,8 +15,8 @@ void main() async {
app.get('/', (req, res) => 'Hello HTTP/2!!!'); app.get('/', (req, res) => 'Hello HTTP/2!!!');
app.fallback((req, res) => app.fallback((req, res) => throw PlatformHttpException.notFound(
throw HttpException.notFound(message: 'No file exists at ${req.uri}')); message: 'No file exists at ${req.uri}'));
var ctx = SecurityContext() var ctx = SecurityContext()
..useCertificateChain('dev.pem') ..useCertificateChain('dev.pem')
@ -32,10 +32,10 @@ void main() async {
); );
} }
var http1 = ProtevusHttp(app); var http1 = PlatformHttp(app);
var http2 = ProtevusHttp2(app, ctx); 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); http2.onHttp1.listen(http1.handleRequest);
await http2.startServer('127.0.0.1', 3000); await http2.startServer('127.0.0.1', 3000);

View file

@ -6,7 +6,7 @@ import 'package:file/local.dart';
import 'package:logging/logging.dart'; import 'package:logging/logging.dart';
void main() async { void main() async {
var app = Protevus(); var app = Application();
app.logger = Logger('protevus') app.logger = Logger('protevus')
..onRecord.listen((rec) { ..onRecord.listen((rec) {
print(rec); print(rec);
@ -51,10 +51,10 @@ void main() async {
st); st);
} }
var http1 = ProtevusHttp(app); var http1 = PlatformHttp(app);
var http2 = ProtevusHttp2(app, ctx); 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); http2.onHttp1.listen(http1.handleRequest);
var server = await http2.startServer('127.0.0.1', 3000); var server = await http2.startServer('127.0.0.1', 3000);

View file

@ -31,9 +31,9 @@ void main() async {
} }
void serverMain(_) async { void serverMain(_) async {
var app = Protevus(); var app = Application();
var http = var http =
ProtevusHttp.custom(app, startShared, useZone: false); // Run a cluster PlatformHttp.custom(app, startShared, useZone: false); // Run a cluster
app.get('/', (req, res) { app.get('/', (req, res) {
return res.serialize({ return res.serialize({

View file

@ -8,7 +8,7 @@ void main() async {
//Logger.root.onRecord.listen(prettyLog); //Logger.root.onRecord.listen(prettyLog);
// Create our server. // Create our server.
var app = Protevus( var app = Application(
logger: Logger('protevus'), logger: Logger('protevus'),
reflector: MirrorsReflector(), reflector: MirrorsReflector(),
); );
@ -41,12 +41,12 @@ void main() async {
// Simple fallback to throw a 404 on unknown paths. // Simple fallback to throw a 404 on unknown paths.
app.fallback((req, res) { app.fallback((req, res) {
throw HttpException.notFound( throw PlatformHttpException.notFound(
message: 'Unknown path: "${req.uri!.path}"', 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 server = await http.startServer('127.0.0.1', 3000);
var url = 'http://${server.address.address}:${server.port}'; var url = 'http://${server.address.address}:${server.port}';
print('Listening at $url'); print('Listening at $url');

View file

@ -8,7 +8,7 @@ void main() async {
Logger.root.onRecord.listen(print); Logger.root.onRecord.listen(print);
// Create our server. // Create our server.
var app = Protevus( var app = Application(
logger: Logger('protevus'), logger: Logger('protevus'),
reflector: MirrorsReflector(), reflector: MirrorsReflector(),
); );
@ -16,7 +16,7 @@ void main() async {
// Create a RESTful service that manages an in-memory collection. // Create a RESTful service that manages an in-memory collection.
app.use('/api/todos', MapService()); app.use('/api/todos', MapService());
var http = ProtevusHttp(app); var http = PlatformHttp(app);
await http.startServer('127.0.0.1', 0); await http.startServer('127.0.0.1', 0);
print('Listening at ${http.uri}'); print('Listening at ${http.uri}');
} }

View file

@ -2,8 +2,8 @@ import 'package:platform_core/core.dart';
import 'package:platform_core/http.dart'; import 'package:platform_core/http.dart';
void main() async { void main() async {
var app = Protevus(); var app = Application();
var http = ProtevusHttp(app); var http = PlatformHttp(app);
app.fallback((req, res) { app.fallback((req, res) {
res.statusCode = 304; res.statusCode = 304;

View file

@ -3,7 +3,7 @@ import 'package:platform_core/core.dart';
import 'package:platform_core/http.dart'; import 'package:platform_core/http.dart';
void main() async { void main() async {
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
app.viewGenerator = (name, [data]) async => app.viewGenerator = (name, [data]) async =>
'View generator invoked with name $name and data: $data'; 'View generator invoked with name $name and data: $data';
@ -11,7 +11,7 @@ void main() async {
// Index route. Returns JSON. // Index route. Returns JSON.
app.get('/', (req, res) => res.render('index', {'foo': 'bar'})); 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 server = await http.startServer('127.0.0.1', 3000);
var url = 'http://${server.address.address}:${server.port}'; var url = 'http://${server.address.address}:${server.port}';
print('Listening at $url'); print('Listening at $url');

View file

@ -9,10 +9,10 @@ import '../core/core.dart';
/// Supports grouping routes with shared functionality. /// Supports grouping routes with shared functionality.
class Controller { class Controller {
Protevus? _app; Application? _app;
/// The [Protevus] application powering this controller. /// The [Application] application powering this controller.
Protevus get app { Application get app {
if (_app == null) { if (_app == null) {
throw ArgumentError("Protevus is not instantiated."); throw ArgumentError("Protevus is not instantiated.");
} }
@ -38,7 +38,7 @@ class Controller {
/// Applies routes, DI, and other configuration to an [app]. /// Applies routes, DI, and other configuration to an [app].
@mustCallSuper @mustCallSuper
Future<void> configureServer(Protevus app) async { Future<void> configureServer(Application app) async {
_app = app; _app = app;
if (injectSingleton != false) { if (injectSingleton != false) {

View file

@ -10,14 +10,14 @@ import 'core.dart';
/// Base driver class for Protevus implementations. /// Base driver class for Protevus implementations.
/// ///
/// Powers both ProtevusHttp and ProtevusHttp2. /// Powers both PlatformHttp and PlatformHttp2.
abstract class Driver< abstract class Driver<
Request, Request,
Response, Response,
Server extends Stream<Request>, Server extends Stream<Request>,
RequestContextType extends RequestContext, RequestContextType extends RequestContext,
ResponseContextType extends ResponseContext> { ResponseContextType extends ResponseContext> {
final Protevus app; final Application app;
final bool useZone; final bool useZone;
bool _closed = false; bool _closed = false;
@ -170,22 +170,23 @@ abstract class Driver<
return f.catchError((e, StackTrace st) { return f.catchError((e, StackTrace st) {
if (e is FormatException) { if (e is FormatException) {
throw HttpException.badRequest(message: e.message) throw PlatformHttpException.badRequest(message: e.message)
..stackTrace = st; ..stackTrace = st;
} }
throw HttpException( throw PlatformHttpException(
stackTrace: st, stackTrace: st,
statusCode: (e is HttpException) ? e.statusCode : 500, statusCode: (e is PlatformHttpException) ? e.statusCode : 500,
message: e?.toString() ?? '500 Internal Server Error'); 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"); //print(">>>> Framework error: $ee");
//var t = (st).runtimeType; //var t = (st).runtimeType;
//print(">>>> StackTrace: $t"); //print(">>>> StackTrace: $t");
HttpException e; PlatformHttpException e;
if (ee is HttpException) { if (ee is PlatformHttpException) {
e = ee; e = ee;
} else { } else {
e = HttpException( e = PlatformHttpException(
stackTrace: st, stackTrace: st,
statusCode: 500, statusCode: 500,
message: ee?.toString() ?? '500 Internal Server Error'); message: ee?.toString() ?? '500 Internal Server Error');
@ -207,14 +208,14 @@ abstract class Driver<
// TODO: To be revisited // TODO: To be revisited
Future(() { Future(() {
HttpException e; PlatformHttpException e;
if (error is FormatException) { if (error is FormatException) {
e = HttpException.badRequest(message: error.message); e = PlatformHttpException.badRequest(message: error.message);
} else if (error is HttpException) { } else if (error is PlatformHttpException) {
e = error; e = error;
} else { } else {
e = HttpException( e = PlatformHttpException(
stackTrace: stackTrace, message: error.toString()); stackTrace: stackTrace, message: error.toString());
} }
@ -251,9 +252,9 @@ abstract class Driver<
}); });
} }
/// Handles an [HttpException]. /// Handles an [PlatformHttpException].
Future handleHttpException( Future handleHttpException(
HttpException e, PlatformHttpException e,
StackTrace st, StackTrace st,
RequestContext? req, RequestContext? req,
ResponseContext? res, ResponseContext? res,
@ -383,7 +384,7 @@ abstract class Driver<
MiddlewarePipelineIterator<RequestHandler> it, MiddlewarePipelineIterator<RequestHandler> it,
RequestContextType req, RequestContextType req,
ResponseContextType res, ResponseContextType res,
Protevus app) async { Application app) async {
var broken = false; var broken = false;
while (it.moveNext()) { while (it.moveNext()) {
var current = it.current.handlers.iterator; var current = it.current.handlers.iterator;

View file

@ -98,7 +98,7 @@ class HookedService<Id, Data, T extends Service<Id, Data>>
} }
/// Adds hooks to this instance. /// Adds hooks to this instance.
void addHooks(Protevus app) { void addHooks(Application app) {
var hooks = getAnnotation<Hooks>(inner, app.container.reflector); var hooks = getAnnotation<Hooks>(inner, app.container.reflector);
var before = <HookedServiceEventListener<Id, Data, T>>[]; var before = <HookedServiceEventListener<Id, Data, T>>[];
var after = <HookedServiceEventListener<Id, Data, T>>[]; var after = <HookedServiceEventListener<Id, Data, T>>[];

View file

@ -24,13 +24,13 @@ import 'server.dart';
/// * `example.*` -> `/example\./[^$]*` /// * `example.*` -> `/example\./[^$]*`
/// * `example.+` -> `/example\./[^$]+` /// * `example.+` -> `/example\./[^$]+`
class HostnameRouter { class HostnameRouter {
final Map<Pattern, Protevus> _apps = {}; final Map<Pattern, Application> _apps = {};
final Map<Pattern, FutureOr<Protevus> Function()> _creators = {}; final Map<Pattern, FutureOr<Application> Function()> _creators = {};
final List<Pattern> _patterns = []; final List<Pattern> _patterns = [];
HostnameRouter( HostnameRouter(
{Map<Pattern, Protevus> apps = const {}, {Map<Pattern, Application> apps = const {},
Map<Pattern, FutureOr<Protevus> Function()> creators = const {}}) { Map<Pattern, FutureOr<Application> Function()> creators = const {}}) {
Map<Pattern, V> parseMap<V>(Map<Pattern, V> map) { Map<Pattern, V> parseMap<V>(Map<Pattern, V> map) {
return map.map((p, c) { return map.map((p, c) {
Pattern pp; Pattern pp;
@ -55,7 +55,7 @@ class HostnameRouter {
} }
factory HostnameRouter.configure( factory HostnameRouter.configure(
Map<Pattern, FutureOr<void> Function(Protevus)> configurers, Map<Pattern, FutureOr<void> Function(Application)> configurers,
{Reflector reflector = const EmptyReflector(), {Reflector reflector = const EmptyReflector(),
ProtevusEnvironment environment = protevusEnv, ProtevusEnvironment environment = protevusEnv,
Logger? logger, Logger? logger,
@ -64,7 +64,7 @@ class HostnameRouter {
ViewGenerator? viewGenerator}) { ViewGenerator? viewGenerator}) {
var creators = configurers.map((p, c) { var creators = configurers.map((p, c) {
return MapEntry(p, () async { return MapEntry(p, () async {
var app = Protevus( var app = Application(
reflector: reflector, reflector: reflector,
environment: environment, environment: environment,
logger: logger, logger: logger,

View file

@ -72,7 +72,7 @@ class MapService extends Service<String?, Map<String, dynamic>> {
Future<Map<String, dynamic>> read(String? id, Future<Map<String, dynamic>> read(String? id,
[Map<String, dynamic>? params]) { [Map<String, dynamic>? params]) {
return Future.value(items.firstWhere(_matchesId(id), return Future.value(items.firstWhere(_matchesId(id),
orElse: (() => throw HttpException.notFound( orElse: (() => throw PlatformHttpException.notFound(
message: 'No record found for ID $id')))); message: 'No record found for ID $id'))));
} }
@ -127,7 +127,8 @@ class MapService extends Service<String?, Map<String, dynamic>> {
return read(id).then((old) { return read(id).then((old) {
if (!items.remove(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<String, dynamic>.from(data); var result = Map<String, dynamic>.from(data);
@ -151,7 +152,7 @@ class MapService extends Service<String?, Map<String, dynamic>> {
// Remove everything... // Remove everything...
if (!(allowRemoveAll == true || if (!(allowRemoveAll == true ||
params?.containsKey('provider') != true)) { params?.containsKey('provider') != true)) {
throw HttpException.forbidden( throw PlatformHttpException.forbidden(
message: 'Clients are not allowed to delete all items.'); message: 'Clients are not allowed to delete all items.');
} else { } else {
items.clear(); items.clear();
@ -163,7 +164,8 @@ class MapService extends Service<String?, Map<String, dynamic>> {
if (items.remove(result)) { if (items.remove(result)) {
return result; return result;
} else { } else {
throw HttpException.notFound(message: 'No record found for ID $id'); throw PlatformHttpException.notFound(
message: 'No record found for ID $id');
} }
}); });
} }

View file

@ -103,15 +103,15 @@ class Parameter {
/// Returns an error that can be thrown when the parameter is not present. /// Returns an error that can be thrown when the parameter is not present.
Object? get error { Object? get error {
if (cookie?.isNotEmpty == true) { if (cookie?.isNotEmpty == true) {
return HttpException.badRequest( return PlatformHttpException.badRequest(
message: 'Missing required cookie "$cookie".'); message: 'Missing required cookie "$cookie".');
} }
if (header?.isNotEmpty == true) { if (header?.isNotEmpty == true) {
return HttpException.badRequest( return PlatformHttpException.badRequest(
message: 'Missing required header "$header".'); message: 'Missing required header "$header".');
} }
if (query?.isNotEmpty == true) { if (query?.isNotEmpty == true) {
return HttpException.badRequest( return PlatformHttpException.badRequest(
message: 'Missing required query parameter "$query".'); message: 'Missing required query parameter "$query".');
} }
if (session?.isNotEmpty == true) { if (session?.isNotEmpty == true) {

View file

@ -18,13 +18,13 @@ import 'package:logging/logging.dart';
import 'metadata.dart'; import 'metadata.dart';
import 'response_context.dart'; import 'response_context.dart';
import 'routable.dart'; import 'routable.dart';
import 'server.dart' show Protevus; import 'server.dart' show Application;
part 'injection.dart'; part 'injection.dart';
/// A convenience wrapper around an incoming [RawRequest]. /// A convenience wrapper around an incoming [RawRequest].
abstract class RequestContext<RawRequest> { abstract class RequestContext<RawRequest> {
/// 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. /// when a [RequestContext] is done being processed.
final _log = Logger('RequestContext'); final _log = Logger('RequestContext');
@ -46,8 +46,8 @@ abstract class RequestContext<RawRequest> {
/// Additional params to be passed to services. /// Additional params to be passed to services.
final Map<String, dynamic> serviceParams = {}; final Map<String, dynamic> serviceParams = {};
/// The [Protevus] instance that is responding to this request. /// The [Application] instance that is responding to this request.
Protevus? app; Application? app;
/// Any cookies sent with this request. /// Any cookies sent with this request.
List<Cookie> get cookies => <Cookie>[]; List<Cookie> get cookies => <Cookie>[];

View file

@ -13,7 +13,7 @@ import 'package:mime/mime.dart';
import 'controller.dart'; import 'controller.dart';
import 'request_context.dart'; import 'request_context.dart';
import 'server.dart' show Protevus; import 'server.dart' show Application;
final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)'); final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)');
@ -29,8 +29,8 @@ abstract class ResponseContext<RawResponse>
Completer? _done; Completer? _done;
int _statusCode = 200; int _statusCode = 200;
/// The [Protevus] instance that is sending a response. /// The [Application] instance that is sending a response.
Protevus? app; Application? app;
/// Is `Transfer-Encoding` chunked? /// Is `Transfer-Encoding` chunked?
bool? chunked; bool? chunked;

View file

@ -21,8 +21,8 @@ import 'service.dart';
//final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)'); //final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)');
/// A function that configures an [Protevus] server. /// A function that configures an [Application] server.
typedef Configurer = FutureOr<void> Function(Protevus app); typedef PlatformConfigurer = FutureOr<void> Function(Application app);
/// A function that asynchronously generates a view from the given path and data. /// A function that asynchronously generates a view from the given path and data.
typedef ViewGenerator = FutureOr<String> Function(String path, typedef ViewGenerator = FutureOr<String> Function(String path,
@ -30,11 +30,11 @@ typedef ViewGenerator = FutureOr<String> Function(String path,
/// A function that handles error /// A function that handles error
typedef PlatformErrorHandler = dynamic Function( 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<bool> _defaultErrorHandler( Future<bool> _defaultErrorHandler(
HttpException e, RequestContext req, ResponseContext res) async { PlatformHttpException e, RequestContext req, ResponseContext res) async {
if (!req.accepts('text/html', strict: true) && if (!req.accepts('text/html', strict: true) &&
(req.accepts('application/json') || (req.accepts('application/json') ||
req.accepts('application/javascript'))) { req.accepts('application/javascript'))) {
@ -65,7 +65,7 @@ Logger _defaultLogger() {
if (rec.error != null) { if (rec.error != null) {
var err = rec.error; 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.message} \n');
print(rec.error); print(rec.error);
if (rec.stackTrace != null) { if (rec.stackTrace != null) {
@ -78,18 +78,18 @@ Logger _defaultLogger() {
} }
/// A powerful real-time/REST/MVC server class. /// A powerful real-time/REST/MVC server class.
class Protevus extends Routable { class Application extends Routable {
static Future<String> _noViewEngineConfigured(String view, [Map? data]) => static Future<String> _noViewEngineConfigured(String view, [Map? data]) =>
Future.value('No view engine has been configured yet.'); Future.value('No view engine has been configured yet.');
final List<Protevus> _children = []; final List<Application> _children = [];
final Map< final Map<
String, String,
Tuple4<List, Map<String, dynamic>, ParseResult<RouteResult>, Tuple4<List, Map<String, dynamic>, ParseResult<RouteResult>,
MiddlewarePipeline>> handlerCache = HashMap(); MiddlewarePipeline>> handlerCache = HashMap();
Router<RequestHandler>? _flattened; Router<RequestHandler>? _flattened;
Protevus? _parent; Application? _parent;
/// A global Map of converters that can transform responses bodies. /// A global Map of converters that can transform responses bodies.
final Map<String, Converter<List<int>, List<int>>> encoders = {}; final Map<String, Converter<List<int>, List<int>>> encoders = {};
@ -114,7 +114,7 @@ class Protevus extends Routable {
bool allowMethodOverrides = true; bool allowMethodOverrides = true;
/// All child application mounted on this instance. /// All child application mounted on this instance.
List<Protevus> get children => List<Protevus>.unmodifiable(_children); List<Application> get children => List<Application>.unmodifiable(_children);
final Map<Pattern, Controller> _controllers = {}; final Map<Pattern, Controller> _controllers = {};
@ -127,7 +127,7 @@ class Protevus extends Routable {
final ProtevusEnvironment environment; final ProtevusEnvironment environment;
/// Returns the parent instance of this application, if any. /// Returns the parent instance of this application, if any.
Protevus? get parent => _parent; Application? get parent => _parent;
/// Outputs diagnostics and debug messages. /// Outputs diagnostics and debug messages.
Logger _logger = _defaultLogger(); Logger _logger = _defaultLogger();
@ -145,12 +145,12 @@ class Protevus extends Routable {
/// Plug-ins to be called right before server startup. /// Plug-ins to be called right before server startup.
/// ///
/// If the server is never started, they will never be called. /// If the server is never started, they will never be called.
final List<Configurer> startupHooks = []; final List<PlatformConfigurer> startupHooks = [];
/// Plug-ins to be called right before server shutdown. /// Plug-ins to be called right before server shutdown.
/// ///
/// If the server is never [close]d, they will never be called. /// If the server is never [close]d, they will never be called.
final List<Configurer> shutdownHooks = []; final List<PlatformConfigurer> shutdownHooks = [];
/// Always run before responses are sent. /// Always run before responses are sent.
/// ///
@ -162,7 +162,7 @@ class Protevus extends Routable {
/// Called by [ResponseContext]@`render`. /// Called by [ResponseContext]@`render`.
ViewGenerator? viewGenerator = _noViewEngineConfigured; ViewGenerator? viewGenerator = _noViewEngineConfigured;
/// The handler currently configured to run on [HttpException]s. /// The handler currently configured to run on [PlatformHttpException]s.
PlatformErrorHandler errorHandler = _defaultErrorHandler; PlatformErrorHandler errorHandler = _defaultErrorHandler;
@override @override
@ -189,7 +189,7 @@ class Protevus extends Routable {
'This route will be ignored, and no requests will ever reach it.'); 'This route will be ignored, and no requests will ever reach it.');
} }
if (router is Protevus) { if (router is Application) {
router._parent = this; router._parent = this;
_children.add(router); _children.add(router);
} }
@ -199,11 +199,11 @@ class Protevus extends Routable {
/// Loads some base dependencies into the service container. /// Loads some base dependencies into the service container.
void bootstrapContainer() { void bootstrapContainer() {
if (runtimeType != Protevus) { if (runtimeType != Application) {
container.registerSingleton(this); container.registerSingleton(this);
} }
container.registerSingleton<Protevus>(this); container.registerSingleton<Application>(this);
container.registerSingleton<Routable>(this); container.registerSingleton<Routable>(this);
container.registerSingleton<Router>(this); container.registerSingleton<Router>(this);
} }
@ -358,8 +358,8 @@ class Protevus extends Routable {
// return closureMirror.apply(args).reflectee; // return closureMirror.apply(args).reflectee;
} }
/// Applies an [Configurer] to this instance. /// Applies an [PlatformConfigurer] to this instance.
Future configure(Configurer configurer) { Future configure(PlatformConfigurer configurer) {
return Future.sync(() => configurer(this)); return Future.sync(() => configurer(this));
} }
@ -396,7 +396,7 @@ class Protevus extends Routable {
'For more, see the documentation:\n' 'For more, see the documentation:\n'
'https://docs.angel-dart.dev/guides/dependency-injection#enabling-dart-mirrors-or-other-reflection'; 'https://docs.angel-dart.dev/guides/dependency-injection#enabling-dart-mirrors-or-other-reflection';
Protevus( Application(
{Reflector reflector = {Reflector reflector =
const ThrowingReflector(errorMessage: _reflectionErrorMessage), const ThrowingReflector(errorMessage: _reflectionErrorMessage),
this.environment = protevusEnv, this.environment = protevusEnv,

View file

@ -67,17 +67,17 @@ class Service<Id, Data> extends Routable {
/// Handlers that must run to ensure this service's functionality. /// Handlers that must run to ensure this service's functionality.
List<RequestHandler> get bootstrappers => []; List<RequestHandler> get bootstrappers => [];
/// The [Protevus] app powering this service. /// The [Application] app powering this service.
Protevus? _app; Application? _app;
Protevus get app { Application get app {
if (_app == null) { if (_app == null) {
throw ArgumentError("Protevus is not initialized"); throw ArgumentError("Protevus is not initialized");
} }
return _app!; return _app!;
} }
set app(Protevus protevus) { set app(Application protevus) {
_app = protevus; _app = protevus;
} }
@ -94,7 +94,7 @@ class Service<Id, Data> extends Routable {
_readData ??= (req, res) { _readData ??= (req, res) {
if (req.bodyAsObject is! Data) { if (req.bodyAsObject is! Data) {
throw HttpException.badRequest( throw PlatformHttpException.badRequest(
message: message:
'Invalid request body. Expected $Data; found ${req.bodyAsObject} instead.'); 'Invalid request body. Expected $Data; found ${req.bodyAsObject} instead.');
} else { } else {
@ -123,7 +123,7 @@ class Service<Id, Data> extends Routable {
String errorMessage = 'No record was found matching the given query.']) { String errorMessage = 'No record was found matching the given query.']) {
return index(params).then((result) { return index(params).then((result) {
if (result.isEmpty) { if (result.isEmpty) {
throw HttpException.notFound(message: errorMessage); throw PlatformHttpException.notFound(message: errorMessage);
} else { } else {
return result.first; return result.first;
} }
@ -132,12 +132,12 @@ class Service<Id, Data> extends Routable {
/// Retrieves all resources. /// Retrieves all resources.
Future<List<Data>> index([Map<String, dynamic>? params]) { Future<List<Data>> index([Map<String, dynamic>? params]) {
throw HttpException.methodNotAllowed(); throw PlatformHttpException.methodNotAllowed();
} }
/// Retrieves the desired resource. /// Retrieves the desired resource.
Future<Data> read(Id id, [Map<String, dynamic>? params]) { Future<Data> read(Id id, [Map<String, dynamic>? params]) {
throw HttpException.methodNotAllowed(); throw PlatformHttpException.methodNotAllowed();
} }
/// Reads multiple resources at once. /// Reads multiple resources at once.
@ -150,22 +150,22 @@ class Service<Id, Data> extends Routable {
/// Creates a resource. /// Creates a resource.
Future<Data> create(Data data, [Map<String, dynamic>? params]) { Future<Data> create(Data data, [Map<String, dynamic>? params]) {
throw HttpException.methodNotAllowed(); throw PlatformHttpException.methodNotAllowed();
} }
/// Modifies a resource. /// Modifies a resource.
Future<Data> modify(Id id, Data data, [Map<String, dynamic>? params]) { Future<Data> modify(Id id, Data data, [Map<String, dynamic>? params]) {
throw HttpException.methodNotAllowed(); throw PlatformHttpException.methodNotAllowed();
} }
/// Overwrites a resource. /// Overwrites a resource.
Future<Data> update(Id id, Data data, [Map<String, dynamic>? params]) { Future<Data> update(Id id, Data data, [Map<String, dynamic>? params]) {
throw HttpException.methodNotAllowed(); throw PlatformHttpException.methodNotAllowed();
} }
/// Removes the given resource. /// Removes the given resource.
Future<Data> remove(Id id, [Map<String, dynamic>? params]) { Future<Data> remove(Id id, [Map<String, dynamic>? params]) {
throw HttpException.methodNotAllowed(); throw PlatformHttpException.methodNotAllowed();
} }
/// Creates an [AnonymousService] that wraps over this one, and maps input and output /// Creates an [AnonymousService] that wraps over this one, and maps input and output
@ -371,8 +371,8 @@ class Service<Id, Data> extends Routable {
]); ]);
// REST compliance // REST compliance
put('/', (req, res) => throw HttpException.notFound()); put('/', (req, res) => throw PlatformHttpException.notFound());
patch('/', (req, res) => throw HttpException.notFound()); patch('/', (req, res) => throw PlatformHttpException.notFound());
} }
/// Invoked when this service is wrapped within a [HookedService]. /// Invoked when this service is wrapped within a [HookedService].

View file

@ -1,5 +1,5 @@
/// Various libraries useful for creating highly-extensible servers. /// Various libraries useful for creating highly-extensible servers.
library angel_framework.http; library platform_core.http;
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';

View file

@ -77,7 +77,7 @@ class HttpRequestContext extends RequestContext<HttpRequest?> {
/// Magically transforms an [HttpRequest] into a [RequestContext]. /// Magically transforms an [HttpRequest] into a [RequestContext].
static Future<HttpRequestContext> from( static Future<HttpRequestContext> from(
HttpRequest request, Protevus app, String path) { HttpRequest request, Application app, String path) {
var ctx = HttpRequestContext().._container = app.container.createChild(); var ctx = HttpRequestContext().._container = app.container.createChild();
var override = request.method; var override = request.method;

View file

@ -18,7 +18,7 @@ class HttpResponseContext extends ResponseContext<HttpResponse> {
final HttpRequestContext? _correspondingRequest; final HttpRequestContext? _correspondingRequest;
bool _isDetached = false, _isClosed = false, _streamInitialized = false; bool _isDetached = false, _isClosed = false, _streamInitialized = false;
HttpResponseContext(this.rawResponse, Protevus? app, HttpResponseContext(this.rawResponse, Application? app,
[this._correspondingRequest]) { [this._correspondingRequest]) {
this.app = app; this.app = app;
} }

View file

@ -17,7 +17,7 @@ final RegExp _straySlashes = RegExp(r'(^/+)|(/+$)');
typedef ServerGeneratorType = Future<HttpServer> Function(dynamic, int); typedef ServerGeneratorType = Future<HttpServer> Function(dynamic, int);
/// Adapts `dart:io`'s [HttpServer] to serve Protevus. /// Adapts `dart:io`'s [HttpServer] to serve Protevus.
class ProtevusHttp extends Driver<HttpRequest, HttpResponse, HttpServer, class PlatformHttp extends Driver<HttpRequest, HttpResponse, HttpServer,
HttpRequestContext, HttpResponseContext> { HttpRequestContext, HttpResponseContext> {
@override @override
Uri get uri { Uri get uri {
@ -25,23 +25,24 @@ class ProtevusHttp extends Driver<HttpRequest, HttpResponse, HttpServer,
scheme: 'http', host: server?.address.address, port: server?.port); scheme: 'http', host: server?.address.address, port: server?.port);
} }
ProtevusHttp._(super.app, super.serverGenerator, bool useZone) PlatformHttp._(super.app, super.serverGenerator, bool useZone)
: super(useZone: useZone); : super(useZone: useZone);
factory ProtevusHttp(Protevus app, {bool useZone = true}) { factory PlatformHttp(Application app, {bool useZone = true}) {
return ProtevusHttp._(app, HttpServer.bind, useZone); return PlatformHttp._(app, HttpServer.bind, useZone);
} }
/// An instance mounted on a server started by the [serverGenerator]. /// An instance mounted on a server started by the [serverGenerator].
factory ProtevusHttp.custom(Protevus app, ServerGeneratorType serverGenerator, factory PlatformHttp.custom(
Application app, ServerGeneratorType serverGenerator,
{bool useZone = true, Map<String, String> headers = const {}}) { {bool useZone = true, Map<String, String> headers = const {}}) {
return ProtevusHttp._(app, serverGenerator, useZone); return PlatformHttp._(app, serverGenerator, useZone);
} }
factory ProtevusHttp.fromSecurityContext( factory PlatformHttp.fromSecurityContext(
Protevus app, SecurityContext context, Application app, SecurityContext context,
{bool useZone = true}) { {bool useZone = true}) {
return ProtevusHttp._(app, (address, int port) { return PlatformHttp._(app, (address, int port) {
return HttpServer.bindSecure(address, port, context); return HttpServer.bindSecure(address, port, context);
}, useZone); }, useZone);
} }
@ -51,8 +52,8 @@ class ProtevusHttp extends Driver<HttpRequest, HttpResponse, HttpServer,
/// Provide paths to a certificate chain and server key (both .pem). /// Provide paths to a certificate chain and server key (both .pem).
/// If no password is provided, a random one will be generated upon running /// If no password is provided, a random one will be generated upon running
/// the server. /// the server.
factory ProtevusHttp.secure( factory PlatformHttp.secure(
Protevus app, String certificateChainPath, String serverKeyPath, Application app, String certificateChainPath, String serverKeyPath,
{String? password, bool useZone = true}) { {String? password, bool useZone = true}) {
var certificateChain = var certificateChain =
Platform.script.resolve(certificateChainPath).toFilePath(); Platform.script.resolve(certificateChainPath).toFilePath();
@ -61,7 +62,7 @@ class ProtevusHttp extends Driver<HttpRequest, HttpResponse, HttpServer,
serverContext.useCertificateChain(certificateChain, password: password); serverContext.useCertificateChain(certificateChain, password: password);
serverContext.usePrivateKey(serverKey, password: password); serverContext.usePrivateKey(serverKey, password: password);
return ProtevusHttp.fromSecurityContext(app, serverContext, return PlatformHttp.fromSecurityContext(app, serverContext,
useZone: useZone); useZone: useZone);
} }

View file

@ -31,7 +31,7 @@ class Http2RequestContext extends RequestContext<ServerTransportStream?> {
static Future<Http2RequestContext> from( static Future<Http2RequestContext> from(
ServerTransportStream stream, ServerTransportStream stream,
Socket socket, Socket socket,
Protevus app, Application app,
Map<String, MockHttpSession> sessions, Map<String, MockHttpSession> sessions,
Uuid uuid) { Uuid uuid) {
var c = Completer<Http2RequestContext>(); var c = Completer<Http2RequestContext>();

View file

@ -23,7 +23,7 @@ class Http2ResponseContext extends ResponseContext<ServerTransportStream> {
Uri? _targetUri; Uri? _targetUri;
Http2ResponseContext(Protevus? app, this.stream, this._req) { Http2ResponseContext(Application? app, this.stream, this._req) {
this.app = app; this.app = app;
_targetUri = _req?.uri; _targetUri = _req?.uri;
} }

View file

@ -16,10 +16,10 @@ Future<SecureServerSocket> startSharedHttp2(
} }
/// Adapts `package:http2`'s [ServerTransportConnection] to serve Protevus. /// Adapts `package:http2`'s [ServerTransportConnection] to serve Protevus.
class ProtevusHttp2 extends Driver<Socket, ServerTransportStream, class PlatformHttp2 extends Driver<Socket, ServerTransportStream,
SecureServerSocket, Http2RequestContext, Http2ResponseContext> { SecureServerSocket, Http2RequestContext, Http2ResponseContext> {
final ServerSettings? settings; final ServerSettings? settings;
late ProtevusHttp _http; late PlatformHttp _http;
final StreamController<HttpRequest> _onHttp1 = StreamController(); final StreamController<HttpRequest> _onHttp1 = StreamController();
final Map<String, MockHttpSession> _sessions = {}; final Map<String, MockHttpSession> _sessions = {};
final Uuid _uuid = Uuid(); final Uuid _uuid = Uuid();
@ -27,8 +27,8 @@ class ProtevusHttp2 extends Driver<Socket, ServerTransportStream,
SecureServerSocket? get socket => _artificial; SecureServerSocket? get socket => _artificial;
ProtevusHttp2._( PlatformHttp2._(
Protevus app, Application app,
Future<SecureServerSocket> Function(dynamic, int) serverGenerator, Future<SecureServerSocket> Function(dynamic, int) serverGenerator,
bool useZone, bool useZone,
bool allowHttp1, bool allowHttp1,
@ -39,21 +39,21 @@ class ProtevusHttp2 extends Driver<Socket, ServerTransportStream,
useZone: useZone, useZone: useZone,
) { ) {
if (allowHttp1) { if (allowHttp1) {
_http = ProtevusHttp(app, useZone: useZone); _http = PlatformHttp(app, useZone: useZone);
onHttp1.listen(_http.handleRequest); onHttp1.listen(_http.handleRequest);
} }
} }
factory ProtevusHttp2(Protevus app, SecurityContext securityContext, factory PlatformHttp2(Application app, SecurityContext securityContext,
{bool useZone = true, {bool useZone = true,
bool allowHttp1 = false, bool allowHttp1 = false,
ServerSettings? settings}) { ServerSettings? settings}) {
return ProtevusHttp2.custom(app, securityContext, SecureServerSocket.bind, return PlatformHttp2.custom(app, securityContext, SecureServerSocket.bind,
allowHttp1: allowHttp1, settings: settings); allowHttp1: allowHttp1, settings: settings);
} }
factory ProtevusHttp2.custom( factory PlatformHttp2.custom(
Protevus app, Application app,
SecurityContext ctx, SecurityContext ctx,
Future<SecureServerSocket> Function( Future<SecureServerSocket> Function(
InternetAddress? address, int port, SecurityContext ctx) InternetAddress? address, int port, SecurityContext ctx)
@ -61,7 +61,7 @@ class ProtevusHttp2 extends Driver<Socket, ServerTransportStream,
{bool useZone = true, {bool useZone = true,
bool allowHttp1 = false, bool allowHttp1 = false,
ServerSettings? settings}) { ServerSettings? settings}) {
return ProtevusHttp2._(app, (address, port) { return PlatformHttp2._(app, (address, port) {
var addr = address is InternetAddress var addr = address is InternetAddress
? address ? address
: InternetAddress(address.toString()); : InternetAddress(address.toString());
@ -186,7 +186,7 @@ class _FakeServerSocket extends Stream<Socket> implements ServerSocket {
class _ProtevusHttp2ServerSocket extends Stream<SecureSocket> class _ProtevusHttp2ServerSocket extends Stream<SecureSocket>
implements SecureServerSocket { implements SecureServerSocket {
final SecureServerSocket socket; final SecureServerSocket socket;
final ProtevusHttp2 driver; final PlatformHttp2 driver;
final _ctrl = StreamController<SecureSocket>(); final _ctrl = StreamController<SecureSocket>();
late _FakeServerSocket _fake; late _FakeServerSocket _fake;
StreamSubscription? _sub; StreamSubscription? _sub;
@ -206,7 +206,7 @@ class _ProtevusHttp2ServerSocket extends Stream<SecureSocket>
} else { } else {
socket.destroy(); socket.destroy();
throw Exception( 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, onDone: _ctrl.close,

View file

@ -5,8 +5,8 @@ import 'package:platform_core/core.dart';
import 'package:platform_core/http.dart'; import 'package:platform_core/http.dart';
void main() async { void main() async {
var app = Protevus(); var app = Application();
var http = ProtevusHttp.custom(app, startShared, useZone: false); var http = PlatformHttp.custom(app, startShared, useZone: false);
app.get('/', (req, res) => res.write('Hello, world!')); app.get('/', (req, res) => res.write('Hello, world!'));
app.optimizeForProduction(force: true); app.optimizeForProduction(force: true);

View file

@ -64,7 +64,7 @@ Future<RequestContext> acceptContentTypes(
var rq = MockHttpRequest('GET', endpoint, persistentConnection: false); var rq = MockHttpRequest('GET', endpoint, persistentConnection: false);
rq.headers.set('accept', headerString); rq.headers.set('accept', headerString);
rq.close(); rq.close();
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
var http = ProtevusHttp(app); var http = PlatformHttp(app);
return http.createRequestContext(rq, rq.response); return http.createRequestContext(rq, rq.response);
} }

View file

@ -23,21 +23,21 @@ void main() {
var svc = AnonymousService(); var svc = AnonymousService();
await svc.read(1); await svc.read(1);
throw 'Should have thrown 405!'; throw 'Should have thrown 405!';
} on HttpException { } on PlatformHttpException {
// print('Ok!'); // print('Ok!');
} }
try { try {
var svc = AnonymousService(); var svc = AnonymousService();
await svc.modify(2, null); await svc.modify(2, null);
throw 'Should have thrown 405!'; throw 'Should have thrown 405!';
} on HttpException { } on PlatformHttpException {
// print('Ok!'); // print('Ok!');
} }
try { try {
var svc = AnonymousService(); var svc = AnonymousService();
await svc.update(3, null); await svc.update(3, null);
throw 'Should have thrown 405!'; throw 'Should have thrown 405!';
} on HttpException { } on PlatformHttpException {
// print('Ok!'); // print('Ok!');
} }
}); });

View file

@ -7,8 +7,8 @@ import 'package:platform_mocking/mocking.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
var app = Protevus(); var app = Application();
var http = ProtevusHttp(app); var http = PlatformHttp(app);
Future<RequestContext> request( Future<RequestContext> request(
{bool asJson = true, {bool asJson = true,

View file

@ -70,7 +70,7 @@ bool bar(RequestContext req, ResponseContext res) {
} }
void main() { void main() {
late Protevus app; late Application app;
late TodoController todoController; late TodoController todoController;
late NoExposeController noExposeCtrl; late NoExposeController noExposeCtrl;
late HttpServer server; late HttpServer server;
@ -78,7 +78,7 @@ void main() {
String? url; String? url;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
app.get( app.get(
'/redirect', '/redirect',
(req, res) async => (req, res) async =>
@ -104,7 +104,7 @@ void main() {
print(app.controllers); print(app.controllers);
app.dumpTree(); app.dumpTree();
server = await ProtevusHttp(app).startServer(); server = await PlatformHttp(app).startServer();
url = 'http://${server.address.address}:${server.port}'; url = 'http://${server.address.address}:${server.port}';
}); });
@ -118,20 +118,20 @@ void main() {
}); });
test('create dynamic handler', () async { test('create dynamic handler', () async {
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
app.get( app.get(
'/foo', '/foo',
ioc(({String? bar}) { ioc(({String? bar}) {
return 2; return 2;
}, optional: ['bar'])); }, optional: ['bar']));
var rq = MockHttpRequest('GET', Uri(path: 'foo')); 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(); var body = await utf8.decoder.bind(rq.response).join();
expect(json.decode(body), 2); expect(json.decode(body), 2);
}); });
test('optional name', () async { test('optional name', () async {
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
await app.configure(NamedController().configureServer); await app.configure(NamedController().configureServer);
expect(app.controllers['foo'], const IsInstanceOf<NamedController>()); expect(app.controllers['foo'], const IsInstanceOf<NamedController>());
}); });

View file

@ -5,11 +5,11 @@ import 'package:platform_mocking/mocking.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
late ProtevusHttp http; late PlatformHttp http;
setUp(() async { setUp(() async {
var app = Protevus(); var app = Application();
http = ProtevusHttp(app); http = PlatformHttp(app);
app.get('/detach', (req, res) async { app.get('/detach', (req, res) async {
if (res is HttpResponseContext) { if (res is HttpResponseContext) {

View file

@ -15,13 +15,13 @@ final String sampleText = 'make your bed';
final String sampleOver = 'never'; final String sampleOver = 'never';
void main() { void main() {
late Protevus app; late Application app;
late http.Client client; late http.Client client;
late HttpServer server; late HttpServer server;
String? url; String? url;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
client = http.Client(); client = http.Client();
// Inject some todos // Inject some todos
@ -41,7 +41,7 @@ void main() {
await app.configure(SingletonController().configureServer); await app.configure(SingletonController().configureServer);
await app.configure(ErrandController().configureServer); await app.configure(ErrandController().configureServer);
server = await ProtevusHttp(app).startServer(); server = await PlatformHttp(app).startServer();
url = 'http://${server.address.host}:${server.port}'; url = 'http://${server.address.host}:${server.port}';
}); });
@ -52,7 +52,7 @@ void main() {
}); });
test('runContained with custom container', () async { test('runContained with custom container', () async {
var app = Protevus(); var app = Application();
var c = Container(const MirrorsReflector()); var c = Container(const MirrorsReflector());
c.registerSingleton(Todo(text: 'Hey!')); c.registerSingleton(Todo(text: 'Hey!'));
@ -63,7 +63,7 @@ void main() {
var rq = MockHttpRequest('GET', Uri(path: '/')); var rq = MockHttpRequest('GET', Uri(path: '/'));
await rq.close(); await rq.close();
var rs = rq.response; var rs = rq.response;
await ProtevusHttp(app).handleRequest(rq); await PlatformHttp(app).handleRequest(rq);
var text = await rs.transform(utf8.decoder).join(); var text = await rs.transform(utf8.decoder).join();
expect(text, json.encode('Hey!')); expect(text, json.encode('Hey!'));
}); });

View file

@ -17,10 +17,10 @@ Future<List<int>> getBody(MockHttpResponse rs) async {
} }
void main() { void main() {
late Protevus app; late Application app;
setUp(() { setUp(() {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
app.encoders.addAll( app.encoders.addAll(
{ {
'deflate': zlib.encoder, 'deflate': zlib.encoder,
@ -40,14 +40,14 @@ void main() {
encodingTests(() => app); encodingTests(() => app);
} }
void encodingTests(Protevus Function() getApp) { void encodingTests(Application Function() getApp) {
group('encoding', () { group('encoding', () {
Protevus app; Application app;
late ProtevusHttp http; late PlatformHttp http;
setUp(() { setUp(() {
app = getApp(); app = getApp();
http = ProtevusHttp(app); http = PlatformHttp(app);
}); });
test('sends plaintext if no accept-encoding', () async { test('sends plaintext if no accept-encoding', () async {

View file

@ -4,41 +4,46 @@ import 'package:test/test.dart';
void main() { void main() {
test('named constructors', () { test('named constructors', () {
expect(HttpException.badRequest(), isException(400, '400 Bad Request')); expect(PlatformHttpException.badRequest(),
expect(HttpException.notAuthenticated(), isException(400, '400 Bad Request'));
expect(PlatformHttpException.notAuthenticated(),
isException(401, '401 Not Authenticated')); isException(401, '401 Not Authenticated'));
expect(HttpException.paymentRequired(), expect(PlatformHttpException.paymentRequired(),
isException(402, '402 Payment Required')); 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( expect(
HttpException.notAcceptable(), isException(406, '406 Not Acceptable')); PlatformHttpException.forbidden(), isException(403, '403 Forbidden'));
expect(HttpException.methodTimeout(), isException(408, '408 Timeout')); expect(PlatformHttpException.notFound(), isException(404, '404 Not Found'));
expect(HttpException.conflict(), isException(409, '409 Conflict')); expect(PlatformHttpException.methodNotAllowed(),
expect(HttpException.notProcessable(), 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')); isException(422, '422 Not Processable'));
expect(HttpException.notImplemented(), expect(PlatformHttpException.notImplemented(),
isException(501, '501 Not Implemented')); isException(501, '501 Not Implemented'));
expect(HttpException.unavailable(), isException(503, '503 Unavailable')); expect(PlatformHttpException.unavailable(),
isException(503, '503 Unavailable'));
}); });
test('fromMap', () { test('fromMap', () {
expect(HttpException.fromMap({'status_code': -1, 'message': 'ok'}), expect(PlatformHttpException.fromMap({'status_code': -1, 'message': 'ok'}),
isException(-1, 'ok')); isException(-1, 'ok'));
}); });
test('toMap = toJson', () { test('toMap = toJson', () {
var exc = HttpException.badRequest(); var exc = PlatformHttpException.badRequest();
expect(exc.toMap(), exc.toJson()); expect(exc.toMap(), exc.toJson());
var json_ = json.encode(exc.toJson()); var json_ = json.encode(exc.toJson());
var exc2 = HttpException.fromJson(json_); var exc2 = PlatformHttpException.fromJson(json_);
expect(exc2.toJson(), exc.toJson()); expect(exc2.toJson(), exc.toJson());
}); });
test('toString', () { test('toString', () {
expect(HttpException(statusCode: 420, message: 'Blaze It').toString(), expect(
PlatformHttpException(statusCode: 420, message: 'Blaze It').toString(),
'420: Blaze It'); '420: Blaze It');
}); });
} }
@ -58,7 +63,7 @@ class _IsException extends Matcher {
@override @override
bool matches(item, Map matchState) { bool matches(item, Map matchState) {
return item is HttpException && return item is PlatformHttpException &&
item.statusCode == statusCode && item.statusCode == statusCode &&
item.message == message; item.message == message;
} }

View file

@ -26,7 +26,7 @@ void main() {
Future<RequestContext> makeRequest(String path) { Future<RequestContext> makeRequest(String path) {
var rq = MockHttpRequest('GET', endpoint.replace(path: path))..close(); var rq = MockHttpRequest('GET', endpoint.replace(path: path))..close();
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
var http = ProtevusHttp(app); var http = PlatformHttp(app);
return http.createRequestContext(rq, rq.response); return http.createRequestContext(rq, rq.response);
} }

View file

@ -3,7 +3,8 @@ import 'package:test/test.dart';
import 'common.dart'; import 'common.dart';
void main() { void main() {
var throwsAnHttpException = throwsA(const IsInstanceOf<HttpException>()); var throwsAnHttpException =
throwsA(const IsInstanceOf<PlatformHttpException>());
/* /*
test('throw 404 on null', () { test('throw 404 on null', () {

View file

@ -7,18 +7,18 @@ import 'package:http/http.dart' as http;
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
late Protevus app; late Application app;
late http.Client client; late http.Client client;
late HttpServer server; late HttpServer server;
late String url; late String url;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()) app = Application(reflector: MirrorsReflector())
..post('/foo', (req, res) => res.serialize({'hello': 'world'})) ..post('/foo', (req, res) => res.serialize({'hello': 'world'}))
..all('*', (req, res) => throw HttpException.notFound()); ..all('*', (req, res) => throw PlatformHttpException.notFound());
client = http.Client(); client = http.Client();
server = await ProtevusHttp(app).startServer(); server = await PlatformHttp(app).startServer();
url = 'http://${server.address.host}:${server.port}'; url = 'http://${server.address.host}:${server.port}';
}); });

View file

@ -13,14 +13,14 @@ void main() {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}; };
late Protevus app; late Application app;
late HttpServer server; late HttpServer server;
late String url; late String url;
late http.Client client; late http.Client client;
late HookedService todoService; late HookedService todoService;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
client = http.Client(); client = http.Client();
app.use('/todos', MapService()); app.use('/todos', MapService());
app.use('/books', BookService()); app.use('/books', BookService());
@ -36,7 +36,7 @@ void main() {
throw e.error as Object; throw e.error as Object;
}; };
server = await ProtevusHttp(app).startServer(); server = await PlatformHttp(app).startServer();
url = 'http://${server.address.host}:${server.port}'; url = 'http://${server.address.host}:${server.port}';
}); });

View file

@ -25,12 +25,12 @@ Stream<List<int>> jfkStream() {
void main() { void main() {
var client = Http2Client(); var client = Http2Client();
late IOClient h1c; late IOClient h1c;
Protevus app; Application app;
late ProtevusHttp2 http2; late PlatformHttp2 http2;
late Uri serverRoot; late Uri serverRoot;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()) app = Application(reflector: MirrorsReflector())
..encoders['gzip'] = gzip.encoder; ..encoders['gzip'] = gzip.encoder;
hierarchicalLoggingEnabled = true; hierarchicalLoggingEnabled = true;
app.logger = Logger.detached('protevus.http2') app.logger = Logger.detached('protevus.http2')
@ -106,7 +106,7 @@ void main() {
// Create an HTTP client that trusts our server. // Create an HTTP client that trusts our server.
h1c = IOClient(HttpClient()..badCertificateCallback = (_, __, ___) => true); h1c = IOClient(HttpClient()..badCertificateCallback = (_, __, ___) => true);
http2 = ProtevusHttp2(app, ctx, allowHttp1: true); http2 = PlatformHttp2(app, ctx, allowHttp1: true);
var server = await http2.startServer(); var server = await http2.startServer();
serverRoot = Uri.parse('https://127.0.0.1:${server.port}'); serverRoot = Uri.parse('https://127.0.0.1:${server.port}');

View file

@ -9,7 +9,7 @@ import 'pretty_log.dart';
void main() { void main() {
late http.IOClient client; late http.IOClient client;
late ProtevusHttp driver; late PlatformHttp driver;
late Logger logger; late Logger logger;
setUp(() async { setUp(() async {
@ -20,7 +20,7 @@ void main() {
..level = Level.ALL ..level = Level.ALL
..onRecord.listen(prettyLog); ..onRecord.listen(prettyLog);
var app = Protevus(logger: logger); var app = Application(logger: logger);
app.fallback(hello); app.fallback(hello);
app.fallback(throw404); app.fallback(throw404);
@ -40,7 +40,7 @@ void main() {
} }
}; };
driver = ProtevusHttp(app); driver = PlatformHttp(app);
await driver.startServer(); await driver.startServer();
}); });
@ -76,5 +76,5 @@ Future<void> hello(RequestContext req, ResponseContext res) {
void throw404(RequestContext req, ResponseContext res) { void throw404(RequestContext req, ResponseContext res) {
Zone.current Zone.current
.handleUncaughtError('This 404 should not occur.', StackTrace.current); .handleUncaughtError('This 404 should not occur.', StackTrace.current);
throw HttpException.notFound(); throw PlatformHttpException.notFound();
} }

View file

@ -7,8 +7,8 @@ import 'package:platform_mocking/mocking.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
var app = Protevus(); var app = Application();
var http = ProtevusHttp(app); var http = PlatformHttp(app);
app.get('/default', (req, res) => res.jsonp({'foo': 'bar'})); app.get('/default', (req, res) => res.jsonp({'foo': 'bar'}));

View file

@ -24,12 +24,12 @@ void main() {
} }
void parameterMetaTests() { void parameterMetaTests() {
Protevus app; Application app;
late ProtevusHttp http; late PlatformHttp http;
setUp(() { setUp(() {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
http = ProtevusHttp(app); http = PlatformHttp(app);
app.get('/cookie', ioc((@CookieValue('token') String jwt) { app.get('/cookie', ioc((@CookieValue('token') String jwt) {
return jwt; return jwt;

View file

@ -9,7 +9,7 @@ import 'package:test/test.dart';
void main() { void main() {
test('preinjects functions', () async { test('preinjects functions', () async {
var app = Protevus(reflector: MirrorsReflector()) var app = Application(reflector: MirrorsReflector())
..configuration['foo'] = 'bar' ..configuration['foo'] = 'bar'
..get('/foo', ioc(echoAppFoo)); ..get('/foo', ioc(echoAppFoo));
app.optimizeForProduction(force: true); app.optimizeForProduction(force: true);
@ -18,7 +18,7 @@ void main() {
var rq = MockHttpRequest('GET', Uri(path: '/foo')); var rq = MockHttpRequest('GET', Uri(path: '/foo'));
await rq.close(); await rq.close();
await ProtevusHttp(app).handleRequest(rq); await PlatformHttp(app).handleRequest(rq);
var rs = rq.response; var rs = rq.response;
var body = await rs.transform(utf8.decoder).join(); var body = await rs.transform(utf8.decoder).join();
expect(body, json.encode('bar')); expect(body, json.encode('bar'));

View file

@ -9,13 +9,13 @@ import 'package:platform_mocking/mocking.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
late Protevus app; late Application app;
late ProtevusHttp http; late PlatformHttp http;
setUp(() { setUp(() {
app = Protevus(reflector: MirrorsReflector()) app = Application(reflector: MirrorsReflector())
..configuration['global'] = 305; // Pitbull! ..configuration['global'] = 305; // Pitbull!
http = ProtevusHttp(app); http = PlatformHttp(app);
app.get('/string/:string', ioc((String string) => string)); app.get('/string/:string', ioc((String string) => string));

View file

@ -13,10 +13,10 @@ void main() {
} }
test('can request the same url twice', () async { 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')); ..get('/test/:id', ioc((id) => 'Hello $id'));
var rq1 = mk(1), rq2 = mk(2), rq3 = mk(1); 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(), var body1 = await rq1.response.transform(utf8.decoder).join(),
body2 = await rq2.response.transform(utf8.decoder).join(), body2 = await rq2.response.transform(utf8.decoder).join(),
body3 = await rq3.response.transform(utf8.decoder).join(); body3 = await rq3.response.transform(utf8.decoder).join();

View file

@ -8,7 +8,7 @@ import 'pretty_log.dart';
void main() { void main() {
late http.IOClient client; late http.IOClient client;
late ProtevusHttp driver; late PlatformHttp driver;
late Logger logger; late Logger logger;
late StringBuffer buf; late StringBuffer buf;
@ -21,14 +21,14 @@ void main() {
..level = Level.ALL ..level = Level.ALL
..onRecord.listen(prettyLog); ..onRecord.listen(prettyLog);
var app = Protevus(logger: logger); var app = Application(logger: logger);
app.fallback((req, res) { app.fallback((req, res) {
req.shutdownHooks.add(() => buf.write('Hello, ')); req.shutdownHooks.add(() => buf.write('Hello, '));
req.shutdownHooks.add(() => buf.write('world!')); req.shutdownHooks.add(() => buf.write('world!'));
}); });
driver = ProtevusHttp(app); driver = PlatformHttp(app);
await driver.startServer(); await driver.startServer();
}); });

View file

@ -6,13 +6,13 @@ import 'package:platform_core/src/http/protevus_http.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
late Protevus app; late Application app;
late ProtevusHttp http; late PlatformHttp http;
late HttpClient client; late HttpClient client;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
http = ProtevusHttp(app); http = PlatformHttp(app);
await http.startServer(); await http.startServer();

View file

@ -36,16 +36,16 @@ bool interceptService(RequestContext req, ResponseContext res) {
} }
void main() { void main() {
late Protevus app; late Application app;
late Protevus nested; late Application nested;
late Protevus todos; late Application todos;
late String url; late String url;
late http.Client client; late http.Client client;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
nested = Protevus(reflector: MirrorsReflector()); nested = Application(reflector: MirrorsReflector());
todos = Protevus(reflector: MirrorsReflector()); todos = Application(reflector: MirrorsReflector());
for (var app in [app, nested, todos]) { for (var app in [app, nested, todos]) {
app.logger = Logger('routing_test') app.logger = Logger('routing_test')
@ -113,7 +113,7 @@ void main() {
//app.dumpTree(header: "DUMPING ROUTES:", showMatchers: true); //app.dumpTree(header: "DUMPING ROUTES:", showMatchers: true);
client = http.Client(); 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}'; url = 'http://${server.address.host}:${server.port}';
}); });

View file

@ -8,13 +8,13 @@ import 'package:http_parser/http_parser.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
late Protevus app; late Application app;
late http.Client client; late http.Client client;
late HttpServer server; late HttpServer server;
late String url; late String url;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()) app = Application(reflector: MirrorsReflector())
..get('/foo', ioc(() => {'hello': 'world'})) ..get('/foo', ioc(() => {'hello': 'world'}))
..get('/bar', (req, res) async { ..get('/bar', (req, res) async {
await res.serialize({'hello': 'world'}, await res.serialize({'hello': 'world'},
@ -22,7 +22,7 @@ void main() {
}); });
client = http.Client(); client = http.Client();
server = await ProtevusHttp(app).startServer(); server = await PlatformHttp(app).startServer();
url = 'http://${server.address.host}:${server.port}'; url = 'http://${server.address.host}:${server.port}';
}); });

View file

@ -14,9 +14,9 @@ final Uri $foo = Uri.parse('http://localhost:3000/foo');
/// Additional tests to improve coverage of server.dart /// Additional tests to improve coverage of server.dart
void main() { void main() {
group('scoping', () { group('scoping', () {
var parent = Protevus(reflector: MirrorsReflector()) var parent = Application(reflector: MirrorsReflector())
..configuration['two'] = 2; ..configuration['two'] = 2;
var child = Protevus(reflector: MirrorsReflector()); var child = Application(reflector: MirrorsReflector());
parent.mount('/child', child); parent.mount('/child', child);
test('sets children', () { test('sets children', () {
@ -33,20 +33,20 @@ void main() {
}); });
test('custom server generator', () { test('custom server generator', () {
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
var http = ProtevusHttp.custom(app, HttpServer.bind); var http = PlatformHttp.custom(app, HttpServer.bind);
expect(http.serverGenerator, HttpServer.bind); expect(http.serverGenerator, HttpServer.bind);
}); });
test('default error handler', () async { test('default error handler', () async {
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
var http = ProtevusHttp(app); var http = PlatformHttp(app);
var rq = MockHttpRequest('GET', $foo); var rq = MockHttpRequest('GET', $foo);
await (rq.close()); await (rq.close());
var rs = rq.response; var rs = rq.response;
var req = await http.createRequestContext(rq, rs); var req = await http.createRequestContext(rq, rs);
var res = await http.createResponseContext(rq, rs); var res = await http.createResponseContext(rq, rs);
var e = HttpException( var e = PlatformHttpException(
statusCode: 321, message: 'Hello', errors: ['foo', 'bar']); statusCode: 321, message: 'Hello', errors: ['foo', 'bar']);
await app.errorHandler(e, req, res); await app.errorHandler(e, req, res);
await http.sendResponse(rq, rs, req, res); await http.sendResponse(rq, rs, req, res);
@ -62,10 +62,10 @@ void main() {
}); });
test('plug-ins run on startup', () async { 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); app.startupHooks.add((app) => app.configuration['two'] = 2);
var http = ProtevusHttp(app); var http = PlatformHttp(app);
await http.startServer(); await http.startServer();
expect(app.configuration['two'], 2); expect(app.configuration['two'], 2);
await app.close(); await app.close();
@ -73,7 +73,7 @@ void main() {
}); });
test('warning when adding routes to flattened router', () { test('warning when adding routes to flattened router', () {
var app = Protevus(reflector: MirrorsReflector()) var app = Application(reflector: MirrorsReflector())
..optimizeForProduction(force: true); ..optimizeForProduction(force: true);
app.dumpTree(); app.dumpTree();
app.get('/', (req, res) => 2); app.get('/', (req, res) => 2);
@ -81,7 +81,7 @@ void main() {
}); });
test('services close on close call', () async { test('services close on close call', () async {
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
var svc = CustomCloseService(); var svc = CustomCloseService();
expect(svc.value, 2); expect(svc.value, 2);
app.use('/', svc); app.use('/', svc);
@ -90,8 +90,9 @@ void main() {
}); });
test('global injection added to injection map', () async { test('global injection added to injection map', () async {
var app = Protevus(reflector: MirrorsReflector())..configuration['a'] = 'b'; var app = Application(reflector: MirrorsReflector())
var http = ProtevusHttp(app); ..configuration['a'] = 'b';
var http = PlatformHttp(app);
app.get('/', ioc((String a) => a)); app.get('/', ioc((String a) => a));
var rq = MockHttpRequest('GET', Uri.parse('/')); var rq = MockHttpRequest('GET', Uri.parse('/'));
await (rq.close()); await (rq.close());
@ -101,8 +102,9 @@ void main() {
}); });
test('global injected serializer', () async { test('global injected serializer', () async {
var app = Protevus(reflector: MirrorsReflector())..serializer = (_) => 'x'; var app = Application(reflector: MirrorsReflector())
var http = ProtevusHttp(app); ..serializer = (_) => 'x';
var http = PlatformHttp(app);
app.get($foo.path, (req, ResponseContext res) => res.serialize(null)); app.get($foo.path, (req, ResponseContext res) => res.serialize(null));
var rq = MockHttpRequest('GET', $foo); var rq = MockHttpRequest('GET', $foo);
await (rq.close()); await (rq.close());
@ -112,9 +114,10 @@ void main() {
}); });
group('handler results', () { group('handler results', () {
var app = Protevus(reflector: MirrorsReflector()); var app = Application(reflector: MirrorsReflector());
var http = ProtevusHttp(app); var http = PlatformHttp(app);
app.responseFinalizers.add((req, res) => throw HttpException.forbidden()); app.responseFinalizers
.add((req, res) => throw PlatformHttpException.forbidden());
late RequestContext req; late RequestContext req;
late ResponseContext res; late ResponseContext res;
@ -154,14 +157,14 @@ void main() {
}); });
group('handleHttpException', () { group('handleHttpException', () {
late Protevus app; late Application app;
late ProtevusHttp http; late PlatformHttp http;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
app.get('/wtf', (req, res) => throw HttpException.forbidden()); app.get('/wtf', (req, res) => throw PlatformHttpException.forbidden());
app.get('/wtf2', (req, res) => throw HttpException.forbidden()); app.get('/wtf2', (req, res) => throw PlatformHttpException.forbidden());
http = ProtevusHttp(app); http = PlatformHttp(app);
await http.startServer('127.0.0.1', 0); await http.startServer('127.0.0.1', 0);
var oldHandler = app.errorHandler; var oldHandler = app.errorHandler;

View file

@ -16,20 +16,20 @@ void main() {
'Accept': 'application/json', 'Accept': 'application/json',
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}; };
late Protevus app; late Application app;
late MapService service; late MapService service;
late String url; late String url;
late http.Client client; late http.Client client;
setUp(() async { setUp(() async {
app = Protevus(reflector: MirrorsReflector()) app = Application(reflector: MirrorsReflector())
..use('/todos', service = MapService()) ..use('/todos', service = MapService())
..errorHandler = (e, req, res) { ..errorHandler = (e, req, res) {
if (e.error != null) print('Whoops: ${e.error}'); if (e.error != null) print('Whoops: ${e.error}');
if (e.stackTrace != null) print(Chain.forTrace(e.stackTrace!).terse); 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(); client = http.Client();
url = 'http://${server.address.host}:${server.port}'; url = 'http://${server.address.host}:${server.port}';
}); });

View file

@ -13,12 +13,12 @@ import 'package:test/test.dart';
import 'encoders_buffer_test.dart' show encodingTests; import 'encoders_buffer_test.dart' show encodingTests;
void main() { void main() {
late Protevus app; late Application app;
late ProtevusHttp http; late PlatformHttp http;
setUp(() { setUp(() {
app = Protevus(reflector: MirrorsReflector()); app = Application(reflector: MirrorsReflector());
http = ProtevusHttp(app, useZone: true); http = PlatformHttp(app, useZone: true);
app.logger = Logger('streaming_test') app.logger = Logger('streaming_test')
..onRecord.listen((rec) { ..onRecord.listen((rec) {

View file

@ -3,7 +3,7 @@ import 'package:test/test.dart';
void main() { void main() {
test('default view generator', () async { test('default view generator', () async {
var app = Protevus(); var app = Application();
var view = await app.viewGenerator!('foo', {'bar': 'baz'}); var view = await app.viewGenerator!('foo', {'bar': 'baz'});
expect(view, contains('No view engine')); expect(view, contains('No view engine'));
}); });

View file

@ -1,3 +1,4 @@
import 'package:platform_exceptions/http_exception.dart'; 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!");

View file

@ -1,4 +1,4 @@
library http_exception; library platform_http_exception;
//import 'package:dart2_constant/convert.dart'; //import 'package:dart2_constant/convert.dart';
import 'dart:convert'; import 'dart:convert';
@ -8,7 +8,7 @@ import 'dart:convert';
/// ///
/// Originally inspired by /// Originally inspired by
/// [feathers-errors](https://github.com/feathersjs/feathers-errors). /// [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. /// A list of errors that occurred when this exception was thrown.
final List<String> errors = []; final List<String> errors = [];
@ -24,7 +24,7 @@ class HttpException implements Exception {
/// An HTTP status code this exception will throw. /// An HTTP status code this exception will throw.
int statusCode; int statusCode;
HttpException( PlatformHttpException(
{this.message = '500 Internal Server Error', {this.message = '500 Internal Server Error',
this.stackTrace, this.stackTrace,
this.statusCode = 500, this.statusCode = 500,
@ -49,8 +49,8 @@ class HttpException implements Exception {
return '$statusCode: $message'; return '$statusCode: $message';
} }
factory HttpException.fromMap(Map data) { factory PlatformHttpException.fromMap(Map data) {
return HttpException( return PlatformHttpException(
statusCode: (data['status_code'] ?? data['statusCode'] ?? 500) as int, statusCode: (data['status_code'] ?? data['statusCode'] ?? 500) as int,
message: data['message']?.toString() ?? 'Internal Server Error', message: data['message']?.toString() ?? 'Internal Server Error',
errors: data['errors'] is Iterable errors: data['errors'] is Iterable
@ -59,63 +59,65 @@ class HttpException implements Exception {
); );
} }
factory HttpException.fromJson(String str) => factory PlatformHttpException.fromJson(String str) =>
HttpException.fromMap(json.decode(str) as Map); PlatformHttpException.fromMap(json.decode(str) as Map);
/// Throws a 400 Bad Request error, including an optional arrray of (validation?) /// Throws a 400 Bad Request error, including an optional arrray of (validation?)
/// errors you specify. /// errors you specify.
factory HttpException.badRequest( factory PlatformHttpException.badRequest(
{String message = '400 Bad Request', {String message = '400 Bad Request',
List<String> errors = const []}) => List<String> errors = const []}) =>
HttpException(message: message, errors: errors, statusCode: 400); PlatformHttpException(message: message, errors: errors, statusCode: 400);
/// Throws a 401 Not Authenticated error. /// Throws a 401 Not Authenticated error.
factory HttpException.notAuthenticated( factory PlatformHttpException.notAuthenticated(
{String message = '401 Not Authenticated'}) => {String message = '401 Not Authenticated'}) =>
HttpException(message: message, statusCode: 401); PlatformHttpException(message: message, statusCode: 401);
/// Throws a 402 Payment Required error. /// Throws a 402 Payment Required error.
factory HttpException.paymentRequired( factory PlatformHttpException.paymentRequired(
{String message = '402 Payment Required'}) => {String message = '402 Payment Required'}) =>
HttpException(message: message, statusCode: 402); PlatformHttpException(message: message, statusCode: 402);
/// Throws a 403 Forbidden error. /// Throws a 403 Forbidden error.
factory HttpException.forbidden({String message = '403 Forbidden'}) => factory PlatformHttpException.forbidden({String message = '403 Forbidden'}) =>
HttpException(message: message, statusCode: 403); PlatformHttpException(message: message, statusCode: 403);
/// Throws a 404 Not Found error. /// Throws a 404 Not Found error.
factory HttpException.notFound({String message = '404 Not Found'}) => factory PlatformHttpException.notFound({String message = '404 Not Found'}) =>
HttpException(message: message, statusCode: 404); PlatformHttpException(message: message, statusCode: 404);
/// Throws a 405 Method Not Allowed error. /// Throws a 405 Method Not Allowed error.
factory HttpException.methodNotAllowed( factory PlatformHttpException.methodNotAllowed(
{String message = '405 Method Not Allowed'}) => {String message = '405 Method Not Allowed'}) =>
HttpException(message: message, statusCode: 405); PlatformHttpException(message: message, statusCode: 405);
/// Throws a 406 Not Acceptable error. /// Throws a 406 Not Acceptable error.
factory HttpException.notAcceptable( factory PlatformHttpException.notAcceptable(
{String message = '406 Not Acceptable'}) => {String message = '406 Not Acceptable'}) =>
HttpException(message: message, statusCode: 406); PlatformHttpException(message: message, statusCode: 406);
/// Throws a 408 Timeout error. /// Throws a 408 Timeout error.
factory HttpException.methodTimeout({String message = '408 Timeout'}) => factory PlatformHttpException.methodTimeout(
HttpException(message: message, statusCode: 408); {String message = '408 Timeout'}) =>
PlatformHttpException(message: message, statusCode: 408);
/// Throws a 409 Conflict error. /// Throws a 409 Conflict error.
factory HttpException.conflict({String message = '409 Conflict'}) => factory PlatformHttpException.conflict({String message = '409 Conflict'}) =>
HttpException(message: message, statusCode: 409); PlatformHttpException(message: message, statusCode: 409);
/// Throws a 422 Not Processable error. /// Throws a 422 Not Processable error.
factory HttpException.notProcessable( factory PlatformHttpException.notProcessable(
{String message = '422 Not Processable'}) => {String message = '422 Not Processable'}) =>
HttpException(message: message, statusCode: 422); PlatformHttpException(message: message, statusCode: 422);
/// Throws a 501 Not Implemented error. /// Throws a 501 Not Implemented error.
factory HttpException.notImplemented( factory PlatformHttpException.notImplemented(
{String message = '501 Not Implemented'}) => {String message = '501 Not Implemented'}) =>
HttpException(message: message, statusCode: 501); PlatformHttpException(message: message, statusCode: 501);
/// Throws a 503 Unavailable error. /// Throws a 503 Unavailable error.
factory HttpException.unavailable({String message = '503 Unavailable'}) => factory PlatformHttpException.unavailable(
HttpException(message: message, statusCode: 503); {String message = '503 Unavailable'}) =>
PlatformHttpException(message: message, statusCode: 503);
} }

View file

@ -20,7 +20,7 @@ void main() {
return res.serialize(req.ip == InternetAddress.loopbackIPv4.address); return res.serialize(req.ip == InternetAddress.loopbackIPv4.address);
}); });
var http = ProtevusHttp(app); var http = PlatformHttp(app);
test('receive a response', () async { test('receive a response', () async {
var rq = MockHttpRequest('GET', uri.resolve('/foo')); var rq = MockHttpRequest('GET', uri.resolve('/foo'));