From 388bdc856716c45ab5c37ca97cd6effba9c81ba2 Mon Sep 17 00:00:00 2001 From: David Morgan Date: Fri, 25 Nov 2016 10:12:57 +0100 Subject: [PATCH] Deleted. Use built_value instead. --- .gitignore | 10 - .travis.yml | 14 - CHANGELOG.md | 4 + README.md | 82 +- built_json/LICENSE | 28 - built_json/lib/built_json.dart | 183 ----- built_json/lib/src/bool_serializer.dart | 24 - .../lib/src/built_json_serializers.dart | 179 ---- built_json/lib/src/built_list_serializer.dart | 53 -- built_json/lib/src/built_map_serializer.dart | 74 -- built_json/lib/src/built_set_serializer.dart | 51 -- built_json/lib/src/double_serializer.dart | 25 - built_json/lib/src/int_serializer.dart | 24 - built_json/lib/src/string_serializer.dart | 24 - built_json/pubspec.yaml | 17 +- built_json/test/bool_serializer_test.dart | 40 - .../test/built_list_serializer_test.dart | 111 --- .../test/built_map_serializer_test.dart | 284 ------- .../test/built_set_serializer_test.dart | 115 --- built_json/test/double_serializer_test.dart | 40 - built_json/test/int_serializer_test.dart | 40 - built_json/test/string_serializer_test.dart | 40 - built_json_generator/LICENSE | 28 - .../lib/built_json_generator.dart | 27 - .../lib/src/library_elements.dart | 45 -- .../lib/src/source_class.dart | 209 ----- .../lib/src/source_class.g.dart | 74 -- .../lib/src/source_field.dart | 135 ---- .../lib/src/source_field.g.dart | 92 --- .../lib/src/source_library.dart | 86 -- .../lib/src/source_library.g.dart | 72 -- built_json_generator/pubspec.yaml | 24 +- .../test/built_json_generator_test.dart | 526 ------------ built_json_generator/tool/build.dart | 17 - chat_example/.analysis_options | 2 - chat_example/README.md | 17 - chat_example/bin/main.dart | 13 - chat_example/lib/client/client.dart | 126 --- .../lib/client/client_connection.dart | 12 - chat_example/lib/client/display.dart | 12 - chat_example/lib/client/html_display.dart | 34 - .../lib/client/http_client_connection.dart | 32 - chat_example/lib/client/input.dart | 25 - chat_example/lib/client/layout.dart | 22 - chat_example/lib/data_model/data_model.dart | 156 ---- chat_example/lib/data_model/data_model.g.dart | 762 ------------------ chat_example/lib/data_model/serializers.dart | 14 - .../lib/data_model/serializers.g.dart | 29 - .../lib/server/http_server_connection.dart | 35 - chat_example/lib/server/resource_server.dart | 75 -- chat_example/lib/server/server.dart | 129 --- .../lib/server/server_connection.dart | 16 - .../lib/testing/fake_client_connection.dart | 23 - chat_example/lib/testing/fake_display.dart | 18 - .../lib/testing/fake_environment.dart | 47 -- .../lib/testing/fake_server_connection.dart | 29 - chat_example/lib/testing/test_user.dart | 31 - chat_example/pubspec.yaml | 24 - chat_example/test/chat_test.dart | 147 ---- chat_example/tool/build.dart | 24 - chat_example/tool/watch.dart | 25 - chat_example/web/index.html | 10 - chat_example/web/main.css | 38 - chat_example/web/main.dart | 15 - example/lib/collections.dart | 40 - example/lib/collections.g.dart | 135 ---- example/lib/compound_value.dart | 31 - example/lib/compound_value.g.dart | 138 ---- example/lib/has_int.dart | 85 -- example/lib/has_int.g.dart | 164 ---- example/lib/serializers.dart | 22 - example/lib/serializers.g.dart | 29 - example/lib/test_enum.dart | 29 - example/lib/test_enum.g.dart | 55 -- example/lib/value.dart | 32 - example/lib/value.g.dart | 174 ---- example/pubspec.yaml | 22 - example/test/collections_test.dart | 34 - example/test/compound_value_test.dart | 54 -- example/test/has_int_test.dart | 39 - example/test/test_enum_test.dart | 22 - example/test/value_test.dart | 36 - example/tool/build.dart | 31 - 83 files changed, 11 insertions(+), 5900 deletions(-) delete mode 100644 .gitignore delete mode 100644 .travis.yml delete mode 100644 built_json/LICENSE delete mode 100644 built_json/lib/built_json.dart delete mode 100644 built_json/lib/src/bool_serializer.dart delete mode 100644 built_json/lib/src/built_json_serializers.dart delete mode 100644 built_json/lib/src/built_list_serializer.dart delete mode 100644 built_json/lib/src/built_map_serializer.dart delete mode 100644 built_json/lib/src/built_set_serializer.dart delete mode 100644 built_json/lib/src/double_serializer.dart delete mode 100644 built_json/lib/src/int_serializer.dart delete mode 100644 built_json/lib/src/string_serializer.dart delete mode 100644 built_json/test/bool_serializer_test.dart delete mode 100644 built_json/test/built_list_serializer_test.dart delete mode 100644 built_json/test/built_map_serializer_test.dart delete mode 100644 built_json/test/built_set_serializer_test.dart delete mode 100644 built_json/test/double_serializer_test.dart delete mode 100644 built_json/test/int_serializer_test.dart delete mode 100644 built_json/test/string_serializer_test.dart delete mode 100644 built_json_generator/LICENSE delete mode 100644 built_json_generator/lib/built_json_generator.dart delete mode 100644 built_json_generator/lib/src/library_elements.dart delete mode 100644 built_json_generator/lib/src/source_class.dart delete mode 100644 built_json_generator/lib/src/source_class.g.dart delete mode 100644 built_json_generator/lib/src/source_field.dart delete mode 100644 built_json_generator/lib/src/source_field.g.dart delete mode 100644 built_json_generator/lib/src/source_library.dart delete mode 100644 built_json_generator/lib/src/source_library.g.dart delete mode 100644 built_json_generator/test/built_json_generator_test.dart delete mode 100644 built_json_generator/tool/build.dart delete mode 100644 chat_example/.analysis_options delete mode 100644 chat_example/README.md delete mode 100644 chat_example/bin/main.dart delete mode 100644 chat_example/lib/client/client.dart delete mode 100644 chat_example/lib/client/client_connection.dart delete mode 100644 chat_example/lib/client/display.dart delete mode 100644 chat_example/lib/client/html_display.dart delete mode 100644 chat_example/lib/client/http_client_connection.dart delete mode 100644 chat_example/lib/client/input.dart delete mode 100644 chat_example/lib/client/layout.dart delete mode 100644 chat_example/lib/data_model/data_model.dart delete mode 100644 chat_example/lib/data_model/data_model.g.dart delete mode 100644 chat_example/lib/data_model/serializers.dart delete mode 100644 chat_example/lib/data_model/serializers.g.dart delete mode 100644 chat_example/lib/server/http_server_connection.dart delete mode 100644 chat_example/lib/server/resource_server.dart delete mode 100644 chat_example/lib/server/server.dart delete mode 100644 chat_example/lib/server/server_connection.dart delete mode 100644 chat_example/lib/testing/fake_client_connection.dart delete mode 100644 chat_example/lib/testing/fake_display.dart delete mode 100644 chat_example/lib/testing/fake_environment.dart delete mode 100644 chat_example/lib/testing/fake_server_connection.dart delete mode 100644 chat_example/lib/testing/test_user.dart delete mode 100644 chat_example/pubspec.yaml delete mode 100644 chat_example/test/chat_test.dart delete mode 100644 chat_example/tool/build.dart delete mode 100644 chat_example/tool/watch.dart delete mode 100644 chat_example/web/index.html delete mode 100644 chat_example/web/main.css delete mode 100644 chat_example/web/main.dart delete mode 100644 example/lib/collections.dart delete mode 100644 example/lib/collections.g.dart delete mode 100644 example/lib/compound_value.dart delete mode 100644 example/lib/compound_value.g.dart delete mode 100644 example/lib/has_int.dart delete mode 100644 example/lib/has_int.g.dart delete mode 100644 example/lib/serializers.dart delete mode 100644 example/lib/serializers.g.dart delete mode 100644 example/lib/test_enum.dart delete mode 100644 example/lib/test_enum.g.dart delete mode 100644 example/lib/value.dart delete mode 100644 example/lib/value.g.dart delete mode 100644 example/pubspec.yaml delete mode 100644 example/test/collections_test.dart delete mode 100644 example/test/compound_value_test.dart delete mode 100644 example/test/has_int_test.dart delete mode 100644 example/test/test_enum_test.dart delete mode 100644 example/test/value_test.dart delete mode 100644 example/tool/build.dart diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 3296fe5..0000000 --- a/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -.buildlog -.DS_Store -.idea -.pub/ -.settings/ -*.iml -**/build -**/packages -**/pubspec.lock -**/.packages diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7688726..0000000 --- a/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: dart -dart: stable -script: - - cd built_json_generator - - pub get - - pub run test - - cd ../example - - pub get - - dart tool/build.dart - - pub run test - - cd ../chat_example - - pub get - - dart tool/build.dart - - pub run test diff --git a/CHANGELOG.md b/CHANGELOG.md index f3e4ed0..85e50df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.2.0 + +- Deleted. Equivalent functionality is now available from built_value. + ## 0.1.5 - Allow quiver 0.23. diff --git a/README.md b/README.md index 8e14b59..ab817c1 100644 --- a/README.md +++ b/README.md @@ -1,83 +1,3 @@ # Built JSON for Dart -[![Build Status](https://travis-ci.org/google/built_json.dart.svg?branch=master)](https://travis-ci.org/google/built_json.dart) -## Introduction -Built JSON provides serialization for the [Libraries for Object Oriented Dart] -(https://github.com/google/built_value.dart/blob/master/libraries_for_object_oriented_dart.md#libraries-for-object-oriented-dart). - -This allows a complete serializable object oriented data model to be based on -[Enum Classes](https://github.com/google/enum_class.dart#enum-classes-for-dart), -[Built Collections] -(https://github.com/google/built_collection.dart#built-collections-for-dart) and -[Built Values] -(https://github.com/google/built_value.dart#built-values-for-dart). - -Built JSON for Java, a separate project, will provide compatible serialization -for Java, mapping Enum Classes to standard Java enums, Built Collections to -[Immutable Collections] -(https://github.com/google/guava/wiki/ImmutableCollectionsExplained) and Built -Values to [AutoValues] -(https://github.com/google/auto/tree/master/value#autovalue). - - -## Example Code - -[Simple examples] -(https://github.com/google/built_json.dart/tree/master/example); for a more -realistic project see the -[chat example](https://github.com/google/built_json.dart/tree/master/chat_example) -for an end to end use of built_json on server and client. - - -## Motivation - -There are many ways to serialize data. Why do we need another? - -Built JSON is about serialization of object oriented data. There are many ways -to do this, too. Built JSON is different to other libraries for a number of -reasons: - -Built JSON _fully supports object oriented design_: any object model that you -can design can be serialized, including full use of generics and interfaces. -Some other libraries require concrete types or do not fully support generics. - -Built JSON _allows different object oriented models over the same data_. For -example, in a client server application, it's likely that the client and server -want different functionality from their data model. So, they are allowed to have -different classes that map to the same data. Most other libraries enforce a 1:1 -mapping between classes and types on the wire. - -Built JSON _requires well behaved types_. They must be immutable, can use -interface but not concrete inheritance, must have predictable nullability, -`hashCode`, `equals` and `toString`. In fact, they must be Enum Classes, Built -Collections or Built Values. Some other libraries allow badly behaved types to -be serialized. - -Built JSON _supports changes to the data model_. Optional fields can be added or -removed, and fields can be switched from optional to required, allowing your -data model to evolve without breaking compatbility. Some other libraries break -compatability on any change to any serializable class. - -Built JSON _is modular_. Each endpoint can choose which classes to know about; -for example, you can have multiple clients that each know about only a subset of -the classes the server knows. Most other libraries are monolithic, requiring all -endpoints to know all types. - -Built JSON _is multi language_. Support will be come first for Dart, Java and -Java/GWT. Many other libraries support a single language only. - -Built JSON _has first class support for validation_ via Built Values. An -important part of a powerful data model is ensuring it's valid, so classes can -make guarantees about what they can do. Other libraries also support validation -but usually in a less prominent way. - -And, finally, Built JSON _is pluggable_. Arbitrary extensions can be added to -give custom JSON serialization for your own types. This could be used to -interoperate with other tools or to add hand coded high performance serializers -for specific classes. Some other libraries are not so extensible. - -## Features and bugs - -Please file feature requests and bugs at the [issue tracker][tracker]. - -[tracker]: https://github.com/google/built_json.dart/issues +Now available from [built_value](https://github.com/google/built_value.dart). diff --git a/built_json/LICENSE b/built_json/LICENSE deleted file mode 100644 index ec8a981..0000000 --- a/built_json/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2015, Google Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/built_json/lib/built_json.dart b/built_json/lib/built_json.dart deleted file mode 100644 index b3023e7..0000000 --- a/built_json/lib/built_json.dart +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library built_json; - -import 'src/bool_serializer.dart'; -import 'src/built_json_serializers.dart'; -import 'src/built_list_serializer.dart'; -import 'src/built_map_serializer.dart'; -import 'src/built_set_serializer.dart'; -import 'src/double_serializer.dart'; -import 'src/int_serializer.dart'; -import 'src/string_serializer.dart'; - -export 'package:built_collection/built_collection.dart' show BuiltList; - -/// Serializes all known classes. -/// -/// See: https://github.com/google/built_json.dart/tree/master/example -abstract class Serializers { - /// Default [Serializers] that can serialize primitives and collections. - /// - /// Use [toBuilder] to add more serializers. - factory Serializers() { - return (new SerializersBuilder() - ..add(new BoolSerializer()) - ..add(new BuiltListSerializer()) - ..add(new BuiltMapSerializer()) - ..add(new BuiltSetSerializer()) - ..add(new DoubleSerializer()) - ..add(new IntSerializer()) - ..add(new StringSerializer())).build(); - } - - /// Serializes [object]. - /// - /// A [Serializer] must have been provided for every type the object uses. - /// - /// Types that are known statically can be provided via [specifiedType]. This - /// will reduce the amount of data needed on the wire. The exact same - /// [specifiedType] will be needed to deserialize. - /// - /// Create one using [SerializersBuilder]. - /// - /// TODO(davidmorgan): document the wire format. - Object serialize(Object object, - {FullType specifiedType: FullType.unspecified}); - - /// Deserializes [serialized]. - /// - /// A [Serializer] must have been provided for every type the object uses. - /// - /// If [serialized] was produced by calling [serialize] with [specifiedType], - /// the exact same [specifiedType] must be provided to deserialize. - Object deserialize(Object serialized, - {FullType specifiedType: FullType.unspecified}); - - /// Creates a new builder for the type represented by [fullType]. - /// - /// For example, if [fullType] is `BuiltList`, returns a - /// `ListBuilder`. This helps serializers to instantiate with - /// correct generic type parameters. - /// - /// May return null if no matching builder factory has been added. In this - /// case the serializer should throw a [StateError]. - Object newBuilder(FullType fullType); - - /// Whether a builder for [fullType] is available via [newBuilder]. - bool hasBuilder(FullType fullType); - - SerializersBuilder toBuilder(); -} - -/// Builder for [Serializers]. -abstract class SerializersBuilder { - factory SerializersBuilder() = BuiltJsonSerializersBuilder; - - void add(Serializer serializer); - - void addBuilderFactory(FullType specifiedType, Function function); - - Serializers build(); -} - -/// A [Type] with, optionally, [FullType] generic type parameters. -/// -/// May also be [unspecified], indicating that no type information is -/// available. -class FullType { - // An unspecified type. - static const unspecified = const FullType(null); - - /// The root of the type. - final Type root; - - /// Type parameters of the type. - final List parameters; - - const FullType(this.root, [this.parameters = const []]); - - bool get isUnspecified => identical(root, null); - - @override - String toString() => isUnspecified - ? 'unspecified' - : parameters.isEmpty - ? root.toString() - : '${root.toString()}<${parameters.join(", ")}>'; -} - -/// Serializes a single type. -/// -/// You should not usually need to implement this interface. Implementations -/// are provided for collections and primitives in `built_json`. Classes using -/// `built_value` and enums using `EnumClass` can have implementations -/// generated using `built_json_generator`. -/// -/// Implementations must extend either [PrimitiveSerializer] or -/// [StructuredSerializer]. -abstract class Serializer { - /// The [Type]s that can be serialized. - /// - /// They must all be equal to T or a subclass of T. Subclasses are used when - /// T is an abstract class, which is the case with built_value generated - /// serializers. - Iterable get types; - - /// The wire name of the serializable type. For most classes, the class name. - /// For primitives and collections a lower-case name is defined as part of - /// the `built_json` wire format. - String get wireName; -} - -/// A [Serializer] that serializes to and from primitive JSON values. -abstract class PrimitiveSerializer implements Serializer { - /// Serializes [object]. - /// - /// Use [serializers] as needed for nested serialization. Information about - /// the type being serialized is provided in [specifiedType]. - /// - /// Returns a value that can be represented as a JSON primitive: a boolean, - /// an integer, a double, or a String. - /// - /// TODO(davidmorgan): document the wire format. - Object serialize(Serializers serializers, T object, - {FullType specifiedType: FullType.unspecified}); - - /// Deserializes [serialized]. - /// - /// [serialized] is a boolean, an integer, a double or a String. - /// - /// Use [serializers] as needed for nested deserialization. Information about - /// the type being deserialized is provided in [specifiedType]. - T deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}); -} - -/// A [Serializer] that serializes to and from an [Iterable] of primitive JSON -/// values. -abstract class StructuredSerializer implements Serializer { - /// Serializes [object]. - /// - /// Use [serializers] as needed for nested serialization. Information about - /// the type being serialized is provided in [specifiedType]. - /// - /// Returns an [Iterable] of values that can be represented as structured - /// JSON: booleans, integers, doubles, Strings and [Iterable]s. - /// - /// TODO(davidmorgan): document the wire format. - Iterable serialize(Serializers serializers, T object, - {FullType specifiedType: FullType.unspecified}); - - /// Deserializes [serialized]. - /// - /// [serialized] is an [Iterable] that may contain booleans, integers, - /// doubles, Strings and/or [Iterable]s. - /// - /// Use [serializers] as needed for nested deserialization. Information about - /// the type being deserialized is provided in [specifiedType]. - T deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}); -} diff --git a/built_json/lib/src/bool_serializer.dart b/built_json/lib/src/bool_serializer.dart deleted file mode 100644 index 1049b4f..0000000 --- a/built_json/lib/src/bool_serializer.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -class BoolSerializer implements PrimitiveSerializer { - final bool structured = false; - final Iterable types = new BuiltList([bool]); - final String wireName = 'bool'; - - @override - Object serialize(Serializers serializers, bool boolean, - {FullType specifiedType: FullType.unspecified}) { - return boolean; - } - - @override - bool deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return serialized as bool; - } -} diff --git a/built_json/lib/src/built_json_serializers.dart b/built_json/lib/src/built_json_serializers.dart deleted file mode 100644 index 52f1ac0..0000000 --- a/built_json/lib/src/built_json_serializers.dart +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. - -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -/// Default implementation of [Serializers]. -class BuiltJsonSerializers implements Serializers { - final BuiltMap _typeToSerializer; - - // Implementation note: wire name is what gets sent in the JSON, type name is - // the runtime type name. Type name is complicated for two reasons: - // - // 1. Built Value classes have two types, the abstract class and the - // generated implementation. - // - // 2. When compiled to javascript the runtime type names are obfuscated. - final BuiltMap _wireNameToSerializer; - final BuiltMap _typeNameToSerializer; - - final BuiltMap _builderFactories; - - BuiltJsonSerializers._(this._typeToSerializer, this._wireNameToSerializer, - this._typeNameToSerializer, this._builderFactories); - - @override - Object serialize(Object object, - {FullType specifiedType: FullType.unspecified}) { - if (specifiedType.isUnspecified) { - final serializer = _getSerializerByType(object.runtimeType); - if (serializer == null) { - throw new StateError("No serializer for '${object.runtimeType}'."); - } - if (serializer is StructuredSerializer) { - final result = [serializer.wireName]; - return result..addAll(serializer.serialize(this, object)); - } else if (serializer is PrimitiveSerializer) { - return [ - serializer.wireName, - serializer.serialize(this, object) - ]; - } else { - throw new StateError( - 'serializer must be StructuredSerializer or PrimitiveSerializer'); - } - } else { - final serializer = _getSerializerByType(specifiedType.root); - if (serializer == null) { - // Might be an interface; try resolving using the runtime type. - return serialize(object); - } - if (serializer is StructuredSerializer) { - return serializer - .serialize(this, object, specifiedType: specifiedType) - .toList(); - } else if (serializer is PrimitiveSerializer) { - return serializer.serialize(this, object, specifiedType: specifiedType); - } else { - throw new StateError( - 'serializer must be StructuredSerializer or PrimitiveSerializer'); - } - } - } - - @override - Object deserialize(Object object, - {FullType specifiedType: FullType.unspecified}) { - if (specifiedType.isUnspecified) { - final wireName = (object as List).first; - - final serializer = _wireNameToSerializer[wireName]; - if (serializer == null) { - throw new StateError("No serializer for '${wireName}'."); - } - - if (serializer is StructuredSerializer) { - return serializer.deserialize(this, (object as List).sublist(1)); - } else if (serializer is PrimitiveSerializer) { - return serializer.deserialize(this, (object as List)[1]); - } else { - throw new StateError( - 'serializer must be StructuredSerializer or PrimitiveSerializer'); - } - } else { - final serializer = _getSerializerByType(specifiedType.root); - if (serializer == null) { - // Might be an interface; try resolving using the runtime type. - return deserialize(object); - } - - if (serializer is StructuredSerializer) { - return serializer.deserialize(this, object as Iterable, specifiedType: specifiedType); - } else if (serializer is PrimitiveSerializer) { - return serializer.deserialize(this, object, specifiedType: specifiedType); - } else { - throw new StateError( - 'serializer must be StructuredSerializer or PrimitiveSerializer'); - } - } - } - - @override - Object newBuilder(FullType fullType) { - final builderFactory = _builderFactories[fullType]; - return builderFactory == null ? null : builderFactory(); - } - - @override - bool hasBuilder(FullType fullType) { - return _builderFactories.containsKey(fullType); - } - - @override - SerializersBuilder toBuilder() { - return new BuiltJsonSerializersBuilder._( - _typeToSerializer.toBuilder(), - _wireNameToSerializer.toBuilder(), - _typeNameToSerializer.toBuilder(), - _builderFactories.toBuilder()); - } - - Serializer _getSerializerByType(Type type) { - return _typeToSerializer[type] ?? _typeNameToSerializer[_getRawName(type)]; - } -} - -/// Default implementation of [SerializersBuilder]. -class BuiltJsonSerializersBuilder implements SerializersBuilder { - MapBuilder _typeToSerializer = - new MapBuilder(); - MapBuilder _wireNameToSerializer = - new MapBuilder(); - MapBuilder _typeNameToSerializer = - new MapBuilder(); - - MapBuilder _builderFactories = - new MapBuilder(); - - BuiltJsonSerializersBuilder(); - - BuiltJsonSerializersBuilder._(this._typeToSerializer, - this._wireNameToSerializer, - this._typeNameToSerializer, - this._builderFactories); - - void add(Serializer serializer) { - if (serializer is! StructuredSerializer && - serializer is! PrimitiveSerializer) { - throw new ArgumentError( - 'serializer must be StructuredSerializer or PrimitiveSerializer'); - } - - _wireNameToSerializer[serializer.wireName] = serializer; - for (final type in serializer.types) { - _typeToSerializer[type] = serializer; - _typeNameToSerializer[_getRawName(type)] = serializer; - } - } - - void addBuilderFactory(FullType types, Function function) { - _builderFactories[types] = function; - } - - Serializers build() { - return new BuiltJsonSerializers._( - _typeToSerializer.build(), - _wireNameToSerializer.build(), - _typeNameToSerializer.build(), - _builderFactories.build()); - } -} - -String _getRawName(Type type) { - final name = type.toString(); - final genericsStart = name.indexOf('<'); - return genericsStart == -1 ? name : name.substring(0, genericsStart); -} diff --git a/built_json/lib/src/built_list_serializer.dart b/built_json/lib/src/built_list_serializer.dart deleted file mode 100644 index a3e825f..0000000 --- a/built_json/lib/src/built_list_serializer.dart +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -class BuiltListSerializer implements StructuredSerializer { - final bool structured = true; - final Iterable types = new BuiltList([BuiltList]); - final String wireName = 'list'; - - @override - Iterable serialize(Serializers serializers, BuiltList builtList, - {FullType specifiedType: FullType.unspecified}) { - final isUnderspecified = - specifiedType.isUnspecified || specifiedType.parameters.isEmpty; - - final elementType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[0]; - - if (!isUnderspecified && !serializers.hasBuilder(specifiedType)) { - throw new StateError( - 'No builder for $specifiedType, cannot serialize.'); - } - - return builtList.map( - (item) => serializers.serialize(item, specifiedType: elementType)); - } - - @override - BuiltList deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final isUnderspecified = - specifiedType.isUnspecified || specifiedType.parameters.isEmpty; - - final elementType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[0]; - - ListBuilder result = isUnderspecified - ? new ListBuilder() - : serializers.newBuilder(specifiedType) as ListBuilder; - if (result == null) { - throw new StateError( - 'No builder for $specifiedType, cannot deserialize.'); - } - result.addAll(serialized.map((item) => - serializers.deserialize(item, specifiedType: elementType))); - return result.build(); - } -} diff --git a/built_json/lib/src/built_map_serializer.dart b/built_json/lib/src/built_map_serializer.dart deleted file mode 100644 index 27a8656..0000000 --- a/built_json/lib/src/built_map_serializer.dart +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -class BuiltMapSerializer implements StructuredSerializer { - final bool structured = true; - final Iterable types = new BuiltList([BuiltMap]); - final String wireName = 'map'; - - @override - Iterable serialize(Serializers serializers, BuiltMap builtMap, - {FullType specifiedType: FullType.unspecified}) { - final isUnderspecified = - specifiedType.isUnspecified || specifiedType.parameters.isEmpty; - - final keyType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[0]; - final valueType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[1]; - - if (!isUnderspecified && !serializers.hasBuilder(specifiedType)) { - throw new StateError('No builder for $specifiedType, cannot serialize.'); - } - - final result = []; - for (final key in builtMap.keys) { - result.add(serializers.serialize(key, specifiedType: keyType)); - final value = builtMap[key]; - result.add(serializers.serialize(value, specifiedType: valueType)); - } - return result; - } - - @override - BuiltMap deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final isUnderspecified = - specifiedType.isUnspecified || specifiedType.parameters.isEmpty; - - final keyType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[0]; - final valueType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[1]; - - MapBuilder result = isUnderspecified - ? new MapBuilder() - : serializers.newBuilder(specifiedType) as MapBuilder; - if (result == null) { - throw new StateError( - 'No builder for $specifiedType, cannot deserialize.'); - } - - if (serialized.length % 2 == 1) { - throw new ArgumentError('odd length'); - } - - for (int i = 0; i != serialized.length; i += 2) { - final key = serializers.deserialize(serialized.elementAt(i), - specifiedType: keyType); - final value = serializers.deserialize(serialized.elementAt(i + 1), - specifiedType: valueType); - result[key] = value; - } - - return result.build(); - } -} diff --git a/built_json/lib/src/built_set_serializer.dart b/built_json/lib/src/built_set_serializer.dart deleted file mode 100644 index 36c6488..0000000 --- a/built_json/lib/src/built_set_serializer.dart +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -class BuiltSetSerializer implements StructuredSerializer { - final bool structured = true; - final Iterable types = new BuiltList([BuiltSet]); - final String wireName = 'set'; - - @override - Iterable serialize(Serializers serializers, BuiltSet builtSet, - {FullType specifiedType: FullType.unspecified}) { - final isUnderspecified = - specifiedType.isUnspecified || specifiedType.parameters.isEmpty; - - final elementType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[0]; - - if (!isUnderspecified && !serializers.hasBuilder(specifiedType)) { - throw new StateError('No builder for $specifiedType, cannot serialize.'); - } - - return builtSet.map( - (item) => serializers.serialize(item, specifiedType: elementType)); - } - - @override - BuiltSet deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final isUnderspecified = - specifiedType.isUnspecified || specifiedType.parameters.isEmpty; - - final elementType = specifiedType.parameters.isEmpty - ? FullType.unspecified - : specifiedType.parameters[0]; - SetBuilder result = isUnderspecified - ? new SetBuilder() - : serializers.newBuilder(specifiedType) as SetBuilder; - if (result == null) { - throw new StateError( - 'No builder for $specifiedType, cannot deserialize.'); - } - result.addAll(serialized.map((item) => - serializers.deserialize(item, specifiedType: elementType))); - return result.build(); - } -} diff --git a/built_json/lib/src/double_serializer.dart b/built_json/lib/src/double_serializer.dart deleted file mode 100644 index 750938d..0000000 --- a/built_json/lib/src/double_serializer.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -// TODO(davidmorgan): support special values. -class DoubleSerializer implements PrimitiveSerializer { - final bool structured = false; - final Iterable types = new BuiltList([double]); - final String wireName = 'double'; - - @override - Object serialize(Serializers serializers, double aDouble, - {FullType specifiedType: FullType.unspecified}) { - return aDouble; - } - - @override - double deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return (serialized as num).toDouble(); - } -} diff --git a/built_json/lib/src/int_serializer.dart b/built_json/lib/src/int_serializer.dart deleted file mode 100644 index b7419bb..0000000 --- a/built_json/lib/src/int_serializer.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -class IntSerializer implements PrimitiveSerializer { - final bool structured = false; - final Iterable types = new BuiltList([int]); - final String wireName = 'int'; - - @override - Object serialize(Serializers serializers, int integer, - {FullType specifiedType: FullType.unspecified}) { - return integer; - } - - @override - int deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return serialized as int; - } -} diff --git a/built_json/lib/src/string_serializer.dart b/built_json/lib/src/string_serializer.dart deleted file mode 100644 index c0e6c5e..0000000 --- a/built_json/lib/src/string_serializer.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; - -class StringSerializer implements PrimitiveSerializer { - final bool structured = false; - final Iterable types = new BuiltList([String]); - final String wireName = 'String'; - - @override - Object serialize(Serializers serializers, String string, - {FullType specifiedType: FullType.unspecified}) { - return string; - } - - @override - String deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return serialized as String; - } -} diff --git a/built_json/pubspec.yaml b/built_json/pubspec.yaml index 22e83df..b2b9240 100644 --- a/built_json/pubspec.yaml +++ b/built_json/pubspec.yaml @@ -1,18 +1,7 @@ name: built_json -version: 0.1.5 +version: 0.2.0 description: > - JSON serialization for Built Collections, Built Values and Enum Classes. - This library is the runtime dependency. + This library has been deleted, please use built_value instead. authors: - David Morgan -homepage: https://github.com/google/built_json.dart - -environment: - sdk: '>=1.8.0 <2.0.0' - -dependencies: - built_collection: '^1.0.0' - quiver: '>=0.21.0 <0.24.0' - -dev_dependencies: - test: any +homepage: https://github.com/google/built_value.dart diff --git a/built_json/test/bool_serializer_test.dart b/built_json/test/bool_serializer_test.dart deleted file mode 100644 index 5cd4b3a..0000000 --- a/built_json/test/bool_serializer_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_json/built_json.dart'; -import 'package:test/test.dart'; - -void main() { - final serializers = new Serializers(); - - group('bool with known specifiedType', () { - final data = true; - final serialized = true; - final specifiedType = const FullType(bool); - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); - - group('bool with unknown specifiedType', () { - final data = true; - final serialized = ['bool', true]; - final specifiedType = FullType.unspecified; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); -} diff --git a/built_json/test/built_list_serializer_test.dart b/built_json/test/built_list_serializer_test.dart deleted file mode 100644 index bee805f..0000000 --- a/built_json/test/built_list_serializer_test.dart +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:test/test.dart'; - -void main() { - group('BuiltList with known specifiedType but missing builder', () { - final data = new BuiltList([1, 2, 3]); - final specifiedType = - const FullType(BuiltList, const [const FullType(int)]); - final serializers = new Serializers(); - final serialized = [1, 2, 3]; - - test('serialize throws', () { - expect(() => serializers.serialize(data, specifiedType: specifiedType), - throws); - }); - - test('deserialize throws', () { - expect( - () => - serializers.deserialize(serialized, specifiedType: specifiedType), - throws); - }); - }); - - group('BuiltList with known specifiedType and correct builder', () { - final data = new BuiltList([1, 2, 3]); - final specifiedType = - const FullType(BuiltList, const [const FullType(int)]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory(specifiedType, () => new ListBuilder())).build(); - final serialized = [1, 2, 3]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - - test('keeps generic type when deserialized', () { - expect( - serializers - .deserialize(serialized, specifiedType: specifiedType) - .runtimeType - .toString(), - 'BuiltList'); - }); - }); - - group('BuiltList nested with known specifiedType and correct builders', () { - final data = new BuiltList>([ - new BuiltList([1, 2, 3]), - new BuiltList([4, 5, 6]), - new BuiltList([7, 8, 9]) - ]); - final specifiedType = const FullType(BuiltList, const [ - const FullType(BuiltList, const [const FullType(int)]) - ]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory( - specifiedType, () => new ListBuilder>()) - ..addBuilderFactory( - const FullType(BuiltList, const [const FullType(int)]), - () => new ListBuilder())).build(); - final serialized = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); - - group('BuiltList with unknown specifiedType and no builders', () { - final data = new BuiltList([1, 2, 3]); - final specifiedType = FullType.unspecified; - final serializers = new Serializers(); - final serialized = [ - 'list', - ['int', 1], - ['int', 2], - ['int', 3] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); -} diff --git a/built_json/test/built_map_serializer_test.dart b/built_json/test/built_map_serializer_test.dart deleted file mode 100644 index afd4376..0000000 --- a/built_json/test/built_map_serializer_test.dart +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:test/test.dart'; - -void main() { - group('BuiltMap with known specifiedType but missing builder', () { - final data = new BuiltMap({1: 'one', 2: 'two', 3: 'three'}); - final specifiedType = const FullType( - BuiltMap, const [const FullType(int), const FullType(String)]); - final serializers = new Serializers(); - final serialized = [1, 'one', 2, 'two', 3, 'three']; - - test('cannot be serialized', () { - expect(() => serializers.serialize(data, specifiedType: specifiedType), - throws); - }); - - test('cannot be deserialized', () { - expect( - () => - serializers.deserialize(serialized, specifiedType: specifiedType), - throws); - }); - }); - - group('BuiltMap with known specifiedType and correct builder', () { - final data = new BuiltMap({1: 'one', 2: 'two', 3: 'three'}); - final specifiedType = const FullType( - BuiltMap, const [const FullType(int), const FullType(String)]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory( - specifiedType, () => new MapBuilder())).build(); - final serialized = [1, 'one', 2, 'two', 3, 'three']; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - - test('keeps generic type when deserialized', () { - expect( - serializers - .deserialize(serialized, specifiedType: specifiedType) - .runtimeType - .toString(), - 'BuiltMap'); - }); - }); - - group('BuiltMap nested left with known specifiedType', () { - final data = new BuiltMap, String>({ - new BuiltMap({1: 'one'}): 'one!', - new BuiltMap({2: 'two'}): 'two!' - }); - const innerTypeLeft = const FullType( - BuiltMap, const [const FullType(int), const FullType(String)]); - final specifiedType = - const FullType(BuiltMap, const [innerTypeLeft, const FullType(String)]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory(innerTypeLeft, () => new MapBuilder()) - ..addBuilderFactory(specifiedType, - () => new MapBuilder, String>())).build(); - final serialized = [ - [1, 'one'], - 'one!', - [2, 'two'], - 'two!' - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); - - group('BuiltMap nested right with known specifiedType', () { - final data = new BuiltMap>({ - 1: new BuiltMap({'one': 'one!'}), - 2: new BuiltMap({'two': 'two!'}) - }); - const innerTypeRight = const FullType( - BuiltMap, const [const FullType(String), const FullType(String)]); - final specifiedType = - const FullType(BuiltMap, const [const FullType(int), innerTypeRight]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory( - innerTypeRight, () => new MapBuilder()) - ..addBuilderFactory(specifiedType, - () => new MapBuilder>())).build(); - final serialized = [ - 1, - ['one', 'one!'], - 2, - ['two', 'two!'] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); - - group('BuiltMap nested both with known specifiedType', () { - final data = new BuiltMap, BuiltMap>({ - new BuiltMap({1: 1}): - new BuiltMap({'one': 'one!'}), - new BuiltMap({2: 2}): - new BuiltMap({'two': 'two!'}) - }); - const builtMapOfIntIntGenericType = const FullType( - BuiltMap, const [const FullType(int), const FullType(int)]); - const builtMapOfStringStringGenericType = const FullType( - BuiltMap, const [const FullType(String), const FullType(String)]); - final specifiedType = const FullType(BuiltMap, - const [builtMapOfIntIntGenericType, builtMapOfStringStringGenericType]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory( - builtMapOfIntIntGenericType, () => new MapBuilder()) - ..addBuilderFactory(builtMapOfStringStringGenericType, - () => new MapBuilder()) - ..addBuilderFactory( - specifiedType, - () => new MapBuilder, - BuiltMap>())).build(); - final serialized = [ - [1, 1], - ['one', 'one!'], - [2, 2], - ['two', 'two!'] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - - test('keeps generic type on deserialization', () { - final genericSerializer = (serializers.toBuilder() - ..addBuilderFactory( - specifiedType, - () => - new MapBuilder, BuiltMap>()) - ..addBuilderFactory( - builtMapOfIntIntGenericType, () => new MapBuilder()) - ..addBuilderFactory(builtMapOfStringStringGenericType, - () => new MapBuilder())).build(); - - expect( - genericSerializer - .deserialize(serialized, specifiedType: specifiedType) - .runtimeType - .toString(), - 'BuiltMap, BuiltMap>'); - }); - }); - - group('BuiltMap with Object values', () { - final data = new BuiltMap({1: 'one', 2: 2, 3: 'three'}); - final specifiedType = - const FullType(BuiltMap, const [const FullType(int), FullType.unspecified]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory( - specifiedType, () => new MapBuilder())).build(); - final serialized = [ - 1, - ['String', 'one'], - 2, - ['int', 2], - 3, - ['String', 'three'] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); - - group('BuiltMap with Object keys', () { - final data = - new BuiltMap({1: 'one', 'two': 'two', 3: 'three'}); - final specifiedType = const FullType( - BuiltMap, const [FullType.unspecified, const FullType(String)]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory( - specifiedType, () => new MapBuilder())).build(); - final serialized = [ - ['int', 1], - 'one', - ['String', 'two'], - 'two', - ['int', 3], - 'three' - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); - - group('BuiltMap with Object keys and values', () { - final data = new BuiltMap({1: 'one', 'two': 2, 3: 'three'}); - final specifiedType = const FullType(BuiltMap); - final serializers = new Serializers(); - final serialized = [ - ['int', 1], - ['String', 'one'], - ['String', 'two'], - ['int', 2], - ['int', 3], - ['String', 'three'] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); - - group('BuiltMap with unknown specifiedType', () { - final data = new BuiltMap({1: 'one', 'two': 2, 3: 'three'}); - final specifiedType = FullType.unspecified; - final serializers = new Serializers(); - final serialized = [ - 'map', - ['int', 1], - ['String', 'one'], - ['String', 'two'], - ['int', 2], - ['int', 3], - ['String', 'three'] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); -} diff --git a/built_json/test/built_set_serializer_test.dart b/built_json/test/built_set_serializer_test.dart deleted file mode 100644 index 20ca565..0000000 --- a/built_json/test/built_set_serializer_test.dart +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:test/test.dart'; - -// Note: BuiltSet preserves order, so comparisons in these tests can assume a -// specific ordering. In fact, these tests are exactly the BuiltListSerializer tests -// with "list" replaced by "set". -void main() { - group('BuiltSet with known specifiedType but missing builder', () { - final data = new BuiltSet([1, 2, 3]); - final specifiedType = - const FullType(BuiltSet, const [const FullType(int)]); - final serializers = new Serializers(); - final serialized = [1, 2, 3]; - - test('serialize throws', () { - expect(() => serializers.serialize(data, specifiedType: specifiedType), - throws); - }); - - test('deserialize throws', () { - expect( - () => - serializers.deserialize(serialized, specifiedType: specifiedType), - throws); - }); - }); - - group('BuiltSet with known specifiedType and correct builder', () { - final data = new BuiltSet([1, 2, 3]); - final specifiedType = - const FullType(BuiltSet, const [const FullType(int)]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory(specifiedType, () => new SetBuilder())).build(); - final serialized = [1, 2, 3]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - - test('keeps generic type when deserialized', () { - expect( - serializers - .deserialize(serialized, specifiedType: specifiedType) - .runtimeType - .toString(), - 'BuiltSet'); - }); - }); - - group('BuiltSet nested with known specifiedType and correct builders', () { - final data = new BuiltSet>([ - new BuiltSet([1, 2, 3]), - new BuiltSet([4, 5, 6]), - new BuiltSet([7, 8, 9]) - ]); - final specifiedType = const FullType(BuiltSet, const [ - const FullType(BuiltSet, const [const FullType(int)]) - ]); - final serializers = (new Serializers().toBuilder() - ..addBuilderFactory( - specifiedType, () => new SetBuilder>()) - ..addBuilderFactory( - const FullType(BuiltSet, const [const FullType(int)]), - () => new SetBuilder())).build(); - final serialized = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); - - group('BuiltSet with unknown specifiedType and no builders', () { - final data = new BuiltSet([1, 2, 3]); - final specifiedType = FullType.unspecified; - final serializers = new Serializers(); - final serialized = [ - 'set', - ['int', 1], - ['int', 2], - ['int', 3] - ]; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), - serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized, specifiedType: specifiedType), - data); - }); - }); -} - diff --git a/built_json/test/double_serializer_test.dart b/built_json/test/double_serializer_test.dart deleted file mode 100644 index 9fee096..0000000 --- a/built_json/test/double_serializer_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_json/built_json.dart'; -import 'package:test/test.dart'; - -void main() { - final serializers = new Serializers(); - - group('double with known specifiedType', () { - final data = 3.141592653589793; - final serialized = data; - final specifiedType = const FullType(double); - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); - - group('double with unknown specifiedType', () { - final data = 3.141592653589793; - final serialized = ['double', data]; - final specifiedType = FullType.unspecified; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); -} diff --git a/built_json/test/int_serializer_test.dart b/built_json/test/int_serializer_test.dart deleted file mode 100644 index 66ccc2e..0000000 --- a/built_json/test/int_serializer_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_json/built_json.dart'; -import 'package:test/test.dart'; - -void main() { - final serializers = new Serializers(); - - group('int with known specifiedType', () { - final data = 42; - final serialized = 42; - final specifiedType = const FullType(int); - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); - - group('int with unknown specifiedType', () { - final data = 42; - final serialized = ['int', 42]; - final specifiedType = FullType.unspecified; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); -} diff --git a/built_json/test/string_serializer_test.dart b/built_json/test/string_serializer_test.dart deleted file mode 100644 index f9511a2..0000000 --- a/built_json/test/string_serializer_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_json/built_json.dart'; -import 'package:test/test.dart'; - -void main() { - final serializers = new Serializers(); - - group('String with known specifiedType', () { - final data = 'testing, testing'; - final serialized = 'testing, testing'; - final specifiedType = const FullType(String); - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); - - group('String with unknown specifiedType', () { - final data = 'testing, testing'; - final serialized = ['String', 'testing, testing']; - final specifiedType = FullType.unspecified; - - test('can be serialized', () { - expect(serializers.serialize(data, specifiedType: specifiedType), serialized); - }); - - test('can be deserialized', () { - expect( - serializers.deserialize(serialized, specifiedType: specifiedType), data); - }); - }); -} diff --git a/built_json_generator/LICENSE b/built_json_generator/LICENSE deleted file mode 100644 index ec8a981..0000000 --- a/built_json_generator/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2015, Google Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/built_json_generator/lib/built_json_generator.dart b/built_json_generator/lib/built_json_generator.dart deleted file mode 100644 index 2d39d2e..0000000 --- a/built_json_generator/lib/built_json_generator.dart +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library built_json_generator; - -import 'dart:async'; - -import 'package:analyzer/dart/element/element.dart'; -import 'package:build/build.dart'; -import 'package:built_json_generator/src/source_library.dart'; -import 'package:source_gen/source_gen.dart'; - -/// Generator for Built JSON. -/// -/// See: https://github.com/google/built_json.dart/tree/master/example -class BuiltJsonGenerator extends Generator { - @override - Future generate(Element element, BuildStep buildStep) async { - if (element is! LibraryElement) return null; - - final sourceLibrary = SourceLibrary.fromLibraryElement(element as LibraryElement); - if (!sourceLibrary.needsBuiltJson && !sourceLibrary.hasSerializers) return null; - - return sourceLibrary.generate(); - } -} diff --git a/built_json_generator/lib/src/library_elements.dart b/built_json_generator/lib/src/library_elements.dart deleted file mode 100644 index 89fa1c1..0000000 --- a/built_json_generator/lib/src/library_elements.dart +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library built_json_generator.library_elements; - -import 'package:analyzer/dart/element/element.dart'; -import 'package:analyzer/dart/element/visitor.dart'; -import 'package:built_collection/built_collection.dart'; - -/// Tools for [LibraryElement]s. -class LibraryElements { - static BuiltList getClassElements( - LibraryElement libraryElement) { - final result = new _GetClassesVisitor(); - libraryElement.visitChildren(result); - return new BuiltList(result.classElements); - } - - static BuiltList getTransitiveClassElements( - LibraryElement libraryElement) { - final result = new ListBuilder(); - for (final source in libraryElement.context.librarySources) { - final otherLibraryElement = - libraryElement.context.computeLibraryElement(source); - result.addAll(getClassElements(otherLibraryElement)); - } - return result.build(); - } -} - -/// Visitor that gets all [ClassElement]s. -class _GetClassesVisitor extends SimpleElementVisitor { - final List classElements = new List(); - - @override - visitClassElement(ClassElement element) { - classElements.add(element); - } - - @override - visitCompilationUnitElement(CompilationUnitElement element) { - element.visitChildren(this); - } -} diff --git a/built_json_generator/lib/src/source_class.dart b/built_json_generator/lib/src/source_class.dart deleted file mode 100644 index 84393a5..0000000 --- a/built_json_generator/lib/src/source_class.dart +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library built_json_generator.source_class; - -import 'package:analyzer/dart/element/element.dart'; -import 'package:built_collection/built_collection.dart'; -import 'package:built_json_generator/src/source_field.dart'; -import 'package:built_value/built_value.dart'; - -part 'source_class.g.dart'; - -abstract class SourceClass implements Built { - String get name; - bool get isBuiltValue; - bool get isEnumClass; - BuiltList get fields; - - factory SourceClass([updates(SourceClassBuilder b)]) = _$SourceClass; - SourceClass._(); - - static SourceClass fromClassElements( - ClassElement classElement, ClassElement builderClassElement) { - final result = new SourceClassBuilder(); - - result.name = classElement.name; - - // TODO(davidmorgan): better check. - result.isBuiltValue = classElement.allSupertypes - .map((type) => type.name) - .any((name) => name.startsWith('Built')) && - !classElement.name.startsWith(r'_$') && - classElement.fields.any((field) => field.name == 'serializer'); - - // TODO(davidmorgan): better check. - result.isEnumClass = classElement.allSupertypes - .map((type) => type.name) - .any((name) => name == 'EnumClass') && - !classElement.name.startsWith(r'_$') && - classElement.fields.any((field) => field.name == 'serializer'); - - for (final fieldElement in classElement.fields) { - final builderFieldElement = - builderClassElement?.getField(fieldElement.displayName); - final sourceField = - SourceField.fromFieldElements(fieldElement, builderFieldElement); - if (sourceField.isSerializable) { - result.fields.add(sourceField); - } - } - - return result.build(); - } - - bool get needsBuiltJson => isBuiltValue || isEnumClass; - - String generateTransitiveSerializerAdder() { - return '..add(${name}.serializer)'; - } - - String generateBuilderFactoryAdders() { - return fields - .where((field) => field.needsBuilder) - .map((field) => - '..addBuilderFactory(${field.generateFullType()}, () => ${field.generateBuilder()})') - .join('\n'); - } - - String generateSerializerDeclaration() { - final camelCaseName = _toCamelCase(name); - return 'Serializer<$name> ' - '_\$${camelCaseName}Serializer = ' - 'new _\$${name}Serializer();'; - } - - String generateSerializer() { - if (isBuiltValue) { - return ''' -class _\$${name}Serializer implements StructuredSerializer<$name> { - final Iterable types = new BuiltList([$name, _\$$name]); - final String wireName = '$name'; - - @override - Iterable serialize(Serializers serializers, $name object, - {FullType specifiedType: FullType.unspecified}) { - final result = [${_generateRequiredFieldSerializers()}]; - ${_generateNullableFieldSerializers()} - return result; - } - - @override - $name deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ${name}Builder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - ${_generateFieldDeserializers()} - } - } - } - - return result.build(); - } -} -'''; - } else if (isEnumClass) { - return ''' -class _\$${name}Serializer implements PrimitiveSerializer<$name> { - final Iterable types = new BuiltList([$name]); - final String wireName = '$name'; - - @override - Object serialize(Serializers serializers, $name object, - {FullType specifiedType: FullType.unspecified}) { - return object.name; - } - - @override - $name deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return ${name}.valueOf(serialized); - } -} -'''; - } else { - throw new UnsupportedError('not serializable'); - } - } - - String _generateRequiredFieldSerializers() { - return fields - .where((field) => !field.isNullable) - .map((field) => "'${field.name}', " - "serializers.serialize(object.${field.name}, " - "specifiedType: ${field.generateFullType()}),") - .join(''); - } - - String _generateNullableFieldSerializers() { - return fields.where((field) => field.isNullable).map((field) => ''' - if (object.${field.name} != null) { - result.add('${field.name}'); - result.add(serializers.serialize( - object.${field.name}, specifiedType: ${field.generateFullType()})); - } -''').join(''); - } - - String _generateFieldDeserializers() { - return fields.map((field) { - if (field.builderFieldUsesNestedBuilder) { - return ''' -case '${field.name}': - result.${field.name}.replace(serializers.deserialize( - value, specifiedType: ${field.generateFullType()})); - break; -'''; - } else { - return ''' -case '${field.name}': - result.${field.name} = serializers.deserialize( - value, specifiedType: ${field.generateFullType()}); - break; -'''; - } - }).join(''); - } - - static String _toCamelCase(String name) { - var result = ''; - var upperCase = false; - var firstCharacter = true; - for (final char in name.split('')) { - if (char == '_') { - upperCase = true; - } else { - result += firstCharacter - ? char.toLowerCase() - : (upperCase ? char.toUpperCase() : char); - upperCase = false; - firstCharacter = false; - } - } - return result; - } -} - -abstract class SourceClassBuilder - implements Builder { - String name; - bool isBuiltValue; - bool isEnumClass; - ListBuilder fields = new ListBuilder(); - - factory SourceClassBuilder() = _$SourceClassBuilder; - SourceClassBuilder._(); -} diff --git a/built_json_generator/lib/src/source_class.g.dart b/built_json_generator/lib/src/source_class.g.dart deleted file mode 100644 index c96b405..0000000 --- a/built_json_generator/lib/src/source_class.g.dart +++ /dev/null @@ -1,74 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of built_json_generator.source_class; - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class SourceClass -// ************************************************************************** - -class _$SourceClass extends SourceClass { - final String name; - final bool isBuiltValue; - final bool isEnumClass; - final BuiltList fields; - - _$SourceClass._({this.name, this.isBuiltValue, this.isEnumClass, this.fields}) - : super._() { - if (name == null) throw new ArgumentError('null name'); - if (isBuiltValue == null) throw new ArgumentError('null isBuiltValue'); - if (isEnumClass == null) throw new ArgumentError('null isEnumClass'); - if (fields == null) throw new ArgumentError('null fields'); - } - - factory _$SourceClass([updates(SourceClassBuilder b)]) => - (new SourceClassBuilder()..update(updates)).build(); - - SourceClass rebuild(updates(SourceClassBuilder b)) => - (toBuilder()..update(updates)).build(); - - _$SourceClassBuilder toBuilder() => new _$SourceClassBuilder()..replace(this); - - bool operator ==(other) { - if (other is! SourceClass) return false; - return name == other.name && - isBuiltValue == other.isBuiltValue && - isEnumClass == other.isEnumClass && - fields == other.fields; - } - - int get hashCode { - return hashObjects([name, isBuiltValue, isEnumClass, fields]); - } - - String toString() { - return 'SourceClass {' - 'name=${name.toString()},\n' - 'isBuiltValue=${isBuiltValue.toString()},\n' - 'isEnumClass=${isEnumClass.toString()},\n' - 'fields=${fields.toString()},\n' - '}'; - } -} - -class _$SourceClassBuilder extends SourceClassBuilder { - _$SourceClassBuilder() : super._(); - void replace(SourceClass other) { - super.name = other.name; - super.isBuiltValue = other.isBuiltValue; - super.isEnumClass = other.isEnumClass; - super.fields = other.fields?.toBuilder(); - } - - void update(updates(SourceClassBuilder b)) { - if (updates != null) updates(this); - } - - SourceClass build() { - return new _$SourceClass._( - name: name, - isBuiltValue: isBuiltValue, - isEnumClass: isEnumClass, - fields: fields?.build()); - } -} diff --git a/built_json_generator/lib/src/source_field.dart b/built_json_generator/lib/src/source_field.dart deleted file mode 100644 index 00188dd..0000000 --- a/built_json_generator/lib/src/source_field.dart +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library built_json_generator.source_field; - -import 'package:analyzer/dart/element/element.dart'; -import 'package:analyzer/dart/element/type.dart'; -import 'package:built_collection/built_collection.dart'; -import 'package:built_value/built_value.dart'; - -part 'source_field.g.dart'; - -BuiltSet _builtCollectionNames = new BuiltSet([ - 'BuiltList', - 'BuiltListMultimap', - 'BuiltMap', - 'BuiltSet', - 'BuiltSetMultimap', -]); - -abstract class SourceField implements Built { - static final BuiltMap typesWithBuilder = - new BuiltMap({ - 'BuiltList': 'ListBuilder', - 'BuiltMap': 'MapBuilder', - 'BuiltSet': 'SetBuilder', - }); - - bool get isSerializable; - bool get isNullable; - String get name; - String get type; - bool get builderFieldUsesNestedBuilder; - - factory SourceField([updates(SourceFieldBuilder b)]) = _$SourceField; - SourceField._(); - - String get rawType => _getBareType(type); - - static SourceField fromFieldElements( - FieldElement fieldElement, FieldElement builderFieldElement) { - final result = new SourceFieldBuilder(); - final isSerializable = fieldElement.getter != null && - fieldElement.getter.isAbstract && - !fieldElement.isStatic; - - result.isSerializable = isSerializable; - - if (isSerializable) { - result.isNullable = fieldElement.getter.metadata.any( - (metadata) => metadata.constantValue.toStringValue() == 'nullable'); - result.name = fieldElement.displayName; - result.type = fieldElement.getter.returnType.displayName; - - // If the builder is present, check it to determine whether a nested - // builder is needed. Otherwise, use the same logic as built_value when - // it decides whether to use a nested builder. - result.builderFieldUsesNestedBuilder = builderFieldElement == null - ? _needsNestedBuilder(fieldElement.getter.returnType) - : fieldElement.getter.returnType.displayName != - builderFieldElement.getter.returnType.displayName; - } - - return result.build(); - } - - String generateFullType() { - return _generateFullType(type); - } - - bool get needsBuilder => typesWithBuilder.containsKey(_getBareType(type)); - - String generateBuilder() { - return 'new ${typesWithBuilder[_getBareType(type)]}<${_getGenerics(type)}>()'; - } - - static String _generateFullType(String type) { - // TODO(davidmorgan): support more than one level of nesting. - final bareType = _getBareType(type); - final generics = _getGenerics(type); - final genericItems = generics.split(', '); - - if (generics.isEmpty) { - return 'const FullType($bareType)'; - } else { - return 'const FullType($bareType, const [${genericItems.map(_generateFullType).join(', ')}])'; - } - } - - static String _getBareType(String name) { - final genericsStart = name.indexOf('<'); - return genericsStart == -1 ? name : name.substring(0, genericsStart); - } - - static String _getGenerics(String name) { - final genericsStart = name.indexOf('<'); - return genericsStart == -1 - ? '' - : name - .substring(genericsStart + 1) - .substring(0, name.length - genericsStart - 2); - } - - // These three methods are copied from built_value to match the behaviour - // when a builder is not explicitly defined. - // TODO(davidmorgan): dedupe. - static bool _needsNestedBuilder(DartType type) { - return _isBuiltValue(type) || _isBuiltCollection(type); - } - - static bool _isBuiltValue(DartType type) { - if (type.element is! ClassElement) return false; - return (type.element as ClassElement) - .allSupertypes - .any((interfaceType) => interfaceType.name == 'Built'); - } - - static bool _isBuiltCollection(DartType type) { - return _builtCollectionNames - .any((name) => type.displayName.startsWith('${name}<')); - } -} - -abstract class SourceFieldBuilder - implements Builder { - bool isSerializable; - bool isNullable = false; - String name = ''; - String type = ''; - bool builderFieldUsesNestedBuilder = false; - - factory SourceFieldBuilder() = _$SourceFieldBuilder; - SourceFieldBuilder._(); -} diff --git a/built_json_generator/lib/src/source_field.g.dart b/built_json_generator/lib/src/source_field.g.dart deleted file mode 100644 index a293ee0..0000000 --- a/built_json_generator/lib/src/source_field.g.dart +++ /dev/null @@ -1,92 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of built_json_generator.source_field; - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class SourceField -// ************************************************************************** - -class _$SourceField extends SourceField { - final bool isSerializable; - final bool isNullable; - final String name; - final String type; - final bool builderFieldUsesNestedBuilder; - - _$SourceField._( - {this.isSerializable, - this.isNullable, - this.name, - this.type, - this.builderFieldUsesNestedBuilder}) - : super._() { - if (isSerializable == null) throw new ArgumentError('null isSerializable'); - if (isNullable == null) throw new ArgumentError('null isNullable'); - if (name == null) throw new ArgumentError('null name'); - if (type == null) throw new ArgumentError('null type'); - if (builderFieldUsesNestedBuilder == null) - throw new ArgumentError('null builderFieldUsesNestedBuilder'); - } - - factory _$SourceField([updates(SourceFieldBuilder b)]) => - (new SourceFieldBuilder()..update(updates)).build(); - - SourceField rebuild(updates(SourceFieldBuilder b)) => - (toBuilder()..update(updates)).build(); - - _$SourceFieldBuilder toBuilder() => new _$SourceFieldBuilder()..replace(this); - - bool operator ==(other) { - if (other is! SourceField) return false; - return isSerializable == other.isSerializable && - isNullable == other.isNullable && - name == other.name && - type == other.type && - builderFieldUsesNestedBuilder == other.builderFieldUsesNestedBuilder; - } - - int get hashCode { - return hashObjects([ - isSerializable, - isNullable, - name, - type, - builderFieldUsesNestedBuilder - ]); - } - - String toString() { - return 'SourceField {' - 'isSerializable=${isSerializable.toString()},\n' - 'isNullable=${isNullable.toString()},\n' - 'name=${name.toString()},\n' - 'type=${type.toString()},\n' - 'builderFieldUsesNestedBuilder=${builderFieldUsesNestedBuilder.toString()},\n' - '}'; - } -} - -class _$SourceFieldBuilder extends SourceFieldBuilder { - _$SourceFieldBuilder() : super._(); - void replace(SourceField other) { - super.isSerializable = other.isSerializable; - super.isNullable = other.isNullable; - super.name = other.name; - super.type = other.type; - super.builderFieldUsesNestedBuilder = other.builderFieldUsesNestedBuilder; - } - - void update(updates(SourceFieldBuilder b)) { - if (updates != null) updates(this); - } - - SourceField build() { - return new _$SourceField._( - isSerializable: isSerializable, - isNullable: isNullable, - name: name, - type: type, - builderFieldUsesNestedBuilder: builderFieldUsesNestedBuilder); - } -} diff --git a/built_json_generator/lib/src/source_library.dart b/built_json_generator/lib/src/source_library.dart deleted file mode 100644 index f8c0dd6..0000000 --- a/built_json_generator/lib/src/source_library.dart +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library built_json_generator.source_library; - -import 'package:analyzer/dart/element/element.dart'; -import 'package:built_collection/built_collection.dart'; -import 'package:built_json_generator/src/library_elements.dart'; -import 'package:built_json_generator/src/source_class.dart'; -import 'package:built_value/built_value.dart'; - -part 'source_library.g.dart'; - -abstract class SourceLibrary - implements Built { - bool get hasSerializers; - BuiltSet get sourceClasses; - BuiltSet get transitiveSourceClasses; - - factory SourceLibrary([updates(SourceLibraryBuilder b)]) = _$SourceLibrary; - SourceLibrary._(); - - static SourceLibrary fromLibraryElement(LibraryElement libraryElement) { - final result = new SourceLibraryBuilder(); - - // TODO(davidmorgan): better way of checking for top level declaration. - result.hasSerializers = libraryElement.definingCompilationUnit.accessors - .any((element) => element.displayName == 'serializers'); - - final classElements = LibraryElements.getClassElements(libraryElement); - for (final classElement in classElements) { - final builderClassElement = - libraryElement.getType(classElement.displayName + 'Builder'); - final sourceClass = - SourceClass.fromClassElements(classElement, builderClassElement); - if (sourceClass.needsBuiltJson) { - result.sourceClasses.add(sourceClass); - } - } - - final transitiveClassElements = - LibraryElements.getTransitiveClassElements(libraryElement); - for (final classElement in transitiveClassElements) { - final sourceClass = SourceClass.fromClassElements(classElement, null); - if (sourceClass.needsBuiltJson) { - result.transitiveSourceClasses.add(sourceClass); - } - } - - return result.build(); - } - - bool get needsBuiltJson => sourceClasses.isNotEmpty; - - /// Generates serializer source for this library. - String generate() { - return (hasSerializers - ? 'Serializers _\$serializers = (new Serializers().toBuilder()' + - transitiveSourceClasses - .map((sourceClass) => - sourceClass.generateTransitiveSerializerAdder() + - '\n' + - sourceClass.generateBuilderFactoryAdders()) - .join('\n') + - ').build();' - : '') + - sourceClasses - .map((sourceClass) => sourceClass.generateSerializerDeclaration()) - .join('\n') + - sourceClasses - .map((sourceClass) => sourceClass.generateSerializer()) - .join('\n'); - } -} - -abstract class SourceLibraryBuilder - implements Builder { - bool hasSerializers = false; - SetBuilder sourceClasses = new SetBuilder(); - SetBuilder transitiveSourceClasses = - new SetBuilder(); - - factory SourceLibraryBuilder() = _$SourceLibraryBuilder; - SourceLibraryBuilder._(); -} diff --git a/built_json_generator/lib/src/source_library.g.dart b/built_json_generator/lib/src/source_library.g.dart deleted file mode 100644 index b051ca8..0000000 --- a/built_json_generator/lib/src/source_library.g.dart +++ /dev/null @@ -1,72 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of built_json_generator.source_library; - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class SourceLibrary -// ************************************************************************** - -class _$SourceLibrary extends SourceLibrary { - final bool hasSerializers; - final BuiltSet sourceClasses; - final BuiltSet transitiveSourceClasses; - - _$SourceLibrary._( - {this.hasSerializers, this.sourceClasses, this.transitiveSourceClasses}) - : super._() { - if (hasSerializers == null) throw new ArgumentError('null hasSerializers'); - if (sourceClasses == null) throw new ArgumentError('null sourceClasses'); - if (transitiveSourceClasses == null) - throw new ArgumentError('null transitiveSourceClasses'); - } - - factory _$SourceLibrary([updates(SourceLibraryBuilder b)]) => - (new SourceLibraryBuilder()..update(updates)).build(); - - SourceLibrary rebuild(updates(SourceLibraryBuilder b)) => - (toBuilder()..update(updates)).build(); - - _$SourceLibraryBuilder toBuilder() => - new _$SourceLibraryBuilder()..replace(this); - - bool operator ==(other) { - if (other is! SourceLibrary) return false; - return hasSerializers == other.hasSerializers && - sourceClasses == other.sourceClasses && - transitiveSourceClasses == other.transitiveSourceClasses; - } - - int get hashCode { - return hashObjects( - [hasSerializers, sourceClasses, transitiveSourceClasses]); - } - - String toString() { - return 'SourceLibrary {' - 'hasSerializers=${hasSerializers.toString()},\n' - 'sourceClasses=${sourceClasses.toString()},\n' - 'transitiveSourceClasses=${transitiveSourceClasses.toString()},\n' - '}'; - } -} - -class _$SourceLibraryBuilder extends SourceLibraryBuilder { - _$SourceLibraryBuilder() : super._(); - void replace(SourceLibrary other) { - super.hasSerializers = other.hasSerializers; - super.sourceClasses = other.sourceClasses?.toBuilder(); - super.transitiveSourceClasses = other.transitiveSourceClasses?.toBuilder(); - } - - void update(updates(SourceLibraryBuilder b)) { - if (updates != null) updates(this); - } - - SourceLibrary build() { - return new _$SourceLibrary._( - hasSerializers: hasSerializers, - sourceClasses: sourceClasses?.build(), - transitiveSourceClasses: transitiveSourceClasses?.build()); - } -} diff --git a/built_json_generator/pubspec.yaml b/built_json_generator/pubspec.yaml index b2414a7..97dc7c6 100644 --- a/built_json_generator/pubspec.yaml +++ b/built_json_generator/pubspec.yaml @@ -1,25 +1,7 @@ name: built_json_generator -version: 0.1.5 +version: 0.2.0 description: > - JSON serialization for Built Collections, Built Values and Enum Classes. - This library is the dev dependency. + This library has been deleted, please use built_value instead. authors: - David Morgan -homepage: https://github.com/google/built_json.dart - -environment: - sdk: '>=1.12.0-dev.5.10 <2.0.0' - -dependencies: - analyzer: '>=0.28.0 <0.29.0' - build: '^0.4.0' - built_collection: '^1.0.1' - built_json: '^0.1.5' - source_gen: '>=0.5.0 <0.6.0' - quiver: '>=0.21.0 <0.24.0' - -dev_dependencies: - build_test: '^0.2.0' - built_value: '^0.1.0' - built_value_generator: '^0.1.0' - test: any +homepage: https://github.com/google/built_value.dart diff --git a/built_json_generator/test/built_json_generator_test.dart b/built_json_generator/test/built_json_generator_test.dart deleted file mode 100644 index 72105b3..0000000 --- a/built_json_generator/test/built_json_generator_test.dart +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:build/build.dart'; -import 'package:build_test/build_test.dart'; -import 'package:built_json_generator/built_json_generator.dart'; -import 'package:source_gen/source_gen.dart'; -import 'package:test/test.dart'; - -void main() { - group('generator', () { - test('ignores empty library', () async { - expect(await generate('library value;'), isEmpty); - }); - - test('ignores normal class', () async { - expect(await generate(r''' -library value; - -class EmptyClass {} -'''), isEmpty); - }); - - test('ignores built_value class without serializer', () async { - expect(await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -abstract class Value implements Built {} -'''), isEmpty); - }); - - test('generates for built_value class with serializer', () async { - expect(await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -abstract class Value implements Built { - static final Serializer serializer = _$serializer; -} -'''), isNotEmpty); - }); - - test('ignores EnumClass without serializer', () async { - expect(await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -class Enum extends EnumClass {} -'''), isEmpty); - }); - - test('generates for EnumClass with serializer', () async { - expect(await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -class Enum extends EnumClass { - static final Serializer serializer = _$serializer; -} -'''), isNotEmpty); - }); - - test('generates for serializers', () async { - expect(await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -final Serializers serializers = _$serializers; -'''), isNotEmpty); - }); - - test('generates correct serializer for built_value with primitives', - () async { - expect( - await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -abstract class Value implements Built { - static final Serializer serializer = _$serializer; - bool get aBool; - double get aDouble; - int get anInt; - String get aString; -} - -abstract class ValueBuilder implements Builder { - bool aBool; - double aDouble; - int anInt; - String aString; -} -'''), - r'''// GENERATED CODE - DO NOT MODIFY BY HAND - -part of value; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library value -// ************************************************************************** - -Serializer _$valueSerializer = new _$ValueSerializer(); - -class _$ValueSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Value, _$Value]); - final String wireName = 'Value'; - - @override - Iterable serialize(Serializers serializers, Value object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'aBool', - serializers.serialize(object.aBool, specifiedType: const FullType(bool)), - 'aDouble', - serializers.serialize(object.aDouble, - specifiedType: const FullType(double)), - 'anInt', - serializers.serialize(object.anInt, specifiedType: const FullType(int)), - 'aString', - serializers.serialize(object.aString, - specifiedType: const FullType(String)), - ]; - - return result; - } - - @override - Value deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ValueBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'aBool': - result.aBool = serializers.deserialize(value, - specifiedType: const FullType(bool)); - break; - case 'aDouble': - result.aDouble = serializers.deserialize(value, - specifiedType: const FullType(double)); - break; - case 'anInt': - result.anInt = serializers.deserialize(value, - specifiedType: const FullType(int)); - break; - case 'aString': - result.aString = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - } - } - } - - return result.build(); - } -} -'''); - }); - - test('generates correct serializer for built_value with nullables', - () async { - expect( - await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -abstract class Value implements Built { - static final Serializer serializer = _$serializer; - bool get aBool; - @nullable double get aDouble; - @nullable int get anInt; -} - -abstract class ValueBuilder implements Builder { - bool aBool; - @nullable double aDouble; - @nullable int anInt; -} -'''), - r'''// GENERATED CODE - DO NOT MODIFY BY HAND - -part of value; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library value -// ************************************************************************** - -Serializer _$valueSerializer = new _$ValueSerializer(); - -class _$ValueSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Value, _$Value]); - final String wireName = 'Value'; - - @override - Iterable serialize(Serializers serializers, Value object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'aBool', - serializers.serialize(object.aBool, specifiedType: const FullType(bool)), - ]; - if (object.aDouble != null) { - result.add('aDouble'); - result.add(serializers.serialize(object.aDouble, - specifiedType: const FullType(double))); - } - if (object.anInt != null) { - result.add('anInt'); - result.add(serializers.serialize(object.anInt, - specifiedType: const FullType(int))); - } - - return result; - } - - @override - Value deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ValueBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'aBool': - result.aBool = serializers.deserialize(value, - specifiedType: const FullType(bool)); - break; - case 'aDouble': - result.aDouble = serializers.deserialize(value, - specifiedType: const FullType(double)); - break; - case 'anInt': - result.anInt = serializers.deserialize(value, - specifiedType: const FullType(int)); - break; - } - } - } - - return result.build(); - } -} -'''); - }); - - test('generates correct serializer for built_value with collections', - () async { - expect( - await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -abstract class Value implements Built { - static final Serializer serializer = _$serializer; - BuiltList get aList; - BuiltMap get aMap; -} - -abstract class ValueBuilder implements Builder { - ListBuilder aList; - MapBuilder aMap; -} -'''), - r''' -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of value; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library value -// ************************************************************************** - -Serializer _$valueSerializer = new _$ValueSerializer(); - -class _$ValueSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Value, _$Value]); - final String wireName = 'Value'; - - @override - Iterable serialize(Serializers serializers, Value object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'aList', - serializers.serialize(object.aList, - specifiedType: - const FullType(BuiltList, const [const FullType(String)])), - 'aMap', - serializers.serialize(object.aMap, - specifiedType: const FullType( - BuiltMap, const [const FullType(String), const FullType(int)])), - ]; - - return result; - } - - @override - Value deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ValueBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'aList': - result.aList.replace(serializers.deserialize(value, - specifiedType: - const FullType(BuiltList, const [const FullType(String)]))); - break; - case 'aMap': - result.aMap.replace(serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, - const [const FullType(String), const FullType(int)]))); - break; - } - } - } - - return result.build(); - } -} -'''); - }); - - test('generates correct serializer for nested built_value', () async { - expect( - await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -abstract class Value implements Built { - static final Serializer serializer = _$serializer; - Value get value; -} - -abstract class ValueBuilder implements Builder { - ValueBuilder value; -} -'''), - r''' -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of value; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library value -// ************************************************************************** - -Serializer _$valueSerializer = new _$ValueSerializer(); - -class _$ValueSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Value, _$Value]); - final String wireName = 'Value'; - - @override - Iterable serialize(Serializers serializers, Value object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'value', - serializers.serialize(object.value, specifiedType: const FullType(Value)), - ]; - - return result; - } - - @override - Value deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ValueBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'value': - result.value.replace(serializers.deserialize(value, - specifiedType: const FullType(Value))); - break; - } - } - } - - return result.build(); - } -} -'''); - }); - - test('generates correct serializer for EnumClass', () async { - expect( - await generate(r''' -library value; - -import 'package:test_support/test_support.dart'; - -abstract class TestEnum extends EnumClass { - static final Serializer serializer = _$serializer; - - static const TestEnum yes = _$yes; - static const TestEnum no = _$no; - static const TestEnum maybe = _$maybe; -} -'''), - r''' -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of value; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library value -// ************************************************************************** - -Serializer _$testEnumSerializer = new _$TestEnumSerializer(); - -class _$TestEnumSerializer implements PrimitiveSerializer { - final Iterable types = new BuiltList([TestEnum]); - final String wireName = 'TestEnum'; - - @override - Object serialize(Serializers serializers, TestEnum object, - {FullType specifiedType: FullType.unspecified}) { - return object.name; - } - - @override - TestEnum deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return TestEnum.valueOf(serialized); - } -} -'''); - }); - }); -} - -// Test setup. - -final String pkgName = 'pkg'; -final PackageGraph packageGraph = - new PackageGraph.fromRoot(new PackageNode(pkgName, null, null, null)); - -final PhaseGroup phaseGroup = new PhaseGroup.singleAction( - new GeneratorBuilder([new BuiltJsonGenerator()]), - new InputSet(pkgName, const ['lib/*.dart'])); - -Future generate(String source) async { - final srcs = { - 'test_support|lib/test_support.dart': testSupportSource, - '$pkgName|lib/value.dart': source, - }; - - final writer = new InMemoryAssetWriter(); - await testPhases(phaseGroup, srcs, - packageGraph: packageGraph, writer: writer); - return writer.assets[new AssetId(pkgName, 'lib/value.g.dart')]?.value ?? ''; -} - -// Classes mentioned in the test input need to exist, but we don't need the -// real versions. So just use minimal ones. -const String testSupportSource = r''' -const String nullable = 'nullable'; - -class Built {} - -class BuiltList {} - -class BuiltMap {} - -class EnumClass {} - -class Serializer {} - -class Serializers {} -'''; diff --git a/built_json_generator/tool/build.dart b/built_json_generator/tool/build.dart deleted file mode 100644 index 649e972..0000000 --- a/built_json_generator/tool/build.dart +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:build/build.dart'; -import 'package:built_value_generator/built_value_generator.dart'; -import 'package:source_gen/source_gen.dart'; - -Future main(List args) async { - await build( - new PhaseGroup.singleAction( - new GeneratorBuilder([new BuiltValueGenerator()]), - new InputSet('built_json_generator', const ['lib/**/*.dart'])), - deleteFilesByDefault: true); -} diff --git a/chat_example/.analysis_options b/chat_example/.analysis_options deleted file mode 100644 index 39114b9..0000000 --- a/chat_example/.analysis_options +++ /dev/null @@ -1,2 +0,0 @@ -analyzer: - strong-mode: true diff --git a/chat_example/README.md b/chat_example/README.md deleted file mode 100644 index bada2c2..0000000 --- a/chat_example/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# built_json chat example - -A simple chat client (dart2js) and server (Dart VM). - -Launch the server: - -`dart bin/main.dart` - -This will immediately work in Dartium, connect to `localhost:26199`. To build for js, run: - -`pub build` - -When developing, run - -`dart tool/watch.dart` - -to continuously update generated source. diff --git a/chat_example/bin/main.dart b/chat_example/bin/main.dart deleted file mode 100644 index b5f393a..0000000 --- a/chat_example/bin/main.dart +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:chat_example/server/http_server_connection.dart'; -import 'package:chat_example/server/resource_server.dart'; -import 'package:chat_example/server/server.dart'; - -void main() { - final server = new Server(); - new ResourceServer().start( - (webSocket) => server.addConnection(new HttpServerConnection(webSocket))); -} diff --git a/chat_example/lib/client/client.dart b/chat_example/lib/client/client.dart deleted file mode 100644 index 85249bd..0000000 --- a/chat_example/lib/client/client.dart +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:convert'; - -import 'package:chat_example/client/client_connection.dart'; -import 'package:chat_example/client/display.dart'; -import 'package:chat_example/data_model/data_model.dart'; -import 'package:chat_example/data_model/serializers.dart'; - -typedef CommandRunner(String command); - -/// Client-side logic for built_json chat example. -class Client { - final Stream _keyboardInput; - final Display _display; - final ClientConnection _connection; - - /// A chat client needs a keyboard, a display and a connection. - Client(this._keyboardInput, this._display, this._connection) { - _keyboardInput.listen(_runLocalCommand); - _connection.dataFromServer.listen(_handleServerData); - } - - void _handleServerData(String data) { - final response = serializers.deserialize(JSON.decode(data)); - - if (response is Response) { - _display.add(response.render()); - } else { - throw new StateError('Invalid data from server: $response'); - } - } - - void _runLocalCommand(String command) { - final handlers = { - '/away': _runAway, - '/help': _runHelp, - '/list': _runList, - '/login': _runLogin, - '/quit': _runQuit, - '/status': _runStatus, - '/tell': _runTell, - }; - - var found = false; - handlers.forEach((prefix, commandRunner) { - if (command.startsWith(prefix)) { - commandRunner(command); - found = true; - } - }); - if (found) return; - - if (command.startsWith('/')) { - _display.addLocal(command); - _display.add('Unknown command.'); - return; - } - - _send(new Chat((b) => b..text = command)); - } - - void _runAway(String command) { - _send(new Status((b) => b - ..message = command.substring('/away '.length) - ..type = StatusType.away)); - } - - void _runHelp(String command) { - _display.add('''Commands: - -/away -- sets away message -/help -- for help -/list -- list online users -/login -- log in or create new user -/quit -- quits with message -/status -- sets status message -/tell -- private message -'''); - } - - void _runList(String command) { - _display.addLocal(command); - _send(new ListUsers( - (b) => b..statusTypes.replace([StatusType.online, StatusType.away]))); - } - - void _runLogin(String command) { - final words = command.split(' '); - _display.addLocal('/login ${words[1]} ********'); - _send(new Login((b) => b - ..username = words[1] - ..password = words[2])); - } - - void _runQuit(String command) { - _display.addLocal(command); - _send(new Status((b) => b - ..message = command.substring('/quit '.length) - ..type = StatusType.offline)); - } - - void _runStatus(String command) { - _display.addLocal(command); - _display.addLocal(command); - _send(new Status((b) => b - ..message = command.substring('/status '.length) - ..type = StatusType.online)); - } - - void _runTell(String command) { - _display.addLocal(command); - final words = command.split(' '); - final targets = words[1].split(','); - _send(new Chat((b) => b - ..text = words.sublist(2).join(' ') - ..targets.replace(targets))); - } - - void _send(Command command) { - _connection.sendToServer(JSON.encode(serializers.serialize(command))); - } -} diff --git a/chat_example/lib/client/client_connection.dart b/chat_example/lib/client/client_connection.dart deleted file mode 100644 index 66f4243..0000000 --- a/chat_example/lib/client/client_connection.dart +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -/// Two-way connection between client and server; the client. -abstract class ClientConnection { - Stream get dataFromServer; - - void sendToServer(String string); -} diff --git a/chat_example/lib/client/display.dart b/chat_example/lib/client/display.dart deleted file mode 100644 index 060b611..0000000 --- a/chat_example/lib/client/display.dart +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/// Chat window main text display. -abstract class Display { - /// Adds [text] to the display, coloured to indicate a local command. - void addLocal(String text); - - /// Adds [text] to the display. - void add(String text); -} diff --git a/chat_example/lib/client/html_display.dart b/chat_example/lib/client/html_display.dart deleted file mode 100644 index 2dd36c4..0000000 --- a/chat_example/lib/client/html_display.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:convert'; -import 'dart:html'; - -import 'package:chat_example/client/display.dart'; - -/// [Display] using `dart:html`. -class HtmlDisplay implements Display { - final Element _element; - final HtmlEscape _htmlEscape = const HtmlEscape(); - - factory HtmlDisplay() { - return new HtmlDisplay._(querySelector('#text')); - } - - HtmlDisplay._(this._element) { - add('Welcome to the built_json chat example. For help, type /help.'); - } - - void addLocal(String text) { - _element.innerHtml += - '
${_htmlEscape.convert(text)}
'; - window.scrollTo(0, document.body.scrollHeight); - } - - void add(String text) { - _element.innerHtml += - '${_htmlEscape.convert(text).replaceAll('\n', '
')}
'; - window.scrollTo(0, document.body.scrollHeight); - } -} diff --git a/chat_example/lib/client/http_client_connection.dart b/chat_example/lib/client/http_client_connection.dart deleted file mode 100644 index a4adaa9..0000000 --- a/chat_example/lib/client/http_client_connection.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:html'; - -import 'package:chat_example/client/client_connection.dart'; - -/// [ClientConnection] using a web socket. -class HttpClientConnection implements ClientConnection { - final WebSocket _websocket; - final StreamController _streamController = - new StreamController(); - - factory HttpClientConnection() { - return new HttpClientConnection._( - new WebSocket('ws://${window.location.host}/ws')); - } - - HttpClientConnection._(this._websocket) { - _websocket.onMessage.listen((message) { - _streamController.add(message.data as String); - }); - } - - Stream get dataFromServer => _streamController.stream; - - void sendToServer(String data) { - _websocket.send(data); - } -} diff --git a/chat_example/lib/client/input.dart b/chat_example/lib/client/input.dart deleted file mode 100644 index a3142ca..0000000 --- a/chat_example/lib/client/input.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:html'; - -/// An input box using `dart:html`. -class Input { - final StreamController _streamController = - new StreamController(); - - Input() { - final input = querySelector('#input') as InputElement; - - input.onKeyPress.listen((keyEvent) { - if (keyEvent.keyCode == KeyCode.ENTER) { - _streamController.add(input.value); - input.value = ''; - } - }); - } - - Stream get keyboardInput => _streamController.stream; -} diff --git a/chat_example/lib/client/layout.dart b/chat_example/lib/client/layout.dart deleted file mode 100644 index 11f753b..0000000 --- a/chat_example/lib/client/layout.dart +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:html'; - -/// Forces focus to the input box. -class Layout { - Layout() { - final screen = querySelector('#screen'); - final text = querySelector('#text'); - final input = querySelector('#input'); - - input.focus(); - - for (final element in [screen, text]) { - element.onClick.listen((e) { - input.focus(); - }); - } - } -} diff --git a/chat_example/lib/data_model/data_model.dart b/chat_example/lib/data_model/data_model.dart deleted file mode 100644 index 6d6b33c..0000000 --- a/chat_example/lib/data_model/data_model.dart +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/// Data model for the built_json chat example. -library data_model; - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:built_value/built_value.dart'; -import 'package:enum_class/enum_class.dart'; - -part 'data_model.g.dart'; - -/// Marker interface for classes sent from client to server. -abstract class Command {} - -/// Sends a chat. -abstract class Chat implements Built, Command { - static Serializer get serializer => _$chatSerializer; - - // Chat text. - String get text; - - /// Set of usernames to send the chat to, or empty to send to everyone. - BuiltSet get targets; - - Chat._(); - factory Chat([updates(ChatBuilder b)]) = _$Chat; -} - -/// Logs in. -abstract class Login implements Built, Command { - static Serializer get serializer => _$loginSerializer; - String get username; - String get password; - - Login._(); - factory Login([updates(LoginBuilder b)]) = _$Login; -} - -/// User status: online, away or offline, and a message. -/// -/// Sent as a command, sets the current user status. -abstract class Status implements Built, Command { - static Serializer get serializer => _$statusSerializer; - String get message; - StatusType get type; - - Status._(); - factory Status([updates(StatusBuilder b)]) = _$Status; -} - -/// User status: online, away or offline. -class StatusType extends EnumClass { - static Serializer serializer = _$statusTypeSerializer; - - static const StatusType online = _$online; - static const StatusType away = _$away; - static const StatusType offline = _$offline; - - const StatusType._(String name) : super(name); - - static BuiltSet get values => _$stValues; - static StatusType valueOf(String name) => _$stValueOf(name); -} - -/// Lists users, filtered by status. -abstract class ListUsers - implements Built, Command { - static Serializer get serializer => _$listUsersSerializer; - - /// Set of statuses to filter by. - BuiltSet get statusTypes; - - ListUsers._(); - factory ListUsers([updates(ListUsersBuilder b)]) = _$ListUsers; -} - -/// Classes sent from server to client. -abstract class Response { - String render(); -} - -/// Response to a login attempt. -class LoginResponse extends EnumClass implements Response { - static Serializer get serializer => _$loginResponseSerializer; - static const LoginResponse success = _$success; - static const LoginResponse badPassword = _$badPassword; - static const LoginResponse reset = _$reset; - - const LoginResponse._(String name) : super(name); - - static BuiltSet get values => _$lrValues; - static LoginResponse valueOf(String name) => _$lrValueOf(name); - - @override - String render() { - switch (this) { - case success: - return 'You have logged in successfully.'; - case badPassword: - return 'Incorrect password.'; - case reset: - return 'You have been logged out.'; - default: - throw new StateError(this.name); - } - } -} - -/// Displays a chat message. -abstract class ShowChat implements Built, Response { - static Serializer get serializer => _$showChatSerializer; - - /// Originator of the message. - String get username; - - /// Whether the message is a /tell or a general message. - bool get private; - - /// Message text. - String get text; - - ShowChat._(); - factory ShowChat([updates(ShowChatBuilder b)]) = _$ShowChat; - - @override - String render() => '$username${private ? " (private)" : ""}: $text'; -} - -/// Displays a list of users and their status messages. -abstract class ListUsersResponse - implements Built, Response { - static Serializer get serializer => - _$listUsersResponseSerializer; - - /// Map from username to status. - BuiltMap get statuses; - - ListUsersResponse._(); - factory ListUsersResponse([updates(ListUsersResponseBuilder b)]) = - _$ListUsersResponse; - - @override - String render() { - final result = new StringBuffer('The following users are online:\n\n'); - for (final username in statuses.keys) { - final status = statuses[username]; - result.write( - status.message.isEmpty ? username : '$username ${status.message}'); - result.write('\n'); - } - return result.toString(); - } -} diff --git a/chat_example/lib/data_model/data_model.g.dart b/chat_example/lib/data_model/data_model.g.dart deleted file mode 100644 index a1b05e6..0000000 --- a/chat_example/lib/data_model/data_model.g.dart +++ /dev/null @@ -1,762 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of data_model; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library data_model -// ************************************************************************** - -Serializer _$chatSerializer = new _$ChatSerializer(); -Serializer _$loginSerializer = new _$LoginSerializer(); -Serializer _$statusSerializer = new _$StatusSerializer(); -Serializer _$statusTypeSerializer = new _$StatusTypeSerializer(); -Serializer _$listUsersSerializer = new _$ListUsersSerializer(); -Serializer _$loginResponseSerializer = - new _$LoginResponseSerializer(); -Serializer _$showChatSerializer = new _$ShowChatSerializer(); -Serializer _$listUsersResponseSerializer = - new _$ListUsersResponseSerializer(); - -class _$ChatSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Chat, _$Chat]); - final String wireName = 'Chat'; - - @override - Iterable serialize(Serializers serializers, Chat object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'text', - serializers.serialize(object.text, specifiedType: const FullType(String)), - 'targets', - serializers.serialize(object.targets, - specifiedType: - const FullType(BuiltSet, const [const FullType(String)])), - ]; - - return result; - } - - @override - Chat deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ChatBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'text': - result.text = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - case 'targets': - result.targets.replace(serializers.deserialize(value, - specifiedType: - const FullType(BuiltSet, const [const FullType(String)]))); - break; - } - } - } - - return result.build(); - } -} - -class _$LoginSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Login, _$Login]); - final String wireName = 'Login'; - - @override - Iterable serialize(Serializers serializers, Login object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'username', - serializers.serialize(object.username, - specifiedType: const FullType(String)), - 'password', - serializers.serialize(object.password, - specifiedType: const FullType(String)), - ]; - - return result; - } - - @override - Login deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new LoginBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'username': - result.username = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - case 'password': - result.password = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - } - } - } - - return result.build(); - } -} - -class _$StatusSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Status, _$Status]); - final String wireName = 'Status'; - - @override - Iterable serialize(Serializers serializers, Status object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'message', - serializers.serialize(object.message, - specifiedType: const FullType(String)), - 'type', - serializers.serialize(object.type, - specifiedType: const FullType(StatusType)), - ]; - - return result; - } - - @override - Status deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new StatusBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'message': - result.message = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - case 'type': - result.type = serializers.deserialize(value, - specifiedType: const FullType(StatusType)); - break; - } - } - } - - return result.build(); - } -} - -class _$StatusTypeSerializer implements PrimitiveSerializer { - final Iterable types = new BuiltList([StatusType]); - final String wireName = 'StatusType'; - - @override - Object serialize(Serializers serializers, StatusType object, - {FullType specifiedType: FullType.unspecified}) { - return object.name; - } - - @override - StatusType deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return StatusType.valueOf(serialized); - } -} - -class _$ListUsersSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([ListUsers, _$ListUsers]); - final String wireName = 'ListUsers'; - - @override - Iterable serialize(Serializers serializers, ListUsers object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'statusTypes', - serializers.serialize(object.statusTypes, - specifiedType: - const FullType(BuiltSet, const [const FullType(StatusType)])), - ]; - - return result; - } - - @override - ListUsers deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ListUsersBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'statusTypes': - result.statusTypes.replace(serializers.deserialize(value, - specifiedType: const FullType( - BuiltSet, const [const FullType(StatusType)]))); - break; - } - } - } - - return result.build(); - } -} - -class _$LoginResponseSerializer implements PrimitiveSerializer { - final Iterable types = new BuiltList([LoginResponse]); - final String wireName = 'LoginResponse'; - - @override - Object serialize(Serializers serializers, LoginResponse object, - {FullType specifiedType: FullType.unspecified}) { - return object.name; - } - - @override - LoginResponse deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return LoginResponse.valueOf(serialized); - } -} - -class _$ShowChatSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([ShowChat, _$ShowChat]); - final String wireName = 'ShowChat'; - - @override - Iterable serialize(Serializers serializers, ShowChat object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'username', - serializers.serialize(object.username, - specifiedType: const FullType(String)), - 'private', - serializers.serialize(object.private, - specifiedType: const FullType(bool)), - 'text', - serializers.serialize(object.text, specifiedType: const FullType(String)), - ]; - - return result; - } - - @override - ShowChat deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ShowChatBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'username': - result.username = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - case 'private': - result.private = serializers.deserialize(value, - specifiedType: const FullType(bool)); - break; - case 'text': - result.text = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - } - } - } - - return result.build(); - } -} - -class _$ListUsersResponseSerializer - implements StructuredSerializer { - final Iterable types = - new BuiltList([ListUsersResponse, _$ListUsersResponse]); - final String wireName = 'ListUsersResponse'; - - @override - Iterable serialize(Serializers serializers, ListUsersResponse object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'statuses', - serializers.serialize(object.statuses, - specifiedType: const FullType(BuiltMap, - const [const FullType(String), const FullType(Status)])), - ]; - - return result; - } - - @override - ListUsersResponse deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ListUsersResponseBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'statuses': - result.statuses.replace(serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, - const [const FullType(String), const FullType(Status)]))); - break; - } - } - } - - return result.build(); - } -} - -// ************************************************************************** -// Generator: EnumClassGenerator -// Target: library data_model -// ************************************************************************** - -const StatusType _$online = const StatusType._('online'); -const StatusType _$away = const StatusType._('away'); -const StatusType _$offline = const StatusType._('offline'); - -StatusType _$stValueOf(String name) { - switch (name) { - case 'online': - return _$online; - case 'away': - return _$away; - case 'offline': - return _$offline; - default: - throw new ArgumentError(name); - } -} - -final BuiltSet _$stValues = new BuiltSet(const [ - _$online, - _$away, - _$offline, -]); - -const LoginResponse _$success = const LoginResponse._('success'); -const LoginResponse _$badPassword = const LoginResponse._('badPassword'); -const LoginResponse _$reset = const LoginResponse._('reset'); - -LoginResponse _$lrValueOf(String name) { - switch (name) { - case 'success': - return _$success; - case 'badPassword': - return _$badPassword; - case 'reset': - return _$reset; - default: - throw new ArgumentError(name); - } -} - -final BuiltSet _$lrValues = new BuiltSet(const [ - _$success, - _$badPassword, - _$reset, -]); - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class Chat -// ************************************************************************** - -class _$Chat extends Chat { - final String text; - final BuiltSet targets; - - _$Chat._({this.text, this.targets}) : super._() { - if (text == null) throw new ArgumentError('null text'); - if (targets == null) throw new ArgumentError('null targets'); - } - - factory _$Chat([updates(ChatBuilder b)]) => - (new ChatBuilder()..update(updates)).build(); - - Chat rebuild(updates(ChatBuilder b)) => - (toBuilder()..update(updates)).build(); - - ChatBuilder toBuilder() => new ChatBuilder()..replace(this); - - bool operator ==(other) { - if (other is! Chat) return false; - return text == other.text && targets == other.targets; - } - - int get hashCode { - return hashObjects([text, targets]); - } - - String toString() { - return 'Chat {' - 'text=${text.toString()},\n' - 'targets=${targets.toString()},\n' - '}'; - } -} - -class ChatBuilder implements Builder { - ChatBuilder(); - String text; - SetBuilder targets = new SetBuilder(); - - void replace(Chat other) { - this.text = other.text; - this.targets = other.targets?.toBuilder(); - } - - void update(updates(ChatBuilder b)) { - if (updates != null) updates(this); - } - - Chat build() { - return new _$Chat._(text: text, targets: targets?.build()); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class Login -// ************************************************************************** - -class _$Login extends Login { - final String username; - final String password; - - _$Login._({this.username, this.password}) : super._() { - if (username == null) throw new ArgumentError('null username'); - if (password == null) throw new ArgumentError('null password'); - } - - factory _$Login([updates(LoginBuilder b)]) => - (new LoginBuilder()..update(updates)).build(); - - Login rebuild(updates(LoginBuilder b)) => - (toBuilder()..update(updates)).build(); - - LoginBuilder toBuilder() => new LoginBuilder()..replace(this); - - bool operator ==(other) { - if (other is! Login) return false; - return username == other.username && password == other.password; - } - - int get hashCode { - return hashObjects([username, password]); - } - - String toString() { - return 'Login {' - 'username=${username.toString()},\n' - 'password=${password.toString()},\n' - '}'; - } -} - -class LoginBuilder implements Builder { - LoginBuilder(); - String username; - String password; - - void replace(Login other) { - this.username = other.username; - this.password = other.password; - } - - void update(updates(LoginBuilder b)) { - if (updates != null) updates(this); - } - - Login build() { - return new _$Login._(username: username, password: password); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class Status -// ************************************************************************** - -class _$Status extends Status { - final String message; - final StatusType type; - - _$Status._({this.message, this.type}) : super._() { - if (message == null) throw new ArgumentError('null message'); - if (type == null) throw new ArgumentError('null type'); - } - - factory _$Status([updates(StatusBuilder b)]) => - (new StatusBuilder()..update(updates)).build(); - - Status rebuild(updates(StatusBuilder b)) => - (toBuilder()..update(updates)).build(); - - StatusBuilder toBuilder() => new StatusBuilder()..replace(this); - - bool operator ==(other) { - if (other is! Status) return false; - return message == other.message && type == other.type; - } - - int get hashCode { - return hashObjects([message, type]); - } - - String toString() { - return 'Status {' - 'message=${message.toString()},\n' - 'type=${type.toString()},\n' - '}'; - } -} - -class StatusBuilder implements Builder { - StatusBuilder(); - String message; - StatusType type; - - void replace(Status other) { - this.message = other.message; - this.type = other.type; - } - - void update(updates(StatusBuilder b)) { - if (updates != null) updates(this); - } - - Status build() { - return new _$Status._(message: message, type: type); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class ListUsers -// ************************************************************************** - -class _$ListUsers extends ListUsers { - final BuiltSet statusTypes; - - _$ListUsers._({this.statusTypes}) : super._() { - if (statusTypes == null) throw new ArgumentError('null statusTypes'); - } - - factory _$ListUsers([updates(ListUsersBuilder b)]) => - (new ListUsersBuilder()..update(updates)).build(); - - ListUsers rebuild(updates(ListUsersBuilder b)) => - (toBuilder()..update(updates)).build(); - - ListUsersBuilder toBuilder() => new ListUsersBuilder()..replace(this); - - bool operator ==(other) { - if (other is! ListUsers) return false; - return statusTypes == other.statusTypes; - } - - int get hashCode { - return hashObjects([statusTypes]); - } - - String toString() { - return 'ListUsers {' - 'statusTypes=${statusTypes.toString()},\n' - '}'; - } -} - -class ListUsersBuilder implements Builder { - ListUsersBuilder(); - SetBuilder statusTypes = new SetBuilder(); - - void replace(ListUsers other) { - this.statusTypes = other.statusTypes?.toBuilder(); - } - - void update(updates(ListUsersBuilder b)) { - if (updates != null) updates(this); - } - - ListUsers build() { - return new _$ListUsers._(statusTypes: statusTypes?.build()); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class ShowChat -// ************************************************************************** - -class _$ShowChat extends ShowChat { - final String username; - final bool private; - final String text; - - _$ShowChat._({this.username, this.private, this.text}) : super._() { - if (username == null) throw new ArgumentError('null username'); - if (private == null) throw new ArgumentError('null private'); - if (text == null) throw new ArgumentError('null text'); - } - - factory _$ShowChat([updates(ShowChatBuilder b)]) => - (new ShowChatBuilder()..update(updates)).build(); - - ShowChat rebuild(updates(ShowChatBuilder b)) => - (toBuilder()..update(updates)).build(); - - ShowChatBuilder toBuilder() => new ShowChatBuilder()..replace(this); - - bool operator ==(other) { - if (other is! ShowChat) return false; - return username == other.username && - private == other.private && - text == other.text; - } - - int get hashCode { - return hashObjects([username, private, text]); - } - - String toString() { - return 'ShowChat {' - 'username=${username.toString()},\n' - 'private=${private.toString()},\n' - 'text=${text.toString()},\n' - '}'; - } -} - -class ShowChatBuilder implements Builder { - ShowChatBuilder(); - String username; - bool private; - String text; - - void replace(ShowChat other) { - this.username = other.username; - this.private = other.private; - this.text = other.text; - } - - void update(updates(ShowChatBuilder b)) { - if (updates != null) updates(this); - } - - ShowChat build() { - return new _$ShowChat._(username: username, private: private, text: text); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class ListUsersResponse -// ************************************************************************** - -class _$ListUsersResponse extends ListUsersResponse { - final BuiltMap statuses; - - _$ListUsersResponse._({this.statuses}) : super._() { - if (statuses == null) throw new ArgumentError('null statuses'); - } - - factory _$ListUsersResponse([updates(ListUsersResponseBuilder b)]) => - (new ListUsersResponseBuilder()..update(updates)).build(); - - ListUsersResponse rebuild(updates(ListUsersResponseBuilder b)) => - (toBuilder()..update(updates)).build(); - - ListUsersResponseBuilder toBuilder() => - new ListUsersResponseBuilder()..replace(this); - - bool operator ==(other) { - if (other is! ListUsersResponse) return false; - return statuses == other.statuses; - } - - int get hashCode { - return hashObjects([statuses]); - } - - String toString() { - return 'ListUsersResponse {' - 'statuses=${statuses.toString()},\n' - '}'; - } -} - -class ListUsersResponseBuilder - implements Builder { - ListUsersResponseBuilder(); - MapBuilder statuses = new MapBuilder(); - - void replace(ListUsersResponse other) { - this.statuses = other.statuses?.toBuilder(); - } - - void update(updates(ListUsersResponseBuilder b)) { - if (updates != null) updates(this); - } - - ListUsersResponse build() { - return new _$ListUsersResponse._(statuses: statuses?.build()); - } -} diff --git a/chat_example/lib/data_model/serializers.dart b/chat_example/lib/data_model/serializers.dart deleted file mode 100644 index b425ad5..0000000 --- a/chat_example/lib/data_model/serializers.dart +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library serializers; - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:chat_example/data_model/data_model.dart'; - -part 'serializers.g.dart'; - -/// Collection of generated serializers for the built_json chat example. -Serializers serializers = _$serializers; diff --git a/chat_example/lib/data_model/serializers.g.dart b/chat_example/lib/data_model/serializers.g.dart deleted file mode 100644 index 3d94bb8..0000000 --- a/chat_example/lib/data_model/serializers.g.dart +++ /dev/null @@ -1,29 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of serializers; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library serializers -// ************************************************************************** - -Serializers _$serializers = (new Serializers().toBuilder() - ..add(Chat.serializer) - ..addBuilderFactory( - const FullType(BuiltSet, const [const FullType(String)]), - () => new SetBuilder()) - ..add(Login.serializer) - ..add(Status.serializer) - ..add(StatusType.serializer) - ..add(ListUsers.serializer) - ..addBuilderFactory( - const FullType(BuiltSet, const [const FullType(StatusType)]), - () => new SetBuilder()) - ..add(LoginResponse.serializer) - ..add(ShowChat.serializer) - ..add(ListUsersResponse.serializer) - ..addBuilderFactory( - const FullType( - BuiltMap, const [const FullType(String), const FullType(Status)]), - () => new MapBuilder())) - .build(); diff --git a/chat_example/lib/server/http_server_connection.dart b/chat_example/lib/server/http_server_connection.dart deleted file mode 100644 index 5e541de..0000000 --- a/chat_example/lib/server/http_server_connection.dart +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:io'; - -import 'package:chat_example/server/server_connection.dart'; - -/// [ServerConnection] using a web socket. -class HttpServerConnection implements ServerConnection { - final WebSocket _webSocket; - final StreamController _streamController = - new StreamController(); - - @override - String username; - - HttpServerConnection(this._webSocket) { - _webSocket.listen((data) { - _streamController.add(data); - }); - } - - Stream get dataFromClient => _streamController.stream; - - void sendToClient(String data) { - _webSocket.add(data); - } - - @override - void close() { - _webSocket.close(); - } -} diff --git a/chat_example/lib/server/resource_server.dart b/chat_example/lib/server/resource_server.dart deleted file mode 100644 index 2a10ff2..0000000 --- a/chat_example/lib/server/resource_server.dart +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; -import 'dart:io'; - -import 'package:package_resolver/package_resolver.dart'; -import 'package:route/server.dart'; - -typedef SocketReceiver(WebSocket webSocket); - -/// Serves static resources for the built_json chat example. -/// -/// Also, accepts web socket connections. -class ResourceServer { - /// Serves resources, passing new sockets to [socketReceiver]. - Future start(SocketReceiver socketReceiver) async { - final server = await HttpServer.bind('localhost', 26199); - print('Serving at localhost:26199.'); - final router = new Router(server); - router.serve('/').listen((request) { - request.response - ..statusCode = HttpStatus.OK - ..headers.contentType = - new ContentType('text', 'html', charset: 'utf-8') - ..write(new File('web/index.html').readAsStringSync()) - ..close(); - }); - - router.serve('/main.dart').listen((request) { - request.response - ..statusCode = HttpStatus.OK - ..headers.contentType = - new ContentType('application', 'dart', charset: 'utf-8') - ..write(new File('web/main.dart').readAsStringSync()) - ..close(); - }); - - router.serve(new RegExp(r'.*\.dart$')).listen((request) async { - var path = request.uri.path; - - if (path.startsWith('/packages/')) { - final package = path - .replaceFirst('/packages/', '') - .replaceFirst(new RegExp('/.*'), ''); - final resolved = await PackageResolver.current.packagePath(package); - path = resolved + '/lib' + path.replaceFirst('/packages/$package', ''); - } else { - path = '.$path'; - } - - request.response - ..statusCode = HttpStatus.OK - ..headers.contentType = - new ContentType('application', 'dart', charset: 'utf-8') - ..write(new File(path).readAsStringSync()) - ..close(); - }); - - router.serve('/main.css').listen((request) { - request.response - ..statusCode = HttpStatus.OK - ..headers.contentType = new ContentType('text', 'css', charset: 'utf-8') - ..write(new File('web/main.css').readAsStringSync()) - ..close(); - }); - - router - .serve('/ws') - .transform( - new WebSocketTransformer(compression: CompressionOptions.OFF)) - .listen(socketReceiver); - } -} diff --git a/chat_example/lib/server/server.dart b/chat_example/lib/server/server.dart deleted file mode 100644 index 63b091a..0000000 --- a/chat_example/lib/server/server.dart +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:convert'; -import 'dart:math'; - -import 'package:built_collection/built_collection.dart'; -import 'package:chat_example/data_model/data_model.dart'; -import 'package:chat_example/data_model/serializers.dart'; -import 'package:chat_example/server/server_connection.dart'; - -/// Server-side logic for the built_json chat example. -class Server { - final Random random = new Random(); - final Set _connections = new Set(); - final Map _passwords = {}; - final Map _statuses = {}; - - /// Adds a new connection to the server. - /// - /// A random username is assigned. - void addConnection(ServerConnection connection) { - final username = 'anon${random.nextInt(10000)}'; - connection.username = username; - _connections.add(connection); - _send( - connection, - new ShowChat((b) => b - ..username = 'server' - ..private = false - ..text = 'You are connected as $username.')); - connection.dataFromClient - .listen((string) => _handleDataFromClient(connection, string)); - } - - void _handleDataFromClient(ServerConnection connection, String data) { - final command = serializers.deserialize(JSON.decode(data)); - - if (command is Chat) { - _chat(connection, command); - } else if (command is Login) { - _login(connection, command); - } else if (command is Status) { - _status(connection, command); - } else if (command is ListUsers) { - _listUsers(connection, command); - } else { - throw new StateError('Invalid data from client: $command'); - } - } - - void _chat(ServerConnection connection, Chat chat) { - if (chat.targets.isEmpty) { - _sendToAll(new ShowChat((b) => b - ..username = connection.username - ..private = false - ..text = chat.text)); - } else { - _sendTo( - chat.targets, - new ShowChat((b) => b - ..username = connection.username - ..private = true - ..text = chat.text)); - } - } - - void _listUsers(ServerConnection connection, ListUsers listUsers) { - _send( - connection, - new ListUsersResponse((b) => _statuses.forEach((username, status) { - if (listUsers.statusTypes.contains(status.type)) { - b.statuses[username] = status; - } - }))); - } - - void _login(ServerConnection connection, Login login) { - if (_passwords.containsKey(login.username)) { - if (_passwords[login.username] != login.password) { - _send(connection, LoginResponse.badPassword); - return; - } - } else { - _passwords[login.username] = login.password; - } - - for (final existingConnection in _connections) { - if (existingConnection.username == login.username) { - existingConnection.username = 'anon${random.nextInt(10000)}'; - _send(existingConnection, LoginResponse.reset); - } - } - - _statuses[login.username] = new Status((b) => b - ..message = '' - ..type = StatusType.online); - - connection.username = login.username; - _send(connection, LoginResponse.success); - } - - void _status(ServerConnection connection, Status status) { - _statuses[connection.username] = status; - if (status.type == StatusType.offline) { - _connections.remove(connection); - connection.close(); - } - } - - void _sendTo(BuiltSet usernames, Response response) { - for (final connection in _connections) { - if (usernames.contains(connection.username)) { - _send(connection, response); - } - } - } - - void _sendToAll(Response response) { - for (final connection in _connections) { - _send(connection, response); - } - } - - static void _send(ServerConnection connection, Response response) { - connection.sendToClient(JSON.encode(serializers.serialize(response))); - } -} diff --git a/chat_example/lib/server/server_connection.dart b/chat_example/lib/server/server_connection.dart deleted file mode 100644 index b7ab0bc..0000000 --- a/chat_example/lib/server/server_connection.dart +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -/// Two-way connection between client and server; the server. -abstract class ServerConnection { - /// The username associated with this connection. - String get username; - set username(String username); - - Stream get dataFromClient; - void sendToClient(String data); - void close(); -} diff --git a/chat_example/lib/testing/fake_client_connection.dart b/chat_example/lib/testing/fake_client_connection.dart deleted file mode 100644 index 1de698f..0000000 --- a/chat_example/lib/testing/fake_client_connection.dart +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:chat_example/client/client_connection.dart'; - -/// Fake [ClientConnection] that exposes stream controllers. -class FakeClientConnection implements ClientConnection { - final StreamController toServerStreamController = - new StreamController(sync: true); - final StreamController fromServerStreamController = - new StreamController(sync: true); - - @override - void sendToServer(String string) { - toServerStreamController.add(string); - } - - @override - Stream get dataFromServer => fromServerStreamController.stream; -} diff --git a/chat_example/lib/testing/fake_display.dart b/chat_example/lib/testing/fake_display.dart deleted file mode 100644 index 8f13363..0000000 --- a/chat_example/lib/testing/fake_display.dart +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:chat_example/client/display.dart'; - -/// Fake [Display] that stores added text. -class FakeDisplay implements Display { - List text = []; - - @override - void add(String text) { - this.text.add(text); - } - - @override - void addLocal(String text) {} -} diff --git a/chat_example/lib/testing/fake_environment.dart b/chat_example/lib/testing/fake_environment.dart deleted file mode 100644 index c65d2b7..0000000 --- a/chat_example/lib/testing/fake_environment.dart +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:chat_example/client/client.dart'; -import 'package:chat_example/server/server.dart'; -import 'package:chat_example/testing/fake_client_connection.dart'; -import 'package:chat_example/testing/fake_display.dart'; -import 'package:chat_example/testing/fake_server_connection.dart'; -import 'package:chat_example/testing/test_user.dart'; - -/// Environment for testing server and client logic together. -/// -/// The HTML display and input are faked, as are the HTTP connections. This -/// leaves the client logic and server logic available for testing. -class FakeEnvironment { - final Server server; - - factory FakeEnvironment() { - final server = new Server(); - - return new FakeEnvironment._(server); - } - - FakeEnvironment._(this.server); - - /// Creates a new user connected to this environment. - TestUser newUser() { - final clientConnection = new FakeClientConnection(); - final serverConnection = new FakeServerConnection(); - - clientConnection.toServerStreamController.stream.listen((string) { - serverConnection.fromClientStreamController.add(string); - }); - serverConnection.toClientStreamController.stream.listen((string) { - clientConnection.fromServerStreamController.add(string); - }); - - final keyboardInputController = new StreamController(sync: true); - final display = new FakeDisplay(); - new Client(keyboardInputController.stream, display, clientConnection); - server.addConnection(serverConnection); - return new TestUser(display, keyboardInputController); - } -} diff --git a/chat_example/lib/testing/fake_server_connection.dart b/chat_example/lib/testing/fake_server_connection.dart deleted file mode 100644 index db47e37..0000000 --- a/chat_example/lib/testing/fake_server_connection.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:chat_example/server/server_connection.dart'; - -/// Fake [ClientConnection] that exposes stream controllers. -class FakeServerConnection implements ServerConnection { - final StreamController toClientStreamController = - new StreamController(sync: true); - final StreamController fromClientStreamController = - new StreamController(sync: true); - - @override - String username; - - @override - void sendToClient(String data) { - toClientStreamController.add(data); - } - - @override - Stream get dataFromClient => fromClientStreamController.stream; - - @override - void close() {} -} diff --git a/chat_example/lib/testing/test_user.dart b/chat_example/lib/testing/test_user.dart deleted file mode 100644 index 8fa514c..0000000 --- a/chat_example/lib/testing/test_user.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:chat_example/testing/fake_display.dart'; -import 'package:test/test.dart'; - -/// A test user connected to the fake environment. -class TestUser { - final FakeDisplay _display; - final StreamController _inputController; - - TestUser(this._display, this._inputController); - - /// Types text as this user. - void type(String text) { - _inputController.add(text); - } - - /// Checks server responses to this user. - void expectMatch(Pattern pattern) { - expect(_display.text, anyElement(matches(pattern))); - } - - /// Checks server responses to this user. - void expectNoMatch(Pattern pattern) { - expect(_display.text, isNot(anyElement(matches(pattern)))); - } -} diff --git a/chat_example/pubspec.yaml b/chat_example/pubspec.yaml deleted file mode 100644 index ded4c8e..0000000 --- a/chat_example/pubspec.yaml +++ /dev/null @@ -1,24 +0,0 @@ -name: chat_example -version: 0.1.2 -description: > - Just an example, not for publishing. -authors: -- David Morgan -homepage: https://github.com/google/built_json.dart - -environment: - sdk: '>=1.8.0 <2.0.0' - -dependencies: - built_collection: '^1.0.0' - built_json: '^0.1.4' - built_value: '^0.1.3' - enum_class: '^1.0.0' - package_resolver: ^1.0.0 - route: '>=0.4.6' - -dev_dependencies: - built_json_generator: '^0.1.4' - built_value_generator: '^0.1.3' - enum_class_generator: '^1.0.0' - test: any diff --git a/chat_example/test/chat_test.dart b/chat_example/test/chat_test.dart deleted file mode 100644 index 692f96e..0000000 --- a/chat_example/test/chat_test.dart +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:chat_example/data_model/data_model.dart'; -import 'package:chat_example/testing/fake_environment.dart'; -import 'package:test/test.dart'; - -void main() { - FakeEnvironment environment; - - setUp(() { - environment = new FakeEnvironment(); - }); - - group('on connect', () { - test('client sees login message', () async { - final alice = environment.newUser(); - - alice.expectMatch('.*You are connected as .*'); - }); - - test('clients can exchange messages', () async { - final alice = environment.newUser(); - final bob = environment.newUser(); - - alice.type('Hi, Bob!'); - bob.expectMatch('anon.*: Hi, Bob!'); - - bob.type('Hi, Alice!'); - alice.expectMatch('anon.*: Hi, Alice!'); - }); - }); - - group('login', () { - test('announces success to self', () async { - final alice = environment.newUser(); - - alice - ..type('/login Alice letmein') - ..expectMatch(LoginResponse.success.render()); - }); - - test('changes name', () async { - final alice = environment.newUser(); - final bob = environment.newUser(); - - alice..type('/login Alice letmein')..type('Hi, Bob!'); - bob.expectMatch('Alice: Hi, Bob!'); - }); - - test('fails with wrong password', () async { - final alice = environment.newUser(); - final bob = environment.newUser(); - - alice.type('/login Alice letmein'); - bob.type('/login Alice wrongpassword'); - bob.expectMatch(LoginResponse.badPassword.render()); - }); - - test('logs out existing user', () async { - final alice = environment.newUser()..type('/login Alice letmein'); - environment.newUser()..type('/login Alice letmein'); - - alice.expectMatch(LoginResponse.reset.render()); - }); - }); - - group('list', () { - test('shows online users', () async { - final alice = environment.newUser()..type('/login Alice letmein'); - environment.newUser()..type('/login Bob letmein'); - - alice - ..type('/list') - ..expectMatch('''The following users are online: - -Alice -Bob -'''); - }); - }); - - group('status', () { - test('changes message in user list', () async { - final alice = environment.newUser()..type('/login Alice letmein'); - - alice - ..type('/status Waiting around.') - ..type('/list') - ..expectMatch('''The following users are online: - -Alice Waiting around. -'''); - }); - }); - - group('away', () { - test('changes message in user list', () async { - final alice = environment.newUser()..type('/login Alice letmein'); - - alice - ..type('/away Not here.') - ..type('/list') - ..expectMatch('''The following users are online: - -Alice Not here. -'''); - }); - }); - - group('quit', () { - test('removes from online list', () async { - final alice = environment.newUser()..type('/login Alice letmein'); - final bob = environment.newUser()..type('/login Bob letmein'); - - alice.type('/quit Gone.'); - bob - ..type('/list') - ..expectMatch('''The following users are online: - -Bob -'''); - }); - - test('stops getting messages', () async { - final alice = environment.newUser()..type('/login Alice letmein'); - final bob = environment.newUser()..type('/login Bob letmein'); - - alice.type('/quit Gone.'); - bob.type('Hi Alice.'); - alice.expectNoMatch('Hi Alice.'); - }); - }); - - group('tell', () { - test('goes to a single user', () async { - final alice = environment.newUser()..type('/login Alice letmein'); - final bob = environment.newUser()..type('/login Bob letmein'); - final eve = environment.newUser(); - - alice.type('/tell Bob Hi there.'); - bob..expectMatch(r'Alice \(private\): Hi there.'); - eve.expectNoMatch('Hi there.'); - }); - }); -} diff --git a/chat_example/tool/build.dart b/chat_example/tool/build.dart deleted file mode 100644 index 2f24d70..0000000 --- a/chat_example/tool/build.dart +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:build/build.dart'; -import 'package:built_json_generator/built_json_generator.dart'; -import 'package:built_value_generator/built_value_generator.dart'; -import 'package:enum_class_generator/enum_class_generator.dart'; -import 'package:source_gen/source_gen.dart'; - -/// Build the generated files in the built_json chat example. -Future main(List args) async { - await build( - new PhaseGroup.singleAction( - new GeneratorBuilder([ - new BuiltJsonGenerator(), - new BuiltValueGenerator(), - new EnumClassGenerator() - ]), - new InputSet('chat_example', const ['lib/**/*.dart'])), - deleteFilesByDefault: true); -} diff --git a/chat_example/tool/watch.dart b/chat_example/tool/watch.dart deleted file mode 100644 index 4b1dad5..0000000 --- a/chat_example/tool/watch.dart +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:build/build.dart'; -import 'package:built_json_generator/built_json_generator.dart'; -import 'package:built_value_generator/built_value_generator.dart'; -import 'package:enum_class_generator/enum_class_generator.dart'; -import 'package:source_gen/source_gen.dart'; - -/// Start a watcher that automatically builds the generated files in the -/// built_json chat example on changes. -Future main(List args) async { - await watch( - new PhaseGroup.singleAction( - new GeneratorBuilder([ - new BuiltJsonGenerator(), - new BuiltValueGenerator(), - new EnumClassGenerator() - ]), - new InputSet('chat_example', const ['lib/**/*.dart'])), - deleteFilesByDefault: true); -} diff --git a/chat_example/web/index.html b/chat_example/web/index.html deleted file mode 100644 index 6d15587..0000000 --- a/chat_example/web/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - -
- - - - diff --git a/chat_example/web/main.css b/chat_example/web/main.css deleted file mode 100644 index 2e24663..0000000 --- a/chat_example/web/main.css +++ /dev/null @@ -1,38 +0,0 @@ -body { - overflow-y: scroll; -} - -.input:focus { - outline: 0; -} - -.screen { - background-color: black; - color: gray; - padding: 0px; - width: 48em; - margin-left: auto; - margin-right: auto; -} - -.text { - width: 100%; - font-family: Ariel, sans-serif; - font-size: 16px; -} - -.local { - color: green; -} - -.input { - position: relative; - top: 0px; - left: 0px; - font-family: Ariel, sans-serif; - font-size: 16px; - background-color: black; - color: green; - border-style: none; - width: 100%; -} diff --git a/chat_example/web/main.dart b/chat_example/web/main.dart deleted file mode 100644 index be6003b..0000000 --- a/chat_example/web/main.dart +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:chat_example/client/client.dart'; -import 'package:chat_example/client/html_display.dart'; -import 'package:chat_example/client/http_client_connection.dart'; -import 'package:chat_example/client/input.dart'; -import 'package:chat_example/client/layout.dart'; - -void main() { - new Layout(); - final input = new Input(); - new Client(input.keyboardInput, new HtmlDisplay(), new HttpClientConnection()); -} diff --git a/example/lib/collections.dart b/example/lib/collections.dart deleted file mode 100644 index 5c23629..0000000 --- a/example/lib/collections.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library collections; - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:built_value/built_value.dart'; - -part 'collections.g.dart'; - -/// Example built_value type containing collections. -abstract class Collections - implements Built { - /// Example of how to make a built_value type serializable. - /// - /// Declare a static final [Serializers] field called `serializer`. - /// The built_json code generator will provide the implementation. You need to - /// do this for every type you want to serialize. - static final Serializer serializer = _$collectionsSerializer; - - BuiltList get list; - BuiltSet get set; - BuiltMap get map; - - Collections._(); - factory Collections([updates(CollectionsBuilder b)]) = _$Collections; -} - -/// Builder class for [Collections]. -abstract class CollectionsBuilder - implements Builder { - ListBuilder list = new ListBuilder(); - SetBuilder set = new SetBuilder(); - MapBuilder map = new MapBuilder(); - - CollectionsBuilder._(); - factory CollectionsBuilder() = _$CollectionsBuilder; -} diff --git a/example/lib/collections.g.dart b/example/lib/collections.g.dart deleted file mode 100644 index f726dd8..0000000 --- a/example/lib/collections.g.dart +++ /dev/null @@ -1,135 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of collections; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library collections -// ************************************************************************** - -Serializer _$collectionsSerializer = new _$CollectionsSerializer(); - -class _$CollectionsSerializer implements StructuredSerializer { - final Iterable types = - new BuiltList([Collections, _$Collections]); - final String wireName = 'Collections'; - - @override - Iterable serialize(Serializers serializers, Collections object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'list', - serializers.serialize(object.list, - specifiedType: - const FullType(BuiltList, const [const FullType(String)])), - 'set', - serializers.serialize(object.set, - specifiedType: const FullType(BuiltSet, const [const FullType(int)])), - 'map', - serializers.serialize(object.map, - specifiedType: const FullType( - BuiltMap, const [const FullType(String), const FullType(int)])), - ]; - - return result; - } - - @override - Collections deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new CollectionsBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'list': - result.list.replace(serializers.deserialize(value, - specifiedType: - const FullType(BuiltList, const [const FullType(String)]))); - break; - case 'set': - result.set.replace(serializers.deserialize(value, - specifiedType: - const FullType(BuiltSet, const [const FullType(int)]))); - break; - case 'map': - result.map.replace(serializers.deserialize(value, - specifiedType: const FullType(BuiltMap, - const [const FullType(String), const FullType(int)]))); - break; - } - } - } - - return result.build(); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class Collections -// ************************************************************************** - -class _$Collections extends Collections { - final BuiltList list; - final BuiltSet set; - final BuiltMap map; - - _$Collections._({this.list, this.set, this.map}) : super._() { - if (list == null) throw new ArgumentError('null list'); - if (set == null) throw new ArgumentError('null set'); - if (map == null) throw new ArgumentError('null map'); - } - - factory _$Collections([updates(CollectionsBuilder b)]) => - (new CollectionsBuilder()..update(updates)).build(); - - Collections rebuild(updates(CollectionsBuilder b)) => - (toBuilder()..update(updates)).build(); - - _$CollectionsBuilder toBuilder() => new _$CollectionsBuilder()..replace(this); - - bool operator ==(other) { - if (other is! Collections) return false; - return list == other.list && set == other.set && map == other.map; - } - - int get hashCode { - return hashObjects([list, set, map]); - } - - String toString() { - return 'Collections {' - 'list=${list.toString()},\n' - 'set=${set.toString()},\n' - 'map=${map.toString()},\n' - '}'; - } -} - -class _$CollectionsBuilder extends CollectionsBuilder { - _$CollectionsBuilder() : super._(); - void replace(Collections other) { - super.list = other.list?.toBuilder(); - super.set = other.set?.toBuilder(); - super.map = other.map?.toBuilder(); - } - - void update(updates(CollectionsBuilder b)) { - if (updates != null) updates(this); - } - - Collections build() { - return new _$Collections._( - list: list?.build(), set: set?.build(), map: map?.build()); - } -} diff --git a/example/lib/compound_value.dart b/example/lib/compound_value.dart deleted file mode 100644 index 2910759..0000000 --- a/example/lib/compound_value.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library compound_value; - -import 'package:built_json/built_json.dart'; -import 'package:built_value/built_value.dart'; -import 'package:example/has_int.dart'; -import 'package:example/test_enum.dart'; -import 'package:example/value.dart'; - -part 'compound_value.g.dart'; - -/// Example built_value type. -abstract class CompoundValue - implements Built { - /// Example of how to make a built_value type serializable. - /// - /// Declare a static final [Serializers] field called `serializer`. - /// The built_json code generator will provide the implementation. You need to - /// do this for every type you want to serialize. - static final Serializer serializer = _$compoundValueSerializer; - - Value get aValue; - HasInt get aHasInt; - TestEnum get aTestEnum; - - CompoundValue._(); - factory CompoundValue([updates(CompoundValueBuilder b)]) = _$CompoundValue; -} diff --git a/example/lib/compound_value.g.dart b/example/lib/compound_value.g.dart deleted file mode 100644 index f4f0562..0000000 --- a/example/lib/compound_value.g.dart +++ /dev/null @@ -1,138 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of compound_value; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library compound_value -// ************************************************************************** - -Serializer _$compoundValueSerializer = - new _$CompoundValueSerializer(); - -class _$CompoundValueSerializer implements StructuredSerializer { - final Iterable types = - new BuiltList([CompoundValue, _$CompoundValue]); - final String wireName = 'CompoundValue'; - - @override - Iterable serialize(Serializers serializers, CompoundValue object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'aValue', - serializers.serialize(object.aValue, - specifiedType: const FullType(Value)), - 'aHasInt', - serializers.serialize(object.aHasInt, - specifiedType: const FullType(HasInt)), - 'aTestEnum', - serializers.serialize(object.aTestEnum, - specifiedType: const FullType(TestEnum)), - ]; - - return result; - } - - @override - CompoundValue deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new CompoundValueBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'aValue': - result.aValue.replace(serializers.deserialize(value, - specifiedType: const FullType(Value))); - break; - case 'aHasInt': - result.aHasInt = serializers.deserialize(value, - specifiedType: const FullType(HasInt)); - break; - case 'aTestEnum': - result.aTestEnum = serializers.deserialize(value, - specifiedType: const FullType(TestEnum)); - break; - } - } - } - - return result.build(); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class CompoundValue -// ************************************************************************** - -class _$CompoundValue extends CompoundValue { - final Value aValue; - final HasInt aHasInt; - final TestEnum aTestEnum; - - _$CompoundValue._({this.aValue, this.aHasInt, this.aTestEnum}) : super._() { - if (aValue == null) throw new ArgumentError('null aValue'); - if (aHasInt == null) throw new ArgumentError('null aHasInt'); - if (aTestEnum == null) throw new ArgumentError('null aTestEnum'); - } - - factory _$CompoundValue([updates(CompoundValueBuilder b)]) => - (new CompoundValueBuilder()..update(updates)).build(); - - CompoundValue rebuild(updates(CompoundValueBuilder b)) => - (toBuilder()..update(updates)).build(); - - CompoundValueBuilder toBuilder() => new CompoundValueBuilder()..replace(this); - - bool operator ==(other) { - if (other is! CompoundValue) return false; - return aValue == other.aValue && - aHasInt == other.aHasInt && - aTestEnum == other.aTestEnum; - } - - int get hashCode { - return hashObjects([aValue, aHasInt, aTestEnum]); - } - - String toString() { - return 'CompoundValue {' - 'aValue=${aValue.toString()},\n' - 'aHasInt=${aHasInt.toString()},\n' - 'aTestEnum=${aTestEnum.toString()},\n' - '}'; - } -} - -class CompoundValueBuilder - implements Builder { - CompoundValueBuilder(); - ValueBuilder aValue = new ValueBuilder(); - HasInt aHasInt; - TestEnum aTestEnum; - - void replace(CompoundValue other) { - this.aValue = other.aValue?.toBuilder(); - this.aHasInt = other.aHasInt; - this.aTestEnum = other.aTestEnum; - } - - void update(updates(CompoundValueBuilder b)) { - if (updates != null) updates(this); - } - - CompoundValue build() { - return new _$CompoundValue._( - aValue: aValue?.build(), aHasInt: aHasInt, aTestEnum: aTestEnum); - } -} diff --git a/example/lib/has_int.dart b/example/lib/has_int.dart deleted file mode 100644 index 67e0c4b..0000000 --- a/example/lib/has_int.dart +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. - -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library has_int; - -import 'package:built_json/built_json.dart'; -import 'package:built_value/built_value.dart'; -import 'package:enum_class/enum_class.dart'; - -part 'has_int.g.dart'; - -/// Example "serializable" interface. -/// -/// In fact it is the implementations of the interface that must be -/// serializable. See examples below. -abstract class HasInt { - int get anInt; -} - -/// Example [HasInt] implementation that is not serializable. -/// -/// To be serializable it must use built_value or enum_class. -abstract class WrongHasInt implements HasInt { - int anInt = 4; -} - -/// Example [HasInt] that is serializable because it uses built_value. -abstract class ValueWithInt - implements Built, HasInt { - /// Serializer field makes the built_value serializable. - static final Serializer serializer = _$valueWithIntSerializer; - static final int youCanHaveStaticFields = 3; - - @override - int get anInt; - - String get note; - - ValueWithInt._(); - - factory ValueWithInt([updates(ValueWithIntBuilder b)]) = _$ValueWithInt; -} - -/// Builder class for [ValueWithInt]. -abstract class ValueWithIntBuilder - implements Builder { - int anInt; - String note; - - ValueWithIntBuilder._(); - - factory ValueWithIntBuilder() = _$ValueWithIntBuilder; -} - -/// Example [HasInt] that is serializable because it uses enum_class. -class EnumWithInt extends EnumClass implements HasInt { - /// Serializer field makes the enum_class serializable. - static final Serializer serializer = _$enumWithIntSerializer; - - static const EnumWithInt one = _$one; - static const EnumWithInt two = _$two; - static const EnumWithInt three = _$three; - - const EnumWithInt._(String name) : super(name); - - static BuiltSet get values => _$values; - - static EnumWithInt valueOf(String name) => _$valueOf(name); - - @override - int get anInt { - switch (this) { - case one: - return 1; - case two: - return 2; - case three: - return 3; - default: - throw new StateError(this.toString()); - } - } -} diff --git a/example/lib/has_int.g.dart b/example/lib/has_int.g.dart deleted file mode 100644 index 25cc8c1..0000000 --- a/example/lib/has_int.g.dart +++ /dev/null @@ -1,164 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of has_int; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library has_int -// ************************************************************************** - -Serializer _$valueWithIntSerializer = - new _$ValueWithIntSerializer(); -Serializer _$enumWithIntSerializer = new _$EnumWithIntSerializer(); - -class _$ValueWithIntSerializer implements StructuredSerializer { - final Iterable types = - new BuiltList([ValueWithInt, _$ValueWithInt]); - final String wireName = 'ValueWithInt'; - - @override - Iterable serialize(Serializers serializers, ValueWithInt object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'anInt', - serializers.serialize(object.anInt, specifiedType: const FullType(int)), - 'note', - serializers.serialize(object.note, specifiedType: const FullType(String)), - ]; - - return result; - } - - @override - ValueWithInt deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ValueWithIntBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'anInt': - result.anInt = serializers.deserialize(value, - specifiedType: const FullType(int)); - break; - case 'note': - result.note = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - } - } - } - - return result.build(); - } -} - -class _$EnumWithIntSerializer implements PrimitiveSerializer { - final Iterable types = new BuiltList([EnumWithInt]); - final String wireName = 'EnumWithInt'; - - @override - Object serialize(Serializers serializers, EnumWithInt object, - {FullType specifiedType: FullType.unspecified}) { - return object.name; - } - - @override - EnumWithInt deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return EnumWithInt.valueOf(serialized); - } -} - -// ************************************************************************** -// Generator: EnumClassGenerator -// Target: library has_int -// ************************************************************************** - -const EnumWithInt _$one = const EnumWithInt._('one'); -const EnumWithInt _$two = const EnumWithInt._('two'); -const EnumWithInt _$three = const EnumWithInt._('three'); - -EnumWithInt _$valueOf(String name) { - switch (name) { - case 'one': - return _$one; - case 'two': - return _$two; - case 'three': - return _$three; - default: - throw new ArgumentError(name); - } -} - -final BuiltSet _$values = new BuiltSet(const [ - _$one, - _$two, - _$three, -]); - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class ValueWithInt -// ************************************************************************** - -class _$ValueWithInt extends ValueWithInt { - final int anInt; - final String note; - - _$ValueWithInt._({this.anInt, this.note}) : super._() { - if (anInt == null) throw new ArgumentError('null anInt'); - if (note == null) throw new ArgumentError('null note'); - } - - factory _$ValueWithInt([updates(ValueWithIntBuilder b)]) => - (new ValueWithIntBuilder()..update(updates)).build(); - - ValueWithInt rebuild(updates(ValueWithIntBuilder b)) => - (toBuilder()..update(updates)).build(); - - _$ValueWithIntBuilder toBuilder() => - new _$ValueWithIntBuilder()..replace(this); - - bool operator ==(other) { - if (other is! ValueWithInt) return false; - return anInt == other.anInt && note == other.note; - } - - int get hashCode { - return hashObjects([anInt, note]); - } - - String toString() { - return 'ValueWithInt {' - 'anInt=${anInt.toString()},\n' - 'note=${note.toString()},\n' - '}'; - } -} - -class _$ValueWithIntBuilder extends ValueWithIntBuilder { - _$ValueWithIntBuilder() : super._(); - void replace(ValueWithInt other) { - super.anInt = other.anInt; - super.note = other.note; - } - - void update(updates(ValueWithIntBuilder b)) { - if (updates != null) updates(this); - } - - ValueWithInt build() { - return new _$ValueWithInt._(anInt: anInt, note: note); - } -} diff --git a/example/lib/serializers.dart b/example/lib/serializers.dart deleted file mode 100644 index 2642a7f..0000000 --- a/example/lib/serializers.dart +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library serializers; - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:example/collections.dart'; -import 'package:example/compound_value.dart'; -import 'package:example/has_int.dart'; -import 'package:example/test_enum.dart'; -import 'package:example/value.dart'; - -part 'serializers.g.dart'; - -/// Example of how to use built_json. -/// -/// Declare a top level [Serializers] field called -/// serializers. The built_json code generator will provide the -/// implementation. You usually only need to do this once per project. -Serializers serializers = _$serializers; diff --git a/example/lib/serializers.g.dart b/example/lib/serializers.g.dart deleted file mode 100644 index 191c6ad..0000000 --- a/example/lib/serializers.g.dart +++ /dev/null @@ -1,29 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of serializers; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library serializers -// ************************************************************************** - -Serializers _$serializers = (new Serializers().toBuilder() - ..add(CompoundValue.serializer) - ..add(TestEnum.serializer) - ..add(ValueWithInt.serializer) - ..add(EnumWithInt.serializer) - ..add(Collections.serializer) - ..addBuilderFactory( - const FullType(BuiltList, const [const FullType(String)]), - () => new ListBuilder()) - ..addBuilderFactory(const FullType(BuiltSet, const [const FullType(int)]), - () => new SetBuilder()) - ..addBuilderFactory( - const FullType( - BuiltMap, const [const FullType(String), const FullType(int)]), - () => new MapBuilder()) - ..add(Value.serializer) - ..addBuilderFactory( - const FullType(BuiltList, const [const FullType(int)]), - () => new ListBuilder())) - .build(); diff --git a/example/lib/test_enum.dart b/example/lib/test_enum.dart deleted file mode 100644 index 4a3099b..0000000 --- a/example/lib/test_enum.dart +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library test_enum; - -import 'package:built_json/built_json.dart'; -import 'package:enum_class/enum_class.dart'; - -part 'test_enum.g.dart'; - -/// Example [EnumClass]. -class TestEnum extends EnumClass { - /// Example of how to make an [EnumClass] serializable. - /// - /// Declare a static final [Serializers] field called `serializer`. - /// The built_json code generator will provide the implementation. You need to - /// do this for every type you want to serialize. - static final Serializer serializer = _$testEnumSerializer; - - static const TestEnum yes = _$yes; - static const TestEnum no = _$no; - static const TestEnum maybe = _$maybe; - - const TestEnum._(String name) : super(name); - - static BuiltSet get values => _$values; - static TestEnum valueOf(String name) => _$valueOf(name); -} diff --git a/example/lib/test_enum.g.dart b/example/lib/test_enum.g.dart deleted file mode 100644 index d53ba07..0000000 --- a/example/lib/test_enum.g.dart +++ /dev/null @@ -1,55 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of test_enum; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library test_enum -// ************************************************************************** - -Serializer _$testEnumSerializer = new _$TestEnumSerializer(); - -class _$TestEnumSerializer implements PrimitiveSerializer { - final Iterable types = new BuiltList([TestEnum]); - final String wireName = 'TestEnum'; - - @override - Object serialize(Serializers serializers, TestEnum object, - {FullType specifiedType: FullType.unspecified}) { - return object.name; - } - - @override - TestEnum deserialize(Serializers serializers, Object serialized, - {FullType specifiedType: FullType.unspecified}) { - return TestEnum.valueOf(serialized); - } -} - -// ************************************************************************** -// Generator: EnumClassGenerator -// Target: library test_enum -// ************************************************************************** - -const TestEnum _$yes = const TestEnum._('yes'); -const TestEnum _$no = const TestEnum._('no'); -const TestEnum _$maybe = const TestEnum._('maybe'); - -TestEnum _$valueOf(String name) { - switch (name) { - case 'yes': - return _$yes; - case 'no': - return _$no; - case 'maybe': - return _$maybe; - default: - throw new ArgumentError(name); - } -} - -final BuiltSet _$values = new BuiltSet(const [ - _$yes, - _$no, - _$maybe, -]); diff --git a/example/lib/value.dart b/example/lib/value.dart deleted file mode 100644 index 66625f7..0000000 --- a/example/lib/value.dart +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -library value; - -import 'package:built_collection/built_collection.dart'; -import 'package:built_json/built_json.dart'; -import 'package:built_value/built_value.dart'; -import 'package:example/has_int.dart'; - -part 'value.g.dart'; - -/// Example built_value type. -abstract class Value implements Built, HasInt { - /// Example of how to make a built_value type serializable. - /// - /// Declare a static final [Serializer] field called `serializer`. - /// The built_json code generator will provide the implementation. You need to - /// do this for every type you want to serialize. - static final Serializer serializer = _$valueSerializer; - static final int youCanHaveStaticFields = 3; - - int get anInt; - String get aString; - @nullable String get anotherString; - @nullable Object get anObject; - BuiltList get listOfInt; - - Value._(); - factory Value([updates(ValueBuilder b)]) = _$Value; -} diff --git a/example/lib/value.g.dart b/example/lib/value.g.dart deleted file mode 100644 index 8eda5c5..0000000 --- a/example/lib/value.g.dart +++ /dev/null @@ -1,174 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of value; - -// ************************************************************************** -// Generator: BuiltJsonGenerator -// Target: library value -// ************************************************************************** - -Serializer _$valueSerializer = new _$ValueSerializer(); - -class _$ValueSerializer implements StructuredSerializer { - final Iterable types = new BuiltList([Value, _$Value]); - final String wireName = 'Value'; - - @override - Iterable serialize(Serializers serializers, Value object, - {FullType specifiedType: FullType.unspecified}) { - final result = [ - 'anInt', - serializers.serialize(object.anInt, specifiedType: const FullType(int)), - 'aString', - serializers.serialize(object.aString, - specifiedType: const FullType(String)), - 'listOfInt', - serializers.serialize(object.listOfInt, - specifiedType: - const FullType(BuiltList, const [const FullType(int)])), - ]; - if (object.anotherString != null) { - result.add('anotherString'); - result.add(serializers.serialize(object.anotherString, - specifiedType: const FullType(String))); - } - if (object.anObject != null) { - result.add('anObject'); - result.add(serializers.serialize(object.anObject, - specifiedType: const FullType(Object))); - } - - return result; - } - - @override - Value deserialize(Serializers serializers, Iterable serialized, - {FullType specifiedType: FullType.unspecified}) { - final result = new ValueBuilder(); - - var key; - var value; - var expectingKey = true; - for (final item in serialized) { - if (expectingKey) { - key = item; - expectingKey = false; - } else { - value = item; - expectingKey = true; - - switch (key as String) { - case 'anInt': - result.anInt = serializers.deserialize(value, - specifiedType: const FullType(int)); - break; - case 'aString': - result.aString = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - case 'anotherString': - result.anotherString = serializers.deserialize(value, - specifiedType: const FullType(String)); - break; - case 'anObject': - result.anObject = serializers.deserialize(value, - specifiedType: const FullType(Object)); - break; - case 'listOfInt': - result.listOfInt.replace(serializers.deserialize(value, - specifiedType: - const FullType(BuiltList, const [const FullType(int)]))); - break; - } - } - } - - return result.build(); - } -} - -// ************************************************************************** -// Generator: BuiltValueGenerator -// Target: abstract class Value -// ************************************************************************** - -class _$Value extends Value { - final int anInt; - final String aString; - final String anotherString; - final Object anObject; - final BuiltList listOfInt; - - _$Value._( - {this.anInt, - this.aString, - this.anotherString, - this.anObject, - this.listOfInt}) - : super._() { - if (anInt == null) throw new ArgumentError('null anInt'); - if (aString == null) throw new ArgumentError('null aString'); - if (listOfInt == null) throw new ArgumentError('null listOfInt'); - } - - factory _$Value([updates(ValueBuilder b)]) => - (new ValueBuilder()..update(updates)).build(); - - Value rebuild(updates(ValueBuilder b)) => - (toBuilder()..update(updates)).build(); - - ValueBuilder toBuilder() => new ValueBuilder()..replace(this); - - bool operator ==(other) { - if (other is! Value) return false; - return anInt == other.anInt && - aString == other.aString && - anotherString == other.anotherString && - anObject == other.anObject && - listOfInt == other.listOfInt; - } - - int get hashCode { - return hashObjects([anInt, aString, anotherString, anObject, listOfInt]); - } - - String toString() { - return 'Value {' - 'anInt=${anInt.toString()},\n' - 'aString=${aString.toString()},\n' - 'anotherString=${anotherString.toString()},\n' - 'anObject=${anObject.toString()},\n' - 'listOfInt=${listOfInt.toString()},\n' - '}'; - } -} - -class ValueBuilder implements Builder { - ValueBuilder(); - int anInt; - String aString; - String anotherString; - Object anObject; - ListBuilder listOfInt = new ListBuilder(); - - void replace(Value other) { - this.anInt = other.anInt; - this.aString = other.aString; - this.anotherString = other.anotherString; - this.anObject = other.anObject; - this.listOfInt = other.listOfInt?.toBuilder(); - } - - void update(updates(ValueBuilder b)) { - if (updates != null) updates(this); - } - - Value build() { - return new _$Value._( - anInt: anInt, - aString: aString, - anotherString: anotherString, - anObject: anObject, - listOfInt: listOfInt?.build()); - } -} diff --git a/example/pubspec.yaml b/example/pubspec.yaml deleted file mode 100644 index 281bb90..0000000 --- a/example/pubspec.yaml +++ /dev/null @@ -1,22 +0,0 @@ -name: example -version: 0.1.5 -description: > - Just an example, not for publishing. -authors: -- David Morgan -homepage: https://github.com/google/built_json.dart - -environment: - sdk: '>=1.8.0 <2.0.0' - -dependencies: - built_collection: '^1.0.0' - built_json: '^0.1.5' - built_value: '^0.1.3' - enum_class: '^1.0.0' - -dev_dependencies: - built_json_generator: '^0.1.5' - built_value_generator: '^0.1.3' - enum_class_generator: '^1.0.0' - test: any diff --git a/example/test/collections_test.dart b/example/test/collections_test.dart deleted file mode 100644 index dc3ef6f..0000000 --- a/example/test/collections_test.dart +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. - -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:example/collections.dart'; -import 'package:example/serializers.dart'; -import 'package:test/test.dart'; - -void main() { - group('Collections', () { - final data = new Collections((b) => b - ..list.add('one') - ..set.add(2) - ..map['three'] = 4); - final serialized = [ - 'Collections', - 'list', - ['one'], - 'set', - [2], - 'map', - ['three', 4], - ]; - - test('can be serialized', () { - expect(serializers.serialize(data), serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized), data); - }); - }); -} diff --git a/example/test/compound_value_test.dart b/example/test/compound_value_test.dart deleted file mode 100644 index 8e2246a..0000000 --- a/example/test/compound_value_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:example/compound_value.dart'; -import 'package:example/serializers.dart'; -import 'package:example/test_enum.dart'; -import 'package:example/value.dart'; -import 'package:test/test.dart'; - -void main() { - group('CompoundValue', () { - final data = new CompoundValue((b) => b - ..aValue.anInt = 1 - ..aValue.aString = 'two' - ..aValue.anObject = 3 - ..aHasInt = new Value((b) => b..anInt = 4..aString = 'five') - ..aTestEnum = TestEnum.no); - final serialized = [ - 'CompoundValue', - 'aValue', - [ - 'anInt', - 1, - 'aString', - 'two', - 'listOfInt', - [], - 'anObject', - ['int', 3], - ], - 'aHasInt', - [ - 'Value', - 'anInt', - 4, - 'aString', - 'five', - 'listOfInt', - [], - ], - 'aTestEnum', - 'no', - ]; - - test('can be serialized', () { - expect(serializers.serialize(data), serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized), data); - }); - }); -} diff --git a/example/test/has_int_test.dart b/example/test/has_int_test.dart deleted file mode 100644 index b023e15..0000000 --- a/example/test/has_int_test.dart +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2016, Google Inc. Please see the AUTHORS file for details. - -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:built_collection/built_collection.dart'; -import 'package:example/has_int.dart'; -import 'package:example/serializers.dart'; -import 'package:test/test.dart'; -import 'package:example/value.dart'; - -void main() { - group('HasInt', () { - final data = new BuiltList([ - new ValueWithInt((b) => b - ..anInt = 2 - ..note = 'two'), - EnumWithInt.one, - new Value((ValueBuilder b) => b - ..anInt = 3 - ..aString = 'four'), - ]); - final serialized = [ - 'list', - ['ValueWithInt', 'anInt', 2, 'note', 'two'], - ['EnumWithInt', 'one'], - ['Value', 'anInt', 3, 'aString', 'four', 'listOfInt', [] - ], - ]; - - test('can be serialized', () { - expect(serializers.serialize(data), serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized), data); - }); - }); -} diff --git a/example/test/test_enum_test.dart b/example/test/test_enum_test.dart deleted file mode 100644 index 5737c56..0000000 --- a/example/test/test_enum_test.dart +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:example/serializers.dart'; -import 'package:example/test_enum.dart'; -import 'package:test/test.dart'; - -void main() { - group('TestEnum', () { - final data = TestEnum.yes; - final serialized = ['TestEnum', 'yes']; - - test('can be serialized', () { - expect(serializers.serialize(data), serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized), data); - }); - }); -} diff --git a/example/test/value_test.dart b/example/test/value_test.dart deleted file mode 100644 index 3823d6c..0000000 --- a/example/test/value_test.dart +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. - -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'package:example/serializers.dart'; -import 'package:example/value.dart'; -import 'package:test/test.dart'; - -void main() { - group('Value', () { - final data = new Value((b) => b - ..anInt = 1 - ..aString = 'two' - ..anObject = 3); - final serialized = [ - 'Value', - 'anInt', - 1, - 'aString', - 'two', - 'listOfInt', - [], - 'anObject', - ['int', 3], - ]; - - test('can be serialized', () { - expect(serializers.serialize(data), serialized); - }); - - test('can be deserialized', () { - expect(serializers.deserialize(serialized), data); - }); - }); -} diff --git a/example/tool/build.dart b/example/tool/build.dart deleted file mode 100644 index e98eca3..0000000 --- a/example/tool/build.dart +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2015, Google Inc. Please see the AUTHORS file for details. -// All rights reserved. Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -import 'dart:async'; - -import 'package:build/build.dart'; -import 'package:built_json_generator/built_json_generator.dart'; -import 'package:built_value_generator/built_value_generator.dart'; -import 'package:enum_class_generator/enum_class_generator.dart'; -import 'package:source_gen/source_gen.dart'; - -/// Example of how to use source_gen with [BuiltJsonGenerator]. -/// -/// [BuiltJsonGenerator] is usually used with [BuiltValueGenerator] and -/// [EnumClassGenerator] because types generated by these generators are -/// automatically serializable. -/// -/// Import the generators you want and pass them to [build] as shown, -/// specifying which files in which packages you want to run against. -Future main(List args) async { - await build( - new PhaseGroup.singleAction( - new GeneratorBuilder([ - new BuiltJsonGenerator(), - new BuiltValueGenerator(), - new EnumClassGenerator() - ]), - new InputSet('example', const ['lib/*.dart'])), - deleteFilesByDefault: true); -}