Showing posts with label dart pub. Show all posts
Showing posts with label dart pub. Show all posts

Friday, March 20, 2015

Bleeding Edge Polymer.dart and Angular.dart


When last I checked, the state of Polymer.dart and Angular.dart was pretty rough. I had to override multiple dependencies just to get the two to install side-by-side. At the time, that seemed to work, but hardly seemed a long-term solution. Let's see if the situation has improved.

I continue to work with the latest development release version of Dart (the newest Polymer.dart requires it):
$ dart --version
Dart VM version: 1.9.0-dev.10.12 (Fri Mar 20 06:26:15 2015) on "linux_x64"
In the angular example code from Patterns in Polymer, I start with optimism in my heart. I comment out the old dependency overrides in my pubspec.yaml package file:
name: angular_example
dependencies:
  angular: any
  polymer: any
  angular_node_bind:
    git: https://github.com/eee-c/angular_node_bind.git
# dependency_overrides:
#   args: any
#   code_transformers: any
#   html5lib: any
#   observe: any
dev_dependencies:
  scheduled_test: any
transformers:
- angular:
    html_files:
      - web/partials/custom.html
- polymer:
    entry_points:
      - web/index.html
      - test/index.html
And then I attempt to upgrade to the latest, compatible versions:
$ pub upgrade   
Resolving dependencies... (38.5s) 
And it just stops there. Well, it does not stop—the CPU is pegged and the fan on my laptop bolts into high gear.

Some time later, pub gives up the ghost:
Connection closed before full header was received
So it seems that I must give Dart Pub a gentle nudge at minimum. I start by explicitly requiring the latest Polymer:
name: angular_example
dependencies:
  angular: any
  polymer: ">=0.16.0"
  angular_node_bind:
    git: https://github.com/eee-c/angular_node_bind.git
# ...
Since this is in support of a Polymer book, it seems more appropriate to get the latest Polymer library working with a possibly older version of Angular. But even that fails. I still timeout when trying to pub upgrade. It would appear that a gentle nudge is insufficient. Time for a good firm shove...

I check the generated pubspec.lock of a Polymer only project and an Angular-old project. Comparing the two, I find that Polymer is using a newer version of the observe package and a new version of the collection package.

In the pubspec.lock for the Polymer-only project, I have:
# ...
  collection:
    description: collection
    source: hosted
    version: "1.1.0"
# ...
  observe:
    description: observe
    source: hosted
    version: "0.13.0+1"
# ...
In the pubspec.lock for the Angular-only project, I have:
# ...
  collection:
    description: collection
    source: hosted
    version: "0.9.4"
# ...
  observe:
    description: observe
    source: hosted
    version: "0.12.2+1"
# ....
In both cases, I opt for Polymer to win (again because I am more interested in evaluating Polymer). So I update my Polymer-Angular example application to include some dependency overrides:
name: angular_example
dependencies:
  angular: any
  polymer: ">=0.16.0"
  angular_node_bind:
    git: https://github.com/eee-c/angular_node_bind.git
dependency_overrides:
  collection: '>=0.9.1 <1.2.0'
  observe: '>=0.12.0 <0.14.0'
# ...
That is less than ideal, but I console myself with two rationalizations. First, this halves the number of dependency overrides that I previously had to use. Second, I am using a pre-release version of Polymer. So I do not look too closely and claim progress.

Especially since a pub upgrade now completes successfully:
$ pub upgrade
Resolving dependencies... (11.7s)
  ...
  angular 1.1.0
  angular_node_bind 0.2.0 from git https://github.com/eee-c/angular_node_bind.git at d7b694
  ...
! collection 1.1.0 (overridden)
  ...
> di 3.3.4 (was 3.3.3)
...
! observe 0.13.0+1 (overridden)
  ...
> polymer 0.16.0+6 (was 0.15.5+4)
  ...
Warning: You are using these overridden dependencies:
! collection 1.1.0
! observe 0.13.0+1
Changed 14 dependencies! 
...
Best of all, the Angular and Polymer code still double binds the shared attributes. Angular binds the <x-pizza> element's value attribute to a local variable of its own, which it also binds in a <textarea>:



When I update the Polymer element, adding sausage to the second half of my <x-pizza> Polymer element, Angular sees the attribute change and binds the new value into the <textarea>:



Similarly, when I manually edit the JSON in the <textarea>, the <x-pizza> Polymer element is updated:



Yay!

I close by noting that a recent commit to Angular.dart relaxed the observe package sufficiently so that overrides will no longer be needed. At that point, only an override of the collection dependency will stand between Angular.dart and Polymer.dart in the same project. Exciting!

Day #4

Thursday, December 4, 2014

One Weird Trick to Getting Polymer.dart Packages Working


Yeah, sorry about the title… I couldn't resist.

I wound up with the strangest little bug in some Polymer.dart code yesterday that I just could not figure out. I had originally started investigating the "is" attribute in Polymer, but quickly realized that I could not use it the way I wanted.

In the end, the best way to implement inheritance in Polymer seems to be with the facilities built into the language. In the case of Dart, that mean regular inheritance with the class extends modifier or via mixins. Both work pretty darn well, unless…

Unless you are trying to extend one Polymer class with another through a Dart Pub package. Consider last night's code:
import 'package:polymer/polymer.dart';
// import 'a_form_input.dart';
import 'package:a-form-input/a_form_input.dart';

@CustomTag('x-pizza')
class XPizza extends AFormInput {
  // ...
}
The a_form_input.dart files in the local directory and in the package are identical:
$ diff -s a_form_input.dart \
  ~/repos/a-form-input-dart/lib/a_form_input.dart
Files a_form_input.dart and 
  /home/chris/repos/a-form-input-dart/lib/a_form_input.dart
  are identical
But when I use the local version, the attributeChanged() in from a_form_input.dart gets invoked:
library a_form_input;

import 'package:polymer/polymer.dart';

@CustomTag('a-form-input')
class AFormInput extends PolymerElement {
  @PublishedProperty(reflect: true)
  String name;
  @PublishedProperty(reflect: true)
  String value;
  AFormInput.created(): super.created();
  // ...
  void attributeChanged(String name, String oldValue, String newValue) {
    print('$name: $oldValue → $newValue');
    if (name == 'name') lightInput.name = newValue;
    if (name == 'value') lightInput.value = newValue;
  }
}
When I add toppings to the <x-pizza> element, it sets the value property internally, which triggers the callback (including the print statement):
value: First Half: []
Second Half: []
Whole: [] → First Half: [pepperoni]
Second Half: []
Whole: []
Making no other change to the <x-pizza> element other that importing the package version of a_form_input.dart results in… nothing. There are no errors, there is no print statement to be seen in the console and the element is certainly not behaving like "a-form-element", which is the whole point of moving this out into a package.

The answer to this little puzzle turns out to be pubspec.yaml. If I add a Polymer transformer to the a-form-element package, then everything magically works:
name: a-form-input
author: "Chris Strom "
description: "Polymer element that mimics a native <form> input."
dependencies:
  polymer: any
transformers:
- polymer
Being somewhat familiar with the idiosyncrasies of Polymer.dart, it did not take long for me to try this. Even so, this fix seems far from obvious. Even now that I know the solution, I cannot rationalize an argument for why this is necessary. I would expect the transformer that is already in my application's pubspec.yaml would apply to any elements that are imported:
name: form_example
dependencies:
  polymer: any
  a-form-input:
    path: /home/chris/repos/a-form-input-dart
transformers:
- polymer:
    entry_points:
      - web/index.html
      - test/index.html
Even if that did not apply to vanilla elements, surely it would apply to elements that only serve as the base class for an element that is being defined in the application, right? I already know the answer, but the "why" of the no answer remains something of a mystery.

One mystery solved (how to make it work) is enough for today. Tomorrow, I may poke through the transformer again to solve the mystery of why it works.


Day #14

Wednesday, December 3, 2014

Is a Form Input (Extending Polymer.dart without Reading Docs)


Now for the fun. Now for Dart.

I kid (a little). One of the joys of writing Patterns in Polymer is slipping back and forth between JavaScript and Dart. If I am being honest, I prefer Dart, but both languages have their joys. More than experiencing those joys, I appreciate trying solutions for Polymer in one language and then another. If a solution is pleasant in both languages, then I feel like I have found a nice solution that transcends language—making it a true Polymer pattern.

In some ways, switch back and forth between languages feels a little like spiking solutions, then doing it for real. In real programming that is loads of fun (not to mention is leads to better solutions). Surprisingly, I have found this to be a bad idea writing the book. It is easy to mistake tinghe post-spike flow for a transcendent pattern. Of course it works when switching languages, I already pushed through the gaps in knowledge in the other language.

Instead, I have been making a concerted effort to push the solution forward when switching between languages. When I got my initial spike of <a-form-input> (it allows Polymer elements to work in native HTML forms) working in Dart, I did not try to get it working in JavaScript. Instead I tried building a base class / element in JavaScript. Now that I have that working in JavaScript, I try something a little different in Dart. Instead of just making <a-form-input> a base class in Dart, I am going to see if I can make it work with the is="a-form-input" syntax.

I start by reproducing my latest JavaScript work in Dart. That is, I create a Dart package for <a-form-input>. In a new git repository, I add a simple Dart Pub pubspec.yaml:
name: a-form-input
dependencies:
  polymer: any
Then, I copy in a_form_element.dart from my initial spike in some of the book's exploratory code into lib/a_form_input.dart. For the most part, the JavaScript version of this library looks identical to the Dart solution—aside from the code annotations:
@CustomTag('a-form-input')
class AFormInput extends PolymerElement {
  @PublishedProperty(reflect: true)
  String name;

  @PublishedProperty(reflect: true)
  String value;
  // ...
}
The same class in JavaScript is the more compact:
Polymer('a-form-input', {
  publish: {
    name: {reflect: true},
    value: {reflect: true}
  },
  // ...
});
I am going to be honest here: I love the Polymer.dart annotations. If you would have told this old dynamic language aficionado a year ago that I'd love annotations, I'd have thought you were crazy. But now I really appreciate how they distinguish meta-information in the class from actual code. These published properties are core to the functionality of <a-form-input>, but in JavaScript that information gets lost in the rest of the code:
Polymer('a-form-input', {
  publish: {
    name: {value: 0, reflect: true},
    value: {value: 0, reflect: true}
  },

  attached: function(){
    this.lightInput = document.createElement('input');
    this.lightInput.type = 'hidden';
    this.lightInput.name = this.getAttribute('name');

    this.parentElement.appendChild(this.lightInput);
  },

  nameChanged: function(){
    this.lightInput.name = this.name;
  },

  valueChanged: function(){
    this.lightInput.value = this.value;
  }
});
Still, the task at hand tonight is not language comparing. Instead, I want to change the test element in Dart from extending the base. So. in the smoke test page for the book example, I add the is attribute:
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="import" href="packages/form_example/elements/x-pizza.html">
    <link rel="import" href="packages/a-form-input/a-form-input.html">
    <script type="application/dart">export 'package:polymer/init.dart';</script>
  </head>
  <body>
    <form action="test" method="post">
      <h1>Plain-old Form</h1>
      <input type=text
             name="plain_old_param"
             placeholder="Plain-old form field">
      <x-pizza name="pizza_toppings" is="a-form-input"></x-pizza>
      <button>Order my pizza!</button>
    </form>
  </body>
</html>
Which almost works… except not at all (some of the functionality works, but ultimately crashes ugly).

I finally read the actual documentation to find that this is not how "is" works at all! It is meant to extends native DOM elements, not arbitrary elements like I am trying to do here. Sometimes there is nothing for it, but to admit that I am an idiot. OK, much times.

But while working this, I ran into an interesting problem. My AFormInput class does not seem to see attributes changing when moved into a package. That is, the same exact a_form_input.dart when used locally or used via a package… behaves differently. And it is an important difference. The attributeChanged() callback is never invoked in the super class via a package:
library a_form_input;

import 'package:polymer/polymer.dart';
import 'dart:html';

@CustomTag('a-form-input')
class AFormInput extends PolymerElement {
  @PublishedProperty(reflect: true)
  String name;

  @PublishedProperty(reflect: true)
  String value;
  // ...

  AFormInput.created(): super.created();
  void attached() {
    print('attached!');
    super.attached();
  }
  void attributeChanged(String name, String oldValue, String newValue) {
    print('$name: $oldValue → $newValue');
    if (name == 'name') lightInput.name = newValue;
    if (name == 'value') lightInput.value = newValue;
  }
}
If my test element (the old <x-pizza> standby) uses a local copy of this same file, then it can update value:
import 'package:polymer/polymer.dart';
import 'a_form_input.dart';
// import 'package:a-form-input/a_form_input.dart';

@CustomTag('x-pizza')
class XPizza extends AFormInput {
  // ...
  _updateText() {
    value = 'First Half: ${model.firstHalfToppings}\n'
      'Second Half: ${model.secondHalfToppings}\n'
      'Whole: ${model.wholeToppings}';
  }
  // ...
}
But if I swap the a_form_input.dart lines, then changes to the value attribute (or the name attribute) never trigger the attributeChanged() callback. I play with this for some time, but I cannot solve this. Everything else works—a hidden input is generated by <a-form-input> in either case. The attached() lifecycle method is called in either case. But I am clearly missing something in the packaged version. Something to solve tomorrow.

Day #13

Friday, September 26, 2014

An Angular App Using a Polymer Element (Dart)


Thanks to a tip from James Hurford, I have a far better approach to working with the “wildly” incompatible Polymer.dart and Angular.dart libraries. Instead of hacking on a forked version of Angular.dart, as I did last night, I instead use Dart Pub's dependency_overrides option.

I am simply not going to start hacking on Angular.dart to get Polymer elements working inside an Angular.dart application—especially not as a solution for Patterns in Polymer. Overriding the minimal dependencies found from last night gives me the best chance of working with the most recent Polymer and Angular libraries to see if it is as all possible.

So I add those dependencies to my project's pubspec.yaml:
name: angular_example
dependencies:
  angular: any
  polymer: any
  angular_node_bind: any
dependency_overrides:
  args: '>=0.10.0 <0.12.0'
  code_transformers: '>=0.1.4+2 <0.3.0'
  html5lib: '>=0.10.0 <0.13.0'
dev_dependencies:
  unittest: any
transformers:
- polymer:
    entry_points:
    - web/index.html
    - test/index.html
I delete my pubspec.lock to be absolutely sure that I am getting a fresh run at this (a pub upgrade should do the same thing). Now when I run pub get, I find:
$ pub install
...
+ angular 0.14.0
...
+ polymer 0.15.0
...
Warning: You are using these overridden dependencies:
! args 0.11.0+1 (0.12.0+2 available)
! code_transformers 0.2.3+1
! html5lib 0.12.0
For reference, Angular.dart would otherwise restrict those three overridden dependencies as:
  args: '>=0.10.0 <0.11.0'
  code_transformers: '>=0.1.4+2 <0.2.0'
  html5lib: '>=0.10.0 <0.11.0'
OK, I have the Dart versions of Polymer and Angular installed in the same application. Now what?

Well, for tonight, I would be satisfied with a working version of the old Angular pizza building application that uses a custom Polymer element. This worked when it went into Patterns in Polymer. Hopefully it can live again.

I modify the Polymer setup as I know that version 0.15 likes it and retain the Angular tags and attributes:
<!doctype html>
<html ng-app lang="en">
  <head>
    <script src="packages/web_components/platform.js"></script>
    <link rel="import" href="packages/angular_example/elements/x-pizza.html">
    <script type="application/dart" src="main.dart"></script>
  </head>
  <body>
    <div class="container">
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <ng-view></ng-view>
    </div>
  </body>
</html>
Aside from the ng-app Angular attribute and the <ng-view> Angular tag, there is one other difference between this and a pure Polymer application: there is no export of package:polymer/init.dart to initialize Polymer. Instead that is done inside main.dart, which also initialized Angular.

At least it used to initialize Angular. Now it just generates errors in the Dartium console:
Exception: No top-level method 'ngBootstrap' declared.

NoSuchMethodError: method not found: 'ngBootstrap'
Receiver: top-level
Arguments: [...] 
No biggie. It seems that the Angular bootstrap process has changed. For now, I leave the initialization inside Polymer's run():
main() {
  initPolymer().run((){
    applicationFactory()
      .addModule(new PizzaStoreApp())
      .run();
  });
}
No doubt other stuff has changed, but I start with the old constructor for PizzaStoreApp and will work my way from there. What I find next is:
Exception: Module.DEFAULT_REFLECTOR not initialized for dependency injection.http://goo.gl/XFXx9G
This appears to be due to the lack of the Angular transformer in my pubspec.yaml. Despite what the documentation says, it would appear that this does more than aid building JavaScript. I add the Angular transformer:
name: angular_example
dependencies:
  angular: any
  polymer: any
  angular_node_bind: any
dependency_overrides:
  args: '>=0.10.0 <0.12.0'
  code_transformers: '>=0.1.4+2 <0.3.0'
  html5lib: '>=0.10.0 <0.13.0'
dev_dependencies:
  unittest: any
transformers:
- angular
- polymer:
    entry_points:
    - web/index.html
    - test/index.html
After a pub serve restart, there is much work to perform to update the Angular portion of my application to 0.14. But I eventually get it.

The application is intentionally “complex-ish” to ensure that I am not just getting by with a trivial example. Mostly this involves routing.

The main.dart file for my Angular & Polymer application starts with the usual imports for both libraries:
import 'package:polymer/polymer.dart';
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
import 'package:angular/routing/module.dart';
There used to be much initialization inside the main application module. Now it is just:
class PizzaStoreApp extends Module {
  PizzaStoreApp() {
    // Stuff used to happen here, now routing and binding happens later...
  }
}
I am unsure if I even need this anymore, but I will answer than another day.

The routing uses two partials, defined as:
void storeRouteInitializer(Router router, RouteViewFactory views) {
  views.configure({
    'start': ngRoute(
        defaultRoute: true,
        view: 'partials/home.html'
      ),
    'custom-pizza': ngRoute(
        path: '/pizza/custom',
        view: 'partials/custom.html'
      )
  });
}
That is relatively self-explanatory. I have two routes: the default route and the custom pizza route. Both use partial templates at the specified locations.

Finally, the Polymer and Angular initialization looks like:
main() {
  initPolymer().run((){
    var app = new PizzaStoreApp()
      ..bind(NgRoutingUsePushState, toValue: new NgRoutingUsePushState.value(false))
      ..bind(RouteInitializerFn, toValue: storeRouteInitializer);

    applicationFactory()
      .addModule(app)
      .run();
  });
}
It took a little time to figure out where the bind() calls go and what gets supplied to addModule(), but it mostly makes sense. What took me quite a while to figure out was how to disable push state. I really hate push state—especially for developing / reloading single page applications. But eventually I figured out how to bind the false value of NgRouteingUsePushState. There may be a cleaner way to accomplish this, but I am not going to worry about that now.

Because I have an Angular.dart 0.14 + Polymer.dart 0.15 application working:

Well, not quite working. I still need to double bind variables in Angular to Polymer attributes. But I am thrilled to have gotten this far tonight.


Day #195

Monday, April 7, 2014

Kicking the Tires on Polymer.dart 0.10 (and js-interop)


Curiosity got the better of me yesterday as I wondered if I might use a Vulcanized JavaScript Polymer element inside a Polymer.dart. It couldn't—but maybe it will be able to...

The CHANGELOG for the 0.10-pre release of Polymer.dart includes this nifty little tidbit:
* Interop with polymer-js elements now works.
That makes it seem like the next release of Polymer.dart will support it. So, letting my curiosity drive me yet again, I will give it a go tonight. First up, I need to replace the 0.9 dependency in my application's pubspec.yaml package configuration. It is currently being locked to 0.9 in the resulting pubspec.lock:
# ...
  polymer:
    description: polymer
    source: hosted
    version: "0.9.5"
# ...
So, back in the application's pubspec.yaml, I try to limit the dependency to 0.10.0-pre.7 or higher:
name: deployment_experiment
# ...
dependencies:
  polymer: ">=0.10.0-pre.7"
# ...
That is, of course a non-started with the current 1.2 version of Dart:
➜  dart git:(master) ✗ pub update    
Resolving dependencies........
Package polymer requires SDK version >=1.3.0-dev.5.0 <2.0.0 but the current SDK is 1.2.0
No worries, I should have been using the prerelease all along and especially should be using it now that it is nearing the release.

So I grab the latest dev channel release of Dart:
➜  Downloads  wget http://storage.googleapis.com/dart-archive/channels/dev/release/latest/editor/darteditor-linux-x64.zip
➜  Downloads  cd ~/local
➜  local  unzip ~/Downloads/darteditor-linux-x64.zip
That expands into the dart directory. I have various locations under $HOME/local/dart in my $PATH:
PATH=$HOME/local/dart/chromium:$HOME/local/dart/content_shell:$HOME/local/dart/dart-sdk/bin:$PATH
Some of those come directly from the ZIP file, others I need to massage or outright download. I complete the installation by downloading and installing (per my $PATH) the content_shell executable for running headless tests:
➜  local  cd dart/
➜  dart  ./chromium/download_contentshell.sh
Downloading http://dartlang.org/editor/update/channels/dev/34756/dartium/content_shell-linux-x64-release.zip to content_shell-linux-x64-release.zip.
Download finished.
➜  dart  mv drt-lucid64-full-dev-34756.0 content_shell
Then I replace the regular Dartium with the debug version:
➜  dart  ./chromium/download_dartium_debug.sh
Downloading http://dartlang.org/editor/update/channels/dev/34756/dartium/dartium-linux-x64-debug.zip to dartium-linux-x64-debug.zip.
Download finished.
➜  dart  unzip dartium-linux-x64-debug.zip 
➜  dart  mv chromium chromium.orig                             
➜  dart  mv dartium-lucid64-debug-dev-34756.0 chromium
Now I am ready to roll. Back in my application, I again pub update to get the latest Polymer.dart:
➜  dart git:(master) ✗ pub update
...
These packages are no longer being depended on:
- custom_element 0.9.2
- html_import 0.9.0
- mutation_observer 0.9.0
- shadow_dom 0.9.2
- unmodifiable_collection 0.9.2+1
Downloading polymer 0.10.0-pre.8...
...
Changed 17 dependencies!
I have to make a few minor changes to the overall application to work with 0.10. First, there is no more initPolymer() (yay!). Instead, I now need to import a Polymer HTML file similar to how it is done in JavaScript-land:
    <link rel="import" href="packages/polymer/polymer.html">
    <link rel="import" href="packages/deployment_experiment/elements/x-pizza.html">
In each of the Polymer template files, I also have to modify the mime-type of the backing script:
<link rel="import" href="x-pizza-toppings.html">
<polymer-element name="x-pizza">
  <template><!-- ... --></template>
  <script type="application/dart;component=1" src="x_pizza.dart"></script>
</polymer-element>
The component=1 parameter is an uglyish way to signal to the Dart VM in the browser that it should not run this script in a separate isolate—that it should be run as part of the same isolate used by other Polymer elements. After making those changes to the Polymer.dart code, my Polymer is working perfectly again. Now to the task at hand. Instead of using the Dart version of the <x-pizza-toppings> Polymer element, I want to use last night's Vulcanized JavaScript version.

So I swap the import from the template definition file of the containing <x-pizza> element:
<!-- <link rel="import" href="x-pizza-toppings.html"> -->
<link rel="import" href="vulcanized.html">
<polymer-element name="x-pizza">
  <template><!-- ... --></template>
  <script type="application/dart;component=1" src="x_pizza.dart"></script>
</polymer-element>
Unfortunately, when I fire this up in Dartium, I get errors:
Uncaught Possible attempt to load Polymer
--
Exception: NoSuchMethodError: method not found: 'whenPolymerReady'
Receiver: Instance of 'JsFunction'
Arguments: [Closure: () => dynamic]
When I vulcanized this polymer, I did so by inlining all of the backing JavaScript, including the platform and polymer libraries. After removing the inlined Polymer library code from vulcanized.html, I am a little closer. The Dart <x-pizza> element now displays as does the template from the 3 JavaScript <x-pizza-toppings> elements:



Some of the bindings between the elements are even working—the button names in the JavaScript <x-pizza-toppings> elements are bound variables from the Dart <x-pizza>. Unfortunately, the ingredient list is not bound properly, nor are the events that transfer information.

Looking through some of the js-interop tests in the Polymer.dart project, it seems that some js-interop method calling from Dart may be in order. I will investigate that further tomorrow and give it a try in code tomorrow night. For now, just getting this far will be enough progress for one day.


Day #27

Saturday, April 5, 2014

A Pub Package for Building a Single JS from Polymer.dart


Up tonight: extracting a command-line Dart script from my application into a Dart Pub package. Hopefully I made the script general enough last night.

Aside from missing generalizations, the challenge for this is how best to bundle the script in a pub package. Dart Pub is great for managing dependencies and smoke testing applications, but it does not quite have a good solution for scripts. Also, I have no idea how to write a script for Windows machines (but that's a task for another day). In my application, I have the script in the bin directory, which makes sense and is the Dart Pub standard location. The problem with that is that the bin directory of a package is not easily reached from an installed package.

In fact, the only thing that is easy to reach is the lib directory, so I start with that. I create a new git repository for my package, give it a reasonable starting point for a pubspec.yaml configuration, and create a lib directory to hold the script:
➜  repos  mkdir polymer-one-script
➜  repos  cd !$
➜  repos  cd polymer-one-script
➜  polymer-one-script  git init .
Initialized empty Git repository in /home/chris/repos/polymer-one-script/.git/
➜  polymer-one-script git:(master) mkdir lib
➜  polymer-one-script git:(master) cp ~/repos/polymer-book/play/deployment/dart/pubspec.yaml .
➜  polymer-one-script git:(master) ✗ cp ~/repos/polymer-book/play/deployment/dart/bin/reduce.dart lib/
➜  polymer-one-script git:(master) ✗ chmod 755 lib/reduce.dart 
I edit the pubspec.yaml of my new package:
name: polymer_one_script
dependencies:
  yaml: any
dev_dependencies:
  scheduled_test: any
With that, I am ready to remove last night's version of the script from my application and replace it with my new packaged script. I start by referencing the local package in my application's pubspec.yaml:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
  polymer_one_script:
    path: /home/chris/repos/polymer-one-script
transformers:
- polymer:
    entry_points:
      - web/index.html
      - web/index2.html
Dart pub really is pretty awesome at packaging—including helping developers to build new packages. With the above path setting, pub build links to my local pub package directly where I am developing it:
➜  dart git:(master) ✗ ls -l packages/polymer_one_script 
lrwxrwxrwx 1 chris chris 40 Apr  5 21:59 packages/polymer_one_script -> /home/chris/repos/polymer-one-script/lib
I cannot run this packaged script directly from this location because the packages that it needs are not available in its installation location:
➜  dart git:(master) ✗ ./packages/polymer_one_script/reduce.dart
Unable to open file: /home/chris/repos/polymer-book/play/deployment/dart/packages/polymer_one_script/packages/yaml/yaml.dart'file:///home/chris/repos/polymer-book/play/deployment/dart/packages/polymer_one_script/reduce.dart': error: line 4 pos 1: library handler failed
import 'package:yaml/yaml.dart';
^
Instead, if I copy or link the packaged script into my application's bin directory, then it works:
➜  dart git:(master) ✗ ln -s packages/polymer_one_script/reduce.dart bin/
➜  dart git:(master) ✗ ./bin/reduce.dart
[web/index.html, web/index2.html]
And that does the trick. I'll upload a package to Pub shortly.

Update: and done.



Day #25

Thursday, April 3, 2014

Command Line Dart to Produce a Single JS Polymer


Up tonight, I try my hand at a Dart command-line script to extract a Dart Pub built Polymer element into a single-file JavaScript for deployment.

I hate to do this, but my efforts at creating a transformer simply ran into a timebox limit past which I am unwilling to invest time (at least for now). I am tempted to implement this as a Bash shell script as I already know the commands that can be used to accomplish this manually. Still, I might as well give this a shot—I have not written many Dart command-line scripts.

I start with a simple skeleton in my application's bin directory:
#!/usr/bin/env dart

import 'dart:io';

main() {
  print('yo');
}
I save that as bin/reduce.dart, make it executable, and run it:
➜  dart git:(master) ✗ chmod 775 bin/reduce.dart 
➜  dart git:(master) ✗ ./bin/reduce.dart
yo
Easy peasy. Now for the more involved part.

And I'll admit here that my motivation for using Dart here wasn't entirely motivated from a desire to learn. At least some of the code that I have written in my transformer for the past few days can be used here. The code that strips <script> tags, extracts <polymer-template> elements, and builds dynamic JavaScript that recreated the <polymer-template> elements can all be used in reduce.dart.

In fact, that goes extremely smoothly. For the most part, I remove references to Trasnformer objects and I replace Asset code with File writes. The main() entry point into my reduce script winds up with two part. One to strip the Polymer entry point web page of its Polymer code:
main() {
  // Strip entry point of polymer-templates and script tags
  var html = new File('build/$filename').readAsStringSync();

  var fixed = html.
    replaceAllMapped(
      polymerElementRegExp,
      (m) { polymer_template = m.group(0); return ''; }
    ).
    replaceAll(new RegExp(r'<script[^<]+</script>'), '').
    replaceFirst('<head>', '<head>\n<script src="scripts/deploy.js"></script>');

  new File('deploy/index.html').
    openSync(mode: FileMode.WRITE).
    writeStringSync(fixed);

  // Build Single JS file
  // ...
}
And the other to combine various assets into a single JavaScript file:
main() {
  // Strip entry point of polymer-templates and script tags
  // ...

  // Build Single JS file
  var js = buildSingleJavaScript(polymer_template);
  new File('deploy/scripts/deploy.js').
    openSync(mode: FileMode.WRITE).
    writeStringSync(js);
}
The regular expression to extract <polymer-element> templates and the buildSingleJavaScript() method both come from my previous efforts. Thankfully, they work!

When I run a simple web server from the deploy directory (which is where this script currently dumps its work), I find that the Polymer runs just fine in non-Dart browsers:



And the smoke test web page now includes only a single <script> tag:
<!DOCTYPE html><html lang="en">
  <head>
    <script src="scripts/deploy.js"></script>
    <title>Pizza Maker</title>
    <meta content="text/html; charset=UTF-8" http-equiv="content-type">
    <link type="text/css" rel="stylesheet" href="/assets/deployment_experiment/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <x-pizza></x-pizza>
    </div>
  </body>
</html>
I still feel bad about my inability to get the pub transformer to work, but wow, this was much easier. The transformer is probably the right way to go about it in the (hopefully not too distant) future. But for today, this is definitely the way to go.


Day #23

Wednesday, April 2, 2014

Giving Up on Single File Polymer.dart Transformers


Up today, I try to hack Polymer.dart, Dart Pub, and dart2js in the most horrible ways possible.

The end goal is to get a pub build of a Polymer element to produce a single deployment script. In its current incarnation, Polymer.dart's pub transformer produces 4 JavaScript files for deployment and it places the <polymer-element> templates directly in the transformed HTML:
<!DOCTYPE html><html lang="en">
<head>
<script src="packages/shadow_dom/shadow_dom.debug.js"></script>
<script src="packages/custom_element/custom-elements.debug.js"></script>
<script src="packages/browser/interop.js"></script>

    <!-- Load component(s) -->
    <!-- Load Polymer -->
    <script src="index.html_bootstrap.dart.js"></script>
</head>
<body>
<polymer-element name="x-pizza-toppings">
  <template><!-- ... --></template>
</polymer-element>
<polymer-element name="x-pizza">
  <template><!-- ... --></template>
</polymer-element>
    <div class="container">
      <h1>Ye Olde Dart Pizza Shoppe</h1>
      <x-pizza></x-pizza>
    </div>
</body></html>
In the previous days, I have managed to manually combine all of that (<polymer-template> and 4 JavaScript files) into a single JavaScript file for reusable deployment. I was unsuccessful in my efforts to write my own pub transformer, primarily because manual dart2js appears to ignore Polymer.dart annotations. If I cannot write my own transformer, I am going to hack as much of the default Polymer.dart transformer as possible to see if I can generate a single, deployable JavaScript file from my Polymer.dart code.

Except if I can't

It turns out that much of dart2js transformer code is, naturally enough, part of Dart's internals instead of Barback or Polymer.

I cannot use the Dart2JSTransformer from internal without compiling Dart from source, which… ugh. It's not that it's a ton of work—just a yak that I do not want to shave tonight for exploring Polymer. So I spend some time looking through the dart2js options that are used by the transformer in the hopes that I am missing some magical setting that would pick up my missing Polymer annotations.

In the end, however, I am unsuccessful. Bother. I think it best to drop this line of exploration for now. There are still a few other avenues of exploration that I need to tackle before Patterns in Polymer is finally done and this avenue is proving less and less fruitful. I will likely throw together a quick shell script tomorrow and then move on. Time permitting, I will return here and investigate compiler Dart so that I have more access to the internal libraries.


Day #22

Tuesday, April 1, 2014

Can't Manually Dart2Js a Polymer


Tonight, I compile Polymer.dart transform assets. No excuses.

I am still trying to compile Polymer code inside a Dart Pub transformer because the default dart2js compilation that pub build does occurs too late for my transformer to use. Without the dart2js output, I cannot compile everything into a single deploy script instead of the multiple JS scripts that are currently created by the built-in Polymer transformer.

I ended last night thinking that I was relatively close. I had written a transform asset to the filesystem, forked a dart2js process, only to find that I needed at least one other asset to successfully compile. Tonight, I add that asset—the generated index.html.0.dart—to the list of files that need to be temporarily available to the transformer:
class SingleJsPolymerTransformer extends Transformer {
  List<AssetId> bootstrappedPolymerElements = [];
  // ...
  Future<bool> isPrimary(Asset input) {
    if (input.id.path.contains('html_bootstrap.dart')) {
      bootstrappedPolymerElements.add(input.id);
    }
    if (input.id.path.contains('html.0.dart')) {
      bootstrappedPolymerElements.add(input.id);
    }
    // ...
  }
  // ...
}
Assets are Future based, which means that I need a way to wait for any and all temporary files to be written to the file system. To make that happen, I write a method that returns a list of Futures that will complete when their files have been written:
  List<Future> writeTemporaryAssets(transform, List<AssetId> assets) {
    return assets.
      map((asset){
        return transform.
          readInputAsString(asset).
          then((code) {
            new File(asset.path).
              openSync(mode: FileMode.WRITE).
              writeStringSync(code);
          });
      });
  }
The return value of the innermost then() is itself a future (the then() method always returns a future), so I have successfully generated a list of Futures, each of which complete when the file has been written to the filesystem. Now I need to wait for all of those Futures to complete before attempting to dart2js compile my Polymer code. This is what Future.wait() does:
  buildSingleJavaScript(templateHtml, transform) {
    return Future.
      wait(writeTemporaryAssets(transform, bootstrappedPolymerElements)).
      then((_){
        var result = Process.runSync('dart2js', [ /* ... */]);
        // Assemble dart2js and various library code...
      });
  }
Given a list of writeTemporaryAssets() futures, Future.wait() returns another Future that will complete only when every future in the list has completed. In other words, I am now waiting until all temporary assets are available on the filesystem before running dart2js. Perfect!

Naturally, this still does not work. Actually, writing the temporary assets works as does compiling. Unfortunately, compiling these temporary assets does not generate the same code that the dart2js pub transformer generated. It is close, but a diff of my dart2js compiled JavaScript with that generated by the pub transformer reveals numerous differences, including:
...
 C.Ka=new H.GD("call")
+C.Je=new H.GD("current")
 C.nN=new H.GD("dynamic")
 C.AZ=new H.GD("dart.core.String")
+C.Kl=new H.GD("ingredients")
 C.Wn=new H.GD("length")a
 C.PC=new H.GD("dart.core.int")
+C.YS=new H.GD("name")
 C.OV=new H.GD("noSuchMethod")
+C.aC=new H.GD("pizzaState")
 C.c8=new H.GD("registerCallback")
 C.ok=new H.GD("dart.core.Null")
...
Unfortunately, the missing objects look to be annotated Polymer attributes:
@CustomTag('x-pizza-toppings')
class XPizzaToppings extends PolymerElement {
  @published String name;
  @published List ingredients = [];
  @observable String current = '';
  // ...
}
Without those observed and published attributes, Polymer code isn't really Polymer code. And, even though there are no errors when I fire up the code, my <x-pizza> builder does not work. It does not even have ingredients:



Darn.

One the one hand, this was a terribly ugly approach, so it is not too much a shame that it will not work. On the other hand, why can't I compile annotated code with dart2js? Given that this approach is such an ugly mess, I likely will not try to answer that. Instead, I will probably take a closer look a the dart2js and Polymer.dart transformers tomorrow to see if I have any luck in there. And if not, I can always fall back to shell scripts.


Day #21

Monday, March 31, 2014

Forking Dart2JS in a Pub Transform (ICK)


My quest to generate a single JS file from a Polymer.dart source continues tonight with an attempt to get dart2js generated code into that single JS file.

After the previous two nights, I have the <polymer-element> template in said JS file (Polymer.dart puts it directly in the HTML by default) and various supporting libraries in that same JS file. But I lack the most important piece of this puzzle—the compiled backing class itself. The problem is that the dart2js transformer is run at the very end of the Dart Pub transform process.

The first thing that I try tonight is to place the $dart2js options before my custom, single JS transformer in my project's pubspec.yaml:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
- $dart2js:
    verbose: true
- deployment_experiment:
    entry_points: web/index.html
I have not looked into the $dart2js transformer code and the documentation never states this explicitly, but my sense is that the dart2js transformer is run last no matter what and that the $dart2js options are just that—options for that last transformer.

Still, best not to assume, so:
$ pub build
Building deployment_experiment.................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................^C
I let that run for a good ten minutes with no discernable results. There is nothing happening to the filesystem:
➜  polymer-book git:(master) ✗ find play/deployment -mmin -60 -ls | grep -v node_modules | grep -v dart/packages
1188688    4 drwxr-xr-x  10 chris    chris        4096 Mar 31 22:17 play/deployment/dart
1196105    4 drwxr-xr-x   2 chris    chris        4096 Mar 31 21:58 play/deployment/dart/test
1186073    0 lrwxrwxrwx   1 chris    chris          11 Mar 31 21:58 play/deployment/dart/test/packages -> ../packages
1196106    4 drwxr-xr-x   2 chris    chris        4096 Mar 31 21:58 play/deployment/dart/web
1186074    0 lrwxrwxrwx   1 chris    chris          11 Mar 31 21:58 play/deployment/dart/web/packages -> ../packages
1188969    4 -rw-r--r--   1 chris    chris         349 Mar 31 22:10 play/deployment/dart/pubspec.yaml
1188960    4 -rw-r--r--   1 chris    chris        2203 Mar 31 21:58 play/deployment/dart/pubspec.lock
1188690    4 drwxr-xr-x   3 chris    chris        4096 Mar 31 22:00 play/deployment/dart/lib
1186103    4 -rw-r--r--   1 chris    chris        2240 Mar 31 22:00 play/deployment/dart/lib/transformer.dart
1196109    4 drwxr-xr-x   2 chris    chris        4096 Mar 31 22:10 play/deployment/dart/build
So I Ctrl-C the process.

If I move the $dart2js configuration to the end of pubspec.yaml, then the pub build works normally, albeit without the ability to transform dart2js output.

So ugh. It seems that I have do this the ugly way. The ugly way involves identifying the Polymer transform assets that get compiled into JavaScript by the default dart2js process at the end of pub build. Using that list, I then need to manually compiled these assets as part of my transform.

I identify the parts as part of the Transformer's determination of which elements are “primary” elements. These dart2js elements are not primary, but I squirrel them away in a list to be processed:
library single_file.transformer;

import 'dart:io';
import 'dart:async';
import 'package:barback/barback.dart';

class SingleJsPolymerTransformer extends Transformer {
  String entry_points;
  List<AssetId> bootstrappedPolymerElements = [];
  // ...
  Future<bool> isPrimary(Asset input) {
    if (input.id.path.contains('html_bootstrap.dart')) {
      bootstrappedPolymerElements.add(input.id);
    }

    if (entry_points == input.id.path) return new Future.value(true);
    return new Future.value(false);
  }
  // ...
}
With that, I can then run dart2js on the assets, but...

But I have to first write them out to the disk. The built-in dart2js transformer must have some kind of compile-from-asset capability. I will look into that at some point, but for tonight I content myself with ugly hacks like:
  buildSingleJavaScript(templateHtml, transform) {
    return transform.
      readInputAsString(bootstrappedPolymerElements.first).
      then((code) {
        new File('index.html_bootstrap.dart').
          openSync(mode: FileMode.WRITE).
          writeStringSync(code);

        var result = Process.runSync(
         'dart2js',
         ['-o', 'index.html_bootstrap.dart.js', 'index.html_bootstrap.dart']
        );
        // ...
      });
  }
Even that does not quite do the trick. It seems that there are secondary Polymer.dart elements that are required because I wind up with compilation errors along the lines of:
index.html_bootstrap.dart:7:8: Error: Can't read 'file:///home/chris/repos/polymer-book/play/deployment/dart/index.html.0.dart' (Error reading
 'index.html.0.dart' (OS Error: No such file or directory, errno = 2)).
import 'index.html.0.dart' as i2;
       ^^^^^^^^^^^^^^^^^^^
index.html_bootstrap.dart:15:3: Warning: Cannot resolve 'i2'.
  i2.main();
  ^^
Error: Compilation failed.
Bother.

I do think I am on the right track, but I call it a night at this point. I will pick back up fresh tomorrow either investigating how dart2js compiles assets or working through the remaining secondary Polymer.dart elements that are needed to compile this darn file.



Day #20

Sunday, March 30, 2014

Reading Files During Dart Pub Transform


After last night, I have my post-Polymer.dart pub transformer on the road to building single-file JavaScript from Dart Polymer elements.

This transformer needs to run after the built-in Polymer.dart transformer and takes identical configuration in the pubspec.yaml file:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
- deployment_experiment:
    entry_points: web/index.html
Where the built-in Polymer.dart transformer leaves the <polymer-element> templates directly in the entry_points HTML, my deployment experiment transformer moves the templates into a new JavaScript file responsible for adding the templates to the DOM.

To complete my transformer, I need to combine the remaining <script> tags from the Polymer.dart transformer into a single script source:
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="/scripts/x_pizza_templates.js"></script>
  <script src="/scripts/shadow_dom.min.js"></script>
  <script src="/scripts/custom-elements.min.js"></script>
  <script src="/scripts/interop.js"></script>
  <script src="/scripts/index.html_bootstrap.dart.js"></script>
</head>
<body>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body>
</html>
The problem I am faced with is that none of those files is included as an asset coming from the Polymer.dart transform. So I cannot put my (admittedly small) pub transformer knowledge to use here. Regardless of how all of that JavaScript is going to get into my single “deploy.js” file, I will need to do the work near the buildSingleJavaScript() method of my transformer:
import 'package:barback/barback.dart';

class SingleJsPolymerTransformer extends Transformer {
  // ...
  buildSingleJavaScript(templateHtml, transform) {
    var templateId = new AssetId(
      'deployment_experiment',
      'web/scripts/deploy.js'
    );
    transform.addOutput(
      new Asset.fromString(templateId, _templateJs(templateHtml))
    );
  }
  // ...
}
This method created a new asset ID to be added to the transform process and it then adds the asset it from a string (which is the crazy JavaScript string version of the <polymer-element> tags from last night).

The absolute dumbest way that I can think to add all of the other JavaScript source files to this asset is read each synchronously from the file system, concatenating each to last night's _templateJS():
  buildSingleJavaScript(templateHtml, transform) {
    var templateId = new AssetId(
      'deployment_experiment',
      'web/scripts/deploy.js'
    );

    var js = _templateJs(templateHtml) +
      new File('packages/shadow_dom/shadow_dom.min.js').readAsStringSync() +
      new File('packages/custom_element/custom-elements.min.js').readAsStringSync() +
      new File('packages/browser/interop.js').readAsStringSync();

    transform.addOutput(new Asset.fromString(templateId, js));
  }
That works perfectly. At least it works perfectly until I try to read the dart2js generated Polymer code:
  buildSingleJavaScript(templateHtml, transform) {
    var templateId = new AssetId(
      'deployment_experiment',
      'web/scripts/deploy.js'
    );

    var js = _templateJs(templateHtml) +
      new File('packages/shadow_dom/shadow_dom.min.js').readAsStringSync() +
      new File('packages/custom_element/custom-elements.min.js').readAsStringSync() +
      new File('packages/browser/interop.js').readAsStringSync() +
      new File('build/web/index.html_bootstrap.dart.js').readAsStringSync();

    transform.addOutput(new Asset.fromString(templateId, js));
  }
When I try to pub build with that in my transformer, I am greeted with:
➜  dart git:(master) ✗ pub build
Building deployment_experiment...
Build error:
Transform SingleJsPolymer on deployment_experiment|web/index.html threw error: Cannot open file, path = 'build/web/index.html_bootstrap.dart.js' (OS E
rror: No such file or directory, errno = 2)
file_impl.dart 558                                                            _File.throwIfError
file_impl.dart 411                                                            _File.openSync
file_impl.dart 456                                                            _File.readAsBytesSync
file_impl.dart 479                                                            _File.readAsStringSync
http://127.0.0.1:46880/packages/deployment_experiment/transformer.dart 54:74  SingleJsPolymerTransformer.buildSingleJavaScript
...
The problem, of course, is that build/web/index.html_bootstrap.dart.js does not exist yet. This file is generated when pub build calls dart2js on *.dart code after the various transforms are invoked. But I need the code during a transform, so am I out of luck?

In fact, I may be out of luck. About the only thing that I can think to try is forking out a separate dart2js process during the transform. That seems ugly, but there may be no other option save for giving up the idea of doing this as a transformer and sticking with shell scripts. As wrong as the fork-dart2js-during-transform feels, I will likely give that a try tomorrow—at least to see just how ugly it is. Unless someone has a better idea?


Day #19

Saturday, March 29, 2014

A Dart Pub Transform to Strip Polymer Elements


Today I start on a build script for a Polymer.dart element.

There is already a nice Dart build transformer that comes with the Polymer.dart package. It does a reasonable job of building a Polymer element into a web page for deployment to the modern web. I want to take it a step further. I would like my script to build the Polymer element for deployment to any page.

I have manually done just that over the past two days, using mostly command-line tools. I could probably work those command-lines into a Bash script without much difficulty, but I think it more useful to rework that effort in the form of another Dart transformer. This Dart transformer will (at least initially) use the results of the Polymer.dart transform, and transform them into a single script for deployment.

I am looking at this as a multi-day effort, so tonight I will extract the Polymer templates that the Polymer.dart transformer leaves in the web page that it builds. As I found two nights ago, it is possible to place them in a JavaScript file to be dynamically added to the DOM for ultimate use by the Polymer.dart platform.

For that, I need to write my own custom transformer. There is a nice article on the subject from the fine Dart folks, which saves me some work. I would like the transformer settings to follow the same convention as the original transformer—at least to start. So my pubspec.yaml becomes:
name: deployment_experiment
dependencies:
  polymer: any
dev_dependencies:
  scheduled_test: any
transformers:
- polymer:
    entry_points: web/index.html
- deployment_experiment:
    entry_points: web/index.html
The bulk of the work in this transformer, which I start in lib/transformer.dart, comes from the aforementioned article. This gives me a skeleton transformer of:
library single_file.transformer;

import 'dart:async';
import 'package:barback/barback.dart';

class SingleJsPolymerTransformer extends Transformer {
  String entry_points;

  SingleJsPolymerTransformer(this.entry_points);

  SingleJsPolymerTransformer.fromList(List a): this(a[0]);

  SingleJsPolymerTransformer.asPlugin(BarbackSettings settings)
    : this.fromList(_parseSettings(settings));

  Future<bool> isPrimary(Asset input) {
    if (entry_points == input.id.path) return new Future.value(true);
    return new Future.value(false);
  }

  Future apply(Transform transform) {
    // Need to do stuff here....
  }
}

List<String> _parseSettings(BarbackSettings settings) {
  var args = settings.configuration;
  return [ args['entry_points'] ];
}
Starting from that skeleton, I need to build the transform that will take the normal Polymer transform and convert everything into a single file. First up, my transformer needs to remove the <polymer-template> tags from the Polymer transformation step:
<!DOCTYPE html><html lang="en"><head>
<script src="/scripts/shadow_dom.min.js"></script>
<script src="/scripts/custom-elements.min.js"></script>
<script src="/scripts/interop.js"></script>
<script src="/scripts/index.html_bootstrap.dart.js"></script>
</head>
<body>
  <polymer-element name="x-pizza-toppings">
    <template><!-- ... --></template>
  </polymer-element>
  <polymer-element name="x-pizza">
    <template><!-- ... --></template>
  </polymer-element>
  <div class="container">
    <h1>Ye Olde Dart Pizza Shoppe</h1>
    <x-pizza></x-pizza>
  </div>
</body></html>
In pub transfomers, that means that I need to search and replace for text in a string, then update the asset in the transform. I accomplish that with:
class SingleJsPolymerTransformer extends Transformer {
  // ...
  Future apply(Transform transform) {
    var input = transform.primaryInput;
    var re = new RegExp(
      r'<polymer-element[\s\S]+/polymer-element>',
      multiLine: true
    );

    return transform.
      readInputAsString(input.id).
      then((html){
        var fixed = html.replaceAllMapped(
          re,
          (m) {
            return '';
          }
        );
        transform.addOutput(new Asset.fromString(input.id, fixed));
      });
  }
}
The hard part comes next. In addition to simply removing this text from an existing asset, I need to create a new asset (which requires a new, unique asset ID) and convert the <polymer-element> text into something that can be dynamically added via a JavaScript resource. Something like this ought to do the trick:
class SingleJsPolymerTransformer extends Transformer {
  // ...
  Future apply(Transform transform) {
    var input = transform.primaryInput;
    var re = new RegExp(
      r'<polymer-element[\s\S]+/polymer-element>',
      multiLine: true
    );

    return transform.
      readInputAsString(input.id).
      then((html){
        var polymer_template;
        var fixed = html.replaceAllMapped(
          re,
          (m) {
            polymer_template = m.group(0);
            return '';
          }
        );
        transform.addOutput(new Asset.fromString(input.id, fixed));

        var templateId = new AssetId(
          'deployment_experiment',
          'web/scripts/polymer_template.js'
        );
        transform.addOutput(
          new Asset.fromString(
            templateId,
            '''
var _html = '' +
${polymer_template.split('\n').map((s)=> "'" + s + "' +").join('\n')}
'';

window.addEventListener('DOMContentLoaded', function(){
  var container = document.createElement('div');
  container.innerHTML = _html;
  document.body.appendChild(container);
});
          '''
          )
        );
      });
  }
}
Inside the replaceAll, I squirrel away the <polymer-element> text in the polymer_template variable so that it can be used later. Then, I create a new web/scripts/polymer_template.js asset. Finally, I convert the <polymer-elements> into a bunch of concatenated JavaScript strings so that this will still work on the modern web (this is more or less what I did manually yesterday).

And, happily, this seems to work. If I use this generated JavaScript file in my build-generated code, then I still have a working Polymer. That seems a good stopping point for today. Up tomorrow, I need to combine this generated JavaScript code with the other JavaScript code that is normally generated in separate files by the normal Polymer transformer. My code is also a little messy, so some cleanup is in order. Hopefully this will prove relatively easy, but there is only one way to really know. Which I will find out tomorrow!


Day #18

Tuesday, December 17, 2013

Pub Serve Polymer Elements


OK. I know I'm doing something incredibly stupid, but... I still cannot get pub serve, the simple web server built into Dart's Pub package manager, to serve up Polymer Element resources.

I do not believe that I am doing any crazy though. I have a very simple, web-only application. The pubspec.yaml contains only the latest versions of Polymer and Polymer Elements:
name: flex
dependencies:
  polymer: any
  polymer_elements: any
dev_dependencies:
  unittest: any
I see no errors upon starting pub serve (though it does take a good 10 seconds to spin up). If I curl for similar resources, then everything works OK:
➜  dart git:(master) ✗ curl http://localhost:8080/packages/polymer_expressions/expression.dart
// Copyright (c) 2013, the Dart project authors.  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.
...
But if I curl for Polymer Elements resources, I get nothing back:
➜  dart git:(master) ✗ curl http://localhost:8080/packages/polymer_elements/polymer_elements.dart
Nothing. The connection just hangs.

Pub's server can be run in verbose mode with pub serve -v (there are verbosity levels, but I just ask for everything here). With that, I find that the regular, working requests look like:
FINE: BarbackServer GET /packages/polymer_expressions/expression.dart
    | Loading polymer_expressions|lib/expression.dart
MSG : GET /packages/polymer_expressions/expression.dart → polymer_expressions|lib/expression.dart
FINE: BarbackServer GET /packages/polymer_expressions/expression.dart
    | Served polymer_expressions|lib/expression.dart
Whereas the failing request look like:
FINE: BarbackServer GET /packages/polymer_elements/polymer_elements.dart
    | Loading polymer_elements|lib/polymer_elements.dart
So the request is coming into the Pub server. It seems to parse it properly—the requests is for the lib/polymer_elements.dart file in the polymer_elements package. But then... nothing.

So I try using the GitHub repository for Polymer Elements instead. Perhaps it hold some insights into my woes:
name: flex
dependencies:
  polymer: any
  polymer_elements:
    git: https://github.com/ErikGrimes/polymer_elements
dev_dependencies:
  unittest: any
But trying a pub upgrade with that yields:
➜  dart git:(master) ✗ pub upgrade
Resolving dependencies.........................
Incompatible dependencies on 'polymer_elements':
- 'flex' depends on it from source git
- 'polymer_ui_elements' depends on it from source hosted
Why on earth is Polymer Elements trying to pull in Polymer UI elements anyway.

I do the usual GitHub upstream dance and use my repository instead:
name: flex
dependencies:
  polymer: any
  polymer_elements:
    git: https://github.com/eee-c/polymer_elements
dev_dependencies:
  unittest: any
And before I realize my mistake, I pub upgrade and pub serve and find that I can now curl for Polymer Element resources:
➜  dart git:(master) ✗ curl http://localhost:8080/packages/polymer_elements/polymer_elements.dart
// needed as entry point for dartdoc generation
/**
 * Polymer Elements
 */
library polymer_elements;
// ...
My mistake is pointing my pubspec.yaml dependencies at my fork of Polymer Elements as it exists on GitHub, not as it exists locally. But at least I know a change in the code since then has affected things. A git diff --stat <SHA1> where <SHA1> points to a0717db12 (my last commit) reveals that there have been a lot of code changes in the meantime. I tend to doubt code changes are my problem here. Instead, I think the problem is in the changes to the project's pubspec.yaml:
➜  polymer_elements git:(master) gd a0717db12 pubspec.yaml
diff --git a/pubspec.yaml b/pubspec.yaml
index 398337d..7df61fd 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,5 +1,5 @@
 name: polymer_elements
-version: 0.0.13
+version: 0.1.2
 authors:
 - Erik Grimes 
 - Günter Zöchbauer 
@@ -11,8 +11,11 @@ documentation: http://erikgrimes.github.io/polymer_elements/docs/index.html
 environment:
   sdk: ">=1.0.0 <2.0.0"
 dependencies:
-  polymer: ">=0.9.0 <0.10.0"
-#  polymer_ui_elements: 0.0.13
+  polymer: ">=0.9.2+3 <0.10.0"
+  polymer_ui_elements: ">=0.1.1 <0.2.0"
+#dependency_overrides:
+#  polymer_ui_elements: 
+#    path: ../polymer_ui_elements  
 dev_dependencies:
   unittest: ">=0.9.0 <0.10.0"
 transformers:
And indeed, if I remove the Polymer UI Elements dependencies from my local fork of Polymer Elements, then I can pub upgrade without error and, more importantly, successfully curl after starting pub serve. In fact, I can now serve my flex-layout web page:
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Flex Test</title>
    <!-- Load component(s) -->
    <link rel="import" href="/packages/polymer_elements/polymer_flex_layout/polymer_flex_layout.html">
    <script type="application/dart">export 'package:polymer/init.dart';</script>
    <script src="packages/browser/dart.js"></script>
  </head>
  <body>
     <polymer-flex-layout isContainer>
       <div>Left</div>
       <div align=center flex>Main</div>
       <div>Right</div>
     </polymer-flex-layout>
  </body>
</html>
And see the results in Dartium:

I suspect that my problems have to do with circular dependencies in Polymer Elements and Polymer UI Elements. I am still not certain that either needs to depend on the other. Regardless, pub serve probably ought to deal with this situation better. PRs and bug reports to come…

Day #968

Saturday, September 28, 2013

Strike Two: Using Big Dart Package Patches


My first attempt at working with a large Dart patch was not quite as smooth as I would have liked. The problem is that the patch spans several Dart packages. Applying the patch was easy enough, but getting my local code to work with the local packages resulted in something akin to dependency hell:



Those are just a few of the changes that I needed to make—not only to the packages that are directly impacted by the patch—but also to the packages that rely on the same code. The problem is that Dart's Pub package system will not allow the same packages to be installed from two different sources (e.g. pub.dartlang.org and the filesystem).

It might be nice for Pub to defer an “any” constraint in favor of a “path” one. That is, if the various packages in the dependency tree includes a bunch of mdv: any dependency and a single mdv: path: /home/chris/repos/dart/dart/pkg/mdv dependency, then the latter could be used everywhere. No matter, this is an edge case for an admittedly early-stage tool like Pub. In the meantime, how might I better handle development in this case?

I try switching my project's dependencies back to the default pub.dartlang.org by reverting the constraints to “any” in pubspec.yaml:
name: ice_code_editor
# ...
dependencies:
  # ...
  polymer: any
After a pub install, a quick check of the project's packages directory shows that the three packages that were addressed by the original patch—polymer, custom_element, and observe—are now coming from pub.dartlang.org:
➜  ice-code-editor git:(polymer) ✗ ls -l packages/{polymer,custom_element,observe}
lrwxrwxrwx 1 chris chris 71 Sep 28 20:07 packages/custom_element -> 
    /home/chris/.pub-cache/hosted/pub.dartlang.org/custom_element-0.7.5/lib
lrwxrwxrwx 1 chris chris 64 Sep 28 20:07 packages/observe -> 
    /home/chris/.pub-cache/hosted/pub.dartlang.org/observe-0.7.5/lib
lrwxrwxrwx 1 chris chris 64 Sep 28 20:07 packages/polymer -> 
    /home/chris/.pub-cache/hosted/pub.dartlang.org/polymer-0.7.5/lib
I remove the symbolic links to the cached, hosted versions of those packages, replacing them with my modified local versions instead:
➜  ice-code-editor git:(polymer) ✗ cd packages 
➜  packages git:(polymer) ✗ rm {polymer,observe,custom_element}
➜  packages git:(polymer) ✗ ln -s ~/repos/dart/dart/pkg/polymer/lib polymer
➜  packages git:(polymer) ✗ ln -s ~/repos/dart/dart/pkg/observe/lib observe    
➜  packages git:(polymer) ✗ ln -s ~/repos/dart/dart/pkg/custom_element/lib custom_element
That seems to work. At the very least, the built-in pub serve web server starts up without complaint:
➜  ice-code-editor git:(polymer) ✗ pub serve
Serving ice_code_editor on http://localhost:8080
Build completed successfully
Sadly, appearances are deceiving in this case. The updated polymer_element.dart file is nearly empty:
➜  ice-code-editor git:(polymer) ✗ cat packages/polymer/polymer_element.dart
// Copyright (c) 2013, the Dart project authors.  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 polymer.polymer_element;

export 'polymer.dart' show PolymerElement, registerPolymerElement;

➜  ice-code-editor git:(polymer) ✗ cat web/packages/polymer/polymer_element.dart
// Copyright (c) 2013, the Dart project authors.  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 polymer.polymer_element;

export 'polymer.dart' show PolymerElement, registerPolymerElement;
But when I curl for that resource, I find the old version of the resource:
➜  ice-code-editor git:(polymer) ✗ curl http://localhost:8080/packages/polymer/polymer_element.dart
// Copyright (c) 2013, the Dart project authors.  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 polymer.polymer_element;

import 'dart:async';
import 'dart:html';
import 'dart:mirrors';
import 'dart:js' as js;

import 'package:custom_element/custom_element.dart';
import 'package:mdv/mdv.dart' show NodeBinding;
import 'package:observe/observe.dart';
import 'package:observe/src/microtask.dart';
import 'package:polymer_expressions/polymer_expressions.dart';

import 'src/utils.dart' show toCamelCase, toHyphenedName;

/**
 * Registers a [PolymerElement]. This is similar to [registerCustomElement]
 * but it is designed to work with the `<element>` element and adds additional
 * features.
 */
void registerPolymerElement(String localName, PolymerElement create()) {

Much more follows...
Bother. It would seem that pub serve is reading pubspec.lock in order to figure out where to find its files—completely ignoring the symbolic links in the packages directory.

Manually manipulating symbolic links in the packages directory is already pretty far off the rails, but before abandoning the effort entirely, I try modifying the pubspec.lock file that is generated by pub install.

Unfortunately, when I try out the Pub server, it notices my modifications and overwrites them:
➜  ice-code-editor git:(polymer) ✗ pub serve
Dependencies have changed, installing...
Resolving dependencies......................
Dependencies installed!
Serving ice_code_editor on http://localhost:8080
Ah well, it was worth a try.

It is a bummer, but pubspec.yaml dependency hell is currently the only way that I can see to try out existing projects with new core-package changes.

Day #888

Sunday, August 25, 2013

I Got Served… at Dart Pub


Last week on the Dart mailing list, I learned that words like "pants" and "scissors" that have no singular form are called "pluralia tantum." The exquisite Bob Nystrom laid that one on us along with the news that Dart Pub supports both assets and bundles its own web server. Wha?

Saaay. I could use both of those things. In the ICE Code Editor, we have a bunch of example files that we serve with a very simple app.dart server that is also included in there:
➜  example git:(master) pwd
/home/chris/repos/ice-code-editor/example
➜  example git:(master) tree -I '*.deps|*.map'
.
├── app.dart
├── packages -> ../packages
└── public
    ├── events.html
    ├── full.dart
    ├── full.dart.js
    ├── full.html
    ├── index.html
    ├── main.dart
    ├── main.dart.js
    └── packages -> ../../packages

3 directories, 8 files
Can I move the examples in the public subdirectory into the new asset top-level directory and pub serve them?
➜  example git:(master) cd ..
➜  ice-code-editor git:(master) mkdir asset
➜  ice-code-editor git:(master) mv example/public asset/examples
➜  ice-code-editor git:(master) ✗ pub serve
Serving ice_code_editor on http://localhost:8080
Build completed successfully

# Meanwhile, in another screen...
➜  ice-code-editor git:(master) ✗ curl http://localhost:8080/assets/ice_code_editor/examples/full.html
<head>
  <script src="packages/browser/dart.js"></script>
  <script src="packages/browser/interop.js"></script>
  <script src="full.dart" type="application/dart"></script>
</head>
Yes I can.

That is much easier than telling folks to spin up the custom app.dart server! But now that I have that working, I realize that my runnable examples are probably better placed in the web subdirectory:
^C
➜  ice-code-editor git:(master) ✗ mkdir web
➜  ice-code-editor git:(master) ✗ mv asset/examples/* web/
➜  ice-code-editor git:(master) ✗ pub serve
Serving ice_code_editor on http://localhost:8080
Build completed successfully
With the full.html and other example pages now in the web subdirectory, I can access them directly at the root of pub serve:
➜  ice-code-editor git:(master) ✗ curl http://localhost:8080/full.html
<head>
  <script src="packages/browser/dart.js"></script>
  <script src="packages/browser/interop.js"></script>
  <script src="full.dart" type="application/dart"></script>
</head>
That is pretty freaking cool.

The asset top-level directory is meant for other kinds of resources. I have been jamming the CSS, HTML, and JavaScript that are needed by ICE directly into the lib top-level directory:
➜  ice-code-editor git:(master) ✗ tree lib -I '*\.dart' 
lib
├── css
│   └── ice.css
├── fonts
│   └── inconsolata.woff
├── full
├── html
│   └── preview_frame.html
└── js
    ├── ace
    │   ├── ace.js
    │   ├── ext-searchbox.js
    │   ├── keybinding-emacs.js
    │   ├── mode-css.js
    │   ├── mode-html.js
    │   ├── mode-javascript.js
    │   ├── theme-chrome.js
    │   ├── theme-textmate.js
    │   └── worker-javascript.js
    └── deflate
        ├── rawdeflate.js
        └── rawinflate.js

7 directories, 14 files
I need them in lib so that, when the ice_code_editor packages is installed, the web server will have access to them. Before these recent changes to Dart Pub, only files in lib were visible outside of a package. This seems to be changing, but is is ready for my needs yet? There is one way to find out…

I move all of those non-dart assets into the asset top-level directory:
➜  ice-code-editor git:(master) ✗ cd lib
➜  lib git:(master) ✗ mv css fonts html js ../asset/
Then, I go through my code to replace any instance of packages/ice_code_editor/<...> with assets/ice_code_editor/<...>:
  static _attachScripts() {
    if (_scripts != null) return;

    var script_paths = [
      "assets/ice_code_editor/js/ace/ace.js",
      "assets/ice_code_editor/js/ace/keybinding-emacs.js",
      "assets/ice_code_editor/js/deflate/rawdeflate.js",
      "assets/ice_code_editor/js/deflate/rawinflate.js"
    ];

    var scripts = script_paths.
      map((path) { /* ... */ });
    return _scripts = scripts;
  }
And, amazingly that Just Works™:



I am getting excited here! My codebase is all kinds of cleaner because of this. I no longer need the app.dart mini-server. My example pages are still contained in a reasonable place. My CSS, JavaScript, and HTML—my assets—are no longer cluttering up the lib directory of my package. Now lib contains only Dart code and I have a working, well-named placed for assets to go.

Of course...

This is not the real use-case for placing my assets in lib. The reason that all of those assets were in there was so that that they could be visible when served from a static web server (on GitHub pages). And there, I think that my luck runs out.

If I update the pubspec.yaml for the http://gamingjs.com/ice-beta, then I see no assets directory exposed:
➜  ice-beta git:(gh-pages) ✗ gd .
diff --git a/ice-beta/pubspec.yaml b/ice-beta/pubspec.yaml
index 1a87698..61c8f7a 100644
--- a/ice-beta/pubspec.yaml
+++ b/ice-beta/pubspec.yaml
@@ -4,4 +4,5 @@ description: Full screen ICE
 author: Chris Strom 
 homepage: https://github.com/eee-c/ice-code-editor
 dependencies:
-  ice_code_editor: any
+  ice_code_editor:
+    path: /home/chris/repos/ice-code-editor
➜  ice-beta git:(gh-pages) ✗ pub update
Resolving dependencies..................
Downloading browser 0.6.19 from hosted...
Downloading path 0.6.19 from hosted...
Downloading meta 0.6.19 from hosted...
Downloading stack_trace 0.6.19 from hosted...
Dependencies updated!
➜  ice-beta git:(gh-pages) ✗ ls packages/ice_code_editor
editor.dart  full  full.dart  gzip.dart  ice.dart  store.dart
Before, when my assets where in the lib directory, they were linked into ice-beta along with the Dart source code. Now, they are nowhere to be found.

That said…

Installing pub packages create symbolic links in the packages directory:
➜  ice-beta git:(gh-pages) ✗ ls -l packages 
total 32
lrwxrwxrwx 1 chris chris 65 Aug 25 21:21 browser -> /home/chris/.pub-cache/hosted/pub.dartlang.org/browser-0.6.19/lib
lrwxrwxrwx 1 chris chris 66 Aug 25 21:21 crypto -> /home/chris/.pub-cache/hosted/pub.dartlang.org/crypto-0.6.17+2/lib
lrwxrwxrwx 1 chris chris 69 Aug 25 21:21 ctrl_alt_foo -> /home/chris/.pub-cache/hosted/pub.dartlang.org/ctrl_alt_foo-0.1.2/lib
lrwxrwxrwx 1 chris chris 37 Aug 25 21:21 ice_code_editor -> /home/chris/repos/ice-code-editor/lib
lrwxrwxrwx 1 chris chris 60 Aug 25 21:21 js -> /home/chris/.pub-cache/hosted/pub.dartlang.org/js-0.0.24/lib
lrwxrwxrwx 1 chris chris 62 Aug 25 21:21 meta -> /home/chris/.pub-cache/hosted/pub.dartlang.org/meta-0.6.19/lib
lrwxrwxrwx 1 chris chris 62 Aug 25 21:21 path -> /home/chris/.pub-cache/hosted/pub.dartlang.org/path-0.6.19/lib
lrwxrwxrwx 1 chris chris 69 Aug 25 21:21 stack_trace -> /home/chris/.pub-cache/hosted/pub.dartlang.org/stack_trace-0.6.19/lib
lrwxrwxrwx 1 chris chris 68 Aug 25 21:21 unittest -> /home/chris/.pub-cache/hosted/pub.dartlang.org/unittest-0.6.15+3/lib
Symbolic links are a no-no on Jekyll/GitHub pages, so I use a Bash script to de-cache them (the current built-in pub actions do this, but only in other use-cases). If I am already doing that, might I also check for the existence of an asset directory in each package and install that as well?

By way of proof-of-concept, I manually copy the assets from ICE into the GitHub pages ice-beta site:
➜  ice-beta git:(gh-pages) ✗ mkdir -p assets/ice_code_editor
➜  ice-beta git:(gh-pages) ✗ cp -r ~/repos/ice-code-editor/asset/* assets/ice_code_editor/
After decaching the packages, I fire up a local jekyll server:
➜  ice-beta git:(gh-pages) ✗ cd ..
➜  gamingjs git:(gh-pages) ✗ jekyll --auto --server
Configuration from /home/chris/repos/gamingjs/_config.yml
Auto-regenerating enabled: /home/chris/repos/gamingjs -> /home/chris/repos/gamingjs/_site
[2013-08-25 21:38:46] regeneration: 492 files changed
[2013-08-25 21:38:46] INFO  WEBrick 1.3.1
[2013-08-25 21:38:46] INFO  ruby 1.9.3 (2012-04-20) [x86_64-linux]
[2013-08-25 21:38:46] INFO  WEBrick::HTTPServer#start: pid=9822 port=4000
And…



It works!

There are no network errors in the Developer Console and the ICE Code Editor looks to be running perfectly well. It is fairly encouraging that it was so easy to adapt the new assets strategy to my GitHub pages sites.

Even so, this is not a fully baked solution. Some of the work that we have been doing in ICE recently is to allow for more re-use. It does no good to make it easier for other folks to use ICE only to implement an assets solution that requires some post-processing. I may include an internal tool for doing just that. Or I may stick with the web directory only solution for now and await future changes in Pub.

Regardless, I am eager for the next improvements in Pub. And hope that the next announcement will come with similarly useful tidbits of information.



Day #854